]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC.pm
mountpoint mount: activate PVE-managed volumes during preparation
[pve-container.git] / src / PVE / LXC.pm
1 package PVE::LXC;
2
3 use strict;
4 use warnings;
5
6 use Cwd qw();
7 use Errno qw(ELOOP ENOENT ENOTDIR EROFS ECONNREFUSED EEXIST);
8 use Fcntl qw(O_RDONLY O_WRONLY O_NOFOLLOW O_DIRECTORY :mode);
9 use File::Path;
10 use File::Spec;
11 use IO::Poll qw(POLLIN POLLHUP);
12 use IO::Socket::UNIX;
13 use POSIX qw(EINTR);
14 use Socket;
15 use Time::HiRes qw (gettimeofday);
16
17 use PVE::AccessControl;
18 use PVE::CGroup;
19 use PVE::CpuSet;
20 use PVE::Exception qw(raise_perm_exc);
21 use PVE::GuestHelpers qw(check_vnet_access safe_string_ne safe_num_ne safe_boolean_ne);
22 use PVE::INotify;
23 use PVE::JSONSchema qw(get_standard_option);
24 use PVE::Network;
25 use PVE::ProcFSTools;
26 use PVE::RESTEnvironment;
27 use PVE::SafeSyslog;
28 use PVE::Storage;
29 use PVE::Tools qw(
30 run_command
31 dir_glob_foreach
32 file_get_contents
33 file_set_contents
34 AT_FDCWD
35 O_PATH
36 $IPV4RE
37 $IPV6RE
38 );
39 use PVE::Syscall qw(:fsmount);
40
41 use PVE::LXC::CGroup;
42 use PVE::LXC::Config;
43 use PVE::LXC::Monitor;
44 use PVE::LXC::Tools;
45
46 my $have_sdn;
47 eval {
48 require PVE::Network::SDN::Zones;
49 require PVE::Network::SDN::Vnets;
50 $have_sdn = 1;
51 };
52
53 my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
54
55 my $nodename = PVE::INotify::nodename();
56
57 my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
58
59 our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
60
61 sub config_list {
62 my $vmlist = PVE::Cluster::get_vmlist();
63 my $res = {};
64 return $res if !$vmlist || !$vmlist->{ids};
65 my $ids = $vmlist->{ids};
66
67 foreach my $vmid (keys %$ids) {
68 next if !$vmid; # skip CT0
69 my $d = $ids->{$vmid};
70 next if !$d->{node} || $d->{node} ne $nodename;
71 next if !$d->{type} || $d->{type} ne 'lxc';
72 $res->{$vmid} = { type => 'lxc', vmid => int($vmid) };
73 }
74 return $res;
75 }
76
77 # container status helpers
78
79 sub list_active_containers {
80
81 my $filename = "/proc/net/unix";
82
83 # similar test is used by lcxcontainers.c: list_active_containers
84 my $res = {};
85
86 my $fh = IO::File->new ($filename, "r");
87 return $res if !$fh;
88
89 while (defined(my $line = <$fh>)) {
90 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
91 my $path = $1;
92 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
93 $res->{$1} = 1;
94 }
95 }
96 }
97
98 close($fh);
99
100 return $res;
101 }
102
103 # warning: this is slow
104 sub check_running {
105 my ($vmid) = @_;
106
107 my $active_hash = list_active_containers();
108
109 return 1 if defined($active_hash->{$vmid});
110
111 return undef;
112 }
113
114 sub get_container_disk_usage {
115 my ($vmid, $pid) = @_;
116
117 return PVE::Tools::df("/proc/$pid/root/", 1);
118 }
119
120 my $last_proc_vmid_stat;
121
122 our $vmstatus_return_properties = {
123 vmid => get_standard_option('pve-vmid'),
124 status => {
125 description => "LXC Container status.",
126 type => 'string',
127 enum => ['stopped', 'running'],
128 },
129 maxmem => {
130 description => "Maximum memory in bytes.",
131 type => 'integer',
132 optional => 1,
133 renderer => 'bytes',
134 },
135 maxswap => {
136 description => "Maximum SWAP memory in bytes.",
137 type => 'integer',
138 optional => 1,
139 renderer => 'bytes',
140 },
141 maxdisk => {
142 description => "Root disk size in bytes.",
143 type => 'integer',
144 optional => 1,
145 renderer => 'bytes',
146 },
147 name => {
148 description => "Container name.",
149 type => 'string',
150 optional => 1,
151 },
152 uptime => {
153 description => "Uptime.",
154 type => 'integer',
155 optional => 1,
156 renderer => 'duration',
157 },
158 cpus => {
159 description => "Maximum usable CPUs.",
160 type => 'number',
161 optional => 1,
162 },
163 lock => {
164 description => "The current config lock, if any.",
165 type => 'string',
166 optional => 1,
167 },
168 tags => {
169 description => "The current configured tags, if any.",
170 type => 'string',
171 optional => 1,
172 }
173 };
174
175 sub vmstatus {
176 my ($opt_vmid) = @_;
177
178 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc', vmid => int($opt_vmid) }} : config_list();
179
180 my $active_hash = list_active_containers();
181
182 my $cpucount = $cpuinfo->{cpus} || 1;
183
184 my $cdtime = gettimeofday;
185
186 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
187 my $clock_ticks = POSIX::sysconf(&POSIX::_SC_CLK_TCK);
188
189 my $unprivileged = {};
190
191 foreach my $vmid (keys %$list) {
192 my $d = $list->{$vmid};
193
194 eval { $d->{pid} = int(find_lxc_pid($vmid)) if defined($active_hash->{$vmid}); };
195 warn $@ if $@; # ignore errors (consider them stopped)
196
197 $d->{status} = $active_hash->{$vmid} ? 'running' : 'stopped';
198
199 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
200 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
201
202 $unprivileged->{$vmid} = $conf->{unprivileged};
203
204 $d->{name} = $conf->{'hostname'} || "CT$vmid";
205 $d->{name} =~ s/[\s]//g;
206
207 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
208 $d->{cpus} = $cpucount if !$d->{cpus};
209
210 $d->{tags} = $conf->{tags} if defined($conf->{tags});
211
212 if ($d->{pid}) {
213 my $res = get_container_disk_usage($vmid, $d->{pid});
214 $d->{disk} = int($res->{used});
215 $d->{maxdisk} = int($res->{total});
216 } else {
217 $d->{disk} = 0;
218 # use 4GB by default ??
219 if (my $rootfs = $conf->{rootfs}) {
220 my $rootinfo = PVE::LXC::Config->parse_volume('rootfs', $rootfs);
221 $d->{maxdisk} = $rootinfo->{size} || (4*1024*1024*1024);
222 } else {
223 $d->{maxdisk} = 4*1024*1024*1024;
224 }
225 }
226
227 $d->{mem} = 0;
228 $d->{swap} = 0;
229 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
230 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
231
232 $d->{uptime} = 0;
233 $d->{cpu} = 0;
234
235 $d->{netout} = 0;
236 $d->{netin} = 0;
237
238 $d->{diskread} = 0;
239 $d->{diskwrite} = 0;
240
241 $d->{template} = 1 if PVE::LXC::Config->is_template($conf);
242 $d->{lock} = $conf->{lock} if $conf->{lock};
243 }
244
245 foreach my $vmid (keys %$list) {
246 my $d = $list->{$vmid};
247 my $pid = $d->{pid};
248
249 next if !$pid; # skip stopped CTs
250
251 my $proc_pid_stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
252 $d->{uptime} = int(($uptime - $proc_pid_stat->{starttime}) / $clock_ticks); # the method lxcfs uses
253
254 my $unpriv = $unprivileged->{$vmid};
255
256 my $cgroups = PVE::LXC::CGroup->new($vmid);
257
258 if (defined(my $mem = $cgroups->get_memory_stat())) {
259 $d->{mem} = int($mem->{mem});
260 $d->{swap} = int($mem->{swap});
261 } else {
262 $d->{mem} = 0;
263 $d->{swap} = 0;
264 }
265
266 if (defined(my $blkio = $cgroups->get_io_stats())) {
267 $d->{diskread} = int($blkio->{diskread});
268 $d->{diskwrite} = int($blkio->{diskwrite});
269 } else {
270 $d->{diskread} = 0;
271 $d->{diskwrite} = 0;
272 }
273
274 if (defined(my $cpu = $cgroups->get_cpu_stat())) {
275 # Total time (in milliseconds) used up by the cpu.
276 my $used_ms = $cpu->{utime} + $cpu->{stime};
277
278 my $old = $last_proc_vmid_stat->{$vmid};
279 if (!$old) {
280 $last_proc_vmid_stat->{$vmid} = {
281 time => $cdtime,
282 used => $used_ms,
283 cpu => 0,
284 };
285 next;
286 }
287
288 my $delta_ms = ($cdtime - $old->{time}) * $cpucount * 1000.0;
289 if ($delta_ms > 1000.0) {
290 my $delta_used_ms = $used_ms - $old->{used};
291 $d->{cpu} = (($delta_used_ms / $delta_ms) * $cpucount) / $d->{cpus};
292 $last_proc_vmid_stat->{$vmid} = {
293 time => $cdtime,
294 used => $used_ms,
295 cpu => $d->{cpu},
296 };
297 } else {
298 $d->{cpu} = $old->{cpu};
299 }
300 } else {
301 $d->{cpu} = 0;
302 }
303 }
304
305 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
306
307 foreach my $dev (keys %$netdev) {
308 next if $dev !~ m/^veth([1-9]\d*)i/;
309 my $vmid = $1;
310 my $d = $list->{$vmid};
311
312 next if !$d;
313
314 $d->{netout} += $netdev->{$dev}->{receive};
315 $d->{netin} += $netdev->{$dev}->{transmit};
316
317 }
318
319 return $list;
320 }
321
322 sub find_lxc_console_pids {
323
324 my $res = {};
325
326 PVE::Tools::dir_glob_foreach('/proc', '\d+', sub {
327 my ($pid) = @_;
328
329 my $cmdline = PVE::Tools::file_read_firstline("/proc/$pid/cmdline");
330 return if !$cmdline;
331
332 my @args = split(/\0/, $cmdline);
333
334 # search for lxc-console -n <vmid>
335 return if scalar(@args) != 3;
336 return if $args[1] ne '-n';
337 return if $args[2] !~ m/^\d+$/;
338 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
339
340 my $vmid = $args[2];
341
342 push @{$res->{$vmid}}, $pid;
343 });
344
345 return $res;
346 }
347
348 sub find_lxc_pid {
349 my ($vmid) = @_;
350
351 my $pid = undef;
352 my $parser = sub {
353 my $line = shift;
354 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
355 };
356 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
357
358 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
359
360 return $pid;
361 }
362
363 sub open_pid_fd($) {
364 my ($pid) = @_;
365 sysopen(my $fd, "/proc/$pid", O_RDONLY | O_DIRECTORY)
366 or die "failed to open /proc/$pid pid fd\n";
367 return $fd;
368 }
369
370 sub open_lxc_pid {
371 my ($vmid) = @_;
372
373 # Find the pid and open:
374 my $pid = find_lxc_pid($vmid);
375 my $fd = open_pid_fd($pid);
376
377 # Verify:
378 my $pid2 = find_lxc_pid($vmid);
379
380 return () if $pid != $pid2;
381 return ($pid, $fd);
382 }
383
384 sub open_ppid {
385 my ($pid) = @_;
386
387 # Find the parent pid via proc and open it:
388 my $stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
389 my $ppid = $stat->{ppid} // die "failed to get parent pid\n";
390
391 my $fd = open_pid_fd($ppid);
392
393 # Verify:
394 $stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
395 my $ppid2 = $stat->{ppid} // die "failed to get parent pid for verification\n";
396
397 return () if $ppid != $ppid2;
398 return ($ppid, $fd);
399 }
400
401 # Note: we cannot use Net:IP, because that only allows strict
402 # CIDR networks
403 sub parse_ipv4_cidr {
404 my ($cidr, $noerr) = @_;
405
406 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
407 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
408 }
409
410 return undef if $noerr;
411
412 die "unable to parse ipv4 address/mask\n";
413 }
414
415 # With seccomp trap to userspace we now have the ability to optionally forward
416 # certain syscalls to the "host" to handle (via our pve-lxc-syscalld daemon).
417 #
418 # This means that there are cases where we need to create an extra seccomp
419 # profile for the container to load.
420 #
421 # This returns a configuration snippet added to the raw lxc config.
422 sub make_seccomp_config {
423 my ($conf, $vmid, $conf_dir, $unprivileged, $features) = @_;
424 # User-configured profile has precedence, note that the user's entry would
425 # be written 'after' this line anyway...
426 if (PVE::LXC::Config->has_lxc_entry($conf, 'lxc.seccomp.profile')) {
427 # Warn the user if this conflicts with a feature:
428 my $warn = join(', ', grep { $features->{$_} } qw(keyctl mknod));
429 warn "explicitly configured lxc.seccomp.profile overrides the following settings: $warn\n"
430 if length($warn) > 0;
431 return '';
432 }
433
434 # Privileged containers keep using the default (which is already part of
435 # the files included via lxc.include, so we don't need to write it out,
436 # that way it stays admin-configurable via /usr/share/lxc/config/... as
437 # well)
438 return '' if !$unprivileged;
439
440 my $rules = {
441 keyctl => ['errno 38'],
442
443 # Disable btrfs ioctrls since they don't work particularly well in user namespaces.
444 # Particularly, without the mount option to enable rmdir removing snapshots, user
445 # namespaces can create snapshots but neither `show` or `delete` them, which is quite
446 # horrible, so for now, just disable this entirely:
447 #
448 # BTRFS_IOCTL_MAGIC 0x94, _IOC type shift is 8,
449 # so `(req & 0xFF00) == 0x9400` is a btrfs ioctl and gets an EPERM
450 ioctl => ['errno 1 [1,0x9400,SCMP_CMP_MASKED_EQ,0xff00]'],
451 };
452
453 my $raw_conf = '';
454
455 # Unprivileged containers will get keyctl() disabled by default as a
456 # workaround for systemd-networkd behavior. But we have an option to
457 # explicitly enable it:
458 if ($features->{keyctl}) {
459 delete $rules->{keyctl};
460 }
461
462 # By default, unprivileged containers cannot use `mknod` at all.
463 # Since lxc 3.2, we can use seccomp's trap to userspace feature for this,
464 # but for now this is experimental, so it has to be enabled via a feature
465 # flag.
466 # Note that we only handle block and char devices (like lxd), the rest we
467 # leave up to the kernel. We may in the future remove this if seccomp gets
468 # a way to tell the kernel to "continue" a syscall.
469 if ($features->{mknod}) {
470 my ($ok, $kernel) = PVE::ProcFSTools::check_kernel_release(5, 3);
471 if (!$ok) {
472 die "'mknod' feature requested, but kernel too old (found $kernel, required >= 5.3)\n";
473 }
474
475 $raw_conf .= "lxc.seccomp.notify.proxy = unix:/run/pve/lxc-syscalld.sock\n";
476 $raw_conf .= "lxc.seccomp.notify.cookie = $vmid\n";
477
478 $rules->{mknod} = [
479 # condition: (mode & S_IFMT) == S_IFCHR
480 'notify [1,8192,SCMP_CMP_MASKED_EQ,61440]',
481 # condition: (mode & S_IFMT) == S_IFBLK
482 'notify [1,24576,SCMP_CMP_MASKED_EQ,61440]',
483 ];
484 $rules->{mknodat} = [
485 # condition: (mode & S_IFMT) == S_IFCHR
486 'notify [2,8192,SCMP_CMP_MASKED_EQ,61440]',
487 # condition: (mode & S_IFMT) == S_IFBLK
488 'notify [2,24576,SCMP_CMP_MASKED_EQ,61440]',
489 ];
490 }
491
492 # Now build the custom seccomp rule text...
493 my $extra_rules = join("\n", map {
494 my $syscall = $_;
495 map { "$syscall $_" } $rules->{$syscall}->@*
496 } sort keys %$rules) . "\n";
497
498 return $raw_conf if $extra_rules eq "\n";
499
500 # We still have the "most common" config readily available, so don't write
501 # out that one:
502 if ($raw_conf eq '' && $extra_rules eq "keyctl errno 38\n") {
503 # we have no extra $raw_conf and use the same we had in pve 6.1:
504 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
505 }
506
507 # Write the rule file to the container's config path:
508 my $rule_file = "$conf_dir/rules.seccomp";
509 my $rule_data = file_get_contents("$LXC_CONFIG_PATH/common.seccomp")
510 . $extra_rules;
511 file_set_contents($rule_file, $rule_data);
512 $raw_conf .= "lxc.seccomp.profile = $rule_file\n";
513
514 return $raw_conf;
515 }
516
517 # Since lxc-3.0.2 we can have lxc generate a profile for the container
518 # automatically. The default should be equivalent to the old
519 # `lxc-container-default-cgns` profile.
520 #
521 # Additionally this also added `lxc.apparmor.raw` which can be used to inject
522 # additional lines into the profile. We can use that to allow mounting specific
523 # file systems.
524 sub make_apparmor_config {
525 my ($conf, $unprivileged, $features) = @_;
526
527 # user-configured profile has precedence, but first we go through our own
528 # code to figure out whether we should warn the user:
529
530 my $raw = "lxc.apparmor.profile = generated\n";
531 my @profile_uses;
532
533 if ($features->{fuse}) {
534 # For the informational warning:
535 push @profile_uses, 'features:fuse';
536 }
537
538 # There's lxc.apparmor.allow_nesting now, which will add the necessary
539 # apparmor lines, create an apparmor namespace for the container, but also
540 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
541 # lxcfs mounted over them, because that would prevent the container from
542 # mounting new instances of them for nested containers.
543 if ($features->{nesting}) {
544 push @profile_uses, 'features:nesting';
545 $raw .= "lxc.apparmor.allow_nesting = 1\n"
546 } else {
547 # In the default profile in /etc/apparmor.d we patch this in because
548 # otherwise a container can for example run `chown` on /sys, breaking
549 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
550 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
551 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
552 # Preferably we could use the 'remount' flag but this does not sit well
553 # with apparmor_parser currently:
554 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
555 }
556
557 if (my $mount = $features->{mount}) {
558 push @profile_uses, 'features:mount';
559 foreach my $fs (PVE::Tools::split_list($mount)) {
560 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
561 }
562 }
563
564 # More to come?
565
566 if (PVE::LXC::Config->has_lxc_entry($conf, 'lxc.apparmor.profile')) {
567 if (length(my $used = join(', ', @profile_uses))) {
568 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
569 }
570 return '';
571 }
572
573 return $raw;
574 }
575
576 sub update_lxc_config {
577 my ($vmid, $conf) = @_;
578
579 my $dir = "/var/lib/lxc/$vmid";
580
581 if ($conf->{template}) {
582
583 unlink "$dir/config";
584
585 return;
586 }
587
588 my ($lxc_major, $lxc_minor) = get_lxc_version();
589
590 my $raw = '';
591
592 if ($lxc_major >= 4) {
593 # Explicitly don't use relative directories, which is the default, but
594 # note that we do this mostly because they are only applied for *some*
595 # cgroups. Our pve-container@.service now starts lxc-start with `-F`,
596 # so we also don't need to worry about the new monitor cgroup to
597 # confuse systemd.
598 $raw .= "lxc.cgroup.relative = 0\n";
599
600 # To make things easier, let's keep our previous cgroup layout and
601 # simply move the monitor outside:
602 $raw .= "lxc.cgroup.dir.monitor = lxc.monitor/$vmid\n";
603 # cgroup namespace separation for stronger limits:
604 $raw .= "lxc.cgroup.dir.container = lxc/$vmid\n";
605 $raw .= "lxc.cgroup.dir.container.inner = ns\n";
606 }
607
608 die "missing 'arch' - internal error" if !$conf->{arch};
609 $raw .= "lxc.arch = $conf->{arch}\n";
610
611 my $custom_idmap = PVE::LXC::Config->has_lxc_entry($conf, 'lxc.idmap');
612 my $unprivileged = $conf->{unprivileged} || $custom_idmap;
613
614 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
615
616 File::Path::mkpath($dir);
617
618 my $cfgpath = '/usr/share/lxc/config';
619 my $inc = "$cfgpath/$ostype.common.conf";
620 $inc ="$cfgpath/common.conf" if !-f $inc;
621 $raw .= "lxc.include = $inc\n";
622 if ($unprivileged) {
623 $inc = "$cfgpath/$ostype.userns.conf";
624 $inc = "$cfgpath/userns.conf" if !-f $inc;
625 $raw .= "lxc.include = $inc\n";
626 }
627
628 my $features = PVE::LXC::Config->parse_features($conf->{features});
629
630 $raw .= make_seccomp_config($conf, $vmid, $dir, $unprivileged, $features);
631 $raw .= make_apparmor_config($conf, $unprivileged, $features);
632 if ($features->{fuse}) {
633 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
634 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
635 }
636
637 if ($unprivileged && !$features->{force_rw_sys}) {
638 # unpriv. CT default to sys:rw, but that doesn't always plays well with
639 # systemd, e.g., systemd-networkd https://systemd.io/CONTAINER_INTERFACE/
640 $raw .= "lxc.mount.auto = sys:mixed\n";
641 }
642
643 PVE::LXC::Config->foreach_passthrough_device($conf, sub {
644 my ($key, $device) = @_;
645
646 die "Path is not defined for passthrough device $key"
647 unless (defined($device->{path}));
648
649 my $absolute_path = $device->{path};
650 my ($mode, $rdev) = (stat($absolute_path))[2, 6];
651
652 die "Device $absolute_path does not exist\n" if $! == ENOENT;
653
654 die "Error accessing device $absolute_path\n"
655 if (!defined($mode) || !defined($rdev));
656
657 die "$absolute_path is not a device\n"
658 if (!S_ISBLK($mode) && !S_ISCHR($mode));
659
660 my $major = PVE::Tools::dev_t_major($rdev);
661 my $minor = PVE::Tools::dev_t_minor($rdev);
662 my $device_type_char = S_ISBLK($mode) ? 'b' : 'c';
663 $raw .= "lxc.cgroup2.devices.allow = $device_type_char $major:$minor rw\n";
664 });
665
666 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
667 # cannot be exposed to the container with r/w access (cgroup perms).
668 # When this is enabled mounts will still remain in the monitor's namespace
669 # after the container unmounted them and thus will not detach from their
670 # files while the container is running!
671 $raw .= "lxc.monitor.unshare = 1\n";
672
673 my ($cgv1, $cgv2) = PVE::CGroup::get_cgroup_controllers();
674
675 # Should we read them from /etc/subuid?
676 if ($unprivileged && !$custom_idmap) {
677 $raw .= "lxc.idmap = u 0 100000 65536\n";
678 $raw .= "lxc.idmap = g 0 100000 65536\n";
679 }
680
681 if (!PVE::LXC::Config->has_dev_console($conf)) {
682 $raw .= "lxc.console.path = none\n";
683 if ($cgv1->{devices}) {
684 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
685 } elsif (defined($cgv2)) {
686 $raw .= "lxc.cgroup2.devices.deny = c 5:1 rwm\n";
687 }
688 }
689
690 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
691 $raw .= "lxc.tty.max = $ttycount\n";
692
693 # some init scripts expect a linux terminal (turnkey).
694 $raw .= "lxc.environment = TERM=linux\n";
695
696 my $utsname = $conf->{hostname} || "CT$vmid";
697 $raw .= "lxc.uts.name = $utsname\n";
698
699 if ($cgv1->{memory}) {
700 my $memory = $conf->{memory} || 512;
701 my $swap = $conf->{swap} // 0;
702
703 my $lxcmem = int($memory*1024*1024);
704 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
705
706 my $lxcswap = int(($memory + $swap)*1024*1024);
707 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
708 } elsif ($cgv2->{memory}) {
709 my $memory = $conf->{memory} || 512;
710 my $swap = $conf->{swap} // 0;
711
712 # cgroup memory usage is limited by the hard 'max' limit (OOM-killer enforced) and the soft
713 # 'high' limit (cgroup processes get throttled and put under heavy reclaim pressure).
714 my ($lxc_mem_max, $lxc_mem_high) = PVE::LXC::Config::calculate_memory_constraints($memory);
715 $raw .= "lxc.cgroup2.memory.max = $lxc_mem_max\n";
716 $raw .= "lxc.cgroup2.memory.high = $lxc_mem_high\n";
717
718 my $lxcswap = int($swap*1024*1024);
719 $raw .= "lxc.cgroup2.memory.swap.max = $lxcswap\n";
720 }
721
722 if ($cgv1->{cpu}) {
723 if (my $cpulimit = $conf->{cpulimit}) {
724 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
725 my $value = int(100000*$cpulimit);
726 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
727 }
728
729 my $shares = PVE::CGroup::clamp_cpu_shares($conf->{cpuunits});
730 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
731 } elsif ($cgv2->{cpu}) {
732 # See PVE::CGroup
733 if (my $cpulimit = $conf->{cpulimit}) {
734 my $value = int(100000*$cpulimit);
735 $raw .= "lxc.cgroup2.cpu.max = $value 100000\n";
736 }
737
738 if (defined(my $shares = $conf->{cpuunits})) {
739 $shares = PVE::CGroup::clamp_cpu_shares($shares);
740 $raw .= "lxc.cgroup2.cpu.weight = $shares\n";
741 }
742 }
743
744 die "missing 'rootfs' configuration\n"
745 if !defined($conf->{rootfs});
746
747 my $mountpoint = PVE::LXC::Config->parse_volume('rootfs', $conf->{rootfs});
748
749 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
750
751 foreach my $k (sort keys %$conf) {
752 next if $k !~ m/^net(\d+)$/;
753 my $ind = $1;
754 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
755 $raw .= "lxc.net.$ind.type = veth\n";
756 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
757 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
758 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name});
759
760 my $bridge_mtu = PVE::Network::read_bridge_mtu($d->{bridge});
761 my $mtu = $d->{mtu} || $bridge_mtu;
762
763 # Keep container from starting with invalid mtu configuration
764 die "$k: MTU size '$mtu' is bigger than bridge MTU '$bridge_mtu'\n"
765 if ($mtu > $bridge_mtu);
766
767 $raw .= "lxc.net.$ind.mtu = $mtu\n";
768
769 # Starting with lxc 4.0, we do not patch lxc to execute our up-scripts.
770 if ($lxc_major >= 4) {
771 $raw .= "lxc.net.$ind.script.up = /usr/share/lxc/lxcnetaddbr\n";
772 }
773 }
774
775 my $had_cpuset = 0;
776 if (my $lxcconf = $conf->{lxc}) {
777 foreach my $entry (@$lxcconf) {
778 my ($k, $v) = @$entry;
779 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus' || $k eq 'lxc.cgroup2.cpuset.cpus';
780 $raw .= "$k = $v\n";
781 }
782 }
783
784 my $cpuset;
785 my ($cpuset_cgroup, $cpuset_version) = eval { PVE::CGroup::cpuset_controller_path() };
786 if (defined($cpuset_cgroup)) {
787 $cpuset = eval { PVE::CpuSet->new_from_path("$cpuset_cgroup/lxc", 1) }
788 || PVE::CpuSet->new_from_path($cpuset_cgroup, 1);
789 }
790 my $cores = $conf->{cores};
791 if (!$had_cpuset && $cores && $cpuset) {
792 my @members = $cpuset->members();
793 while (scalar(@members) > $cores) {
794 my $randidx = int(rand(scalar(@members)));
795 $cpuset->delete($members[$randidx]);
796 splice(@members, $randidx, 1); # keep track of the changes
797 }
798 my $ver = $cpuset_version == 1 ? '' : '2';
799 $raw .= "lxc.cgroup$ver.cpuset.cpus = ".$cpuset->short_string()."\n";
800 }
801
802 File::Path::mkpath("$dir/rootfs");
803
804 PVE::Tools::file_set_contents("$dir/config", $raw);
805 }
806
807 # verify and cleanup nameserver list (replace \0 with ' ')
808 sub verify_nameserver_list {
809 my ($nameserver_list) = @_;
810
811 my @list = ();
812 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
813 PVE::LXC::Config::verify_ip_with_ll_iface($server);
814 push @list, $server;
815 }
816
817 return join(' ', @list);
818 }
819
820 sub verify_searchdomain_list {
821 my ($searchdomain_list) = @_;
822
823 my @list = ();
824 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
825 # todo: should we add checks for valid dns domains?
826 push @list, $server;
827 }
828
829 return join(' ', @list);
830 }
831
832 sub get_console_command {
833 my ($vmid, $conf, $escapechar) = @_;
834
835 # '-1' as $escapechar disables keyboard escape sequence
836 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
837
838 my $cmode = PVE::LXC::Config->get_cmode($conf);
839
840 my $cmd = [];
841 if ($cmode eq 'console') {
842 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
843 push @$cmd, '-e', $escapechar if $escapechar;
844 } elsif ($cmode eq 'tty') {
845 push @$cmd, 'lxc-console', '-n', $vmid;
846 push @$cmd, '-e', $escapechar if $escapechar;
847 } elsif ($cmode eq 'shell') {
848 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
849 } else {
850 die "internal error";
851 }
852
853 return $cmd;
854 }
855
856 sub get_primary_ips {
857 my ($conf) = @_;
858
859 # return data from net0
860
861 return undef if !defined($conf->{net0});
862 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
863
864 my $ipv4 = $net->{ip};
865 if ($ipv4) {
866 if ($ipv4 =~ /^(dhcp|manual)$/) {
867 $ipv4 = undef
868 } else {
869 $ipv4 =~ s!/\d+$!!;
870 }
871 }
872 my $ipv6 = $net->{ip6};
873 if ($ipv6) {
874 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
875 $ipv6 = undef;
876 } else {
877 $ipv6 =~ s!/\d+$!!;
878 }
879 }
880
881 return ($ipv4, $ipv6);
882 }
883
884 sub delete_mountpoint_volume {
885 my ($storage_cfg, $vmid, $volume) = @_;
886
887 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
888
889 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
890
891 if ($vmid == $owner) {
892 PVE::Storage::vdisk_free($storage_cfg, $volume);
893 } else {
894 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
895 }
896 }
897
898 sub destroy_lxc_container {
899 my ($storage_cfg, $vmid, $conf, $replacement_conf, $purge_unreferenced) = @_;
900
901 my $volids = {};
902 my $remove_volume = sub {
903 my ($ms, $mountpoint) = @_;
904
905 my $volume = $mountpoint->{volume};
906
907 return if $volids->{$volume};
908 $volids->{$volume} = 1;
909
910 delete_mountpoint_volume($storage_cfg, $vmid, $volume);
911 };
912 PVE::LXC::Config->foreach_volume_full($conf, {include_unused => 1}, $remove_volume);
913
914 PVE::LXC::Config->foreach_volume_full($conf->{pending}, {include_unused => 1}, $remove_volume);
915
916 if ($purge_unreferenced) { # also remove unreferenced disk
917 my $vmdisks = PVE::Storage::vdisk_list($storage_cfg, undef, $vmid, undef, 'rootdir');
918 PVE::Storage::foreach_volid($vmdisks, sub {
919 my ($volid, $sid, $volname, $d) = @_;
920 eval { PVE::Storage::vdisk_free($storage_cfg, $volid) };
921 warn $@ if $@;
922 });
923 }
924
925 delete_ifaces_ipams_ips($conf, $vmid);
926
927 rmdir "/var/lib/lxc/$vmid/rootfs";
928 unlink "/var/lib/lxc/$vmid/config";
929 rmdir "/var/lib/lxc/$vmid";
930 if (defined $replacement_conf) {
931 PVE::LXC::Config->write_config($vmid, $replacement_conf);
932 } else {
933 PVE::LXC::Config->destroy_config($vmid);
934 }
935 }
936
937 sub vm_stop_cleanup {
938 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
939
940 return if $keepActive;
941
942 eval {
943 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
944 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
945 };
946 warn $@ if $@; # avoid errors - just warn
947 }
948
949 sub net_tap_plug : prototype($$) {
950 my ($iface, $net) = @_;
951
952 if (defined($net->{link_down})) {
953 PVE::Tools::run_command(['/sbin/ip', 'link', 'set', 'dev', $iface, 'down']);
954 # Don't add disconnected interfaces to the bridge, otherwise e.g. applying any network
955 # change (e.g. `ifreload -a`) could (re-)activate it unintentionally.
956 return;
957 }
958
959 my ($bridge, $tag, $firewall, $trunks, $rate, $hwaddr) =
960 $net->@{'bridge', 'tag', 'firewall', 'trunks', 'rate', 'hwaddr'};
961
962 if ($have_sdn) {
963 PVE::Network::SDN::Zones::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate);
964 PVE::Network::SDN::Zones::add_bridge_fdb($iface, $hwaddr, $bridge);
965 } else {
966 PVE::Network::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate, { mac => $hwaddr });
967 }
968
969 PVE::Tools::run_command(['/sbin/ip', 'link', 'set', 'dev', $iface, 'up']);
970 }
971
972 sub update_net {
973 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
974
975 if ($newnet->{type} ne 'veth') {
976 # for when there are physical interfaces
977 die "cannot update interface of type $newnet->{type}";
978 }
979
980 my $veth = "veth${vmid}i${netid}";
981 my $eth = $newnet->{name};
982
983 if (my $oldnetcfg = $conf->{$opt}) {
984 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
985
986 if (safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
987 safe_string_ne($oldnet->{name}, $newnet->{name})) {
988
989 PVE::Network::veth_delete($veth);
990
991 if ($have_sdn && safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr})) {
992 eval { PVE::Network::SDN::Vnets::del_ips_from_mac($oldnet->{bridge}, $oldnet->{hwaddr}, $conf->{hostname}) };
993 warn $@ if $@;
994
995 PVE::Network::SDN::Vnets::add_next_free_cidr($newnet->{bridge}, $conf->{hostname}, $newnet->{hwaddr}, $vmid, undef, 1);
996 PVE::Network::SDN::Vnets::add_dhcp_mapping($newnet->{bridge}, $newnet->{hwaddr}, $vmid, $conf->{hostname});
997 }
998
999 delete $conf->{$opt};
1000 PVE::LXC::Config->write_config($vmid, $conf);
1001
1002 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
1003
1004 } else {
1005 my $bridge_changed = safe_string_ne($oldnet->{bridge}, $newnet->{bridge});
1006
1007 if ($bridge_changed ||
1008 safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
1009 safe_num_ne($oldnet->{firewall}, $newnet->{firewall}) ||
1010 safe_boolean_ne($oldnet->{link_down}, $newnet->{link_down})
1011 ) {
1012 if ($oldnet->{bridge}) {
1013 my $oldbridge = $oldnet->{bridge};
1014
1015 PVE::Network::tap_unplug($veth);
1016 foreach (qw(bridge tag firewall)) {
1017 delete $oldnet->{$_};
1018 }
1019 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
1020 PVE::LXC::Config->write_config($vmid, $conf);
1021
1022 if ($have_sdn && $bridge_changed) {
1023 eval { PVE::Network::SDN::Vnets::del_ips_from_mac($oldbridge, $oldnet->{hwaddr}, $conf->{hostname}) };
1024 warn $@ if $@;
1025 }
1026 }
1027
1028 if ($have_sdn && $bridge_changed) {
1029 PVE::Network::SDN::Vnets::add_next_free_cidr($newnet->{bridge}, $conf->{hostname}, $newnet->{hwaddr}, $vmid, undef, 1);
1030 }
1031 PVE::LXC::net_tap_plug($veth, $newnet);
1032
1033 # This includes the rate:
1034 foreach (qw(bridge tag firewall rate link_down)) {
1035 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
1036 }
1037 } elsif (safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
1038 # Rate can be applied on its own but any change above needs to
1039 # include the rate in tap_plug since OVS resets everything.
1040 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
1041 $oldnet->{rate} = $newnet->{rate}
1042 }
1043 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
1044 PVE::LXC::Config->write_config($vmid, $conf);
1045 }
1046 } else {
1047 if ($have_sdn) {
1048 PVE::Network::SDN::Vnets::add_next_free_cidr($newnet->{bridge}, $conf->{hostname}, $newnet->{hwaddr}, $vmid, undef, 1);
1049 PVE::Network::SDN::Vnets::add_dhcp_mapping($newnet->{bridge}, $newnet->{hwaddr}, $vmid, $conf->{hostname});
1050 }
1051
1052 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
1053 }
1054
1055 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
1056 }
1057
1058 sub hotplug_net {
1059 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
1060
1061 my $veth = "veth${vmid}i${netid}";
1062 my $vethpeer = $veth . "p";
1063 my $eth = $newnet->{name};
1064
1065 if ($have_sdn) {
1066 PVE::Network::SDN::Zones::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
1067 } else {
1068 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
1069 }
1070
1071 PVE::LXC::net_tap_plug($veth, $newnet);
1072
1073 # attach peer in container
1074 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
1075 PVE::Tools::run_command($cmd);
1076
1077 # link up peer in container
1078 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
1079 PVE::Tools::run_command($cmd);
1080
1081 my $done = { type => 'veth' };
1082 foreach (qw(bridge tag firewall hwaddr name link_down)) {
1083 $done->{$_} = $newnet->{$_} if $newnet->{$_};
1084 }
1085 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
1086
1087 PVE::LXC::Config->write_config($vmid, $conf);
1088 }
1089
1090 sub get_interfaces {
1091 my ($vmid) = @_;
1092
1093 my $pid = eval { find_lxc_pid($vmid); };
1094 return if $@;
1095
1096 my $output;
1097 # enters the network namespace of the container and executes 'ip a'
1098 run_command(['nsenter', '-t', $pid, '--net', '--', 'ip', '--json', 'a'],
1099 outfunc => sub { $output .= shift; });
1100
1101 my $config = JSON::decode_json($output);
1102
1103 my $res;
1104 for my $interface ($config->@*) {
1105 my $obj = { name => $interface->{ifname} };
1106 for my $ip ($interface->{addr_info}->@*) {
1107 $obj->{$ip->{family}} = $ip->{local} . "/" . $ip->{prefixlen};
1108 }
1109 $obj->{hwaddr} = $interface->{address};
1110 push @$res, $obj
1111 }
1112
1113 return $res;
1114 }
1115
1116 sub update_ipconfig {
1117 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
1118
1119 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
1120
1121 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
1122 my $deleted = [];
1123 my $added = [];
1124 my $nscmd = sub {
1125 my $cmdargs = shift;
1126 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
1127 };
1128 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
1129
1130 my $change_ip_config = sub {
1131 my ($ipversion) = @_;
1132
1133 my $family_opt = "-$ipversion";
1134 my $suffix = $ipversion == 4 ? '' : $ipversion;
1135 my $gw= "gw$suffix";
1136 my $ip= "ip$suffix";
1137
1138 my $newip = $newnet->{$ip};
1139 my $newgw = $newnet->{$gw};
1140 my $oldip = $optdata->{$ip};
1141 my $oldgw = $optdata->{$gw};
1142
1143 my $change_ip = safe_string_ne($oldip, $newip);
1144 my $change_gw = safe_string_ne($oldgw, $newgw);
1145
1146 return if !$change_ip && !$change_gw;
1147
1148 # step 1: add new IP, if this fails we cancel
1149 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
1150 if ($change_ip && $is_real_ip) {
1151 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
1152 if (my $err = $@) {
1153 warn $err;
1154 return;
1155 }
1156 }
1157
1158 # step 2: replace gateway
1159 # If this fails we delete the added IP and cancel.
1160 # If it succeeds we save the config and delete the old IP, ignoring
1161 # errors. The config is then saved.
1162 # Note: 'ip route replace' can add
1163 if ($change_gw) {
1164 if ($newgw) {
1165 eval {
1166 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
1167 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
1168 }
1169 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
1170 };
1171 if (my $err = $@) {
1172 warn $err;
1173 # the route was not replaced, the old IP is still available
1174 # rollback (delete new IP) and cancel
1175 if ($change_ip) {
1176 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
1177 warn $@ if $@; # no need to die here
1178 }
1179 return;
1180 }
1181 } else {
1182 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
1183 # if the route was not deleted, the guest might have deleted it manually
1184 # warn and continue
1185 warn $@ if $@;
1186 }
1187 if ($oldgw && $oldip && !PVE::Network::is_ip_in_cidr($oldgw, $oldip)) {
1188 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
1189 # warn if the route was deleted manually
1190 warn $@ if $@;
1191 }
1192 }
1193
1194 # from this point on we save the configuration
1195 # step 3: delete old IP ignoring errors
1196 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
1197 # We need to enable promote_secondaries, otherwise our newly added
1198 # address will be removed along with the old one.
1199 my $promote = 0;
1200 eval {
1201 if ($ipversion == 4) {
1202 &$nscmd({ outfunc => sub { $promote = int(shift) } },
1203 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1204 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1205 }
1206 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1207 };
1208 warn $@ if $@; # no need to die here
1209
1210 if ($ipversion == 4) {
1211 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1212 }
1213 }
1214
1215 foreach my $property ($ip, $gw) {
1216 if ($newnet->{$property}) {
1217 $optdata->{$property} = $newnet->{$property};
1218 } else {
1219 delete $optdata->{$property};
1220 }
1221 }
1222 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
1223 PVE::LXC::Config->write_config($vmid, $conf);
1224 $lxc_setup->setup_network($conf);
1225 };
1226
1227 &$change_ip_config(4);
1228 &$change_ip_config(6);
1229
1230 }
1231
1232 my $open_namespace = sub {
1233 my ($vmid, $pid, $kind) = @_;
1234 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1235 or die "failed to open $kind namespace of container $vmid: $!\n";
1236 return $fd;
1237 };
1238
1239 my $enter_namespace = sub {
1240 my ($vmid, $pid, $kind, $type) = @_;
1241 my $fd = $open_namespace->($vmid, $pid, $kind);
1242 PVE::Tools::setns(fileno($fd), $type)
1243 or die "failed to enter $kind namespace of container $vmid: $!\n";
1244 close $fd;
1245 };
1246
1247 my $get_container_namespace = sub {
1248 my ($vmid, $pid, $kind) = @_;
1249
1250 my $pidfd;
1251 if (!defined($pid)) {
1252 # Pin the pid while we're grabbing its stuff from /proc
1253 ($pid, $pidfd) = open_lxc_pid($vmid)
1254 or die "failed to open pidfd of container $vmid\'s init process\n";
1255 }
1256
1257 return $open_namespace->($vmid, $pid, $kind);
1258 };
1259
1260 my $do_syncfs = sub {
1261 my ($vmid, $pid, $socket) = @_;
1262
1263 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
1264
1265 # Tell the parent process to start reading our /proc/mounts
1266 print {$socket} "go\n";
1267 $socket->flush();
1268
1269 # Receive /proc/self/mounts
1270 my $mountdata = do { local $/ = undef; <$socket> };
1271 close $socket;
1272
1273 my %nosyncfs = (
1274 cgroup => 1,
1275 cgroup2 => 1,
1276 devtmpfs => 1,
1277 devpts => 1,
1278 'fuse.lxcfs' => 1,
1279 fusectl => 1,
1280 mqueue => 1,
1281 proc => 1,
1282 sysfs => 1,
1283 tmpfs => 1,
1284 );
1285
1286 # Now sync all mountpoints...
1287 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
1288 foreach my $mp (@$mounts) {
1289 my ($what, $dir, $fs) = @$mp;
1290 next if $nosyncfs{$fs};
1291 eval { PVE::Tools::sync_mountpoint($dir); };
1292 warn $@ if $@;
1293 }
1294 };
1295
1296 sub sync_container_namespace {
1297 my ($vmid) = @_;
1298 my $pid = find_lxc_pid($vmid);
1299
1300 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1301 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
1302 or die "failed to create socketpair: $!\n";
1303
1304 my $child = fork();
1305 die "fork failed: $!\n" if !defined($child);
1306
1307 if (!$child) {
1308 eval {
1309 close $pfd;
1310 &$do_syncfs($vmid, $pid, $cfd);
1311 };
1312 if (my $err = $@) {
1313 warn $err;
1314 POSIX::_exit(1);
1315 }
1316 POSIX::_exit(0);
1317 }
1318 close $cfd;
1319 my $go = <$pfd>;
1320 die "failed to enter container namespace\n" if $go ne "go\n";
1321
1322 open my $mounts, '<', "/proc/$child/mounts"
1323 or die "failed to open container's /proc/mounts: $!\n";
1324 my $mountdata = do { local $/ = undef; <$mounts> };
1325 close $mounts;
1326 print {$pfd} $mountdata;
1327 close $pfd;
1328
1329 while (waitpid($child, 0) != $child) {}
1330 die "failed to sync container namespace\n" if $? != 0;
1331 }
1332
1333 sub template_create {
1334 my ($vmid, $conf) = @_;
1335
1336 my $storecfg = PVE::Storage::config();
1337
1338 PVE::LXC::Config->foreach_volume($conf, sub {
1339 my ($ms, $mountpoint) = @_;
1340
1341 my $volid = $mountpoint->{volume};
1342
1343 die "Template feature is not available for '$volid'\n"
1344 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
1345 });
1346
1347 PVE::LXC::Config->foreach_volume($conf, sub {
1348 my ($ms, $mountpoint) = @_;
1349
1350 my $volid = $mountpoint->{volume};
1351
1352 PVE::Storage::activate_volumes($storecfg, [$volid]);
1353
1354 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
1355 $mountpoint->{volume} = $template_volid;
1356 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1357 });
1358
1359 PVE::LXC::Config->write_config($vmid, $conf);
1360 }
1361
1362 sub check_ct_modify_config_perm {
1363 my ($rpcenv, $authuser, $vmid, $pool, $oldconf, $newconf, $delete, $unprivileged) = @_;
1364
1365 return 1 if $authuser eq 'root@pam';
1366 my $storage_cfg = PVE::Storage::config();
1367
1368 my $check = sub {
1369 my ($opt, $delete) = @_;
1370 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1371 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1372 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1373 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1374 return if $delete;
1375 my $data = PVE::LXC::Config->parse_volume($opt, $newconf->{$opt});
1376 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
1377 if $data->{type} ne 'volume';
1378 my $volid = $data->{volume};
1379 if ($volid =~ $NEW_DISK_RE) {
1380 my $sid = $1;
1381 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
1382 } else {
1383 PVE::Storage::check_volume_access(
1384 $rpcenv,
1385 $authuser,
1386 $storage_cfg,
1387 $vmid,
1388 $volid,
1389 'rootdir',
1390 );
1391 }
1392 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1393 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1394 } elsif ($opt =~ m/^net\d+$/) {
1395 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1396 check_bridge_access($rpcenv, $authuser, $oldconf->{$opt}) if $oldconf->{$opt};
1397 check_bridge_access($rpcenv, $authuser, $newconf->{$opt}) if $newconf->{$opt};
1398 } elsif ($opt =~ m/^dev\d+$/) {
1399 raise_perm_exc("configuring device passthrough is only allowed for root\@pam");
1400 } elsif ($opt eq 'nameserver' || $opt eq 'searchdomain' || $opt eq 'hostname') {
1401 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1402 } elsif ($opt eq 'features') {
1403 raise_perm_exc("changing feature flags for privileged container is only allowed for root\@pam")
1404 if !$unprivileged;
1405
1406 my $nesting_changed = 0;
1407 my $other_changed = 0;
1408 if (!$delete) {
1409 my $features = PVE::LXC::Config->parse_features($newconf->{$opt});
1410 if (defined($oldconf) && $oldconf->{$opt}) {
1411 # existing container with features
1412 my $old_features = PVE::LXC::Config->parse_features($oldconf->{$opt});
1413 for my $feature ((keys %$old_features, keys %$features)) {
1414 my $old = $old_features->{$feature} // '';
1415 my $new = $features->{$feature} // '';
1416 if ($old ne $new) {
1417 if ($feature eq 'nesting') {
1418 $nesting_changed = 1;
1419 next;
1420 } else {
1421 $other_changed = 1;
1422 last;
1423 }
1424 }
1425 }
1426 } else {
1427 # new container or no features defined
1428 if (scalar(keys %$features) == 1 && $features->{nesting}) {
1429 $nesting_changed = 1;
1430 } elsif (scalar(keys %$features) > 0) {
1431 $other_changed = 1;
1432 }
1433 }
1434 } else {
1435 my $features = PVE::LXC::Config->parse_features($oldconf->{$opt});
1436 if (scalar(keys %$features) == 1 && $features->{nesting}) {
1437 $nesting_changed = 1;
1438 } elsif (scalar(keys %$features) > 0) {
1439 $other_changed = 1;
1440 }
1441 }
1442 raise_perm_exc("changing feature flags (except nesting) is only allowed for root\@pam")
1443 if $other_changed;
1444 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Allocate'])
1445 if $nesting_changed;
1446 } elsif ($opt eq 'hookscript') {
1447 # For now this is restricted to root@pam
1448 raise_perm_exc("changing the hookscript is only allowed for root\@pam");
1449 } elsif ($opt eq 'tags') {
1450 my $old = $oldconf->{$opt};
1451 my $new = $delete ? '' : $newconf->{$opt};
1452 PVE::GuestHelpers::assert_tag_permissions($vmid, $old, $new, $rpcenv, $authuser);
1453 } else {
1454 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1455 }
1456 };
1457
1458 foreach my $opt (keys %$newconf) {
1459 &$check($opt, 0);
1460 }
1461 foreach my $opt (@$delete) {
1462 &$check($opt, 1);
1463 }
1464
1465 return 1;
1466 }
1467
1468 sub check_bridge_access {
1469 my ($rpcenv, $authuser, $raw) = @_;
1470
1471 return 1 if $authuser eq 'root@pam';
1472
1473 my $net = PVE::LXC::Config->parse_lxc_network($raw);
1474 my ($bridge, $tag, $trunks) = $net->@{'bridge', 'tag', 'trunks'};
1475 check_vnet_access($rpcenv, $authuser, $bridge, $tag, $trunks);
1476
1477 return 1;
1478 };
1479
1480 sub umount_all {
1481 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1482
1483 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1484 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
1485
1486 my $res = 1;
1487
1488 PVE::LXC::Config->foreach_volume_full($conf, {'reverse' => 1}, sub {
1489 my ($ms, $mountpoint) = @_;
1490
1491 my $volid = $mountpoint->{volume};
1492 my $mount = $mountpoint->{mp};
1493
1494 return if !$volid || !$mount;
1495
1496 my $mount_path = "$rootdir/$mount";
1497 $mount_path =~ s!/+!/!g;
1498
1499 return if !PVE::ProcFSTools::is_mounted($mount_path);
1500
1501 eval {
1502 PVE::Tools::run_command(['umount', '-d', $mount_path]);
1503 };
1504 if (my $err = $@) {
1505 if ($noerr) {
1506 $res = 0;
1507 warn $err;
1508 } else {
1509 die $err;
1510 }
1511 }
1512 });
1513
1514 return $res; # tell caller if (some) umounts failed for the noerr case
1515 }
1516
1517 sub mount_all {
1518 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1519
1520 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1521 File::Path::make_path($rootdir);
1522
1523 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
1524 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
1525
1526 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
1527
1528 eval {
1529 PVE::LXC::Config->foreach_volume($conf, sub {
1530 my ($ms, $mountpoint) = @_;
1531
1532 $mountpoint->{ro} = 0 if $ignore_ro;
1533
1534 mountpoint_mount($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1535 });
1536 };
1537 if (my $err = $@) {
1538 warn "mounting container failed\n";
1539 umount_all($vmid, $storage_cfg, $conf, 1);
1540 die $err;
1541 }
1542
1543 return $rootdir;
1544 }
1545
1546
1547 sub mountpoint_mount_path {
1548 my ($mountpoint, $storage_cfg, $snapname) = @_;
1549
1550 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
1551 }
1552
1553 sub query_loopdev {
1554 my ($path) = @_;
1555 my $found;
1556 my $parser = sub {
1557 my $line = shift;
1558 if ($line =~ m@^(/dev/loop\d+):@) {
1559 $found = $1;
1560 }
1561 };
1562 my $cmd = ['losetup', '--associated', $path];
1563 PVE::Tools::run_command($cmd, outfunc => $parser);
1564 return $found;
1565 }
1566
1567 # Run a function with a file attached to a loop device.
1568 # The loop device is always detached afterwards (or set to autoclear).
1569 # Returns the loop device.
1570 sub run_with_loopdev {
1571 my ($func, $file, $readonly) = @_;
1572 my $device = query_loopdev($file);
1573 # Try to reuse an existing device
1574 if ($device) {
1575 # We assume that whoever setup the loop device is responsible for
1576 # detaching it.
1577 &$func($device);
1578 return $device;
1579 }
1580
1581 my $parser = sub {
1582 my $line = shift;
1583 if ($line =~ m@^(/dev/loop\d+)$@) {
1584 $device = $1;
1585 }
1586 };
1587 my $losetup_cmd = [
1588 'losetup',
1589 '--show',
1590 '-f',
1591 $file,
1592 ];
1593 push @$losetup_cmd, '-r' if $readonly;
1594 PVE::Tools::run_command($losetup_cmd, outfunc => $parser);
1595 die "failed to setup loop device for $file\n" if !$device;
1596 eval { &$func($device); };
1597 my $err = $@;
1598 PVE::Tools::run_command(['losetup', '-d', $device]);
1599 die $err if $err;
1600 return $device;
1601 }
1602
1603 # In scalar mode: returns a file handle to the deepest directory node.
1604 # In list context: returns a list of:
1605 # * the deepest directory node
1606 # * the 2nd deepest directory (parent of the above)
1607 # * directory name of the last directory
1608 # So that the path $2/$3 should lead to $1 afterwards.
1609 sub walk_tree_nofollow($$$;$$) {
1610 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1611
1612 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1613 or die "failed to open start directory $start: $!\n";
1614
1615 return walk_tree_nofollow_fd($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1616 }
1617
1618
1619 sub walk_tree_nofollow_fd($$$$;$$) {
1620 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1621
1622 # splitdir() returns '' for empty components including the leading /
1623 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1624
1625 my $fd = $start_fd;
1626 my $dir = $start_dirname;
1627 my $last_component = undef;
1628 my $second = $fd;
1629 foreach my $component (@comps) {
1630 $dir .= "/$component";
1631 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1632
1633 if (!$next) {
1634 # failed, check for symlinks and try to create the path
1635 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
1636 die "cannot open directory $dir: $!\n" if !$mkdir;
1637
1638 # We don't check for errors on mkdirat() here and just try to
1639 # openat() again, since at least one error (EEXIST) is an
1640 # expected possibility if multiple containers start
1641 # simultaneously. If someone else injects a symlink now then
1642 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1643 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1644
1645 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1646 die "failed to create path: $dir: $!\n" if !$next;
1647
1648 PVE::Tools::fchownat(fileno($next), '', $rootuid, $rootgid, PVE::Tools::AT_EMPTY_PATH)
1649 if defined($rootuid) && defined($rootgid);
1650 }
1651
1652 close $second if defined($last_component) && $second != $start_fd;
1653 $last_component = $component;
1654 $second = $fd;
1655 $fd = $next;
1656 }
1657
1658 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1659 close $second if defined($last_component) && $second != $start_fd;
1660 return $fd;
1661 }
1662
1663 # To guard against symlink attack races against other currently running
1664 # containers with shared recursive bind mount hierarchies we prepare a
1665 # directory handle for the directory we're mounting over to verify the
1666 # mountpoint afterwards.
1667 sub __bindmount_prepare {
1668 my ($hostroot, $dir) = @_;
1669 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1670 return $srcdh;
1671 }
1672
1673 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1674 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1675 # we intended to bind mount.
1676 sub __bindmount_verify {
1677 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1678 my $destdh;
1679 if ($parentfd) {
1680 # Open the mount point path coming from the parent directory since the
1681 # filehandle we would have gotten as first result of walk_tree_nofollow
1682 # earlier is still a handle to the underlying directory instead of the
1683 # mounted path.
1684 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1685 die "failed to open mount point: $!\n" if !$destdh;
1686 if ($ro) {
1687 my $dot = '.';
1688 # no separate function because 99% of the time it's the wrong thing to use.
1689 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
1690 die "failed to mark bind mount read only\n";
1691 }
1692 die "read-only check failed: $!\n" if $! != EROFS;
1693 }
1694 } else {
1695 # For the rootfs we don't have a parentfd so we open the path directly.
1696 # Note that this means bindmounting any prefix of the host's
1697 # /var/lib/lxc/$vmid path into another container is considered a grave
1698 # security error.
1699 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
1700 die "failed to open mount point: $!\n" if !$destdh;
1701 }
1702
1703 my ($srcdev, $srcinode) = stat($srcdh);
1704 my ($dstdev, $dstinode) = stat($destdh);
1705 close $srcdh;
1706 close $destdh;
1707
1708 return ($srcdev == $dstdev && $srcinode == $dstinode);
1709 }
1710
1711 # Perform the actual bind mounting:
1712 sub __bindmount_do {
1713 my ($dir, $dest, $ro, @extra_opts) = @_;
1714 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1715 if ($ro) {
1716 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1717 if (my $err = $@) {
1718 warn "bindmount error\n";
1719 # don't leave writable bind-mounts behind...
1720 PVE::Tools::run_command(['umount', $dest]);
1721 die $err;
1722 }
1723 }
1724 }
1725
1726 sub bindmount {
1727 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1728
1729 my $srcdh = __bindmount_prepare('/', $dir);
1730
1731 __bindmount_do($dir, $dest, $ro, @extra_opts);
1732
1733 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
1734 PVE::Tools::run_command(['umount', $dest]);
1735 die "detected mount path change at: $dir\n";
1736 }
1737 }
1738
1739 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1740 # from $rootdir and $mount and walk the path from $rootdir to the final
1741 # directory to check for symlinks.
1742 sub __mount_prepare_rootdir {
1743 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
1744 $rootdir =~ s!/+!/!g;
1745 $rootdir =~ s!/+$!!;
1746 my $mount_path = "$rootdir/$mount";
1747 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1, $rootuid, $rootgid);
1748 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1749 }
1750
1751 # use $rootdir = undef to just return the corresponding mount path
1752 sub mountpoint_mount {
1753 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1754 return __mountpoint_mount($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1755 }
1756
1757 sub mountpoint_stage {
1758 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1759 my ($path, $loop, $dev) =
1760 __mountpoint_mount($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1761
1762 if (!defined($path)) {
1763 die "failed to mount subvolume: $!\n";
1764 }
1765
1766 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1767 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1768 # point).
1769 my $err;
1770 my $fd = PVE::Tools::open_tree(&AT_FDCWD, $stage_dir, &OPEN_TREE_CLOEXEC | &OPEN_TREE_CLONE)
1771 or die "open_tree() on mount point failed: $!\n";
1772
1773 return wantarray ? ($path, $loop, $dev, $fd) : $fd;
1774 }
1775
1776 sub mountpoint_insert_staged {
1777 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1778
1779 if (!defined($rootdir_fd)) {
1780 sysopen($rootdir_fd, '.', O_PATH | O_DIRECTORY)
1781 or die "failed to open '.': $!\n";
1782 }
1783
1784 my $dest_fd = walk_tree_nofollow_fd('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1785
1786 PVE::Tools::move_mount(
1787 fileno($mount_fd),
1788 '',
1789 fileno($dest_fd),
1790 '',
1791 &MOVE_MOUNT_F_EMPTY_PATH | &MOVE_MOUNT_T_EMPTY_PATH,
1792 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1793 }
1794
1795 # Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1796 # can then open a file descriptor to it which can be used with the `move_mount` syscall.
1797 sub __mountpoint_mount {
1798 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1799
1800 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1801 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1802 # which we use in __bindmount_verify()!
1803 my $mount = $stage_mount ? '/': $mountpoint->{mp};
1804
1805 my $volid = $mountpoint->{volume};
1806 my $type = $mountpoint->{type};
1807 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1808 my $mounted_dev;
1809
1810 return if !$volid || !$mount;
1811
1812 $mount =~ s!/+!/!g;
1813
1814 my $mount_path;
1815 my ($mpfd, $parentfd, $last_dir);
1816
1817 if (defined($rootdir)) {
1818 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1819 __mount_prepare_rootdir($rootdir, $mount, $rootuid, $rootgid);
1820 }
1821
1822 if (defined($stage_mount)) {
1823 $mount_path = $rootdir;
1824 }
1825
1826 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1827
1828 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1829
1830 my $optlist = [];
1831
1832 if (my $mountopts = $mountpoint->{mountoptions}) {
1833 my @opts = split(/;/, $mountpoint->{mountoptions});
1834 push @$optlist, grep { PVE::LXC::Config::is_valid_mount_option($_) } @opts;
1835 }
1836
1837 my $acl = $mountpoint->{acl};
1838 if (defined($acl)) {
1839 push @$optlist, ($acl ? 'acl' : 'noacl');
1840 }
1841
1842 my $optstring = join(',', @$optlist);
1843 my $readonly = $mountpoint->{ro};
1844
1845 my @extra_opts;
1846 @extra_opts = ('-o', $optstring) if $optstring;
1847
1848 if ($storage) {
1849
1850 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
1851
1852 PVE::Storage::activate_volumes($storage_cfg, [$volid], $snapname);
1853 my $path = PVE::Storage::map_volume($storage_cfg, $volid, $snapname);
1854
1855 $path = PVE::Storage::path($storage_cfg, $volid, $snapname) if !defined($path);
1856
1857 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1858 PVE::Storage::parse_volname($storage_cfg, $volid);
1859
1860 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1861
1862 if ($format eq 'subvol') {
1863 if ($mount_path) {
1864 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1865 if (defined($snapname)) {
1866 $name .= "\@$snapname";
1867 if ($scfg->{type} eq 'zfspool') {
1868 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', "$scfg->{pool}/$name", $mount_path]);
1869 } else {
1870 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1871 }
1872 } else {
1873 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1874 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1875 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1876 }
1877 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1878 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1879 }
1880 }
1881 return wantarray ? ($path, 0, undef) : $path;
1882 } elsif ($format eq 'raw' || $format eq 'iso') {
1883 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1884 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1885 # Our autodev hook expects the /dev/dm-* device currently
1886 # and will create the /dev/mapper symlink accordingly
1887 $path = Cwd::realpath($path);
1888 die "failed to get device path\n" if !$path;
1889 ($path) = ($path =~ /^(.*)$/s); #untaint
1890 my $domount = sub {
1891 my ($path) = @_;
1892 if ($mount_path) {
1893 if ($format eq 'iso') {
1894 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1895 } elsif ($isBase || defined($snapname)) {
1896 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1897 } else {
1898 if ($quota) {
1899 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1900 }
1901 push @extra_opts, '-o', 'ro' if $readonly;
1902 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1903 }
1904 }
1905 };
1906 my $use_loopdev = 0;
1907 if ($scfg->{content}->{rootdir}) {
1908 if ($scfg->{path}) {
1909 $mounted_dev = run_with_loopdev($domount, $path, $readonly);
1910 $use_loopdev = 1;
1911 } else {
1912 $mounted_dev = $path;
1913 &$domount($path);
1914 }
1915 } else {
1916 die "storage '$storage' does not support containers\n";
1917 }
1918 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
1919 } else {
1920 die "unsupported image format '$format'\n";
1921 }
1922 } elsif ($type eq 'device') {
1923 push @extra_opts, '-o', 'ro' if $readonly;
1924 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1925 # See the NOTE above about devicemapper canonicalization
1926 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
1927 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1928 return wantarray ? ($volid, 0, $devpath) : $volid;
1929 } elsif ($type eq 'bind') {
1930 die "directory '$volid' does not exist\n" if ! -d $volid;
1931 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1932 warn "cannot enable quota control for bind mounts\n" if $quota;
1933 return wantarray ? ($volid, 0, undef) : $volid;
1934 }
1935
1936 die "unsupported storage";
1937 }
1938
1939 sub mountpoint_hotplug :prototype($$$$$) {
1940 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1941
1942 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1943
1944 # We do the rest in a fork with an unshared mount namespace, because:
1945 # -) change our papparmor profile to that of /usr/bin/lxc-start
1946 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1947 # container's namespace, then mount it.
1948
1949 PVE::Tools::run_fork(sub {
1950 # Pin the container pid longer, we also need to get its monitor/parent:
1951 my ($ct_pid, $ct_pidfd) = open_lxc_pid($vmid)
1952 or die "failed to open pidfd of container $vmid\'s init process\n";
1953
1954 my ($monitor_pid, $monitor_pidfd) = open_ppid($ct_pid)
1955 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1956
1957 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1958 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1959
1960 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1961 # profile to lower our privileges to the same level we have in the start hook:
1962 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY)
1963 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1964 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1965 # apparmor.
1966
1967 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1968 # namespace for it to remain active there since the container will be able to unmount
1969 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1970 # concern.
1971 PVE::Tools::setns(fileno($monitor_mnt_ns), PVE::Tools::CLONE_NEWNS);
1972 chdir('/')
1973 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1974
1975 my $dir = get_staging_mount_path($opt);
1976
1977 # Now switch our apparmor profile before mounting:
1978 my $data = 'changeprofile pve-container-mounthotplug';
1979 my $data_written = syswrite($aa_fd, $data, length($data));
1980 if (!defined($data_written) || $data_written != length($data)) {
1981 die "failed to change apparmor profile: $!\n";
1982 }
1983 # Check errors on close as well:
1984 close($aa_fd)
1985 or die "failed to change apparmor profile (close() failed): $!\n";
1986
1987 my $mount_fd = mountpoint_stage($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1988
1989 PVE::Tools::setns(fileno($ct_mnt_ns), PVE::Tools::CLONE_NEWNS);
1990 chdir('/')
1991 or die "failed to change root directory within the container's mount namespace: $!\n";
1992
1993 mountpoint_insert_staged($mount_fd, undef, $mp->{mp}, $opt, $rootuid, $rootgid);
1994 });
1995 }
1996
1997 # Create a directory in the mountpoint staging tempfs.
1998 sub get_staging_mount_path($) {
1999 my ($opt) = @_;
2000
2001 my $target = get_staging_tempfs() . "/$opt";
2002 if (!mkdir($target) && $! != EEXIST) {
2003 die "failed to create directory $target: $!\n";
2004 }
2005
2006 return $target;
2007 }
2008
2009 # Mount tmpfs for mount point staging and return the path.
2010 sub get_staging_tempfs() {
2011 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
2012 # mounts to that.
2013 my $target = '/var/lib/lxc/.pve-staged-mounts';
2014 if (!mkdir($target)) {
2015 return $target if $! == EEXIST;
2016 die "failed to create directory $target: $!\n";
2017 }
2018
2019 PVE::Tools::mount("none", $target, 'tmpfs', 0, "size=8k,mode=755")
2020 or die "failed to mount $target as tmpfs: $!\n";
2021
2022 return $target;
2023 }
2024
2025 sub mkfs {
2026 my ($dev, $rootuid, $rootgid) = @_;
2027
2028 run_command(
2029 [
2030 'mkfs.ext4',
2031 '-O',
2032 'mmp',
2033 '-E',
2034 "root_owner=$rootuid:$rootgid",
2035 $dev,
2036 ],
2037 outfunc => sub {
2038 my $line = shift;
2039 # a hack to print only the relevant stuff, i.e., the one which could help on repair
2040 if ($line =~ /^(Creating filesystem|Filesystem UUID|Superblock backups|\s+\d+, \d)/) {
2041 print "$line\n";
2042 }
2043 },
2044 errfunc => sub {
2045 my $line = shift;
2046 print STDERR "$line\n" if $line && $line !~ /^mke2fs \d\.\d/;
2047 }
2048 );
2049 }
2050
2051 sub format_disk {
2052 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
2053
2054 if ($volid =~ m!^/dev/.+!) {
2055 mkfs($volid);
2056 return;
2057 }
2058
2059 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2060
2061 die "cannot format volume '$volid' with no storage\n" if !$storage;
2062
2063 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
2064
2065 my $path = PVE::Storage::map_volume($storage_cfg, $volid);
2066
2067 $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
2068
2069 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
2070 PVE::Storage::parse_volname($storage_cfg, $volid);
2071
2072 die "cannot format volume '$volid' (format == $format)\n"
2073 if $format ne 'raw';
2074
2075 mkfs($path, $rootuid, $rootgid);
2076 }
2077
2078 sub destroy_disks {
2079 my ($storecfg, $vollist) = @_;
2080
2081 foreach my $volid (@$vollist) {
2082 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2083 warn $@ if $@;
2084 }
2085 }
2086
2087 sub alloc_disk {
2088 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
2089
2090 my $needs_chown = 0;
2091 my $volid;
2092
2093 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
2094 # fixme: use better naming ct-$vmid-disk-X.raw?
2095
2096 eval {
2097 my $do_format = 0;
2098 if ($scfg->{content}->{rootdir} && $scfg->{path}) {
2099 if ($size_kb > 0 && !($scfg->{type} eq 'btrfs' && $scfg->{quotas})) {
2100 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2101 $do_format = 1;
2102 } else {
2103 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
2104 $needs_chown = 1;
2105 }
2106 } elsif ($scfg->{type} eq 'zfspool') {
2107 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
2108 $needs_chown = 1;
2109 } elsif ($scfg->{content}->{rootdir}) {
2110 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2111 $do_format = 1;
2112 } else {
2113 die "content type 'rootdir' is not available or configured on storage '$storage'\n";
2114 }
2115 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
2116 };
2117 if (my $err = $@) {
2118 # in case formatting got interrupted:
2119 if (defined($volid)) {
2120 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2121 warn $@ if $@;
2122 }
2123 die $err;
2124 }
2125
2126 return ($volid, $needs_chown);
2127 }
2128
2129 sub create_disks {
2130 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
2131
2132 my $vollist = [];
2133
2134 eval {
2135 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
2136 my $chown_vollist = [];
2137
2138 PVE::LXC::Config->foreach_volume($settings, sub {
2139 my ($ms, $mountpoint) = @_;
2140
2141 my $volid = $mountpoint->{volume};
2142 my $mp = $mountpoint->{mp};
2143
2144 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2145
2146 if ($storage && ($volid =~ $NEW_DISK_RE)) {
2147 my ($storeid, $size_gb) = ($1, $2);
2148
2149 my $size_kb = int(${size_gb}*1024) * 1024;
2150
2151 my $needs_chown = 0;
2152 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
2153 push @$chown_vollist, $volid if $needs_chown;
2154 push @$vollist, $volid;
2155 $mountpoint->{volume} = $volid;
2156 $mountpoint->{size} = $size_kb * 1024;
2157 if ($pending) {
2158 $conf->{pending}->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2159 } else {
2160 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2161 }
2162 } else {
2163 # use specified/existing volid/dir/device
2164 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2165 }
2166 });
2167
2168 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
2169 foreach my $volid (@$chown_vollist) {
2170 my $path = PVE::Storage::path($storecfg, $volid, undef);
2171 chown($rootuid, $rootgid, $path);
2172 }
2173 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
2174 };
2175 # free allocated images on error
2176 if (my $err = $@) {
2177 destroy_disks($storecfg, $vollist);
2178 die $err;
2179 }
2180 return $vollist;
2181 }
2182
2183 sub update_disksize {
2184 my ($vmid, $conf, $all_volumes) = @_;
2185
2186 my $changes;
2187 my $prefix = "CT $vmid:";
2188
2189 my $update_mp = sub {
2190 my ($key, $mp, @param) = @_;
2191 my $size = $all_volumes->{$mp->{volume}}->{size} // 0;
2192
2193 if (!defined($mp->{size}) || $size != $mp->{size}) {
2194 $changes = 1;
2195 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
2196 $mp->{size} = $size;
2197 my $no_mp = $key eq 'rootfs'; # rootfs is handled different from other mount points
2198 $conf->{$key} = PVE::LXC::Config->print_ct_mountpoint($mp, $no_mp);
2199 }
2200 };
2201
2202 PVE::LXC::Config->foreach_volume($conf, $update_mp);
2203
2204 return $changes;
2205 }
2206
2207 sub update_unused {
2208 my ($vmid, $conf, $all_volumes) = @_;
2209
2210 my $changes;
2211 my $prefix = "CT $vmid:";
2212
2213 # Note: it is allowed to define multiple storage entries with the same path
2214 # (alias), so we need to check both 'volid' and real 'path' (two different
2215 # volid can point to the same path).
2216
2217 # used and unused disks
2218 my $refpath = {};
2219 my $orphans = {};
2220
2221 foreach my $opt (keys %$conf) {
2222 next if ($opt !~ m/^unused\d+$/);
2223 my $vol = $all_volumes->{$conf->{$opt}};
2224 $refpath->{$vol->{path}} = $vol->{volid};
2225 }
2226
2227 foreach my $key (keys %$all_volumes) {
2228 my $vol = $all_volumes->{$key};
2229 my $in_use = PVE::LXC::Config->is_volume_in_use($conf, $vol->{volid});
2230 my $path = $vol->{path};
2231
2232 if ($in_use) {
2233 $refpath->{$path} = $key;
2234 delete $orphans->{$path};
2235 } else {
2236 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
2237 $orphans->{$path} = $key;
2238 }
2239 }
2240 }
2241
2242 for my $key (keys %$orphans) {
2243 my $disk = $orphans->{$key};
2244 my $unused = PVE::LXC::Config->add_unused_volume($conf, $disk);
2245
2246 if ($unused) {
2247 $changes = 1;
2248 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
2249 }
2250 }
2251
2252 return $changes;
2253 }
2254
2255 sub scan_volids {
2256 my ($cfg, $vmid) = @_;
2257
2258 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid, undef, 'rootdir');
2259
2260 my $all_volumes = {};
2261 foreach my $storeid (keys %$info) {
2262 foreach my $item (@{$info->{$storeid}}) {
2263 my $volid = $item->{volid};
2264 next if !($volid && $item->{size});
2265 $item->{path} = PVE::Storage::path($cfg, $volid);
2266 $all_volumes->{$volid} = $item;
2267 }
2268 }
2269
2270 return $all_volumes;
2271 }
2272
2273 sub rescan {
2274 my ($vmid, $nolock, $dryrun) = @_;
2275
2276 my $cfg = PVE::Storage::config();
2277
2278 print "rescan volumes...\n";
2279 my $all_volumes = scan_volids($cfg, $vmid);
2280
2281 my $updatefn = sub {
2282 my ($vmid) = @_;
2283
2284 my $changes;
2285 my $conf = PVE::LXC::Config->load_config($vmid);
2286
2287 PVE::LXC::Config->check_lock($conf);
2288
2289 my $vm_volids = {};
2290 foreach my $volid (keys %$all_volumes) {
2291 my $info = $all_volumes->{$volid};
2292 $vm_volids->{$volid} = $info if $info->{vmid} == $vmid;
2293 }
2294
2295 my $upu = update_unused($vmid, $conf, $vm_volids);
2296 my $upd = update_disksize($vmid, $conf, $vm_volids);
2297 $changes = $upu || $upd;
2298
2299 PVE::LXC::Config->write_config($vmid, $conf) if $changes && !$dryrun;
2300 };
2301
2302 if (defined($vmid)) {
2303 if ($nolock) {
2304 &$updatefn($vmid);
2305 } else {
2306 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2307 }
2308 } else {
2309 my $vmlist = config_list();
2310 foreach my $vmid (keys %$vmlist) {
2311 if ($nolock) {
2312 &$updatefn($vmid);
2313 } else {
2314 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2315 }
2316 }
2317 }
2318 }
2319
2320
2321 # bash completion helper
2322
2323 sub complete_os_templates {
2324 my ($cmdname, $pname, $cvalue) = @_;
2325
2326 my $cfg = PVE::Storage::config();
2327
2328 my $storeid;
2329
2330 if ($cvalue =~ m/^([^:]+):/) {
2331 $storeid = $1;
2332 }
2333
2334 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
2335 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
2336
2337 my $res = [];
2338 foreach my $id (keys %$data) {
2339 foreach my $item (@{$data->{$id}}) {
2340 push @$res, $item->{volid} if defined($item->{volid});
2341 }
2342 }
2343
2344 return $res;
2345 }
2346
2347 my $complete_ctid_full = sub {
2348 my ($running) = @_;
2349
2350 my $idlist = vmstatus();
2351
2352 my $active_hash = list_active_containers();
2353
2354 my $res = [];
2355
2356 foreach my $id (keys %$idlist) {
2357 my $d = $idlist->{$id};
2358 if (defined($running)) {
2359 next if $d->{template};
2360 next if $running && !$active_hash->{$id};
2361 next if !$running && $active_hash->{$id};
2362 }
2363 push @$res, $id;
2364
2365 }
2366 return $res;
2367 };
2368
2369 sub complete_ctid {
2370 return &$complete_ctid_full();
2371 }
2372
2373 sub complete_ctid_stopped {
2374 return &$complete_ctid_full(0);
2375 }
2376
2377 sub complete_ctid_running {
2378 return &$complete_ctid_full(1);
2379 }
2380
2381 sub parse_id_maps {
2382 my ($conf) = @_;
2383
2384 my $id_map = [];
2385 my $rootuid = 0;
2386 my $rootgid = 0;
2387
2388 my $lxc = $conf->{lxc};
2389 foreach my $entry (@$lxc) {
2390 my ($key, $value) = @$entry;
2391
2392 next if $key ne 'lxc.idmap';
2393
2394 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2395 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2396 push @$id_map, [$type, $ct, $host, $length];
2397 if ($ct == 0) {
2398 $rootuid = $host if $type eq 'u';
2399 $rootgid = $host if $type eq 'g';
2400 }
2401 } else {
2402 die "failed to parse idmap: $value\n";
2403 }
2404 }
2405
2406 if (!@$id_map && $conf->{unprivileged}) {
2407 # Should we read them from /etc/subuid?
2408 $id_map = [ ['u', '0', '100000', '65536'],
2409 ['g', '0', '100000', '65536'] ];
2410 $rootuid = $rootgid = 100000;
2411 }
2412
2413 return ($id_map, $rootuid, $rootgid);
2414 }
2415
2416 sub validate_id_maps {
2417 my ($id_map) = @_;
2418
2419 # $mappings->{$type}->{$side} = [ { line => $line, start => $start, count => $count }, ... ]
2420 # $type: either "u" or "g"
2421 # $side: either "container" or "host"
2422 # $line: index of this mapping in @$id_map
2423 # $start, $count: interval of this mapping
2424 my $mappings = { u => {}, g => {} };
2425 for (my $i = 0; $i < scalar(@$id_map); $i++) {
2426 my ($type, $ct_start, $host_start, $count) = $id_map->[$i]->@*;
2427 my $sides = $mappings->{$type};
2428 push $sides->{host}->@*, { line => $i, start => $host_start, count => $count };
2429 push $sides->{container}->@*, { line => $i, start => $ct_start, count => $count };
2430 }
2431
2432 # find the first conflict between two consecutive mappings when sorted by their start id
2433 for my $type (qw(u g)) {
2434 for my $side (qw(container host)) {
2435 my @entries = sort { $a->{start} <=> $b->{start} } $mappings->{$type}->{$side}->@*;
2436 for my $idx (1..scalar(@entries) - 1) {
2437 my $previous = $entries[$idx - 1];
2438 my $current = $entries[$idx];
2439 if ($previous->{start} + $previous->{count} > $current->{start}) {
2440 my $conflict = $current->{start};
2441 my @previous_line = $id_map->[$previous->{line}]->@*;
2442 my @current_line = $id_map->[$current->{line}]->@*;
2443 die "invalid map entry '@current_line': $side ${type}id $conflict "
2444 ."is also mapped by entry '@previous_line'\n";
2445 }
2446 }
2447 }
2448 }
2449 }
2450
2451 sub map_ct_id_to_host {
2452 my ($id, $id_map, $id_type) = @_;
2453
2454 for my $mapping (@$id_map) {
2455 my ($type, $ct, $host, $length) = @$mapping;
2456
2457 next if ($type ne $id_type);
2458
2459 if ($id >= $ct && $id < ($ct + $length)) {
2460 return $host - $ct + $id;
2461 }
2462 }
2463
2464 return $id;
2465 }
2466
2467 sub map_ct_uid_to_host {
2468 my ($uid, $id_map) = @_;
2469
2470 return map_ct_id_to_host($uid, $id_map, 'u');
2471 }
2472
2473 sub map_ct_gid_to_host {
2474 my ($gid, $id_map) = @_;
2475
2476 return map_ct_id_to_host($gid, $id_map, 'g');
2477 }
2478
2479 sub userns_command {
2480 my ($id_map) = @_;
2481 if (@$id_map) {
2482 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2483 }
2484 return [];
2485 }
2486
2487 my sub print_ct_stderr_log {
2488 my ($vmid) = @_;
2489 my $log = eval { file_get_contents("/run/pve/ct-$vmid.stderr") };
2490 return if !$log;
2491
2492 while ($log =~ /^\h*(lxc-start:?\s+$vmid:?\s*\S+\s*)?(.*?)\h*$/gm) {
2493 my $line = $2;
2494 print STDERR "$line\n";
2495 }
2496 }
2497 my sub print_ct_warn_log {
2498 my ($vmid) = @_;
2499 my $log_fn = "/run/pve/ct-$vmid.warnings";
2500 my $log = eval { file_get_contents($log_fn) };
2501 return if !$log;
2502
2503 while ($log =~ /^\h*\s*(.*?)\h*$/gm) {
2504 PVE::RESTEnvironment::log_warn($1);
2505 }
2506 unlink $log_fn or warn "could not unlink '$log_fn' - $!\n";
2507 }
2508
2509 my sub monitor_state_change($$) {
2510 my ($monitor_socket, $vmid) = @_;
2511 die "no monitor socket\n" if !defined($monitor_socket);
2512
2513 while (1) {
2514 my ($type, $name, $value) = PVE::LXC::Monitor::read_lxc_message($monitor_socket);
2515
2516 die "monitor socket: got EOF\n" if !defined($type);
2517
2518 next if $name ne "$vmid" || $type ne 'STATE';
2519
2520 if ($value eq PVE::LXC::Monitor::STATE_STARTING) {
2521 alarm(0); # don't timeout after seeing the starting state
2522 } elsif ($value eq PVE::LXC::Monitor::STATE_ABORTING ||
2523 $value eq PVE::LXC::Monitor::STATE_STOPPING ||
2524 $value eq PVE::LXC::Monitor::STATE_STOPPED) {
2525 return 0;
2526 } elsif ($value eq PVE::LXC::Monitor::STATE_RUNNING) {
2527 return 1;
2528 } else {
2529 warn "unexpected message from monitor socket - " .
2530 "type: '$type' - value: '$value'\n";
2531 }
2532 }
2533 }
2534 my sub monitor_start($$) {
2535 my ($monitor_socket, $vmid) = @_;
2536
2537 my $success = eval {
2538 PVE::Tools::run_with_timeout(10, \&monitor_state_change, $monitor_socket, $vmid)
2539 };
2540 if (my $err = $@) {
2541 warn "problem with monitor socket, but continuing anyway: $err\n";
2542 } elsif (!$success) {
2543 print_ct_stderr_log($vmid);
2544 die "startup for container '$vmid' failed\n";
2545 }
2546 }
2547
2548 sub vm_start {
2549 my ($vmid, $conf, $skiplock, $debug) = @_;
2550
2551 # apply pending changes while starting
2552 if (scalar(keys %{$conf->{pending}})) {
2553 my $storecfg = PVE::Storage::config();
2554 PVE::LXC::Config->vmconfig_apply_pending($vmid, $conf, $storecfg);
2555 PVE::LXC::Config->write_config($vmid, $conf);
2556 $conf = PVE::LXC::Config->load_config($vmid); # update/reload
2557 }
2558
2559 update_lxc_config($vmid, $conf);
2560
2561 eval {
2562 my ($id_map, undef, undef) = PVE::LXC::parse_id_maps($conf);
2563 PVE::LXC::validate_id_maps($id_map);
2564 };
2565 warn "lxc.idmap: $@" if $@;
2566
2567 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2568
2569 if ($skiplock) {
2570 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2571 close($fh);
2572 }
2573
2574 my $storage_cfg = PVE::Storage::config();
2575 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
2576
2577 PVE::Storage::activate_volumes($storage_cfg, $vollist);
2578
2579 my $monitor_socket = eval { PVE::LXC::Monitor::get_monitor_socket() };
2580 warn $@ if $@;
2581
2582 unlink "/run/pve/ct-$vmid.stderr"; # systemd does not truncate log files
2583
2584 my $is_debug = $debug || (!defined($debug) && $conf->{debug});
2585 my $base_unit = $is_debug ? 'pve-container-debug' : 'pve-container';
2586
2587 my $cmd = ['systemctl', 'start', "$base_unit\@$vmid"];
2588
2589 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
2590 eval {
2591 run_command($cmd);
2592
2593 monitor_start($monitor_socket, $vmid) if defined($monitor_socket);
2594
2595 # if debug is requested, print the log it also when the start succeeded
2596 print_ct_stderr_log($vmid) if $is_debug;
2597
2598 print_ct_warn_log($vmid); # always print warn log, if any
2599 };
2600 if (my $err = $@) {
2601 unlink $skiplock_flag_fn;
2602 die $err;
2603 }
2604 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
2605
2606 return;
2607 }
2608
2609 # Helper to stop a container completely and make sure it has stopped completely.
2610 # This is necessary because we want the post-stop hook to have completed its
2611 # unmount-all step, but post-stop happens after lxc puts the container into the
2612 # STOPPED state.
2613 # $kill - if true it will always do an immediate hard-stop
2614 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
2615 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
2616 sub vm_stop {
2617 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
2618
2619 # Open the container's command socket.
2620 my $path = "\0/var/lib/lxc/$vmid/command";
2621 my $sock = IO::Socket::UNIX->new(
2622 Type => SOCK_STREAM(),
2623 Peer => $path,
2624 );
2625 if (!$sock) {
2626 return if $! == ECONNREFUSED; # The container is not running
2627 die "failed to open container ${vmid}'s command socket: $!\n";
2628 }
2629
2630 my $conf = PVE::LXC::Config->load_config($vmid);
2631 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
2632
2633 # Stop the container:
2634
2635 my $cmd = ['lxc-stop', '-n', $vmid];
2636
2637 if ($kill) {
2638 push @$cmd, '--kill'; # doesn't allow timeouts
2639 } else {
2640 # lxc-stop uses a default timeout
2641 push @$cmd, '--nokill' if !$kill_after_timeout;
2642
2643 if (defined($shutdown_timeout)) {
2644 push @$cmd, '--timeout', $shutdown_timeout;
2645 # Give run_command 5 extra seconds
2646 $shutdown_timeout += 5;
2647 }
2648 }
2649
2650 eval { run_command($cmd, timeout => $shutdown_timeout) };
2651
2652 # Wait until the command socket is closed.
2653 # In case the lxc-stop call failed, reading from the command socket may block forever,
2654 # so poll with another timeout to avoid freezing the shutdown task.
2655 if (my $err = $@) {
2656 warn $err if $err;
2657
2658 my $poll = IO::Poll->new();
2659 $poll->mask($sock => POLLIN | POLLHUP); # watch for input and EOF events
2660 $poll->poll($shutdown_timeout); # IO::Poll timeout is in seconds
2661 return if ($poll->events($sock) & POLLHUP);
2662 } else {
2663 my $result = <$sock>;
2664 return if !defined $result; # monitor is gone and the ct has stopped.
2665 }
2666
2667 die "container did not stop\n";
2668 }
2669
2670 sub vm_reboot {
2671 my ($vmid, $timeout, $skiplock) = @_;
2672
2673 PVE::LXC::Config->lock_config($vmid, sub {
2674 return if !check_running($vmid);
2675
2676 vm_stop($vmid, 0, $timeout, 1); # kill if timeout exceeds
2677
2678 my $conf = PVE::LXC::Config->load_config($vmid);
2679 vm_start($vmid, $conf);
2680 });
2681 }
2682
2683 sub run_unshared {
2684 my ($code) = @_;
2685
2686 return PVE::Tools::run_fork(sub {
2687 # Unshare the mount namespace
2688 die "failed to unshare mount namespace: $!\n"
2689 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
2690 run_command(['mount', '--make-rslave', '/']);
2691 return $code->();
2692 });
2693 }
2694
2695 my $copy_volume = sub {
2696 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2697
2698 my $src_mp = { volume => $src_volid, mp => '/', ro => 1 };
2699 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
2700
2701 my $dst_mp = { volume => $dst_volid, mp => '/', ro => 0 };
2702 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
2703
2704 my @mounted;
2705 eval {
2706 # mount and copy
2707 mkdir $src;
2708 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2709 push @mounted, $src;
2710 mkdir $dest;
2711 mountpoint_mount($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2712 push @mounted, $dest;
2713
2714 $bwlimit //= 0;
2715
2716 run_command([
2717 'rsync',
2718 '--stats',
2719 '-X',
2720 '-A',
2721 '--numeric-ids',
2722 '-aH',
2723 '--whole-file',
2724 '--sparse',
2725 '--one-file-system',
2726 "--bwlimit=$bwlimit",
2727 "$src/",
2728 $dest
2729 ]);
2730 };
2731 my $err = $@;
2732
2733 # Wait for rsync's children to release dest so that
2734 # consequent file operations (umount, remove) are possible
2735 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2736
2737 foreach my $mount (reverse @mounted) {
2738 eval { run_command(['/bin/umount', $mount], errfunc => sub{})};
2739 warn "Can't umount $mount\n" if $@;
2740 }
2741
2742 # If this fails they're used as mount points in a concurrent operation
2743 # (which should not happen but there's also no real need to get rid of them).
2744 rmdir $dest;
2745 rmdir $src;
2746
2747 die $err if $err;
2748 };
2749
2750 # Should not be called after unsharing the mount namespace!
2751 sub copy_volume {
2752 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2753
2754 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
2755 File::Path::make_path("/var/lib/lxc/$vmid");
2756 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2757 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2758
2759 # get id's for unprivileged container
2760 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
2761
2762 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2763 # are visible in this namespace, otherwise the host only sees the empty
2764 # (not-mounted) directory.
2765 my $new_volid;
2766 eval {
2767 # Make sure $mp contains a correct size.
2768 $mp->{size} = PVE::Storage::volume_size_info($storage_cfg, $mp->{volume});
2769 my $needs_chown;
2770 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
2771 if ($needs_chown) {
2772 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
2773 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
2774 chown($rootuid, $rootgid, $path);
2775 }
2776
2777 run_unshared(sub {
2778 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2779 });
2780 };
2781 if (my $err = $@) {
2782 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
2783 if defined($new_volid);
2784 die $err;
2785 }
2786
2787 return $new_volid;
2788 }
2789
2790 sub get_lxc_version() {
2791 my $version;
2792 run_command([qw(lxc-start --version)], outfunc => sub {
2793 my ($line) = @_;
2794 # We only parse out major & minor version numbers.
2795 if ($line =~ /^(\d+)\.(\d+)(?:\D.*)?$/) {
2796 $version = [$1, $2];
2797 }
2798 });
2799
2800 die "failed to get lxc version\n" if !defined($version);
2801
2802 # return as a list:
2803 return $version->@*;
2804 }
2805
2806 sub freeze($) {
2807 my ($vmid) = @_;
2808 if (PVE::CGroup::cgroup_mode() == 2) {
2809 PVE::LXC::Command::freeze($vmid, 30);
2810 } else {
2811 PVE::LXC::CGroup->new($vmid)->freeze_thaw(1);
2812 }
2813 }
2814
2815 sub thaw($) {
2816 my ($vmid) = @_;
2817 if (PVE::CGroup::cgroup_mode() == 2) {
2818 PVE::LXC::Command::unfreeze($vmid, 30);
2819 } else {
2820 PVE::LXC::CGroup->new($vmid)->freeze_thaw(0);
2821 }
2822 }
2823
2824 sub create_ifaces_ipams_ips {
2825 my ($conf, $vmid) = @_;
2826
2827 return if !$have_sdn;
2828
2829 for my $opt (keys %$conf) {
2830 next if $opt !~ m/^net(\d+)$/;
2831 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
2832 next if $net->{type} ne 'veth';
2833 PVE::Network::SDN::Vnets::add_next_free_cidr($net->{bridge}, $conf->{hostname}, $net->{hwaddr}, $vmid, undef, 1);
2834 }
2835 }
2836
2837 sub delete_ifaces_ipams_ips {
2838 my ($conf, $vmid) = @_;
2839
2840 return if !$have_sdn;
2841
2842 for my $opt (keys %$conf) {
2843 next if $opt !~ m/^net(\d+)$/;
2844 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
2845 eval { PVE::Network::SDN::Vnets::del_ips_from_mac($net->{bridge}, $net->{hwaddr}, $conf->{hostname}) };
2846 warn $@ if $@;
2847 }
2848 }
2849
2850 1;