]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC.pm
fix invalid device passthrough being added to config
[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 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\n"
647 if !defined($device->{path});
648
649 my ($mode, $rdev) = PVE::LXC::Tools::get_device_mode_and_rdev($device->{path});
650 my $major = PVE::Tools::dev_t_major($rdev);
651 my $minor = PVE::Tools::dev_t_minor($rdev);
652 my $device_type_char = S_ISBLK($mode) ? 'b' : 'c';
653 $raw .= "lxc.cgroup2.devices.allow = $device_type_char $major:$minor rw\n";
654 });
655
656 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
657 # cannot be exposed to the container with r/w access (cgroup perms).
658 # When this is enabled mounts will still remain in the monitor's namespace
659 # after the container unmounted them and thus will not detach from their
660 # files while the container is running!
661 $raw .= "lxc.monitor.unshare = 1\n";
662
663 my ($cgv1, $cgv2) = PVE::CGroup::get_cgroup_controllers();
664
665 # Should we read them from /etc/subuid?
666 if ($unprivileged && !$custom_idmap) {
667 $raw .= "lxc.idmap = u 0 100000 65536\n";
668 $raw .= "lxc.idmap = g 0 100000 65536\n";
669 }
670
671 if (!PVE::LXC::Config->has_dev_console($conf)) {
672 $raw .= "lxc.console.path = none\n";
673 if ($cgv1->{devices}) {
674 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
675 } elsif (defined($cgv2)) {
676 $raw .= "lxc.cgroup2.devices.deny = c 5:1 rwm\n";
677 }
678 }
679
680 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
681 $raw .= "lxc.tty.max = $ttycount\n";
682
683 # some init scripts expect a linux terminal (turnkey).
684 $raw .= "lxc.environment = TERM=linux\n";
685
686 my $utsname = $conf->{hostname} || "CT$vmid";
687 $raw .= "lxc.uts.name = $utsname\n";
688
689 if ($cgv1->{memory}) {
690 my $memory = $conf->{memory} || 512;
691 my $swap = $conf->{swap} // 0;
692
693 my $lxcmem = int($memory*1024*1024);
694 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
695
696 my $lxcswap = int(($memory + $swap)*1024*1024);
697 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
698 } elsif ($cgv2->{memory}) {
699 my $memory = $conf->{memory} || 512;
700 my $swap = $conf->{swap} // 0;
701
702 # cgroup memory usage is limited by the hard 'max' limit (OOM-killer enforced) and the soft
703 # 'high' limit (cgroup processes get throttled and put under heavy reclaim pressure).
704 my ($lxc_mem_max, $lxc_mem_high) = PVE::LXC::Config::calculate_memory_constraints($memory);
705 $raw .= "lxc.cgroup2.memory.max = $lxc_mem_max\n";
706 $raw .= "lxc.cgroup2.memory.high = $lxc_mem_high\n";
707
708 my $lxcswap = int($swap*1024*1024);
709 $raw .= "lxc.cgroup2.memory.swap.max = $lxcswap\n";
710 }
711
712 if ($cgv1->{cpu}) {
713 if (my $cpulimit = $conf->{cpulimit}) {
714 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
715 my $value = int(100000*$cpulimit);
716 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
717 }
718
719 my $shares = PVE::CGroup::clamp_cpu_shares($conf->{cpuunits});
720 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
721 } elsif ($cgv2->{cpu}) {
722 # See PVE::CGroup
723 if (my $cpulimit = $conf->{cpulimit}) {
724 my $value = int(100000*$cpulimit);
725 $raw .= "lxc.cgroup2.cpu.max = $value 100000\n";
726 }
727
728 if (defined(my $shares = $conf->{cpuunits})) {
729 $shares = PVE::CGroup::clamp_cpu_shares($shares);
730 $raw .= "lxc.cgroup2.cpu.weight = $shares\n";
731 }
732 }
733
734 die "missing 'rootfs' configuration\n"
735 if !defined($conf->{rootfs});
736
737 my $mountpoint = PVE::LXC::Config->parse_volume('rootfs', $conf->{rootfs});
738
739 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
740
741 foreach my $k (sort keys %$conf) {
742 next if $k !~ m/^net(\d+)$/;
743 my $ind = $1;
744 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
745 $raw .= "lxc.net.$ind.type = veth\n";
746 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
747 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
748 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name});
749
750 my $bridge_mtu = PVE::Network::read_bridge_mtu($d->{bridge});
751 my $mtu = $d->{mtu} || $bridge_mtu;
752
753 # Keep container from starting with invalid mtu configuration
754 die "$k: MTU size '$mtu' is bigger than bridge MTU '$bridge_mtu'\n"
755 if ($mtu > $bridge_mtu);
756
757 $raw .= "lxc.net.$ind.mtu = $mtu\n";
758
759 # Starting with lxc 4.0, we do not patch lxc to execute our up-scripts.
760 if ($lxc_major >= 4) {
761 $raw .= "lxc.net.$ind.script.up = /usr/share/lxc/lxcnetaddbr\n";
762 }
763 }
764
765 my $had_cpuset = 0;
766 if (my $lxcconf = $conf->{lxc}) {
767 foreach my $entry (@$lxcconf) {
768 my ($k, $v) = @$entry;
769 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus' || $k eq 'lxc.cgroup2.cpuset.cpus';
770 $raw .= "$k = $v\n";
771 }
772 }
773
774 my $cpuset;
775 my ($cpuset_cgroup, $cpuset_version) = eval { PVE::CGroup::cpuset_controller_path() };
776 if (defined($cpuset_cgroup)) {
777 $cpuset = eval { PVE::CpuSet->new_from_path("$cpuset_cgroup/lxc", 1) }
778 || PVE::CpuSet->new_from_path($cpuset_cgroup, 1);
779 }
780 my $cores = $conf->{cores};
781 if (!$had_cpuset && $cores && $cpuset) {
782 my @members = $cpuset->members();
783 while (scalar(@members) > $cores) {
784 my $randidx = int(rand(scalar(@members)));
785 $cpuset->delete($members[$randidx]);
786 splice(@members, $randidx, 1); # keep track of the changes
787 }
788 my $ver = $cpuset_version == 1 ? '' : '2';
789 $raw .= "lxc.cgroup$ver.cpuset.cpus = ".$cpuset->short_string()."\n";
790 }
791
792 File::Path::mkpath("$dir/rootfs");
793
794 PVE::Tools::file_set_contents("$dir/config", $raw);
795 }
796
797 # verify and cleanup nameserver list (replace \0 with ' ')
798 sub verify_nameserver_list {
799 my ($nameserver_list) = @_;
800
801 my @list = ();
802 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
803 PVE::LXC::Config::verify_ip_with_ll_iface($server);
804 push @list, $server;
805 }
806
807 return join(' ', @list);
808 }
809
810 sub verify_searchdomain_list {
811 my ($searchdomain_list) = @_;
812
813 my @list = ();
814 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
815 # todo: should we add checks for valid dns domains?
816 push @list, $server;
817 }
818
819 return join(' ', @list);
820 }
821
822 sub get_console_command {
823 my ($vmid, $conf, $escapechar) = @_;
824
825 # '-1' as $escapechar disables keyboard escape sequence
826 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
827
828 my $cmode = PVE::LXC::Config->get_cmode($conf);
829
830 my $cmd = [];
831 if ($cmode eq 'console') {
832 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
833 push @$cmd, '-e', $escapechar if $escapechar;
834 } elsif ($cmode eq 'tty') {
835 push @$cmd, 'lxc-console', '-n', $vmid;
836 push @$cmd, '-e', $escapechar if $escapechar;
837 } elsif ($cmode eq 'shell') {
838 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
839 } else {
840 die "internal error";
841 }
842
843 return $cmd;
844 }
845
846 sub get_primary_ips {
847 my ($conf) = @_;
848
849 # return data from net0
850
851 return undef if !defined($conf->{net0});
852 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
853
854 my $ipv4 = $net->{ip};
855 if ($ipv4) {
856 if ($ipv4 =~ /^(dhcp|manual)$/) {
857 $ipv4 = undef
858 } else {
859 $ipv4 =~ s!/\d+$!!;
860 }
861 }
862 my $ipv6 = $net->{ip6};
863 if ($ipv6) {
864 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
865 $ipv6 = undef;
866 } else {
867 $ipv6 =~ s!/\d+$!!;
868 }
869 }
870
871 return ($ipv4, $ipv6);
872 }
873
874 sub delete_mountpoint_volume {
875 my ($storage_cfg, $vmid, $volume) = @_;
876
877 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
878
879 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
880
881 if ($vmid == $owner) {
882 PVE::Storage::vdisk_free($storage_cfg, $volume);
883 } else {
884 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
885 }
886 }
887
888 sub destroy_lxc_container {
889 my ($storage_cfg, $vmid, $conf, $replacement_conf, $purge_unreferenced) = @_;
890
891 my $volids = {};
892 my $remove_volume = sub {
893 my ($ms, $mountpoint) = @_;
894
895 my $volume = $mountpoint->{volume};
896
897 return if $volids->{$volume};
898 $volids->{$volume} = 1;
899
900 delete_mountpoint_volume($storage_cfg, $vmid, $volume);
901 };
902 PVE::LXC::Config->foreach_volume_full($conf, {include_unused => 1}, $remove_volume);
903
904 PVE::LXC::Config->foreach_volume_full($conf->{pending}, {include_unused => 1}, $remove_volume);
905
906 if ($purge_unreferenced) { # also remove unreferenced disk
907 my $vmdisks = PVE::Storage::vdisk_list($storage_cfg, undef, $vmid, undef, 'rootdir');
908 PVE::Storage::foreach_volid($vmdisks, sub {
909 my ($volid, $sid, $volname, $d) = @_;
910 eval { PVE::Storage::vdisk_free($storage_cfg, $volid) };
911 warn $@ if $@;
912 });
913 }
914
915 delete_ifaces_ipams_ips($conf, $vmid);
916
917 rmdir "/var/lib/lxc/$vmid/rootfs";
918 unlink "/var/lib/lxc/$vmid/config";
919 rmdir "/var/lib/lxc/$vmid";
920 if (defined $replacement_conf) {
921 PVE::LXC::Config->write_config($vmid, $replacement_conf);
922 } else {
923 PVE::LXC::Config->destroy_config($vmid);
924 }
925 }
926
927 sub vm_stop_cleanup {
928 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
929
930 return if $keepActive;
931
932 eval {
933 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
934 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
935 };
936 warn $@ if $@; # avoid errors - just warn
937 }
938
939 sub net_tap_plug : prototype($$) {
940 my ($iface, $net) = @_;
941
942 if (defined($net->{link_down})) {
943 PVE::Tools::run_command(['/sbin/ip', 'link', 'set', 'dev', $iface, 'down']);
944 # Don't add disconnected interfaces to the bridge, otherwise e.g. applying any network
945 # change (e.g. `ifreload -a`) could (re-)activate it unintentionally.
946 return;
947 }
948
949 my ($bridge, $tag, $firewall, $trunks, $rate, $hwaddr) =
950 $net->@{'bridge', 'tag', 'firewall', 'trunks', 'rate', 'hwaddr'};
951
952 if ($have_sdn) {
953 PVE::Network::SDN::Zones::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate);
954 PVE::Network::SDN::Zones::add_bridge_fdb($iface, $hwaddr, $bridge);
955 } else {
956 PVE::Network::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate, { mac => $hwaddr });
957 }
958
959 PVE::Tools::run_command(['/sbin/ip', 'link', 'set', 'dev', $iface, 'up']);
960 }
961
962 sub update_net {
963 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
964
965 if ($newnet->{type} ne 'veth') {
966 # for when there are physical interfaces
967 die "cannot update interface of type $newnet->{type}";
968 }
969
970 my $veth = "veth${vmid}i${netid}";
971 my $eth = $newnet->{name};
972
973 if (my $oldnetcfg = $conf->{$opt}) {
974 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
975
976 if (safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
977 safe_string_ne($oldnet->{name}, $newnet->{name})) {
978
979 PVE::Network::veth_delete($veth);
980
981 if ($have_sdn && safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr})) {
982 eval { PVE::Network::SDN::Vnets::del_ips_from_mac($oldnet->{bridge}, $oldnet->{hwaddr}, $conf->{hostname}) };
983 warn $@ if $@;
984
985 PVE::Network::SDN::Vnets::add_next_free_cidr($newnet->{bridge}, $conf->{hostname}, $newnet->{hwaddr}, $vmid, undef, 1);
986 PVE::Network::SDN::Vnets::add_dhcp_mapping($newnet->{bridge}, $newnet->{hwaddr}, $vmid, $conf->{hostname});
987 }
988
989 delete $conf->{$opt};
990 PVE::LXC::Config->write_config($vmid, $conf);
991
992 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
993
994 } else {
995 my $bridge_changed = safe_string_ne($oldnet->{bridge}, $newnet->{bridge});
996
997 if ($bridge_changed ||
998 safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
999 safe_num_ne($oldnet->{firewall}, $newnet->{firewall}) ||
1000 safe_boolean_ne($oldnet->{link_down}, $newnet->{link_down})
1001 ) {
1002 if ($oldnet->{bridge}) {
1003 my $oldbridge = $oldnet->{bridge};
1004
1005 PVE::Network::tap_unplug($veth);
1006 foreach (qw(bridge tag firewall)) {
1007 delete $oldnet->{$_};
1008 }
1009 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
1010 PVE::LXC::Config->write_config($vmid, $conf);
1011
1012 if ($have_sdn && $bridge_changed) {
1013 eval { PVE::Network::SDN::Vnets::del_ips_from_mac($oldbridge, $oldnet->{hwaddr}, $conf->{hostname}) };
1014 warn $@ if $@;
1015 }
1016 }
1017
1018 if ($have_sdn && $bridge_changed) {
1019 PVE::Network::SDN::Vnets::add_next_free_cidr($newnet->{bridge}, $conf->{hostname}, $newnet->{hwaddr}, $vmid, undef, 1);
1020 }
1021 PVE::LXC::net_tap_plug($veth, $newnet);
1022
1023 # This includes the rate:
1024 foreach (qw(bridge tag firewall rate link_down)) {
1025 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
1026 }
1027 } elsif (safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
1028 # Rate can be applied on its own but any change above needs to
1029 # include the rate in tap_plug since OVS resets everything.
1030 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
1031 $oldnet->{rate} = $newnet->{rate}
1032 }
1033 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
1034 PVE::LXC::Config->write_config($vmid, $conf);
1035 }
1036 } else {
1037 if ($have_sdn) {
1038 PVE::Network::SDN::Vnets::add_next_free_cidr($newnet->{bridge}, $conf->{hostname}, $newnet->{hwaddr}, $vmid, undef, 1);
1039 PVE::Network::SDN::Vnets::add_dhcp_mapping($newnet->{bridge}, $newnet->{hwaddr}, $vmid, $conf->{hostname});
1040 }
1041
1042 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
1043 }
1044
1045 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
1046 }
1047
1048 sub hotplug_net {
1049 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
1050
1051 my $veth = "veth${vmid}i${netid}";
1052 my $vethpeer = $veth . "p";
1053 my $eth = $newnet->{name};
1054
1055 if ($have_sdn) {
1056 PVE::Network::SDN::Zones::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
1057 } else {
1058 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
1059 }
1060
1061 PVE::LXC::net_tap_plug($veth, $newnet);
1062
1063 # attach peer in container
1064 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
1065 PVE::Tools::run_command($cmd);
1066
1067 # link up peer in container
1068 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
1069 PVE::Tools::run_command($cmd);
1070
1071 my $done = { type => 'veth' };
1072 foreach (qw(bridge tag firewall hwaddr name link_down)) {
1073 $done->{$_} = $newnet->{$_} if $newnet->{$_};
1074 }
1075 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
1076
1077 PVE::LXC::Config->write_config($vmid, $conf);
1078 }
1079
1080 sub get_interfaces {
1081 my ($vmid) = @_;
1082
1083 my $pid = eval { find_lxc_pid($vmid); };
1084 return if $@;
1085
1086 my $output;
1087 # enters the network namespace of the container and executes 'ip a'
1088 run_command(['nsenter', '-t', $pid, '--net', '--', 'ip', '--json', 'a'],
1089 outfunc => sub { $output .= shift; });
1090
1091 my $config = JSON::decode_json($output);
1092
1093 my $res;
1094 for my $interface ($config->@*) {
1095 my $obj = { name => $interface->{ifname} };
1096 for my $ip ($interface->{addr_info}->@*) {
1097 $obj->{$ip->{family}} = $ip->{local} . "/" . $ip->{prefixlen};
1098 }
1099 $obj->{hwaddr} = $interface->{address};
1100 push @$res, $obj
1101 }
1102
1103 return $res;
1104 }
1105
1106 sub update_ipconfig {
1107 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
1108
1109 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
1110
1111 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
1112 my $deleted = [];
1113 my $added = [];
1114 my $nscmd = sub {
1115 my $cmdargs = shift;
1116 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
1117 };
1118 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
1119
1120 my $change_ip_config = sub {
1121 my ($ipversion) = @_;
1122
1123 my $family_opt = "-$ipversion";
1124 my $suffix = $ipversion == 4 ? '' : $ipversion;
1125 my $gw= "gw$suffix";
1126 my $ip= "ip$suffix";
1127
1128 my $newip = $newnet->{$ip};
1129 my $newgw = $newnet->{$gw};
1130 my $oldip = $optdata->{$ip};
1131 my $oldgw = $optdata->{$gw};
1132
1133 my $change_ip = safe_string_ne($oldip, $newip);
1134 my $change_gw = safe_string_ne($oldgw, $newgw);
1135
1136 return if !$change_ip && !$change_gw;
1137
1138 # step 1: add new IP, if this fails we cancel
1139 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
1140 if ($change_ip && $is_real_ip) {
1141 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
1142 if (my $err = $@) {
1143 warn $err;
1144 return;
1145 }
1146 }
1147
1148 # step 2: replace gateway
1149 # If this fails we delete the added IP and cancel.
1150 # If it succeeds we save the config and delete the old IP, ignoring
1151 # errors. The config is then saved.
1152 # Note: 'ip route replace' can add
1153 if ($change_gw) {
1154 if ($newgw) {
1155 eval {
1156 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
1157 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
1158 }
1159 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
1160 };
1161 if (my $err = $@) {
1162 warn $err;
1163 # the route was not replaced, the old IP is still available
1164 # rollback (delete new IP) and cancel
1165 if ($change_ip) {
1166 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
1167 warn $@ if $@; # no need to die here
1168 }
1169 return;
1170 }
1171 } else {
1172 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
1173 # if the route was not deleted, the guest might have deleted it manually
1174 # warn and continue
1175 warn $@ if $@;
1176 }
1177 if ($oldgw && $oldip && !PVE::Network::is_ip_in_cidr($oldgw, $oldip)) {
1178 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
1179 # warn if the route was deleted manually
1180 warn $@ if $@;
1181 }
1182 }
1183
1184 # from this point on we save the configuration
1185 # step 3: delete old IP ignoring errors
1186 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
1187 # We need to enable promote_secondaries, otherwise our newly added
1188 # address will be removed along with the old one.
1189 my $promote = 0;
1190 eval {
1191 if ($ipversion == 4) {
1192 &$nscmd({ outfunc => sub { $promote = int(shift) } },
1193 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1194 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1195 }
1196 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1197 };
1198 warn $@ if $@; # no need to die here
1199
1200 if ($ipversion == 4) {
1201 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1202 }
1203 }
1204
1205 foreach my $property ($ip, $gw) {
1206 if ($newnet->{$property}) {
1207 $optdata->{$property} = $newnet->{$property};
1208 } else {
1209 delete $optdata->{$property};
1210 }
1211 }
1212 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
1213 PVE::LXC::Config->write_config($vmid, $conf);
1214 $lxc_setup->setup_network($conf);
1215 };
1216
1217 &$change_ip_config(4);
1218 &$change_ip_config(6);
1219
1220 }
1221
1222 my $open_namespace = sub {
1223 my ($vmid, $pid, $kind) = @_;
1224 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1225 or die "failed to open $kind namespace of container $vmid: $!\n";
1226 return $fd;
1227 };
1228
1229 my $enter_namespace = sub {
1230 my ($vmid, $pid, $kind, $type) = @_;
1231 my $fd = $open_namespace->($vmid, $pid, $kind);
1232 PVE::Tools::setns(fileno($fd), $type)
1233 or die "failed to enter $kind namespace of container $vmid: $!\n";
1234 close $fd;
1235 };
1236
1237 my $get_container_namespace = sub {
1238 my ($vmid, $pid, $kind) = @_;
1239
1240 my $pidfd;
1241 if (!defined($pid)) {
1242 # Pin the pid while we're grabbing its stuff from /proc
1243 ($pid, $pidfd) = open_lxc_pid($vmid)
1244 or die "failed to open pidfd of container $vmid\'s init process\n";
1245 }
1246
1247 return $open_namespace->($vmid, $pid, $kind);
1248 };
1249
1250 my $do_syncfs = sub {
1251 my ($vmid, $pid, $socket) = @_;
1252
1253 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
1254
1255 # Tell the parent process to start reading our /proc/mounts
1256 print {$socket} "go\n";
1257 $socket->flush();
1258
1259 # Receive /proc/self/mounts
1260 my $mountdata = do { local $/ = undef; <$socket> };
1261 close $socket;
1262
1263 my %nosyncfs = (
1264 cgroup => 1,
1265 cgroup2 => 1,
1266 devtmpfs => 1,
1267 devpts => 1,
1268 'fuse.lxcfs' => 1,
1269 fusectl => 1,
1270 mqueue => 1,
1271 proc => 1,
1272 sysfs => 1,
1273 tmpfs => 1,
1274 );
1275
1276 # Now sync all mountpoints...
1277 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
1278 foreach my $mp (@$mounts) {
1279 my ($what, $dir, $fs) = @$mp;
1280 next if $nosyncfs{$fs};
1281 eval { PVE::Tools::sync_mountpoint($dir); };
1282 warn $@ if $@;
1283 }
1284 };
1285
1286 sub sync_container_namespace {
1287 my ($vmid) = @_;
1288 my $pid = find_lxc_pid($vmid);
1289
1290 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1291 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
1292 or die "failed to create socketpair: $!\n";
1293
1294 my $child = fork();
1295 die "fork failed: $!\n" if !defined($child);
1296
1297 if (!$child) {
1298 eval {
1299 close $pfd;
1300 &$do_syncfs($vmid, $pid, $cfd);
1301 };
1302 if (my $err = $@) {
1303 warn $err;
1304 POSIX::_exit(1);
1305 }
1306 POSIX::_exit(0);
1307 }
1308 close $cfd;
1309 my $go = <$pfd>;
1310 die "failed to enter container namespace\n" if $go ne "go\n";
1311
1312 open my $mounts, '<', "/proc/$child/mounts"
1313 or die "failed to open container's /proc/mounts: $!\n";
1314 my $mountdata = do { local $/ = undef; <$mounts> };
1315 close $mounts;
1316 print {$pfd} $mountdata;
1317 close $pfd;
1318
1319 while (waitpid($child, 0) != $child) {}
1320 die "failed to sync container namespace\n" if $? != 0;
1321 }
1322
1323 sub template_create {
1324 my ($vmid, $conf) = @_;
1325
1326 my $storecfg = PVE::Storage::config();
1327
1328 PVE::LXC::Config->foreach_volume($conf, sub {
1329 my ($ms, $mountpoint) = @_;
1330
1331 my $volid = $mountpoint->{volume};
1332
1333 die "Template feature is not available for '$volid'\n"
1334 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
1335 });
1336
1337 PVE::LXC::Config->foreach_volume($conf, sub {
1338 my ($ms, $mountpoint) = @_;
1339
1340 my $volid = $mountpoint->{volume};
1341
1342 PVE::Storage::activate_volumes($storecfg, [$volid]);
1343
1344 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
1345 $mountpoint->{volume} = $template_volid;
1346 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1347 });
1348
1349 PVE::LXC::Config->write_config($vmid, $conf);
1350 }
1351
1352 sub check_ct_modify_config_perm {
1353 my ($rpcenv, $authuser, $vmid, $pool, $oldconf, $newconf, $delete, $unprivileged) = @_;
1354
1355 return 1 if $authuser eq 'root@pam';
1356 my $storage_cfg = PVE::Storage::config();
1357
1358 my $check = sub {
1359 my ($opt, $delete) = @_;
1360 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
1361 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
1362 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
1363 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
1364 return if $delete;
1365 my $data = PVE::LXC::Config->parse_volume($opt, $newconf->{$opt});
1366 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
1367 if $data->{type} ne 'volume';
1368 my $volid = $data->{volume};
1369 if ($volid =~ $NEW_DISK_RE) {
1370 my $sid = $1;
1371 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
1372 } else {
1373 PVE::Storage::check_volume_access(
1374 $rpcenv,
1375 $authuser,
1376 $storage_cfg,
1377 $vmid,
1378 $volid,
1379 'rootdir',
1380 );
1381 }
1382 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1383 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1384 } elsif ($opt =~ m/^net\d+$/) {
1385 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1386 check_bridge_access($rpcenv, $authuser, $oldconf->{$opt}) if $oldconf->{$opt};
1387 check_bridge_access($rpcenv, $authuser, $newconf->{$opt}) if $newconf->{$opt};
1388 } elsif ($opt =~ m/^dev\d+$/) {
1389 raise_perm_exc("configuring device passthrough is only allowed for root\@pam");
1390 } elsif ($opt eq 'nameserver' || $opt eq 'searchdomain' || $opt eq 'hostname') {
1391 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
1392 } elsif ($opt eq 'features') {
1393 raise_perm_exc("changing feature flags for privileged container is only allowed for root\@pam")
1394 if !$unprivileged;
1395
1396 my $nesting_changed = 0;
1397 my $other_changed = 0;
1398 if (!$delete) {
1399 my $features = PVE::LXC::Config->parse_features($newconf->{$opt});
1400 if (defined($oldconf) && $oldconf->{$opt}) {
1401 # existing container with features
1402 my $old_features = PVE::LXC::Config->parse_features($oldconf->{$opt});
1403 for my $feature ((keys %$old_features, keys %$features)) {
1404 my $old = $old_features->{$feature} // '';
1405 my $new = $features->{$feature} // '';
1406 if ($old ne $new) {
1407 if ($feature eq 'nesting') {
1408 $nesting_changed = 1;
1409 next;
1410 } else {
1411 $other_changed = 1;
1412 last;
1413 }
1414 }
1415 }
1416 } else {
1417 # new container or no features defined
1418 if (scalar(keys %$features) == 1 && $features->{nesting}) {
1419 $nesting_changed = 1;
1420 } elsif (scalar(keys %$features) > 0) {
1421 $other_changed = 1;
1422 }
1423 }
1424 } else {
1425 my $features = PVE::LXC::Config->parse_features($oldconf->{$opt});
1426 if (scalar(keys %$features) == 1 && $features->{nesting}) {
1427 $nesting_changed = 1;
1428 } elsif (scalar(keys %$features) > 0) {
1429 $other_changed = 1;
1430 }
1431 }
1432 raise_perm_exc("changing feature flags (except nesting) is only allowed for root\@pam")
1433 if $other_changed;
1434 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Allocate'])
1435 if $nesting_changed;
1436 } elsif ($opt eq 'hookscript') {
1437 # For now this is restricted to root@pam
1438 raise_perm_exc("changing the hookscript is only allowed for root\@pam");
1439 } elsif ($opt eq 'tags') {
1440 my $old = $oldconf->{$opt};
1441 my $new = $delete ? '' : $newconf->{$opt};
1442 PVE::GuestHelpers::assert_tag_permissions($vmid, $old, $new, $rpcenv, $authuser);
1443 } else {
1444 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1445 }
1446 };
1447
1448 foreach my $opt (keys %$newconf) {
1449 &$check($opt, 0);
1450 }
1451 foreach my $opt (@$delete) {
1452 &$check($opt, 1);
1453 }
1454
1455 return 1;
1456 }
1457
1458 sub check_bridge_access {
1459 my ($rpcenv, $authuser, $raw) = @_;
1460
1461 return 1 if $authuser eq 'root@pam';
1462
1463 my $net = PVE::LXC::Config->parse_lxc_network($raw);
1464 my ($bridge, $tag, $trunks) = $net->@{'bridge', 'tag', 'trunks'};
1465 check_vnet_access($rpcenv, $authuser, $bridge, $tag, $trunks);
1466
1467 return 1;
1468 };
1469
1470 sub umount_all {
1471 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
1472
1473 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1474 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
1475
1476 my $res = 1;
1477
1478 PVE::LXC::Config->foreach_volume_full($conf, {'reverse' => 1}, sub {
1479 my ($ms, $mountpoint) = @_;
1480
1481 my $volid = $mountpoint->{volume};
1482 my $mount = $mountpoint->{mp};
1483
1484 return if !$volid || !$mount;
1485
1486 my $mount_path = "$rootdir/$mount";
1487 $mount_path =~ s!/+!/!g;
1488
1489 return if !PVE::ProcFSTools::is_mounted($mount_path);
1490
1491 eval {
1492 PVE::Tools::run_command(['umount', '-d', $mount_path]);
1493 };
1494 if (my $err = $@) {
1495 if ($noerr) {
1496 $res = 0;
1497 warn $err;
1498 } else {
1499 die $err;
1500 }
1501 }
1502 });
1503
1504 return $res; # tell caller if (some) umounts failed for the noerr case
1505 }
1506
1507 sub mount_all {
1508 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
1509
1510 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1511 File::Path::make_path($rootdir);
1512
1513 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
1514 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
1515
1516 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
1517
1518 eval {
1519 PVE::LXC::Config->foreach_volume($conf, sub {
1520 my ($ms, $mountpoint) = @_;
1521
1522 $mountpoint->{ro} = 0 if $ignore_ro;
1523
1524 mountpoint_mount($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
1525 });
1526 };
1527 if (my $err = $@) {
1528 warn "mounting container failed\n";
1529 umount_all($vmid, $storage_cfg, $conf, 1);
1530 die $err;
1531 }
1532
1533 return $rootdir;
1534 }
1535
1536
1537 sub mountpoint_mount_path {
1538 my ($mountpoint, $storage_cfg, $snapname) = @_;
1539
1540 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
1541 }
1542
1543 sub query_loopdev {
1544 my ($path) = @_;
1545 my $found;
1546 my $parser = sub {
1547 my $line = shift;
1548 if ($line =~ m@^(/dev/loop\d+):@) {
1549 $found = $1;
1550 }
1551 };
1552 my $cmd = ['losetup', '--associated', $path];
1553 PVE::Tools::run_command($cmd, outfunc => $parser);
1554 return $found;
1555 }
1556
1557 # Run a function with a file attached to a loop device.
1558 # The loop device is always detached afterwards (or set to autoclear).
1559 # Returns the loop device.
1560 sub run_with_loopdev {
1561 my ($func, $file, $readonly) = @_;
1562 my $device = query_loopdev($file);
1563 # Try to reuse an existing device
1564 if ($device) {
1565 # We assume that whoever setup the loop device is responsible for
1566 # detaching it.
1567 &$func($device);
1568 return $device;
1569 }
1570
1571 my $parser = sub {
1572 my $line = shift;
1573 if ($line =~ m@^(/dev/loop\d+)$@) {
1574 $device = $1;
1575 }
1576 };
1577 my $losetup_cmd = [
1578 'losetup',
1579 '--show',
1580 '-f',
1581 $file,
1582 ];
1583 push @$losetup_cmd, '-r' if $readonly;
1584 PVE::Tools::run_command($losetup_cmd, outfunc => $parser);
1585 die "failed to setup loop device for $file\n" if !$device;
1586 eval { &$func($device); };
1587 my $err = $@;
1588 PVE::Tools::run_command(['losetup', '-d', $device]);
1589 die $err if $err;
1590 return $device;
1591 }
1592
1593 # In scalar mode: returns a file handle to the deepest directory node.
1594 # In list context: returns a list of:
1595 # * the deepest directory node
1596 # * the 2nd deepest directory (parent of the above)
1597 # * directory name of the last directory
1598 # So that the path $2/$3 should lead to $1 afterwards.
1599 sub walk_tree_nofollow($$$;$$) {
1600 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1601
1602 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1603 or die "failed to open start directory $start: $!\n";
1604
1605 return walk_tree_nofollow_fd($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1606 }
1607
1608
1609 sub walk_tree_nofollow_fd($$$$;$$) {
1610 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1611
1612 # splitdir() returns '' for empty components including the leading /
1613 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1614
1615 my $fd = $start_fd;
1616 my $dir = $start_dirname;
1617 my $last_component = undef;
1618 my $second = $fd;
1619 foreach my $component (@comps) {
1620 $dir .= "/$component";
1621 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1622
1623 if (!$next) {
1624 # failed, check for symlinks and try to create the path
1625 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
1626 die "cannot open directory $dir: $!\n" if !$mkdir;
1627
1628 # We don't check for errors on mkdirat() here and just try to
1629 # openat() again, since at least one error (EEXIST) is an
1630 # expected possibility if multiple containers start
1631 # simultaneously. If someone else injects a symlink now then
1632 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1633 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1634
1635 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1636 die "failed to create path: $dir: $!\n" if !$next;
1637
1638 PVE::Tools::fchownat(fileno($next), '', $rootuid, $rootgid, PVE::Tools::AT_EMPTY_PATH)
1639 if defined($rootuid) && defined($rootgid);
1640 }
1641
1642 close $second if defined($last_component) && $second != $start_fd;
1643 $last_component = $component;
1644 $second = $fd;
1645 $fd = $next;
1646 }
1647
1648 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1649 close $second if defined($last_component) && $second != $start_fd;
1650 return $fd;
1651 }
1652
1653 # To guard against symlink attack races against other currently running
1654 # containers with shared recursive bind mount hierarchies we prepare a
1655 # directory handle for the directory we're mounting over to verify the
1656 # mountpoint afterwards.
1657 sub __bindmount_prepare {
1658 my ($hostroot, $dir) = @_;
1659 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1660 return $srcdh;
1661 }
1662
1663 # Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1664 # ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1665 # we intended to bind mount.
1666 sub __bindmount_verify {
1667 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
1668 my $destdh;
1669 if ($parentfd) {
1670 # Open the mount point path coming from the parent directory since the
1671 # filehandle we would have gotten as first result of walk_tree_nofollow
1672 # earlier is still a handle to the underlying directory instead of the
1673 # mounted path.
1674 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1675 die "failed to open mount point: $!\n" if !$destdh;
1676 if ($ro) {
1677 my $dot = '.';
1678 # no separate function because 99% of the time it's the wrong thing to use.
1679 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
1680 die "failed to mark bind mount read only\n";
1681 }
1682 die "read-only check failed: $!\n" if $! != EROFS;
1683 }
1684 } else {
1685 # For the rootfs we don't have a parentfd so we open the path directly.
1686 # Note that this means bindmounting any prefix of the host's
1687 # /var/lib/lxc/$vmid path into another container is considered a grave
1688 # security error.
1689 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
1690 die "failed to open mount point: $!\n" if !$destdh;
1691 }
1692
1693 my ($srcdev, $srcinode) = stat($srcdh);
1694 my ($dstdev, $dstinode) = stat($destdh);
1695 close $srcdh;
1696 close $destdh;
1697
1698 return ($srcdev == $dstdev && $srcinode == $dstinode);
1699 }
1700
1701 # Perform the actual bind mounting:
1702 sub __bindmount_do {
1703 my ($dir, $dest, $ro, @extra_opts) = @_;
1704 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1705 if ($ro) {
1706 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1707 if (my $err = $@) {
1708 warn "bindmount error\n";
1709 # don't leave writable bind-mounts behind...
1710 PVE::Tools::run_command(['umount', $dest]);
1711 die $err;
1712 }
1713 }
1714 }
1715
1716 sub bindmount {
1717 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1718
1719 my $srcdh = __bindmount_prepare('/', $dir);
1720
1721 __bindmount_do($dir, $dest, $ro, @extra_opts);
1722
1723 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
1724 PVE::Tools::run_command(['umount', $dest]);
1725 die "detected mount path change at: $dir\n";
1726 }
1727 }
1728
1729 # Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1730 # from $rootdir and $mount and walk the path from $rootdir to the final
1731 # directory to check for symlinks.
1732 sub __mount_prepare_rootdir {
1733 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
1734 $rootdir =~ s!/+!/!g;
1735 $rootdir =~ s!/+$!!;
1736 my $mount_path = "$rootdir/$mount";
1737 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1, $rootuid, $rootgid);
1738 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1739 }
1740
1741 # use $rootdir = undef to just return the corresponding mount path
1742 sub mountpoint_mount {
1743 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1744 return __mountpoint_mount($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1745 }
1746
1747 sub mountpoint_stage {
1748 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1749 my ($path, $loop, $dev) =
1750 __mountpoint_mount($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1751
1752 if (!defined($path)) {
1753 die "failed to mount subvolume: $!\n";
1754 }
1755
1756 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1757 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1758 # point).
1759 my $err;
1760 my $fd = PVE::Tools::open_tree(&AT_FDCWD, $stage_dir, &OPEN_TREE_CLOEXEC | &OPEN_TREE_CLONE)
1761 or die "open_tree() on mount point failed: $!\n";
1762
1763 return wantarray ? ($path, $loop, $dev, $fd) : $fd;
1764 }
1765
1766 sub mountpoint_insert_staged {
1767 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1768
1769 if (!defined($rootdir_fd)) {
1770 sysopen($rootdir_fd, '.', O_PATH | O_DIRECTORY)
1771 or die "failed to open '.': $!\n";
1772 }
1773
1774 my $dest_fd = walk_tree_nofollow_fd('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1775
1776 PVE::Tools::move_mount(
1777 fileno($mount_fd),
1778 '',
1779 fileno($dest_fd),
1780 '',
1781 &MOVE_MOUNT_F_EMPTY_PATH | &MOVE_MOUNT_T_EMPTY_PATH,
1782 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1783 }
1784
1785 # Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1786 # can then open a file descriptor to it which can be used with the `move_mount` syscall.
1787 sub __mountpoint_mount {
1788 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1789
1790 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1791 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1792 # which we use in __bindmount_verify()!
1793 my $mount = $stage_mount ? '/': $mountpoint->{mp};
1794
1795 my $volid = $mountpoint->{volume};
1796 my $type = $mountpoint->{type};
1797 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1798 my $mounted_dev;
1799
1800 return if !$volid || !$mount;
1801
1802 $mount =~ s!/+!/!g;
1803
1804 my $mount_path;
1805 my ($mpfd, $parentfd, $last_dir);
1806
1807 if (defined($rootdir)) {
1808 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1809 __mount_prepare_rootdir($rootdir, $mount, $rootuid, $rootgid);
1810 }
1811
1812 if (defined($stage_mount)) {
1813 $mount_path = $rootdir;
1814 }
1815
1816 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1817
1818 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
1819
1820 my $optlist = [];
1821
1822 if (my $mountopts = $mountpoint->{mountoptions}) {
1823 my @opts = split(/;/, $mountpoint->{mountoptions});
1824 push @$optlist, grep { PVE::LXC::Config::is_valid_mount_option($_) } @opts;
1825 }
1826
1827 my $acl = $mountpoint->{acl};
1828 if (defined($acl)) {
1829 push @$optlist, ($acl ? 'acl' : 'noacl');
1830 }
1831
1832 my $optstring = join(',', @$optlist);
1833 my $readonly = $mountpoint->{ro};
1834
1835 my @extra_opts;
1836 @extra_opts = ('-o', $optstring) if $optstring;
1837
1838 if ($storage) {
1839
1840 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
1841
1842 PVE::Storage::activate_volumes($storage_cfg, [$volid], $snapname);
1843 my $path = PVE::Storage::map_volume($storage_cfg, $volid, $snapname);
1844
1845 $path = PVE::Storage::path($storage_cfg, $volid, $snapname) if !defined($path);
1846
1847 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1848 PVE::Storage::parse_volname($storage_cfg, $volid);
1849
1850 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1851
1852 if ($format eq 'subvol') {
1853 if ($mount_path) {
1854 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1855 if (defined($snapname)) {
1856 $name .= "\@$snapname";
1857 if ($scfg->{type} eq 'zfspool') {
1858 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', "$scfg->{pool}/$name", $mount_path]);
1859 } else {
1860 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1861 }
1862 } else {
1863 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1864 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1865 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1866 }
1867 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
1868 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
1869 }
1870 }
1871 return wantarray ? ($path, 0, undef) : $path;
1872 } elsif ($format eq 'raw' || $format eq 'iso') {
1873 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1874 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1875 # Our autodev hook expects the /dev/dm-* device currently
1876 # and will create the /dev/mapper symlink accordingly
1877 $path = Cwd::realpath($path);
1878 die "failed to get device path\n" if !$path;
1879 ($path) = ($path =~ /^(.*)$/s); #untaint
1880 my $domount = sub {
1881 my ($path) = @_;
1882 if ($mount_path) {
1883 if ($format eq 'iso') {
1884 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1885 } elsif ($isBase || defined($snapname)) {
1886 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1887 } else {
1888 if ($quota) {
1889 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1890 }
1891 push @extra_opts, '-o', 'ro' if $readonly;
1892 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1893 }
1894 }
1895 };
1896 my $use_loopdev = 0;
1897 if ($scfg->{content}->{rootdir}) {
1898 if ($scfg->{path}) {
1899 $mounted_dev = run_with_loopdev($domount, $path, $readonly);
1900 $use_loopdev = 1;
1901 } else {
1902 $mounted_dev = $path;
1903 &$domount($path);
1904 }
1905 } else {
1906 die "storage '$storage' does not support containers\n";
1907 }
1908 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
1909 } else {
1910 die "unsupported image format '$format'\n";
1911 }
1912 } elsif ($type eq 'device') {
1913 push @extra_opts, '-o', 'ro' if $readonly;
1914 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1915 # See the NOTE above about devicemapper canonicalization
1916 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
1917 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
1918 return wantarray ? ($volid, 0, $devpath) : $volid;
1919 } elsif ($type eq 'bind') {
1920 die "directory '$volid' does not exist\n" if ! -d $volid;
1921 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
1922 warn "cannot enable quota control for bind mounts\n" if $quota;
1923 return wantarray ? ($volid, 0, undef) : $volid;
1924 }
1925
1926 die "unsupported storage";
1927 }
1928
1929 sub mountpoint_hotplug :prototype($$$$$) {
1930 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1931
1932 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1933
1934 # We do the rest in a fork with an unshared mount namespace, because:
1935 # -) change our papparmor profile to that of /usr/bin/lxc-start
1936 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1937 # container's namespace, then mount it.
1938
1939 PVE::Tools::run_fork(sub {
1940 # Pin the container pid longer, we also need to get its monitor/parent:
1941 my ($ct_pid, $ct_pidfd) = open_lxc_pid($vmid)
1942 or die "failed to open pidfd of container $vmid\'s init process\n";
1943
1944 my ($monitor_pid, $monitor_pidfd) = open_ppid($ct_pid)
1945 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1946
1947 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1948 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1949
1950 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1951 # profile to lower our privileges to the same level we have in the start hook:
1952 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY)
1953 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1954 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1955 # apparmor.
1956
1957 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1958 # namespace for it to remain active there since the container will be able to unmount
1959 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1960 # concern.
1961 PVE::Tools::setns(fileno($monitor_mnt_ns), PVE::Tools::CLONE_NEWNS);
1962 chdir('/')
1963 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1964
1965 my $dir = get_staging_mount_path($opt);
1966
1967 # Now switch our apparmor profile before mounting:
1968 my $data = 'changeprofile pve-container-mounthotplug';
1969 my $data_written = syswrite($aa_fd, $data, length($data));
1970 if (!defined($data_written) || $data_written != length($data)) {
1971 die "failed to change apparmor profile: $!\n";
1972 }
1973 # Check errors on close as well:
1974 close($aa_fd)
1975 or die "failed to change apparmor profile (close() failed): $!\n";
1976
1977 my $mount_fd = mountpoint_stage($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1978
1979 PVE::Tools::setns(fileno($ct_mnt_ns), PVE::Tools::CLONE_NEWNS);
1980 chdir('/')
1981 or die "failed to change root directory within the container's mount namespace: $!\n";
1982
1983 mountpoint_insert_staged($mount_fd, undef, $mp->{mp}, $opt, $rootuid, $rootgid);
1984 });
1985 }
1986
1987 # Create a directory in the mountpoint staging tempfs.
1988 sub get_staging_mount_path($) {
1989 my ($opt) = @_;
1990
1991 my $target = get_staging_tempfs() . "/$opt";
1992 if (!mkdir($target) && $! != EEXIST) {
1993 die "failed to create directory $target: $!\n";
1994 }
1995
1996 return $target;
1997 }
1998
1999 # Mount tmpfs for mount point staging and return the path.
2000 sub get_staging_tempfs() {
2001 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
2002 # mounts to that.
2003 my $target = '/var/lib/lxc/.pve-staged-mounts';
2004 if (!mkdir($target)) {
2005 return $target if $! == EEXIST;
2006 die "failed to create directory $target: $!\n";
2007 }
2008
2009 PVE::Tools::mount("none", $target, 'tmpfs', 0, "size=8k,mode=755")
2010 or die "failed to mount $target as tmpfs: $!\n";
2011
2012 return $target;
2013 }
2014
2015 sub mkfs {
2016 my ($dev, $rootuid, $rootgid) = @_;
2017
2018 run_command(
2019 [
2020 'mkfs.ext4',
2021 '-O',
2022 'mmp',
2023 '-E',
2024 "root_owner=$rootuid:$rootgid",
2025 $dev,
2026 ],
2027 outfunc => sub {
2028 my $line = shift;
2029 # a hack to print only the relevant stuff, i.e., the one which could help on repair
2030 if ($line =~ /^(Creating filesystem|Filesystem UUID|Superblock backups|\s+\d+, \d)/) {
2031 print "$line\n";
2032 }
2033 },
2034 errfunc => sub {
2035 my $line = shift;
2036 print STDERR "$line\n" if $line && $line !~ /^mke2fs \d\.\d/;
2037 }
2038 );
2039 }
2040
2041 sub format_disk {
2042 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
2043
2044 if ($volid =~ m!^/dev/.+!) {
2045 mkfs($volid);
2046 return;
2047 }
2048
2049 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2050
2051 die "cannot format volume '$volid' with no storage\n" if !$storage;
2052
2053 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
2054
2055 my $path = PVE::Storage::map_volume($storage_cfg, $volid);
2056
2057 $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
2058
2059 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
2060 PVE::Storage::parse_volname($storage_cfg, $volid);
2061
2062 die "cannot format volume '$volid' (format == $format)\n"
2063 if $format ne 'raw';
2064
2065 mkfs($path, $rootuid, $rootgid);
2066 }
2067
2068 sub destroy_disks {
2069 my ($storecfg, $vollist) = @_;
2070
2071 foreach my $volid (@$vollist) {
2072 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2073 warn $@ if $@;
2074 }
2075 }
2076
2077 sub alloc_disk {
2078 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
2079
2080 my $needs_chown = 0;
2081 my $volid;
2082
2083 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
2084 # fixme: use better naming ct-$vmid-disk-X.raw?
2085
2086 eval {
2087 my $do_format = 0;
2088 if ($scfg->{content}->{rootdir} && $scfg->{path}) {
2089 if ($size_kb > 0 && !($scfg->{type} eq 'btrfs' && $scfg->{quotas})) {
2090 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2091 $do_format = 1;
2092 } else {
2093 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
2094 $needs_chown = 1;
2095 }
2096 } elsif ($scfg->{type} eq 'zfspool') {
2097 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
2098 $needs_chown = 1;
2099 } elsif ($scfg->{content}->{rootdir}) {
2100 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2101 $do_format = 1;
2102 } else {
2103 die "content type 'rootdir' is not available or configured on storage '$storage'\n";
2104 }
2105 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
2106 };
2107 if (my $err = $@) {
2108 # in case formatting got interrupted:
2109 if (defined($volid)) {
2110 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2111 warn $@ if $@;
2112 }
2113 die $err;
2114 }
2115
2116 return ($volid, $needs_chown);
2117 }
2118
2119 sub create_disks {
2120 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
2121
2122 my $vollist = [];
2123
2124 eval {
2125 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
2126 my $chown_vollist = [];
2127
2128 PVE::LXC::Config->foreach_volume($settings, sub {
2129 my ($ms, $mountpoint) = @_;
2130
2131 my $volid = $mountpoint->{volume};
2132 my $mp = $mountpoint->{mp};
2133
2134 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2135
2136 if ($storage && ($volid =~ $NEW_DISK_RE)) {
2137 my ($storeid, $size_gb) = ($1, $2);
2138
2139 my $size_kb = int(${size_gb}*1024) * 1024;
2140
2141 my $needs_chown = 0;
2142 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
2143 push @$chown_vollist, $volid if $needs_chown;
2144 push @$vollist, $volid;
2145 $mountpoint->{volume} = $volid;
2146 $mountpoint->{size} = $size_kb * 1024;
2147 if ($pending) {
2148 $conf->{pending}->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2149 } else {
2150 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2151 }
2152 } else {
2153 # use specified/existing volid/dir/device
2154 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2155 }
2156 });
2157
2158 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
2159 foreach my $volid (@$chown_vollist) {
2160 my $path = PVE::Storage::path($storecfg, $volid, undef);
2161 chown($rootuid, $rootgid, $path);
2162 }
2163 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
2164 };
2165 # free allocated images on error
2166 if (my $err = $@) {
2167 destroy_disks($storecfg, $vollist);
2168 die $err;
2169 }
2170 return $vollist;
2171 }
2172
2173 sub update_disksize {
2174 my ($vmid, $conf, $all_volumes) = @_;
2175
2176 my $changes;
2177 my $prefix = "CT $vmid:";
2178
2179 my $update_mp = sub {
2180 my ($key, $mp, @param) = @_;
2181 my $size = $all_volumes->{$mp->{volume}}->{size} // 0;
2182
2183 if (!defined($mp->{size}) || $size != $mp->{size}) {
2184 $changes = 1;
2185 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
2186 $mp->{size} = $size;
2187 my $no_mp = $key eq 'rootfs'; # rootfs is handled different from other mount points
2188 $conf->{$key} = PVE::LXC::Config->print_ct_mountpoint($mp, $no_mp);
2189 }
2190 };
2191
2192 PVE::LXC::Config->foreach_volume($conf, $update_mp);
2193
2194 return $changes;
2195 }
2196
2197 sub update_unused {
2198 my ($vmid, $conf, $all_volumes) = @_;
2199
2200 my $changes;
2201 my $prefix = "CT $vmid:";
2202
2203 # Note: it is allowed to define multiple storage entries with the same path
2204 # (alias), so we need to check both 'volid' and real 'path' (two different
2205 # volid can point to the same path).
2206
2207 # used and unused disks
2208 my $refpath = {};
2209 my $orphans = {};
2210
2211 foreach my $opt (keys %$conf) {
2212 next if ($opt !~ m/^unused\d+$/);
2213 my $vol = $all_volumes->{$conf->{$opt}};
2214 $refpath->{$vol->{path}} = $vol->{volid};
2215 }
2216
2217 foreach my $key (keys %$all_volumes) {
2218 my $vol = $all_volumes->{$key};
2219 my $in_use = PVE::LXC::Config->is_volume_in_use($conf, $vol->{volid});
2220 my $path = $vol->{path};
2221
2222 if ($in_use) {
2223 $refpath->{$path} = $key;
2224 delete $orphans->{$path};
2225 } else {
2226 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
2227 $orphans->{$path} = $key;
2228 }
2229 }
2230 }
2231
2232 for my $key (keys %$orphans) {
2233 my $disk = $orphans->{$key};
2234 my $unused = PVE::LXC::Config->add_unused_volume($conf, $disk);
2235
2236 if ($unused) {
2237 $changes = 1;
2238 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
2239 }
2240 }
2241
2242 return $changes;
2243 }
2244
2245 sub scan_volids {
2246 my ($cfg, $vmid) = @_;
2247
2248 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid, undef, 'rootdir');
2249
2250 my $all_volumes = {};
2251 foreach my $storeid (keys %$info) {
2252 foreach my $item (@{$info->{$storeid}}) {
2253 my $volid = $item->{volid};
2254 next if !($volid && $item->{size});
2255 $item->{path} = PVE::Storage::path($cfg, $volid);
2256 $all_volumes->{$volid} = $item;
2257 }
2258 }
2259
2260 return $all_volumes;
2261 }
2262
2263 sub rescan {
2264 my ($vmid, $nolock, $dryrun) = @_;
2265
2266 my $cfg = PVE::Storage::config();
2267
2268 print "rescan volumes...\n";
2269 my $all_volumes = scan_volids($cfg, $vmid);
2270
2271 my $updatefn = sub {
2272 my ($vmid) = @_;
2273
2274 my $changes;
2275 my $conf = PVE::LXC::Config->load_config($vmid);
2276
2277 PVE::LXC::Config->check_lock($conf);
2278
2279 my $vm_volids = {};
2280 foreach my $volid (keys %$all_volumes) {
2281 my $info = $all_volumes->{$volid};
2282 $vm_volids->{$volid} = $info if $info->{vmid} == $vmid;
2283 }
2284
2285 my $upu = update_unused($vmid, $conf, $vm_volids);
2286 my $upd = update_disksize($vmid, $conf, $vm_volids);
2287 $changes = $upu || $upd;
2288
2289 PVE::LXC::Config->write_config($vmid, $conf) if $changes && !$dryrun;
2290 };
2291
2292 if (defined($vmid)) {
2293 if ($nolock) {
2294 &$updatefn($vmid);
2295 } else {
2296 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2297 }
2298 } else {
2299 my $vmlist = config_list();
2300 foreach my $vmid (keys %$vmlist) {
2301 if ($nolock) {
2302 &$updatefn($vmid);
2303 } else {
2304 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2305 }
2306 }
2307 }
2308 }
2309
2310
2311 # bash completion helper
2312
2313 sub complete_os_templates {
2314 my ($cmdname, $pname, $cvalue) = @_;
2315
2316 my $cfg = PVE::Storage::config();
2317
2318 my $storeid;
2319
2320 if ($cvalue =~ m/^([^:]+):/) {
2321 $storeid = $1;
2322 }
2323
2324 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
2325 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
2326
2327 my $res = [];
2328 foreach my $id (keys %$data) {
2329 foreach my $item (@{$data->{$id}}) {
2330 push @$res, $item->{volid} if defined($item->{volid});
2331 }
2332 }
2333
2334 return $res;
2335 }
2336
2337 my $complete_ctid_full = sub {
2338 my ($running) = @_;
2339
2340 my $idlist = vmstatus();
2341
2342 my $active_hash = list_active_containers();
2343
2344 my $res = [];
2345
2346 foreach my $id (keys %$idlist) {
2347 my $d = $idlist->{$id};
2348 if (defined($running)) {
2349 next if $d->{template};
2350 next if $running && !$active_hash->{$id};
2351 next if !$running && $active_hash->{$id};
2352 }
2353 push @$res, $id;
2354
2355 }
2356 return $res;
2357 };
2358
2359 sub complete_ctid {
2360 return &$complete_ctid_full();
2361 }
2362
2363 sub complete_ctid_stopped {
2364 return &$complete_ctid_full(0);
2365 }
2366
2367 sub complete_ctid_running {
2368 return &$complete_ctid_full(1);
2369 }
2370
2371 sub parse_id_maps {
2372 my ($conf) = @_;
2373
2374 my $id_map = [];
2375 my $rootuid = 0;
2376 my $rootgid = 0;
2377
2378 my $lxc = $conf->{lxc};
2379 foreach my $entry (@$lxc) {
2380 my ($key, $value) = @$entry;
2381
2382 next if $key ne 'lxc.idmap';
2383
2384 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2385 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2386 push @$id_map, [$type, $ct, $host, $length];
2387 if ($ct == 0) {
2388 $rootuid = $host if $type eq 'u';
2389 $rootgid = $host if $type eq 'g';
2390 }
2391 } else {
2392 die "failed to parse idmap: $value\n";
2393 }
2394 }
2395
2396 if (!@$id_map && $conf->{unprivileged}) {
2397 # Should we read them from /etc/subuid?
2398 $id_map = [ ['u', '0', '100000', '65536'],
2399 ['g', '0', '100000', '65536'] ];
2400 $rootuid = $rootgid = 100000;
2401 }
2402
2403 return ($id_map, $rootuid, $rootgid);
2404 }
2405
2406 sub validate_id_maps {
2407 my ($id_map) = @_;
2408
2409 # $mappings->{$type}->{$side} = [ { line => $line, start => $start, count => $count }, ... ]
2410 # $type: either "u" or "g"
2411 # $side: either "container" or "host"
2412 # $line: index of this mapping in @$id_map
2413 # $start, $count: interval of this mapping
2414 my $mappings = { u => {}, g => {} };
2415 for (my $i = 0; $i < scalar(@$id_map); $i++) {
2416 my ($type, $ct_start, $host_start, $count) = $id_map->[$i]->@*;
2417 my $sides = $mappings->{$type};
2418 push $sides->{host}->@*, { line => $i, start => $host_start, count => $count };
2419 push $sides->{container}->@*, { line => $i, start => $ct_start, count => $count };
2420 }
2421
2422 # find the first conflict between two consecutive mappings when sorted by their start id
2423 for my $type (qw(u g)) {
2424 for my $side (qw(container host)) {
2425 my @entries = sort { $a->{start} <=> $b->{start} } $mappings->{$type}->{$side}->@*;
2426 for my $idx (1..scalar(@entries) - 1) {
2427 my $previous = $entries[$idx - 1];
2428 my $current = $entries[$idx];
2429 if ($previous->{start} + $previous->{count} > $current->{start}) {
2430 my $conflict = $current->{start};
2431 my @previous_line = $id_map->[$previous->{line}]->@*;
2432 my @current_line = $id_map->[$current->{line}]->@*;
2433 die "invalid map entry '@current_line': $side ${type}id $conflict "
2434 ."is also mapped by entry '@previous_line'\n";
2435 }
2436 }
2437 }
2438 }
2439 }
2440
2441 sub map_ct_id_to_host {
2442 my ($id, $id_map, $id_type) = @_;
2443
2444 for my $mapping (@$id_map) {
2445 my ($type, $ct, $host, $length) = @$mapping;
2446
2447 next if ($type ne $id_type);
2448
2449 if ($id >= $ct && $id < ($ct + $length)) {
2450 return $host - $ct + $id;
2451 }
2452 }
2453
2454 return $id;
2455 }
2456
2457 sub map_ct_uid_to_host {
2458 my ($uid, $id_map) = @_;
2459
2460 return map_ct_id_to_host($uid, $id_map, 'u');
2461 }
2462
2463 sub map_ct_gid_to_host {
2464 my ($gid, $id_map) = @_;
2465
2466 return map_ct_id_to_host($gid, $id_map, 'g');
2467 }
2468
2469 sub userns_command {
2470 my ($id_map) = @_;
2471 if (@$id_map) {
2472 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2473 }
2474 return [];
2475 }
2476
2477 my sub print_ct_stderr_log {
2478 my ($vmid) = @_;
2479 my $log = eval { file_get_contents("/run/pve/ct-$vmid.stderr") };
2480 return if !$log;
2481
2482 while ($log =~ /^\h*(lxc-start:?\s+$vmid:?\s*\S+\s*)?(.*?)\h*$/gm) {
2483 my $line = $2;
2484 print STDERR "$line\n";
2485 }
2486 }
2487 my sub print_ct_warn_log {
2488 my ($vmid) = @_;
2489 my $log_fn = "/run/pve/ct-$vmid.warnings";
2490 my $log = eval { file_get_contents($log_fn) };
2491 return if !$log;
2492
2493 while ($log =~ /^\h*\s*(.*?)\h*$/gm) {
2494 PVE::RESTEnvironment::log_warn($1);
2495 }
2496 unlink $log_fn or warn "could not unlink '$log_fn' - $!\n";
2497 }
2498
2499 my sub monitor_state_change($$) {
2500 my ($monitor_socket, $vmid) = @_;
2501 die "no monitor socket\n" if !defined($monitor_socket);
2502
2503 while (1) {
2504 my ($type, $name, $value) = PVE::LXC::Monitor::read_lxc_message($monitor_socket);
2505
2506 die "monitor socket: got EOF\n" if !defined($type);
2507
2508 next if $name ne "$vmid" || $type ne 'STATE';
2509
2510 if ($value eq PVE::LXC::Monitor::STATE_STARTING) {
2511 alarm(0); # don't timeout after seeing the starting state
2512 } elsif ($value eq PVE::LXC::Monitor::STATE_ABORTING ||
2513 $value eq PVE::LXC::Monitor::STATE_STOPPING ||
2514 $value eq PVE::LXC::Monitor::STATE_STOPPED) {
2515 return 0;
2516 } elsif ($value eq PVE::LXC::Monitor::STATE_RUNNING) {
2517 return 1;
2518 } else {
2519 warn "unexpected message from monitor socket - " .
2520 "type: '$type' - value: '$value'\n";
2521 }
2522 }
2523 }
2524 my sub monitor_start($$) {
2525 my ($monitor_socket, $vmid) = @_;
2526
2527 my $success = eval {
2528 PVE::Tools::run_with_timeout(10, \&monitor_state_change, $monitor_socket, $vmid)
2529 };
2530 if (my $err = $@) {
2531 warn "problem with monitor socket, but continuing anyway: $err\n";
2532 } elsif (!$success) {
2533 print_ct_stderr_log($vmid);
2534 die "startup for container '$vmid' failed\n";
2535 }
2536 }
2537
2538 sub vm_start {
2539 my ($vmid, $conf, $skiplock, $debug) = @_;
2540
2541 # apply pending changes while starting
2542 if (scalar(keys %{$conf->{pending}})) {
2543 my $storecfg = PVE::Storage::config();
2544 PVE::LXC::Config->vmconfig_apply_pending($vmid, $conf, $storecfg);
2545 PVE::LXC::Config->write_config($vmid, $conf);
2546 $conf = PVE::LXC::Config->load_config($vmid); # update/reload
2547 }
2548
2549 update_lxc_config($vmid, $conf);
2550
2551 eval {
2552 my ($id_map, undef, undef) = PVE::LXC::parse_id_maps($conf);
2553 PVE::LXC::validate_id_maps($id_map);
2554 };
2555 warn "lxc.idmap: $@" if $@;
2556
2557 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2558
2559 if ($skiplock) {
2560 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2561 close($fh);
2562 }
2563
2564 my $storage_cfg = PVE::Storage::config();
2565 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
2566
2567 PVE::Storage::activate_volumes($storage_cfg, $vollist);
2568
2569 my $monitor_socket = eval { PVE::LXC::Monitor::get_monitor_socket() };
2570 warn $@ if $@;
2571
2572 unlink "/run/pve/ct-$vmid.stderr"; # systemd does not truncate log files
2573
2574 my $is_debug = $debug || (!defined($debug) && $conf->{debug});
2575 my $base_unit = $is_debug ? 'pve-container-debug' : 'pve-container';
2576
2577 my $cmd = ['systemctl', 'start', "$base_unit\@$vmid"];
2578
2579 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
2580 eval {
2581 run_command($cmd);
2582
2583 monitor_start($monitor_socket, $vmid) if defined($monitor_socket);
2584
2585 # if debug is requested, print the log it also when the start succeeded
2586 print_ct_stderr_log($vmid) if $is_debug;
2587
2588 print_ct_warn_log($vmid); # always print warn log, if any
2589 };
2590 if (my $err = $@) {
2591 unlink $skiplock_flag_fn;
2592 die $err;
2593 }
2594 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
2595
2596 return;
2597 }
2598
2599 # Helper to stop a container completely and make sure it has stopped completely.
2600 # This is necessary because we want the post-stop hook to have completed its
2601 # unmount-all step, but post-stop happens after lxc puts the container into the
2602 # STOPPED state.
2603 # $kill - if true it will always do an immediate hard-stop
2604 # $shutdown_timeout - the timeout to wait for a gracefull shutdown
2605 # $kill_after_timeout - if true, send a hardstop if shutdown timed out
2606 sub vm_stop {
2607 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
2608
2609 # Open the container's command socket.
2610 my $path = "\0/var/lib/lxc/$vmid/command";
2611 my $sock = IO::Socket::UNIX->new(
2612 Type => SOCK_STREAM(),
2613 Peer => $path,
2614 );
2615 if (!$sock) {
2616 return if $! == ECONNREFUSED; # The container is not running
2617 die "failed to open container ${vmid}'s command socket: $!\n";
2618 }
2619
2620 my $conf = PVE::LXC::Config->load_config($vmid);
2621 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
2622
2623 # Stop the container:
2624
2625 my $cmd = ['lxc-stop', '-n', $vmid];
2626
2627 if ($kill) {
2628 push @$cmd, '--kill'; # doesn't allow timeouts
2629 } else {
2630 # lxc-stop uses a default timeout
2631 push @$cmd, '--nokill' if !$kill_after_timeout;
2632
2633 if (defined($shutdown_timeout)) {
2634 push @$cmd, '--timeout', $shutdown_timeout;
2635 # Give run_command 5 extra seconds
2636 $shutdown_timeout += 5;
2637 }
2638 }
2639
2640 eval { run_command($cmd, timeout => $shutdown_timeout) };
2641
2642 # Wait until the command socket is closed.
2643 # In case the lxc-stop call failed, reading from the command socket may block forever,
2644 # so poll with another timeout to avoid freezing the shutdown task.
2645 if (my $err = $@) {
2646 warn $err if $err;
2647
2648 my $poll = IO::Poll->new();
2649 $poll->mask($sock => POLLIN | POLLHUP); # watch for input and EOF events
2650 $poll->poll($shutdown_timeout); # IO::Poll timeout is in seconds
2651 return if ($poll->events($sock) & POLLHUP);
2652 } else {
2653 my $result = <$sock>;
2654 return if !defined $result; # monitor is gone and the ct has stopped.
2655 }
2656
2657 die "container did not stop\n";
2658 }
2659
2660 sub vm_reboot {
2661 my ($vmid, $timeout, $skiplock) = @_;
2662
2663 PVE::LXC::Config->lock_config($vmid, sub {
2664 return if !check_running($vmid);
2665
2666 vm_stop($vmid, 0, $timeout, 1); # kill if timeout exceeds
2667
2668 my $conf = PVE::LXC::Config->load_config($vmid);
2669 vm_start($vmid, $conf);
2670 });
2671 }
2672
2673 sub run_unshared {
2674 my ($code) = @_;
2675
2676 return PVE::Tools::run_fork(sub {
2677 # Unshare the mount namespace
2678 die "failed to unshare mount namespace: $!\n"
2679 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
2680 run_command(['mount', '--make-rslave', '/']);
2681 return $code->();
2682 });
2683 }
2684
2685 my $copy_volume = sub {
2686 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
2687
2688 my $src_mp = { volume => $src_volid, mp => '/', ro => 1 };
2689 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
2690
2691 my $dst_mp = { volume => $dst_volid, mp => '/', ro => 0 };
2692 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
2693
2694 my @mounted;
2695 eval {
2696 # mount and copy
2697 mkdir $src;
2698 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
2699 push @mounted, $src;
2700 mkdir $dest;
2701 mountpoint_mount($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
2702 push @mounted, $dest;
2703
2704 $bwlimit //= 0;
2705
2706 run_command([
2707 'rsync',
2708 '--stats',
2709 '-X',
2710 '-A',
2711 '--numeric-ids',
2712 '-aH',
2713 '--whole-file',
2714 '--sparse',
2715 '--one-file-system',
2716 "--bwlimit=$bwlimit",
2717 "$src/",
2718 $dest
2719 ]);
2720 };
2721 my $err = $@;
2722
2723 # Wait for rsync's children to release dest so that
2724 # consequent file operations (umount, remove) are possible
2725 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2726
2727 foreach my $mount (reverse @mounted) {
2728 eval { run_command(['/bin/umount', $mount], errfunc => sub{})};
2729 warn "Can't umount $mount\n" if $@;
2730 }
2731
2732 # If this fails they're used as mount points in a concurrent operation
2733 # (which should not happen but there's also no real need to get rid of them).
2734 rmdir $dest;
2735 rmdir $src;
2736
2737 die $err if $err;
2738 };
2739
2740 # Should not be called after unsharing the mount namespace!
2741 sub copy_volume {
2742 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
2743
2744 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
2745 File::Path::make_path("/var/lib/lxc/$vmid");
2746 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2747 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2748
2749 # get id's for unprivileged container
2750 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
2751
2752 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2753 # are visible in this namespace, otherwise the host only sees the empty
2754 # (not-mounted) directory.
2755 my $new_volid;
2756 eval {
2757 # Make sure $mp contains a correct size.
2758 $mp->{size} = PVE::Storage::volume_size_info($storage_cfg, $mp->{volume});
2759 my $needs_chown;
2760 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
2761 if ($needs_chown) {
2762 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
2763 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
2764 chown($rootuid, $rootgid, $path);
2765 }
2766
2767 run_unshared(sub {
2768 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
2769 });
2770 };
2771 if (my $err = $@) {
2772 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
2773 if defined($new_volid);
2774 die $err;
2775 }
2776
2777 return $new_volid;
2778 }
2779
2780 sub get_lxc_version() {
2781 my $version;
2782 run_command([qw(lxc-start --version)], outfunc => sub {
2783 my ($line) = @_;
2784 # We only parse out major & minor version numbers.
2785 if ($line =~ /^(\d+)\.(\d+)(?:\D.*)?$/) {
2786 $version = [$1, $2];
2787 }
2788 });
2789
2790 die "failed to get lxc version\n" if !defined($version);
2791
2792 # return as a list:
2793 return $version->@*;
2794 }
2795
2796 sub freeze($) {
2797 my ($vmid) = @_;
2798 if (PVE::CGroup::cgroup_mode() == 2) {
2799 PVE::LXC::Command::freeze($vmid, 30);
2800 } else {
2801 PVE::LXC::CGroup->new($vmid)->freeze_thaw(1);
2802 }
2803 }
2804
2805 sub thaw($) {
2806 my ($vmid) = @_;
2807 if (PVE::CGroup::cgroup_mode() == 2) {
2808 PVE::LXC::Command::unfreeze($vmid, 30);
2809 } else {
2810 PVE::LXC::CGroup->new($vmid)->freeze_thaw(0);
2811 }
2812 }
2813
2814 sub create_ifaces_ipams_ips {
2815 my ($conf, $vmid) = @_;
2816
2817 return if !$have_sdn;
2818
2819 for my $opt (keys %$conf) {
2820 next if $opt !~ m/^net(\d+)$/;
2821 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
2822 next if $net->{type} ne 'veth';
2823 PVE::Network::SDN::Vnets::add_next_free_cidr($net->{bridge}, $conf->{hostname}, $net->{hwaddr}, $vmid, undef, 1);
2824 }
2825 }
2826
2827 sub delete_ifaces_ipams_ips {
2828 my ($conf, $vmid) = @_;
2829
2830 return if !$have_sdn;
2831
2832 for my $opt (keys %$conf) {
2833 next if $opt !~ m/^net(\d+)$/;
2834 my $net = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
2835 eval { PVE::Network::SDN::Vnets::del_ips_from_mac($net->{bridge}, $net->{hwaddr}, $conf->{hostname}) };
2836 warn $@ if $@;
2837 }
2838 }
2839
2840 1;