fix order of openning a file and checking its inode (#16887)
Costa Tsaousis committed
Jan 31, 2024 at 12:46 UTC
2371fec7a3be30bc56ef5530bfab82361ca446f7
1 file changed
+12
-5
collectors/plugins.d/local-sockets.h
+12
-5
@@ -811,15 +811,22 @@ static inline bool local_sockets_get_namespace_sockets(LS_STATE *ls, struct pid_
811
snprintfz(filename, sizeof(filename), "%s/proc/%d/ns/net", ls->config.host_prefix, ps->pid);
812
813
// verify the pid is in the target namespace
814
+ int fd = open(filename, O_RDONLY);
815
+ if (fd == -1) {
816
+ local_sockets_log(ls, "cannot open file '%s'", filename);
817
+ return false;
818
+ }
819
+
820
struct stat statbuf;
815
- if (stat(filename, &statbuf) == -1 || statbuf.st_ino != ps->net_ns_inode) {
816
- local_sockets_log(ls, "pid %d is not in the wanted network namespace", ps->pid);
821
+ if (fstat(fd, &statbuf) == -1) {
822
+ close(fd);
823
+ local_sockets_log(ls, "failed to get file statistics for '%s'", filename);
824
return false;
825
}
826
820
- int fd = open(filename, O_RDONLY);
821
- if(!fd) {
822
- local_sockets_log(ls, "cannot open file '%s'", filename);
827
+ if (statbuf.st_ino != ps->net_ns_inode) {
828
+ close(fd);
829
+ local_sockets_log(ls, "pid %d is not in the wanted network namespace", ps->pid);
830
return false;
831
}
832