From ab74a9ba3aa9b5a50a3eb789930e185f4133450e Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Wed, 20 Nov 2019 08:31:00 +0100 Subject: [PATCH] add open_pid_fd, open_lxc_pid, open_ppid helpers Getting a pid and acting on it is always a race, so add safer helpers for this. Signed-off-by: Wolfgang Bumiller --- src/PVE/LXC.pm | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/PVE/LXC.pm b/src/PVE/LXC.pm index d747039..e5b765a 100644 --- a/src/PVE/LXC.pm +++ b/src/PVE/LXC.pm @@ -388,6 +388,44 @@ sub find_lxc_pid { return $pid; } +sub open_pid_fd($) { + my ($pid) = @_; + sysopen(my $fd, "/proc/$pid", O_RDONLY | O_DIRECTORY) + or die "failed to open /proc/$pid pid fd\n"; + return $fd; +} + +sub open_lxc_pid { + my ($vmid) = @_; + + # Find the pid and open: + my $pid = find_lxc_pid($vmid); + my $fd = open_pid_fd($pid); + + # Verify: + my $pid2 = find_lxc_pid($vmid); + + return () if $pid != $pid2; + return ($pid, $fd); +} + +sub open_ppid { + my ($pid) = @_; + + # Find the parent pid via proc and open it: + my $stat = PVE::ProcFSTools::read_proc_pid_stat($pid); + my $ppid = $stat->{ppid} // die "failed to get parent pid\n"; + + my $fd = open_pid_fd($ppid); + + # Verify: + $stat = PVE::ProcFSTools::read_proc_pid_stat($pid); + my $ppid2 = $stat->{ppid} // die "failed to get parent pid for verification\n"; + + return () if $ppid != $ppid2; + return ($ppid, $fd); +} + # Note: we cannot use Net:IP, because that only allows strict # CIDR networks sub parse_ipv4_cidr { -- 2.39.2