]> git.proxmox.com Git - pve-container.git/blame - src/PVE/LXC.pm
hotplug net: whitespace/indentation fixup
[pve-container.git] / src / PVE / LXC.pm
CommitLineData
f76a2828
DM
1package PVE::LXC;
2
3use strict;
4use warnings;
67afe46e 5
d14a9a1b 6use POSIX qw(EINTR);
f76a2828 7
34fdb3d7
WB
8use Socket;
9
f76a2828 10use File::Path;
2cfae16e
WB
11use File::Spec;
12use Cwd qw();
172ea186 13use Fcntl qw(O_RDONLY O_WRONLY O_NOFOLLOW O_DIRECTORY);
180c05c5 14use Errno qw(ELOOP ENOTDIR EROFS ECONNREFUSED ENOSYS EEXIST);
b1bad293 15use IO::Socket::UNIX;
0d1d137e 16use IO::Poll qw(POLLIN POLLHUP);
f76a2828 17
f1ba1a4b 18use PVE::Exception qw(raise_perm_exc);
c65e0a6d 19use PVE::Storage;
f76a2828
DM
20use PVE::SafeSyslog;
21use PVE::INotify;
8233d33d 22use PVE::JSONSchema qw(get_standard_option);
2df08734 23use PVE::Tools qw(
10937f87
TL
24 run_command
25 dir_glob_foreach
26 file_get_contents
27 file_set_contents
28 AT_FDCWD
29 O_PATH
30 $IPV4RE
31 $IPV6RE
2df08734 32);
92902047 33use PVE::CpuSet;
68fba17b 34use PVE::Network;
52389a07 35use PVE::AccessControl;
228a5a1d 36use PVE::ProcFSTools;
0e0ae7e0 37use PVE::RESTEnvironment;
ef447944 38use PVE::Syscall qw(:fsmount);
67afe46e 39use PVE::LXC::Config;
e954d016 40use PVE::GuestHelpers qw(safe_string_ne safe_num_ne safe_boolean_ne);
ef447944 41use PVE::LXC::Tools;
0b1b12e0 42use PVE::LXC::CGroup;
abaa24bd 43use PVE::LXC::Monitor;
85ccb17f 44use PVE::CGroup;
8233d33d 45
688afc63 46use Time::HiRes qw (gettimeofday);
ab2ec461
AD
47my $have_sdn;
48eval {
49 require PVE::Network::SDN::Zones;
50 $have_sdn = 1;
51};
f76a2828 52
5a63f1c5
WB
53my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
54
27916659
DM
55my $nodename = PVE::INotify::nodename();
56
688afc63
WL
57my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
58
c824fbed
FG
59our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
60
f76a2828
DM
61sub 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';
8233d33d 72 $res->{$vmid} = { type => 'lxc', vmid => $vmid };
f76a2828
DM
73 }
74 return $res;
75}
76
822de0c3
DM
77# container status helpers
78
79sub list_active_containers {
cbb03fea 80
822de0c3
DM
81 my $filename = "/proc/net/unix";
82
83 # similar test is used by lcxcontainers.c: list_active_containers
84 my $res = {};
cbb03fea 85
822de0c3
DM
86 my $fh = IO::File->new ($filename, "r");
87 return $res if !$fh;
88
89 while (defined(my $line = <$fh>)) {
28df2cde 90 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
822de0c3 91 my $path = $1;
27916659 92 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
822de0c3
DM
93 $res->{$1} = 1;
94 }
95 }
96 }
97
98 close($fh);
cbb03fea 99
822de0c3
DM
100 return $res;
101}
f76a2828 102
5c752bbf
DM
103# warning: this is slow
104sub check_running {
105 my ($vmid) = @_;
106
107 my $active_hash = list_active_containers();
108
109 return 1 if defined($active_hash->{$vmid});
cbb03fea 110
5c752bbf
DM
111 return undef;
112}
113
10fc3ba5 114sub get_container_disk_usage {
73e03cb7 115 my ($vmid, $pid) = @_;
10fc3ba5 116
73e03cb7 117 return PVE::Tools::df("/proc/$pid/root/", 1);
10fc3ba5
DM
118}
119
688afc63
WL
120my $last_proc_vmid_stat;
121
8233d33d
DM
122our $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 },
440b6427 163 lock => {
87c5dc96 164 description => "The current config lock, if any.",
440b6427
DC
165 type => 'string',
166 optional => 1,
733e52ec
DC
167 },
168 tags => {
169 description => "The current configured tags, if any.",
170 type => 'string',
171 optional => 1,
440b6427 172 }
8233d33d
DM
173};
174
f76a2828
DM
175sub vmstatus {
176 my ($opt_vmid) = @_;
177
8808fb65 178 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc', vmid => int($opt_vmid) }} : config_list();
f76a2828 179
822de0c3 180 my $active_hash = list_active_containers();
cbb03fea 181
688afc63
WL
182 my $cpucount = $cpuinfo->{cpus} || 1;
183
184 my $cdtime = gettimeofday;
185
186 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
80d56111 187 my $clock_ticks = POSIX::sysconf(&POSIX::_SC_CLK_TCK);
688afc63 188
3b5070d4
WB
189 my $unprivileged = {};
190
f76a2828 191 foreach my $vmid (keys %$list) {
f76a2828 192 my $d = $list->{$vmid};
10fc3ba5 193
8808fb65 194 eval { $d->{pid} = int(find_lxc_pid($vmid)) if defined($active_hash->{$vmid}); };
d5588ee3 195 warn $@ if $@; # ignore errors (consider them stopped)
cbb03fea 196
2ff1c49c 197 $d->{status} = $active_hash->{$vmid} ? 'running' : 'stopped';
f76a2828 198
67afe46e 199 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
238a56cb 200 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
cbb03fea 201
3b5070d4
WB
202 $unprivileged->{$vmid} = $conf->{unprivileged};
203
aec218c7 204 $d->{name} = $conf->{'hostname'} || "CT$vmid";
238a56cb 205 $d->{name} =~ s/[\s]//g;
cbb03fea 206
f2357408
DM
207 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
208 $d->{cpus} = $cpucount if !$d->{cpus};
44da0641 209
733e52ec 210 $d->{tags} = $conf->{tags} if defined($conf->{tags});
d0226204 211
d5588ee3
DM
212 if ($d->{pid}) {
213 my $res = get_container_disk_usage($vmid, $d->{pid});
8808fb65
FE
214 $d->{disk} = int($res->{used});
215 $d->{maxdisk} = int($res->{total});
27916659
DM
216 } else {
217 $d->{disk} = 0;
218 # use 4GB by default ??
219 if (my $rootfs = $conf->{rootfs}) {
e4034859 220 my $rootinfo = PVE::LXC::Config->parse_volume('rootfs', $rootfs);
af02245c 221 $d->{maxdisk} = $rootinfo->{size} || (4*1024*1024*1024);
27916659
DM
222 } else {
223 $d->{maxdisk} = 4*1024*1024*1024;
10fc3ba5 224 }
238a56cb 225 }
cbb03fea 226
238a56cb
DM
227 $d->{mem} = 0;
228 $d->{swap} = 0;
95df9a12
DM
229 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
230 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
e901d418 231
238a56cb
DM
232 $d->{uptime} = 0;
233 $d->{cpu} = 0;
e901d418 234
238a56cb
DM
235 $d->{netout} = 0;
236 $d->{netin} = 0;
f76a2828 237
238a56cb
DM
238 $d->{diskread} = 0;
239 $d->{diskwrite} = 0;
bb1ac2de 240
b4eaaabd 241 $d->{template} = 1 if PVE::LXC::Config->is_template($conf);
440b6427 242 $d->{lock} = $conf->{lock} if $conf->{lock};
f76a2828 243 }
cbb03fea 244
238a56cb
DM
245 foreach my $vmid (keys %$list) {
246 my $d = $list->{$vmid};
d5588ee3
DM
247 my $pid = $d->{pid};
248
249 next if !$pid; # skip stopped CTs
f76a2828 250
80d56111
DC
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
22a77285 253
3b5070d4
WB
254 my $unpriv = $unprivileged->{$vmid};
255
0b1b12e0
WB
256 my $cgroups = PVE::LXC::CGroup->new($vmid);
257
571e61b4 258 if (defined(my $mem = $cgroups->get_memory_stat())) {
8808fb65
FE
259 $d->{mem} = int($mem->{mem});
260 $d->{swap} = int($mem->{swap});
0b6a2f0e
WB
261 } else {
262 $d->{mem} = 0;
263 $d->{swap} = 0;
264 }
265
0b1b12e0 266 if (defined(my $blkio = $cgroups->get_io_stats())) {
8808fb65
FE
267 $d->{diskread} = int($blkio->{diskread});
268 $d->{diskwrite} = int($blkio->{diskwrite});
0b6a2f0e
WB
269 } else {
270 $d->{diskread} = 0;
271 $d->{diskwrite} = 0;
b5289322 272 }
688afc63 273
204f4fbf
WB
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};
688afc63 277
0b6a2f0e
WB
278 my $old = $last_proc_vmid_stat->{$vmid};
279 if (!$old) {
280 $last_proc_vmid_stat->{$vmid} = {
281 time => $cdtime,
204f4fbf 282 used => $used_ms,
0b6a2f0e
WB
283 cpu => 0,
284 };
285 next;
286 }
688afc63 287
204f4fbf
WB
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};
0b6a2f0e
WB
292 $last_proc_vmid_stat->{$vmid} = {
293 time => $cdtime,
204f4fbf 294 used => $used_ms,
0b6a2f0e
WB
295 cpu => $d->{cpu},
296 };
297 } else {
298 $d->{cpu} = $old->{cpu};
299 }
688afc63 300 } else {
0b6a2f0e 301 $d->{cpu} = 0;
688afc63 302 }
238a56cb 303 }
cbb03fea 304
68b8f4d1
WL
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
f76a2828
DM
319 return $list;
320}
321
52f1d76b
DM
322sub 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
c31ad455 334 # search for lxc-console -n <vmid>
cbb03fea 335 return if scalar(@args) != 3;
52f1d76b
DM
336 return if $args[1] ne '-n';
337 return if $args[2] !~ m/^\d+$/;
338 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
cbb03fea 339
52f1d76b 340 my $vmid = $args[2];
cbb03fea 341
52f1d76b
DM
342 push @{$res->{$vmid}}, $pid;
343 });
344
345 return $res;
346}
347
bedeaaf1
AD
348sub find_lxc_pid {
349 my ($vmid) = @_;
350
351 my $pid = undef;
352 my $parser = sub {
353 my $line = shift;
8b25977f 354 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
bedeaaf1 355 };
c39aa40a 356 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
bedeaaf1 357
8b25977f 358 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
cbb03fea 359
8b25977f 360 return $pid;
bedeaaf1
AD
361}
362
ab74a9ba
WB
363sub 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
370sub 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
384sub 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
cbb03fea 401# Note: we cannot use Net:IP, because that only allows strict
55fa4e09
DM
402# CIDR networks
403sub parse_ipv4_cidr {
404 my ($cidr, $noerr) = @_;
405
f7a7b413
WB
406 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
407 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
55fa4e09 408 }
cbb03fea 409
55fa4e09 410 return undef if $noerr;
cbb03fea 411
55fa4e09
DM
412 die "unable to parse ipv4 address/mask\n";
413}
93285df8 414
2df08734
WB
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).
5a63f1c5 417#
2df08734
WB
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.
5a63f1c5 422sub make_seccomp_config {
fb766003 423 my ($conf, $vmid, $conf_dir, $unprivileged, $features) = @_;
5a63f1c5
WB
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:
2df08734
WB
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;
5a63f1c5
WB
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
2df08734
WB
440 my $rules = {
441 keyctl => ['errno 38'],
3e4a69e9
WB
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]'],
2df08734
WB
451 };
452
453 my $raw_conf = '';
454
5a63f1c5
WB
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:
2df08734
WB
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}) {
b6bbd32c
WB
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
2df08734 475 $raw_conf .= "lxc.seccomp.notify.proxy = unix:/run/pve/lxc-syscalld.sock\n";
fb766003 476 $raw_conf .= "lxc.seccomp.notify.cookie = $vmid\n";
2df08734
WB
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";
5a63f1c5 513
2df08734 514 return $raw_conf;
5a63f1c5
WB
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.
524sub 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
96f8d2a2
WB
533 if ($features->{fuse}) {
534 # For the informational warning:
535 push @profile_uses, 'features:fuse';
536 }
537
5a63f1c5
WB
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
27916659 576sub update_lxc_config {
f91f3669 577 my ($vmid, $conf) = @_;
b80dd50a 578
bb1ac2de
DM
579 my $dir = "/var/lib/lxc/$vmid";
580
581 if ($conf->{template}) {
582
583 unlink "$dir/config";
584
585 return;
586 }
587
2bae8172
WB
588 my ($lxc_major, $lxc_minor) = get_lxc_version();
589
27916659 590 my $raw = '';
b80dd50a 591
c37069e8
WB
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:
e532a362
WB
604 $raw .= "lxc.cgroup.dir.container = lxc/$vmid\n";
605 $raw .= "lxc.cgroup.dir.container.inner = ns\n";
c37069e8
WB
606 }
607
27916659
DM
608 die "missing 'arch' - internal error" if !$conf->{arch};
609 $raw .= "lxc.arch = $conf->{arch}\n";
b80dd50a 610
5a63f1c5
WB
611 my $custom_idmap = PVE::LXC::Config->has_lxc_entry($conf, 'lxc.idmap');
612 my $unprivileged = $conf->{unprivileged} || $custom_idmap;
425b62cb 613
27916659 614 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
866e0611 615
ebc027a8
WB
616 File::Path::mkpath($dir);
617
059f7bb4
WB
618 my $cfgpath = '/usr/share/lxc/config';
619 my $inc = "$cfgpath/$ostype.common.conf";
620 $inc ="$cfgpath/common.conf" if !-f $inc;
866e0611 621 $raw .= "lxc.include = $inc\n";
5a63f1c5 622 if ($unprivileged) {
059f7bb4
WB
623 $inc = "$cfgpath/$ostype.userns.conf";
624 $inc = "$cfgpath/userns.conf" if !-f $inc;
625 $raw .= "lxc.include = $inc\n";
27916659 626 }
b80dd50a 627
5a63f1c5
WB
628 my $features = PVE::LXC::Config->parse_features($conf->{features});
629
fb766003 630 $raw .= make_seccomp_config($conf, $vmid, $dir, $unprivileged, $features);
5a63f1c5 631 $raw .= make_apparmor_config($conf, $unprivileged, $features);
96f8d2a2
WB
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 }
5a63f1c5 636
741b7737
TL
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
50df544c
WB
643 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
644 # cannot be exposed to the container with r/w access (cgroup perms).
645 # When this is enabled mounts will still remain in the monitor's namespace
646 # after the container unmounted them and thus will not detach from their
647 # files while the container is running!
c16b8890 648 $raw .= "lxc.monitor.unshare = 1\n";
58cc92a9 649
36def186 650 my ($cgv1, $cgv2) = PVE::CGroup::get_cgroup_controllers();
0b6a2f0e 651
425b62cb
WB
652 # Should we read them from /etc/subuid?
653 if ($unprivileged && !$custom_idmap) {
108c6cab
WB
654 $raw .= "lxc.idmap = u 0 100000 65536\n";
655 $raw .= "lxc.idmap = g 0 100000 65536\n";
425b62cb
WB
656 }
657
d250604f 658 if (!PVE::LXC::Config->has_dev_console($conf)) {
108c6cab 659 $raw .= "lxc.console.path = none\n";
36def186
WB
660 if ($cgv1->{devices}) {
661 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
662 } elsif (defined($cgv2)) {
663 $raw .= "lxc.cgroup2.devices.deny = c 5:1 rwm\n";
664 }
eeaea429 665 }
4f958489 666
1b4cf758 667 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
108c6cab 668 $raw .= "lxc.tty.max = $ttycount\n";
cbb03fea 669
c31ad455 670 # some init scripts expect a linux terminal (turnkey).
a691a5a3 671 $raw .= "lxc.environment = TERM=linux\n";
f598979f 672
27916659 673 my $utsname = $conf->{hostname} || "CT$vmid";
108c6cab 674 $raw .= "lxc.uts.name = $utsname\n";
cbb03fea 675
0b6a2f0e
WB
676 if ($cgv1->{memory}) {
677 my $memory = $conf->{memory} || 512;
678 my $swap = $conf->{swap} // 0;
a12a36e0 679
0b6a2f0e
WB
680 my $lxcmem = int($memory*1024*1024);
681 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
27916659 682
0b6a2f0e
WB
683 my $lxcswap = int(($memory + $swap)*1024*1024);
684 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
36def186
WB
685 } elsif ($cgv2->{memory}) {
686 my $memory = $conf->{memory} || 512;
687 my $swap = $conf->{swap} // 0;
688
689 my $lxcmem = int($memory*1024*1024);
690 $raw .= "lxc.cgroup2.memory.max = $lxcmem\n";
691
692 my $lxcswap = int($swap*1024*1024);
693 $raw .= "lxc.cgroup2.memory.swap.max = $lxcswap\n";
a12a36e0
WL
694 }
695
0b6a2f0e
WB
696 if ($cgv1->{cpu}) {
697 if (my $cpulimit = $conf->{cpulimit}) {
698 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
699 my $value = int(100000*$cpulimit);
700 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
701 }
702
a3d114d7 703 my $shares = PVE::CGroup::clamp_cpu_shares($conf->{cpuunits});
0b6a2f0e 704 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
36def186
WB
705 } elsif ($cgv2->{cpu}) {
706 # See PVE::CGroup
707 if (my $cpulimit = $conf->{cpulimit}) {
708 my $value = int(100000*$cpulimit);
709 $raw .= "lxc.cgroup2.cpu.max = $value 100000\n";
710 }
711
712 if (defined(my $shares = $conf->{cpuunits})) {
a3d114d7 713 $shares = PVE::CGroup::clamp_cpu_shares($shares);
36def186
WB
714 $raw .= "lxc.cgroup2.cpu.weight = $shares\n";
715 }
0b6a2f0e 716 }
27916659 717
fddaa91b
DM
718 die "missing 'rootfs' configuration\n"
719 if !defined($conf->{rootfs});
720
e4034859 721 my $mountpoint = PVE::LXC::Config->parse_volume('rootfs', $conf->{rootfs});
a3076d81 722
108c6cab 723 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
27916659 724
e756bdd6 725 foreach my $k (sort keys %$conf) {
27916659
DM
726 next if $k !~ m/^net(\d+)$/;
727 my $ind = $1;
1b4cf758 728 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
108c6cab
WB
729 $raw .= "lxc.net.$ind.type = veth\n";
730 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
731 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
732 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name});
5fbd58cb
DT
733
734 # Keep container from starting with invalid mtu configuration
735 if (my $mtu = $d->{mtu}) {
736 my $bridge_mtu = PVE::Network::read_bridge_mtu($d->{bridge});
737 die "$k: MTU size '$mtu' is bigger than bridge MTU '$bridge_mtu'\n"
738 if ($mtu > $bridge_mtu);
739
740 $raw .= "lxc.net.$ind.mtu = $mtu\n";
741 }
2bae8172
WB
742
743 # Starting with lxc 4.0, we do not patch lxc to execute our up-scripts.
744 if ($lxc_major >= 4) {
745 $raw .= "lxc.net.$ind.script.up = /usr/share/lxc/lxcnetaddbr\n";
746 }
a12a36e0
WL
747 }
748
42b51c01
WB
749 my $had_cpuset = 0;
750 if (my $lxcconf = $conf->{lxc}) {
751 foreach my $entry (@$lxcconf) {
752 my ($k, $v) = @$entry;
2222f9f4 753 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus' || $k eq 'lxc.cgroup2.cpuset.cpus';
42b51c01 754 $raw .= "$k = $v\n";
e576f689 755 }
42b51c01 756 }
27916659 757
42b51c01 758 my $cpuset;
85ccb17f 759 my ($cpuset_cgroup, $cpuset_version) = eval { PVE::CGroup::cpuset_controller_path() };
42b51c01
WB
760 if (defined($cpuset_cgroup)) {
761 $cpuset = eval { PVE::CpuSet->new_from_path("$cpuset_cgroup/lxc", 1) }
762 || PVE::CpuSet->new_from_path($cpuset_cgroup, 1);
763 }
764 my $cores = $conf->{cores};
765 if (!$had_cpuset && $cores && $cpuset) {
766 my @members = $cpuset->members();
767 while (scalar(@members) > $cores) {
768 my $randidx = int(rand(scalar(@members)));
769 $cpuset->delete($members[$randidx]);
770 splice(@members, $randidx, 1); # keep track of the changes
92902047 771 }
4c97a31d
WB
772 my $ver = $cpuset_version == 1 ? '' : '2';
773 $raw .= "lxc.cgroup$ver.cpuset.cpus = ".$cpuset->short_string()."\n";
92902047 774 }
0b6a2f0e 775
27916659
DM
776 File::Path::mkpath("$dir/rootfs");
777
778 PVE::Tools::file_set_contents("$dir/config", $raw);
b80dd50a
DM
779}
780
117636e5
DM
781# verify and cleanup nameserver list (replace \0 with ' ')
782sub verify_nameserver_list {
783 my ($nameserver_list) = @_;
784
785 my @list = ();
786 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
08a58f12 787 PVE::LXC::Config::verify_ip_with_ll_iface($server);
117636e5
DM
788 push @list, $server;
789 }
790
791 return join(' ', @list);
792}
793
794sub verify_searchdomain_list {
795 my ($searchdomain_list) = @_;
796
797 my @list = ();
798 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
799 # todo: should we add checks for valid dns domains?
800 push @list, $server;
801 }
802
803 return join(' ', @list);
804}
805
aca816ad 806sub get_console_command {
65213b67 807 my ($vmid, $conf, $escapechar) = @_;
39413635 808
65213b67
TM
809 # '-1' as $escapechar disables keyboard escape sequence
810 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
aca816ad 811
1b4cf758 812 my $cmode = PVE::LXC::Config->get_cmode($conf);
aca816ad 813
4d494664 814 my $cmd = [];
aca816ad 815 if ($cmode eq 'console') {
4d494664 816 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
65213b67 817 push @$cmd, '-e', $escapechar if $escapechar;
aca816ad 818 } elsif ($cmode eq 'tty') {
4d494664 819 push @$cmd, 'lxc-console', '-n', $vmid;
65213b67 820 push @$cmd, '-e', $escapechar if $escapechar;
aca816ad 821 } elsif ($cmode eq 'shell') {
4d494664 822 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
aca816ad
DM
823 } else {
824 die "internal error";
825 }
4d494664
DC
826
827 return $cmd;
aca816ad
DM
828}
829
c325b32f
DM
830sub get_primary_ips {
831 my ($conf) = @_;
832
833 # return data from net0
cbb03fea 834
27916659 835 return undef if !defined($conf->{net0});
1b4cf758 836 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
c325b32f
DM
837
838 my $ipv4 = $net->{ip};
db78a181
WB
839 if ($ipv4) {
840 if ($ipv4 =~ /^(dhcp|manual)$/) {
841 $ipv4 = undef
842 } else {
843 $ipv4 =~ s!/\d+$!!;
844 }
845 }
65e5eaa3 846 my $ipv6 = $net->{ip6};
db78a181 847 if ($ipv6) {
5f291c7d 848 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
db78a181
WB
849 $ipv6 = undef;
850 } else {
851 $ipv6 =~ s!/\d+$!!;
852 }
853 }
cbb03fea 854
c325b32f
DM
855 return ($ipv4, $ipv6);
856}
148d1cb4 857
b407293b
WB
858sub delete_mountpoint_volume {
859 my ($storage_cfg, $vmid, $volume) = @_;
860
d250604f 861 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
b407293b
WB
862
863 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
6b81ef77
TL
864
865 if ($vmid == $owner) {
866 PVE::Storage::vdisk_free($storage_cfg, $volume);
867 } else {
868 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
869 }
b407293b 870}
ef241384 871
27916659 872sub destroy_lxc_container {
3b1c0970 873 my ($storage_cfg, $vmid, $conf, $replacement_conf, $purge_unreferenced) = @_;
148d1cb4 874
6cac5615
FG
875 my $volids = {};
876 my $remove_volume = sub {
db8989e1 877 my ($ms, $mountpoint) = @_;
6cac5615
FG
878
879 my $volume = $mountpoint->{volume};
880
881 return if $volids->{$volume};
882 $volids->{$volume} = 1;
883
884 delete_mountpoint_volume($storage_cfg, $vmid, $volume);
885 };
886 PVE::LXC::Config->foreach_volume_full($conf, {include_unused => 1}, $remove_volume);
887
888 PVE::LXC::Config->foreach_volume_full($conf->{pending}, {include_unused => 1}, $remove_volume);
db8989e1 889
3b1c0970 890 if ($purge_unreferenced) { # also remove unreferenced disk
5a0db48a 891 my $vmdisks = PVE::Storage::vdisk_list($storage_cfg, undef, $vmid, undef, 'rootdir');
3b1c0970
TL
892 PVE::Storage::foreach_volid($vmdisks, sub {
893 my ($volid, $sid, $volname, $d) = @_;
894 eval { PVE::Storage::vdisk_free($storage_cfg, $volid) };
895 warn $@ if $@;
896 });
897 }
898
27916659
DM
899 rmdir "/var/lib/lxc/$vmid/rootfs";
900 unlink "/var/lib/lxc/$vmid/config";
901 rmdir "/var/lib/lxc/$vmid";
bccaa371
FG
902 if (defined $replacement_conf) {
903 PVE::LXC::Config->write_config($vmid, $replacement_conf);
904 } else {
4eeb9af1 905 PVE::LXC::Config->destroy_config($vmid);
bccaa371 906 }
148d1cb4 907}
68fba17b 908
ef241384 909sub vm_stop_cleanup {
5fa890f0 910 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
bf9d912c 911
38e7891a
TL
912 return if $keepActive;
913
914 eval {
915 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
916 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
ef241384
DM
917 };
918 warn $@ if $@; # avoid errors - just warn
919}
920
2b181f39
CH
921sub net_tap_plug : prototype($$$$$$;$) {
922 my ($iface, $bridge, $tag, $firewall, $trunks, $rate, $opts) = @_;
923
924 if ($have_sdn) {
925 PVE::Network::SDN::Zones::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate);
926 PVE::Network::SDN::Zones::add_bridge_fdb($iface, $opts->{mac}, $bridge, $firewall)
927 if defined($opts->{mac});
928 } else {
929 PVE::Network::tap_plug($iface, $bridge, $tag, $firewall, $trunks, $rate, $opts);
930 }
931}
932
93cdbbfb 933sub update_net {
bedeaaf1 934 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
93cdbbfb 935
18862537
WB
936 if ($newnet->{type} ne 'veth') {
937 # for when there are physical interfaces
938 die "cannot update interface of type $newnet->{type}";
939 }
940
941 my $veth = "veth${vmid}i${netid}";
93cdbbfb
AD
942 my $eth = $newnet->{name};
943
18862537 944 if (my $oldnetcfg = $conf->{$opt}) {
1b4cf758 945 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
18862537 946
2ae004ec
OB
947 if (safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
948 safe_string_ne($oldnet->{name}, $newnet->{name})) {
93cdbbfb 949
18862537 950 PVE::Network::veth_delete($veth);
bedeaaf1 951 delete $conf->{$opt};
67afe46e 952 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb 953
18862537 954 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
bedeaaf1 955
380962c7 956 } else {
2ae004ec
OB
957 if (safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
958 safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
d21e45d5
TL
959 safe_num_ne($oldnet->{firewall}, $newnet->{firewall})
960 ) {
bedeaaf1 961
18862537 962 if ($oldnet->{bridge}) {
bedeaaf1 963 PVE::Network::tap_unplug($veth);
18862537
WB
964 foreach (qw(bridge tag firewall)) {
965 delete $oldnet->{$_};
966 }
1b4cf758 967 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
67afe46e 968 PVE::LXC::Config->write_config($vmid, $conf);
bedeaaf1 969 }
93cdbbfb 970
d21e45d5 971 my ($bridge, $mac, $firewall, $rate) = $newnet->@{'bridge', 'hwaddr', 'firewall', 'rate'};
2b181f39 972 PVE::LXC::net_tap_plug($veth, $bridge, $newnet->{tag}, $firewall, $newnet->{trunks}, $rate, { mac => $mac });
ab2ec461 973
380962c7
WB
974 # This includes the rate:
975 foreach (qw(bridge tag firewall rate)) {
18862537
WB
976 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
977 }
2ae004ec 978 } elsif (safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
380962c7
WB
979 # Rate can be applied on its own but any change above needs to
980 # include the rate in tap_plug since OVS resets everything.
981 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
982 $oldnet->{rate} = $newnet->{rate}
983 }
984 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
985 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
986 }
987 } else {
18862537 988 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
93cdbbfb
AD
989 }
990
bedeaaf1 991 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
93cdbbfb
AD
992}
993
994sub hotplug_net {
18862537 995 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
93cdbbfb 996
18862537 997 my $veth = "veth${vmid}i${netid}";
cbb03fea 998 my $vethpeer = $veth . "p";
93cdbbfb
AD
999 my $eth = $newnet->{name};
1000
a1ff8c37 1001 if ($have_sdn) {
ab2ec461 1002 PVE::Network::SDN::Zones::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
ab2ec461
AD
1003 } else {
1004 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
ab2ec461 1005 }
2b181f39 1006 PVE::LXC::net_tap_plug(
d7b593de
TL
1007 $veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks},
1008 $newnet->{rate}, { mac => $newnet->{hwaddr} },
1009 );
93cdbbfb 1010
cbb03fea 1011 # attach peer in container
93cdbbfb
AD
1012 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
1013 PVE::Tools::run_command($cmd);
1014
cbb03fea 1015 # link up peer in container
93cdbbfb
AD
1016 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
1017 PVE::Tools::run_command($cmd);
bedeaaf1 1018
18862537
WB
1019 my $done = { type => 'veth' };
1020 foreach (qw(bridge tag firewall hwaddr name)) {
1021 $done->{$_} = $newnet->{$_} if $newnet->{$_};
1022 }
1b4cf758 1023 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
bedeaaf1 1024
67afe46e 1025 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
1026}
1027
68a05bb3 1028sub update_ipconfig {
bedeaaf1
AD
1029 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
1030
f2104b80 1031 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
bedeaaf1 1032
1b4cf758 1033 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
84e0c123
WB
1034 my $deleted = [];
1035 my $added = [];
8d723477
WB
1036 my $nscmd = sub {
1037 my $cmdargs = shift;
1038 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
84e0c123 1039 };
8d723477 1040 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
2bfd1615 1041
84e0c123 1042 my $change_ip_config = sub {
f39002a6
DM
1043 my ($ipversion) = @_;
1044
1045 my $family_opt = "-$ipversion";
1046 my $suffix = $ipversion == 4 ? '' : $ipversion;
84e0c123
WB
1047 my $gw= "gw$suffix";
1048 my $ip= "ip$suffix";
bedeaaf1 1049
6178b0dd
WB
1050 my $newip = $newnet->{$ip};
1051 my $newgw = $newnet->{$gw};
1052 my $oldip = $optdata->{$ip};
ded5d25a 1053 my $oldgw = $optdata->{$gw};
6178b0dd 1054
2ae004ec
OB
1055 my $change_ip = safe_string_ne($oldip, $newip);
1056 my $change_gw = safe_string_ne($oldgw, $newgw);
bedeaaf1 1057
84e0c123 1058 return if !$change_ip && !$change_gw;
68a05bb3 1059
84e0c123 1060 # step 1: add new IP, if this fails we cancel
292aff54
WB
1061 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
1062 if ($change_ip && $is_real_ip) {
8d723477 1063 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
84e0c123
WB
1064 if (my $err = $@) {
1065 warn $err;
1066 return;
1067 }
bedeaaf1 1068 }
bedeaaf1 1069
84e0c123
WB
1070 # step 2: replace gateway
1071 # If this fails we delete the added IP and cancel.
1072 # If it succeeds we save the config and delete the old IP, ignoring
1073 # errors. The config is then saved.
1074 # Note: 'ip route replace' can add
1075 if ($change_gw) {
6178b0dd 1076 if ($newgw) {
292aff54
WB
1077 eval {
1078 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
1079 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
1080 }
1081 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
1082 };
84e0c123
WB
1083 if (my $err = $@) {
1084 warn $err;
1085 # the route was not replaced, the old IP is still available
1086 # rollback (delete new IP) and cancel
1087 if ($change_ip) {
8d723477 1088 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
84e0c123
WB
1089 warn $@ if $@; # no need to die here
1090 }
1091 return;
1092 }
1093 } else {
8d723477 1094 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
84e0c123
WB
1095 # if the route was not deleted, the guest might have deleted it manually
1096 # warn and continue
1097 warn $@ if $@;
1098 }
ded5d25a
DL
1099 if ($oldgw && $oldip && !PVE::Network::is_ip_in_cidr($oldgw, $oldip)) {
1100 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
1101 # warn if the route was deleted manually
1102 warn $@ if $@;
1103 }
2bfd1615 1104 }
2bfd1615 1105
6178b0dd 1106 # from this point on we save the configuration
84e0c123 1107 # step 3: delete old IP ignoring errors
6178b0dd 1108 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
8d723477
WB
1109 # We need to enable promote_secondaries, otherwise our newly added
1110 # address will be removed along with the old one.
1111 my $promote = 0;
1112 eval {
1113 if ($ipversion == 4) {
1114 &$nscmd({ outfunc => sub { $promote = int(shift) } },
1115 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1116 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1117 }
1118 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1119 };
84e0c123 1120 warn $@ if $@; # no need to die here
8d723477
WB
1121
1122 if ($ipversion == 4) {
1123 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1124 }
bedeaaf1
AD
1125 }
1126
84e0c123
WB
1127 foreach my $property ($ip, $gw) {
1128 if ($newnet->{$property}) {
1129 $optdata->{$property} = $newnet->{$property};
1130 } else {
1131 delete $optdata->{$property};
1132 }
bedeaaf1 1133 }
1b4cf758 1134 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
67afe46e 1135 PVE::LXC::Config->write_config($vmid, $conf);
84e0c123
WB
1136 $lxc_setup->setup_network($conf);
1137 };
bedeaaf1 1138
f39002a6
DM
1139 &$change_ip_config(4);
1140 &$change_ip_config(6);
489e960d
WL
1141
1142}
1143
9a14c1fa
WB
1144my $open_namespace = sub {
1145 my ($vmid, $pid, $kind) = @_;
1146 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1147 or die "failed to open $kind namespace of container $vmid: $!\n";
1148 return $fd;
1149};
1150
34fdb3d7 1151my $enter_namespace = sub {
9a14c1fa
WB
1152 my ($vmid, $pid, $kind, $type) = @_;
1153 my $fd = $open_namespace->($vmid, $pid, $kind);
34fdb3d7 1154 PVE::Tools::setns(fileno($fd), $type)
9a14c1fa 1155 or die "failed to enter $kind namespace of container $vmid: $!\n";
34fdb3d7
WB
1156 close $fd;
1157};
1158
418b94fe
WB
1159my $get_container_namespace = sub {
1160 my ($vmid, $pid, $kind) = @_;
1161
1162 my $pidfd;
1163 if (!defined($pid)) {
1164 # Pin the pid while we're grabbing its stuff from /proc
1165 ($pid, $pidfd) = open_lxc_pid($vmid)
1166 or die "failed to open pidfd of container $vmid\'s init process\n";
1167 }
1168
1169 return $open_namespace->($vmid, $pid, $kind);
1170};
1171
34fdb3d7
WB
1172my $do_syncfs = sub {
1173 my ($vmid, $pid, $socket) = @_;
1174
1175 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
1176
1177 # Tell the parent process to start reading our /proc/mounts
1178 print {$socket} "go\n";
1179 $socket->flush();
1180
1181 # Receive /proc/self/mounts
1182 my $mountdata = do { local $/ = undef; <$socket> };
1183 close $socket;
1184
0c0be8e4
SI
1185 my %nosyncfs = (
1186 cgroup => 1,
1187 cgroup2 => 1,
1188 devtmpfs => 1,
1189 devpts => 1,
1190 'fuse.lxcfs' => 1,
1191 fusectl => 1,
1192 mqueue => 1,
1193 proc => 1,
1194 sysfs => 1,
1195 tmpfs => 1,
1196 );
1197
34fdb3d7
WB
1198 # Now sync all mountpoints...
1199 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
1200 foreach my $mp (@$mounts) {
1201 my ($what, $dir, $fs) = @$mp;
0c0be8e4 1202 next if $nosyncfs{$fs};
34fdb3d7
WB
1203 eval { PVE::Tools::sync_mountpoint($dir); };
1204 warn $@ if $@;
1205 }
1206};
1207
1208sub sync_container_namespace {
1209 my ($vmid) = @_;
1210 my $pid = find_lxc_pid($vmid);
1211
1212 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1213 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
1214 or die "failed to create socketpair: $!\n";
1215
1216 my $child = fork();
1217 die "fork failed: $!\n" if !defined($child);
1218
1219 if (!$child) {
1220 eval {
1221 close $pfd;
1222 &$do_syncfs($vmid, $pid, $cfd);
1223 };
1224 if (my $err = $@) {
1225 warn $err;
1226 POSIX::_exit(1);
1227 }
1228 POSIX::_exit(0);
1229 }
1230 close $cfd;
1231 my $go = <$pfd>;
1232 die "failed to enter container namespace\n" if $go ne "go\n";
1233
1234 open my $mounts, '<', "/proc/$child/mounts"
1235 or die "failed to open container's /proc/mounts: $!\n";
1236 my $mountdata = do { local $/ = undef; <$mounts> };
1237 close $mounts;
1238 print {$pfd} $mountdata;
1239 close $pfd;
1240
1241 while (waitpid($child, 0) != $child) {}
1242 die "failed to sync container namespace\n" if $? != 0;
1243}
1244
bb1ac2de
DM
1245sub template_create {
1246 my ($vmid, $conf) = @_;
1247
1248 my $storecfg = PVE::Storage::config();
1249
015740e6 1250 PVE::LXC::Config->foreach_volume($conf, sub {
9d1cb46b 1251 my ($ms, $mountpoint) = @_;
bb1ac2de 1252
9d1cb46b 1253 my $volid = $mountpoint->{volume};
bb1ac2de 1254
9d1cb46b
WL
1255 die "Template feature is not available for '$volid'\n"
1256 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
1257 });
bb1ac2de 1258
015740e6 1259 PVE::LXC::Config->foreach_volume($conf, sub {
9d1cb46b
WL
1260 my ($ms, $mountpoint) = @_;
1261
1262 my $volid = $mountpoint->{volume};
1263
1264 PVE::Storage::activate_volumes($storecfg, [$volid]);
1265
1266 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
1267 $mountpoint->{volume} = $template_volid;
1268 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1269 });
bb1ac2de 1270
67afe46e 1271 PVE::LXC::Config->write_config($vmid, $conf);
bb1ac2de
DM
1272}
1273
52389a07 1274sub check_ct_modify_config_perm {
de41bced 1275 my ($rpcenv, $authuser, $vmid, $pool, $oldconf, $newconf, $delete, $unprivileged) = @_;
52389a07 1276
c81f19d1 1277 return 1 if $authuser eq 'root@pam';
c824fbed 1278 my $storage_cfg = PVE::Storage::config();
52389a07 1279
f1ba1a4b
WB
1280 my $check = sub {
1281 my ($opt, $delete) = @_;
f2357408 1282 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
52389a07 1283 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
e59a61ed 1284 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
52389a07 1285 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
f1ba1a4b 1286 return if $delete;
e4034859 1287 my $data = PVE::LXC::Config->parse_volume($opt, $newconf->{$opt});
9d294016
FG
1288 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
1289 if $data->{type} ne 'volume';
c824fbed
FG
1290 my $volid = $data->{volume};
1291 if ($volid =~ $NEW_DISK_RE) {
1292 my $sid = $1;
1293 $rpcenv->check($authuser, "/storage/$sid", ['Datastore.AllocateSpace']);
1294 } else {
d387c0be
FE
1295 PVE::Storage::check_volume_access(
1296 $rpcenv,
1297 $authuser,
1298 $storage_cfg,
1299 $vmid,
1300 $volid,
1301 'rootdir',
1302 );
c824fbed 1303 }
52389a07
DM
1304 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1305 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1306 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1307 $opt eq 'searchdomain' || $opt eq 'hostname') {
1308 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
5a63f1c5 1309 } elsif ($opt eq 'features') {
88ef1700
DC
1310 raise_perm_exc("changing feature flags for privileged container is only allowed for root\@pam")
1311 if !$unprivileged;
1312
1313 my $nesting_changed = 0;
1314 my $other_changed = 0;
1315 if (!$delete) {
1316 my $features = PVE::LXC::Config->parse_features($newconf->{$opt});
1317 if (defined($oldconf) && $oldconf->{$opt}) {
1318 # existing container with features
1319 my $old_features = PVE::LXC::Config->parse_features($oldconf->{$opt});
1320 for my $feature ((keys %$old_features, keys %$features)) {
1321 my $old = $old_features->{$feature} // '';
1322 my $new = $features->{$feature} // '';
1323 if ($old ne $new) {
1324 if ($feature eq 'nesting') {
1325 $nesting_changed = 1;
1326 next;
1327 } else {
1328 $other_changed = 1;
1329 last;
1330 }
1331 }
1332 }
1333 } else {
1334 # new container or no features defined
1335 if (scalar(keys %$features) == 1 && $features->{nesting}) {
1336 $nesting_changed = 1;
1337 } elsif (scalar(keys %$features) > 0) {
1338 $other_changed = 1;
1339 }
1340 }
1341 } else {
1342 my $features = PVE::LXC::Config->parse_features($oldconf->{$opt});
1343 if (scalar(keys %$features) == 1 && $features->{nesting}) {
1344 $nesting_changed = 1;
1345 } elsif (scalar(keys %$features) > 0) {
1346 $other_changed = 1;
1347 }
1348 }
1349 raise_perm_exc("changing feature flags (except nesting) is only allowed for root\@pam")
1350 if $other_changed;
1351 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Allocate'])
1352 if $nesting_changed;
1a416433
DC
1353 } elsif ($opt eq 'hookscript') {
1354 # For now this is restricted to root@pam
1355 raise_perm_exc("changing the hookscript is only allowed for root\@pam");
7a57f63a
DC
1356 } elsif ($opt eq 'tags') {
1357 my $old = $oldconf->{$opt};
1358 my $new = $delete ? '' : $newconf->{$opt};
1359 PVE::GuestHelpers::assert_tag_permissions($vmid, $old, $new, $rpcenv, $authuser);
52389a07
DM
1360 } else {
1361 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1362 }
f1ba1a4b
WB
1363 };
1364
1365 foreach my $opt (keys %$newconf) {
1366 &$check($opt, 0);
1367 }
1368 foreach my $opt (@$delete) {
1369 &$check($opt, 1);
52389a07
DM
1370 }
1371
1372 return 1;
1373}
1374
9622e848 1375sub umount_all {
da629848 1376 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
9622e848
DM
1377
1378 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
d250604f 1379 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848 1380
73058b84
TL
1381 my $res = 1;
1382
015740e6 1383 PVE::LXC::Config->foreach_volume_full($conf, {'reverse' => 1}, sub {
9622e848
DM
1384 my ($ms, $mountpoint) = @_;
1385
1386 my $volid = $mountpoint->{volume};
1387 my $mount = $mountpoint->{mp};
1388
1389 return if !$volid || !$mount;
1390
d18f96b4 1391 my $mount_path = "$rootdir/$mount";
f845a93d 1392 $mount_path =~ s!/+!/!g;
9622e848 1393
228a5a1d
WL
1394 return if !PVE::ProcFSTools::is_mounted($mount_path);
1395
9622e848 1396 eval {
d18f96b4 1397 PVE::Tools::run_command(['umount', '-d', $mount_path]);
9622e848
DM
1398 };
1399 if (my $err = $@) {
1400 if ($noerr) {
73058b84 1401 $res = 0;
9622e848
DM
1402 warn $err;
1403 } else {
1404 die $err;
1405 }
1406 }
1407 });
73058b84
TL
1408
1409 return $res; # tell caller if (some) umounts failed for the noerr case
9622e848
DM
1410}
1411
1412sub mount_all {
25321b68 1413 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
9622e848
DM
1414
1415 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1adc7e53 1416 File::Path::make_path($rootdir);
9622e848 1417
d250604f 1418 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848
DM
1419 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
1420
4c98d66c
FG
1421 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
1422
9622e848 1423 eval {
015740e6 1424 PVE::LXC::Config->foreach_volume($conf, sub {
9622e848
DM
1425 my ($ms, $mountpoint) = @_;
1426
25321b68
FG
1427 $mountpoint->{ro} = 0 if $ignore_ro;
1428
4c98d66c 1429 mountpoint_mount($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
9622e848
DM
1430 });
1431 };
1432 if (my $err = $@) {
e2007ac2 1433 warn "mounting container failed\n";
9622e848 1434 umount_all($vmid, $storage_cfg, $conf, 1);
e2007ac2 1435 die $err;
9622e848
DM
1436 }
1437
da629848 1438 return $rootdir;
9622e848
DM
1439}
1440
1441
b15c75fc 1442sub mountpoint_mount_path {
da629848 1443 my ($mountpoint, $storage_cfg, $snapname) = @_;
b15c75fc 1444
da629848 1445 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
b15c75fc 1446}
cc6b0307 1447
21f292ff
WB
1448sub query_loopdev {
1449 my ($path) = @_;
1450 my $found;
1451 my $parser = sub {
1452 my $line = shift;
1453 if ($line =~ m@^(/dev/loop\d+):@) {
1454 $found = $1;
1455 }
1456 };
1457 my $cmd = ['losetup', '--associated', $path];
1458 PVE::Tools::run_command($cmd, outfunc => $parser);
1459 return $found;
1460}
1461
50df544c
WB
1462# Run a function with a file attached to a loop device.
1463# The loop device is always detached afterwards (or set to autoclear).
1464# Returns the loop device.
1465sub run_with_loopdev {
fd8cab92 1466 my ($func, $file, $readonly) = @_;
54d11e5c
WB
1467 my $device = query_loopdev($file);
1468 # Try to reuse an existing device
1469 if ($device) {
1470 # We assume that whoever setup the loop device is responsible for
1471 # detaching it.
1472 &$func($device);
1473 return $device;
1474 }
1475
50df544c
WB
1476 my $parser = sub {
1477 my $line = shift;
1478 if ($line =~ m@^(/dev/loop\d+)$@) {
1479 $device = $1;
1480 }
1481 };
fd8cab92
DL
1482 my $losetup_cmd = [
1483 'losetup',
1484 '--show',
1485 '-f',
1486 $file,
1487 ];
1488 push @$losetup_cmd, '-r' if $readonly;
1489 PVE::Tools::run_command($losetup_cmd, outfunc => $parser);
50df544c
WB
1490 die "failed to setup loop device for $file\n" if !$device;
1491 eval { &$func($device); };
1492 my $err = $@;
1493 PVE::Tools::run_command(['losetup', '-d', $device]);
1494 die $err if $err;
1495 return $device;
1496}
1497
ab3722b3
WB
1498# In scalar mode: returns a file handle to the deepest directory node.
1499# In list context: returns a list of:
1500# * the deepest directory node
1501# * the 2nd deepest directory (parent of the above)
1502# * directory name of the last directory
1503# So that the path $2/$3 should lead to $1 afterwards.
4c98d66c
FG
1504sub walk_tree_nofollow($$$;$$) {
1505 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
ab3722b3 1506
ab3722b3
WB
1507 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1508 or die "failed to open start directory $start: $!\n";
1509
2c6830d5
WB
1510 return walk_tree_nofollow_fd($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1511}
1512
1513
1514sub walk_tree_nofollow_fd($$$$;$$) {
1515 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1516
1517 # splitdir() returns '' for empty components including the leading /
1518 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1519
1520 my $fd = $start_fd;
1521 my $dir = $start_dirname;
ab3722b3
WB
1522 my $last_component = undef;
1523 my $second = $fd;
1524 foreach my $component (@comps) {
1525 $dir .= "/$component";
1526 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1527
1528 if (!$next) {
1529 # failed, check for symlinks and try to create the path
3eb5f47b 1530 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
ab3722b3
WB
1531 die "cannot open directory $dir: $!\n" if !$mkdir;
1532
1533 # We don't check for errors on mkdirat() here and just try to
1534 # openat() again, since at least one error (EEXIST) is an
1535 # expected possibility if multiple containers start
1536 # simultaneously. If someone else injects a symlink now then
1537 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1538 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1539
1540 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1541 die "failed to create path: $dir: $!\n" if !$next;
4c98d66c
FG
1542
1543 PVE::Tools::fchownat(fileno($next), '', $rootuid, $rootgid, PVE::Tools::AT_EMPTY_PATH)
1544 if defined($rootuid) && defined($rootgid);
ab3722b3
WB
1545 }
1546
2c6830d5 1547 close $second if defined($last_component) && $second != $start_fd;
ab3722b3
WB
1548 $last_component = $component;
1549 $second = $fd;
1550 $fd = $next;
1551 }
1552
1553 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
2c6830d5 1554 close $second if defined($last_component) && $second != $start_fd;
ab3722b3
WB
1555 return $fd;
1556}
1557
619f27b4
WB
1558# To guard against symlink attack races against other currently running
1559# containers with shared recursive bind mount hierarchies we prepare a
1560# directory handle for the directory we're mounting over to verify the
1561# mountpoint afterwards.
1562sub __bindmount_prepare {
1563 my ($hostroot, $dir) = @_;
1564 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1565 return $srcdh;
1566}
ab3722b3 1567
619f27b4
WB
1568# Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1569# ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1570# we intended to bind mount.
1571sub __bindmount_verify {
1572 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
ab3722b3
WB
1573 my $destdh;
1574 if ($parentfd) {
1575 # Open the mount point path coming from the parent directory since the
1576 # filehandle we would have gotten as first result of walk_tree_nofollow
1577 # earlier is still a handle to the underlying directory instead of the
1578 # mounted path.
619f27b4
WB
1579 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1580 die "failed to open mount point: $!\n" if !$destdh;
1581 if ($ro) {
1582 my $dot = '.';
619f27b4 1583 # no separate function because 99% of the time it's the wrong thing to use.
0389da0d 1584 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
619f27b4
WB
1585 die "failed to mark bind mount read only\n";
1586 }
1587 die "read-only check failed: $!\n" if $! != EROFS;
1588 }
ab3722b3
WB
1589 } else {
1590 # For the rootfs we don't have a parentfd so we open the path directly.
1591 # Note that this means bindmounting any prefix of the host's
1592 # /var/lib/lxc/$vmid path into another container is considered a grave
1593 # security error.
1594 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
619f27b4 1595 die "failed to open mount point: $!\n" if !$destdh;
ab3722b3 1596 }
ab3722b3
WB
1597
1598 my ($srcdev, $srcinode) = stat($srcdh);
1599 my ($dstdev, $dstinode) = stat($destdh);
1600 close $srcdh;
1601 close $destdh;
1602
619f27b4
WB
1603 return ($srcdev == $dstdev && $srcinode == $dstinode);
1604}
1605
1606# Perform the actual bind mounting:
1607sub __bindmount_do {
1608 my ($dir, $dest, $ro, @extra_opts) = @_;
1609 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1610 if ($ro) {
1611 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1612 if (my $err = $@) {
1613 warn "bindmount error\n";
1614 # don't leave writable bind-mounts behind...
1615 PVE::Tools::run_command(['umount', $dest]);
1616 die $err;
1617 }
1618 }
1619}
1620
1621sub bindmount {
1622 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1623
1624 my $srcdh = __bindmount_prepare('/', $dir);
1625
1626 __bindmount_do($dir, $dest, $ro, @extra_opts);
1627
1628 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
ab3722b3
WB
1629 PVE::Tools::run_command(['umount', $dest]);
1630 die "detected mount path change at: $dir\n";
1631 }
c2744c97
WB
1632}
1633
619f27b4
WB
1634# Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1635# from $rootdir and $mount and walk the path from $rootdir to the final
1636# directory to check for symlinks.
1637sub __mount_prepare_rootdir {
4c98d66c 1638 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
619f27b4
WB
1639 $rootdir =~ s!/+!/!g;
1640 $rootdir =~ s!/+$!!;
1641 my $mount_path = "$rootdir/$mount";
4c98d66c 1642 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1, $rootuid, $rootgid);
619f27b4
WB
1643 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1644}
1645
b15c75fc 1646# use $rootdir = undef to just return the corresponding mount path
cc6b0307 1647sub mountpoint_mount {
4c98d66c 1648 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
ef447944
WB
1649 return __mountpoint_mount($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1650}
1651
1652sub mountpoint_stage {
1653 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1654 my ($path, $loop, $dev) =
1655 __mountpoint_mount($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1656
1657 if (!defined($path)) {
1658 return undef if $! == ENOSYS;
1659 die "failed to mount subvolume: $!\n";
1660 }
1661
87962670
WB
1662 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1663 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1664 # point).
ef447944
WB
1665 my $err;
1666 my $fd = PVE::Tools::open_tree(&AT_FDCWD, $stage_dir, &OPEN_TREE_CLOEXEC | &OPEN_TREE_CLONE)
1667 or die "open_tree() on mount point failed: $!\n";
1668
1669 return wantarray ? ($path, $loop, $dev, $fd) : $fd;
1670}
1671
aee0902b
WB
1672sub mountpoint_insert_staged {
1673 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1674
1675 if (!defined($rootdir_fd)) {
1676 sysopen($rootdir_fd, '.', O_PATH | O_DIRECTORY)
1677 or die "failed to open '.': $!\n";
1678 }
1679
1680 my $dest_fd = walk_tree_nofollow_fd('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1681
1682 PVE::Tools::move_mount(
1683 fileno($mount_fd),
1684 '',
1685 fileno($dest_fd),
1686 '',
1687 &MOVE_MOUNT_F_EMPTY_PATH | &MOVE_MOUNT_T_EMPTY_PATH,
1688 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1689}
1690
ef447944
WB
1691# Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1692# can then open a file descriptor to it which can be used with the `move_mount` syscall.
1693# Note that if the kernel does not support the new mount API, this will not perform any action
1694# and return `undef` with $! = ENOSYS.
1695sub __mountpoint_mount {
1696 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1697
1698 if (defined($stage_mount) && !PVE::LXC::Tools::can_use_new_mount_api()) {
1699 $! = ENOSYS;
1700 return undef;
1701 }
cc6b0307 1702
48e36ac2
WB
1703 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1704 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1705 # which we use in __bindmount_verify()!
1706 my $mount = $stage_mount ? '/': $mountpoint->{mp};
1707
cc6b0307 1708 my $volid = $mountpoint->{volume};
7c921c80 1709 my $type = $mountpoint->{type};
50df544c
WB
1710 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1711 my $mounted_dev;
f598979f 1712
cc6b0307
AD
1713 return if !$volid || !$mount;
1714
ab3722b3
WB
1715 $mount =~ s!/+!/!g;
1716
b15c75fc 1717 my $mount_path;
ab3722b3 1718 my ($mpfd, $parentfd, $last_dir);
f598979f 1719
b15c75fc 1720 if (defined($rootdir)) {
619f27b4 1721 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
4c98d66c 1722 __mount_prepare_rootdir($rootdir, $mount, $rootuid, $rootgid);
116ce06f 1723 }
ef447944
WB
1724
1725 if (defined($stage_mount)) {
1726 $mount_path = $rootdir;
1727 }
f598979f 1728
b15c75fc 1729 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
cc6b0307 1730
b15c75fc 1731 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
cc6b0307 1732
2bf24eb3 1733 my $optlist = [];
e80cb0cd
TL
1734
1735 if (my $mountopts = $mountpoint->{mountoptions}) {
1736 my @opts = split(/;/, $mountpoint->{mountoptions});
1737 push @$optlist, grep { PVE::LXC::Config::is_valid_mount_option($_) } @opts;
2bf24eb3
OB
1738 }
1739
719129ea
WB
1740 my $acl = $mountpoint->{acl};
1741 if (defined($acl)) {
2bf24eb3 1742 push @$optlist, ($acl ? 'acl' : 'noacl');
471dd315 1743 }
2bf24eb3
OB
1744
1745 my $optstring = join(',', @$optlist);
c2744c97 1746 my $readonly = $mountpoint->{ro};
471dd315 1747
9de0505c
WL
1748 my @extra_opts;
1749 @extra_opts = ('-o', $optstring) if $optstring;
471dd315 1750
b15c75fc
DM
1751 if ($storage) {
1752
1753 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
7c138f58 1754
841fba68 1755 my $path = PVE::Storage::map_volume($storage_cfg, $volid, $snapname);
7c138f58 1756
841fba68 1757 $path = PVE::Storage::path($storage_cfg, $volid, $snapname) if !defined($path);
b15c75fc
DM
1758
1759 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1760 PVE::Storage::parse_volname($storage_cfg, $volid);
1761
c87b9dd8
DM
1762 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1763
b15c75fc 1764 if ($format eq 'subvol') {
30de33be 1765 if ($mount_path) {
3ceee38d
FE
1766 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1767 if (defined($snapname)) {
1768 $name .= "\@$snapname";
e84f7f5d 1769 if ($scfg->{type} eq 'zfspool') {
3ceee38d 1770 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', "$scfg->{pool}/$name", $mount_path]);
e84f7f5d 1771 } else {
30de33be
DM
1772 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1773 }
e84f7f5d 1774 } else {
719129ea
WB
1775 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1776 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
719129ea
WB
1777 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1778 }
ab3722b3 1779 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
50df544c 1780 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
30de33be 1781 }
b15c75fc 1782 }
5f6280cf 1783 return wantarray ? ($path, 0, undef) : $path;
c87b9dd8 1784 } elsif ($format eq 'raw' || $format eq 'iso') {
ada088e6
WB
1785 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1786 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1787 # Our autodev hook expects the /dev/dm-* device currently
1788 # and will create the /dev/mapper symlink accordingly
e439a713
WB
1789 $path = Cwd::realpath($path);
1790 die "failed to get device path\n" if !$path;
1791 ($path) = ($path =~ /^(.*)$/s); #untaint
50df544c
WB
1792 my $domount = sub {
1793 my ($path) = @_;
1794 if ($mount_path) {
1795 if ($format eq 'iso') {
1796 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1797 } elsif ($isBase || defined($snapname)) {
1798 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1799 } else {
1800 if ($quota) {
1801 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1802 }
c2744c97 1803 push @extra_opts, '-o', 'ro' if $readonly;
50df544c
WB
1804 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1805 }
1806 }
1807 };
30de33be 1808 my $use_loopdev = 0;
e6da5357
LS
1809 if ($scfg->{content}->{rootdir}) {
1810 if ($scfg->{path}) {
1811 $mounted_dev = run_with_loopdev($domount, $path, $readonly);
1812 $use_loopdev = 1;
1813 } else {
1814 $mounted_dev = $path;
1815 &$domount($path);
1816 }
b15c75fc 1817 } else {
e6da5357 1818 die "storage '$storage' does not support containers\n";
b15c75fc 1819 }
50df544c 1820 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
b15c75fc
DM
1821 } else {
1822 die "unsupported image format '$format'\n";
1823 }
7c921c80 1824 } elsif ($type eq 'device') {
c9bc95a1 1825 push @extra_opts, '-o', 'ro' if $readonly;
0d449e38
WB
1826 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1827 # See the NOTE above about devicemapper canonicalization
1828 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
471dd315 1829 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
0d449e38 1830 return wantarray ? ($volid, 0, $devpath) : $volid;
e2007ac2
DM
1831 } elsif ($type eq 'bind') {
1832 die "directory '$volid' does not exist\n" if ! -d $volid;
ab3722b3 1833 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
50df544c
WB
1834 warn "cannot enable quota control for bind mounts\n" if $quota;
1835 return wantarray ? ($volid, 0, undef) : $volid;
b15c75fc 1836 }
f598979f 1837
b15c75fc 1838 die "unsupported storage";
cc6b0307
AD
1839}
1840
2e8f5857 1841sub mountpoint_hotplug :prototype($$$$$) {
b2de4c04
WB
1842 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1843
1844 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1845
172ea186
WB
1846 # We do the rest in a fork with an unshared mount namespace, because:
1847 # -) change our papparmor profile to that of /usr/bin/lxc-start
1848 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1849 # container's namespace, then mount it.
b2de4c04
WB
1850
1851 PVE::Tools::run_fork(sub {
1852 # Pin the container pid longer, we also need to get its monitor/parent:
1853 my ($ct_pid, $ct_pidfd) = open_lxc_pid($vmid)
1854 or die "failed to open pidfd of container $vmid\'s init process\n";
1855
1856 my ($monitor_pid, $monitor_pidfd) = open_ppid($ct_pid)
1857 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1858
1859 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1860 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1861
172ea186
WB
1862 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1863 # profile to lower our privileges to the same level we have in the start hook:
1864 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY)
1865 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1866 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1867 # apparmor.
1868
b2de4c04
WB
1869 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1870 # namespace for it to remain active there since the container will be able to unmount
1871 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1872 # concern.
1873 PVE::Tools::setns(fileno($monitor_mnt_ns), PVE::Tools::CLONE_NEWNS);
1874 chdir('/')
1875 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1876
1877 my $dir = get_staging_mount_path($opt);
172ea186
WB
1878
1879 # Now switch our apparmor profile before mounting:
1880 my $data = 'changeprofile /usr/bin/lxc-start';
1881 if (syswrite($aa_fd, $data, length($data)) != length($data)) {
1882 die "failed to change apparmor profile: $!\n";
1883 }
1884 # Check errors on close as well:
1885 close($aa_fd)
1886 or die "failed to change apparmor profile (close() failed): $!\n";
1887
b2de4c04
WB
1888 my $mount_fd = mountpoint_stage($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1889
1890 PVE::Tools::setns(fileno($ct_mnt_ns), PVE::Tools::CLONE_NEWNS);
1891 chdir('/')
1892 or die "failed to change root directory within the container's mount namespace: $!\n";
1893
1894 mountpoint_insert_staged($mount_fd, undef, $mp->{mp}, $opt, $rootuid, $rootgid);
1895 });
1896}
1897
180c05c5
WB
1898# Create a directory in the mountpoint staging tempfs.
1899sub get_staging_mount_path($) {
1900 my ($opt) = @_;
1901
1902 my $target = get_staging_tempfs() . "/$opt";
1903 if (!mkdir($target) && $! != EEXIST) {
1904 die "failed to create directory $target: $!\n";
1905 }
1906
1907 return $target;
1908}
1909
1910# Mount /run/pve/mountpoints as tmpfs
1911sub get_staging_tempfs() {
1912 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
1913 # mounts to that.
1914 my $target = '/var/lib/lxc/.pve-staged-mounts';
1915 if (!mkdir($target)) {
1916 return $target if $! == EEXIST;
1917 die "failed to create directory $target: $!\n";
1918 }
1919
1920 PVE::Tools::mount("none", $target, 'tmpfs', 0, "size=8k,mode=755")
1921 or die "failed to mount $target as tmpfs: $!\n";
1922
1923 return $target;
1924}
1925
6c871c36 1926sub mkfs {
d216e891 1927 my ($dev, $rootuid, $rootgid) = @_;
6c871c36 1928
06c7c7f1
TL
1929 run_command(
1930 [
1931 'mkfs.ext4',
1932 '-O',
1933 'mmp',
1934 '-E',
1935 "root_owner=$rootuid:$rootgid",
1936 $dev,
1937 ],
1938 outfunc => sub {
1939 my $line = shift;
1940 # a hack to print only the relevant stuff, i.e., the one which could help on repair
1941 if ($line =~ /^(Creating filesystem|Filesystem UUID|Superblock backups|\s+\d+, \d)/) {
1942 print "$line\n";
1943 }
1944 },
1945 errfunc => sub {
1946 my $line = shift;
1947 print STDERR "$line\n" if $line && $line !~ /^mke2fs \d\.\d/;
1948 }
1949 );
6c871c36
DM
1950}
1951
1952sub format_disk {
d216e891 1953 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
6c871c36
DM
1954
1955 if ($volid =~ m!^/dev/.+!) {
1956 mkfs($volid);
1957 return;
1958 }
1959
1960 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1961
1962 die "cannot format volume '$volid' with no storage\n" if !$storage;
1963
08ca136d
DM
1964 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1965
841fba68
DM
1966 my $path = PVE::Storage::map_volume($storage_cfg, $volid);
1967
1968 $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
6c871c36
DM
1969
1970 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1971 PVE::Storage::parse_volname($storage_cfg, $volid);
1972
1973 die "cannot format volume '$volid' (format == $format)\n"
1974 if $format ne 'raw';
1975
d216e891 1976 mkfs($path, $rootuid, $rootgid);
6c871c36
DM
1977}
1978
1979sub destroy_disks {
1980 my ($storecfg, $vollist) = @_;
1981
1982 foreach my $volid (@$vollist) {
1983 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1984 warn $@ if $@;
1985 }
1986}
1987
c9cf8008
WB
1988sub alloc_disk {
1989 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1990
1991 my $needs_chown = 0;
1992 my $volid;
1993
1994 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1995 # fixme: use better naming ct-$vmid-disk-X.raw?
1996
1997 eval {
1998 my $do_format = 0;
e6da5357 1999 if ($scfg->{content}->{rootdir} && $scfg->{path}) {
1b0d36cc 2000 if ($size_kb > 0 && !($scfg->{type} eq 'btrfs' && $scfg->{quotas})) {
ac2f06e1 2001 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
c9cf8008
WB
2002 $do_format = 1;
2003 } else {
94c74a54 2004 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
c9cf8008
WB
2005 $needs_chown = 1;
2006 }
2007 } elsif ($scfg->{type} eq 'zfspool') {
ac2f06e1 2008 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol', undef, $size_kb);
c9cf8008 2009 $needs_chown = 1;
e6da5357 2010 } elsif ($scfg->{content}->{rootdir}) {
c9cf8008
WB
2011 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
2012 $do_format = 1;
2013 } else {
4ffbea26 2014 die "content type 'rootdir' is not available or configured on storage '$storage'\n";
c9cf8008
WB
2015 }
2016 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
2017 };
2018 if (my $err = $@) {
2019 # in case formatting got interrupted:
2020 if (defined($volid)) {
2021 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
2022 warn $@ if $@;
2023 }
2024 die $err;
2025 }
2026
2027 return ($volid, $needs_chown);
2028}
2029
6c871c36 2030sub create_disks {
32e15a2b 2031 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
6c871c36
DM
2032
2033 my $vollist = [];
2034
2035 eval {
d216e891
WB
2036 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
2037 my $chown_vollist = [];
2038
015740e6 2039 PVE::LXC::Config->foreach_volume($settings, sub {
6c871c36
DM
2040 my ($ms, $mountpoint) = @_;
2041
2042 my $volid = $mountpoint->{volume};
2043 my $mp = $mountpoint->{mp};
2044
2045 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
2046
2aee38e5 2047 if ($storage && ($volid =~ $NEW_DISK_RE)) {
8ed5ff9d 2048 my ($storeid, $size_gb) = ($1, $2);
6c871c36 2049
8ed5ff9d 2050 my $size_kb = int(${size_gb}*1024) * 1024;
6c871c36 2051
c9cf8008
WB
2052 my $needs_chown = 0;
2053 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
2054 push @$chown_vollist, $volid if $needs_chown;
6c871c36 2055 push @$vollist, $volid;
71c780b9
WB
2056 $mountpoint->{volume} = $volid;
2057 $mountpoint->{size} = $size_kb * 1024;
32e15a2b
OB
2058 if ($pending) {
2059 $conf->{pending}->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2060 } else {
2061 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
2062 }
6c871c36 2063 } else {
32e15a2b
OB
2064 # use specified/existing volid/dir/device
2065 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36
DM
2066 }
2067 });
d216e891
WB
2068
2069 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
2070 foreach my $volid (@$chown_vollist) {
2071 my $path = PVE::Storage::path($storecfg, $volid, undef);
2072 chown($rootuid, $rootgid, $path);
2073 }
2074 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
6c871c36
DM
2075 };
2076 # free allocated images on error
2077 if (my $err = $@) {
2078 destroy_disks($storecfg, $vollist);
32e15a2b 2079 die $err;
6c871c36
DM
2080 }
2081 return $vollist;
2082}
2083
6827e44d
AA
2084sub update_disksize {
2085 my ($vmid, $conf, $all_volumes) = @_;
2086
2087 my $changes;
2088 my $prefix = "CT $vmid:";
2089
2090 my $update_mp = sub {
2091 my ($key, $mp, @param) = @_;
2092 my $size = $all_volumes->{$mp->{volume}}->{size} // 0;
2093
2094 if (!defined($mp->{size}) || $size != $mp->{size}) {
2095 $changes = 1;
2096 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
2097 $mp->{size} = $size;
2098 my $nomp = 1 if ($key eq 'rootfs');
2099 $conf->{$key} = PVE::LXC::Config->print_ct_mountpoint($mp, $nomp);
2100 }
2101 };
2102
015740e6 2103 PVE::LXC::Config->foreach_volume($conf, $update_mp);
6827e44d
AA
2104
2105 return $changes;
2106}
2107
2108sub update_unused {
2109 my ($vmid, $conf, $all_volumes) = @_;
2110
2111 my $changes;
2112 my $prefix = "CT $vmid:";
2113
2114 # Note: it is allowed to define multiple storage entries with the same path
2115 # (alias), so we need to check both 'volid' and real 'path' (two different
2116 # volid can point to the same path).
2117
2118 # used and unused disks
2119 my $refpath = {};
2120 my $orphans = {};
2121
2122 foreach my $opt (keys %$conf) {
2123 next if ($opt !~ m/^unused\d+$/);
2124 my $vol = $all_volumes->{$conf->{$opt}};
2125 $refpath->{$vol->{path}} = $vol->{volid};
2126 }
2127
2128 foreach my $key (keys %$all_volumes) {
2129 my $vol = $all_volumes->{$key};
2130 my $in_use = PVE::LXC::Config->is_volume_in_use($conf, $vol->{volid});
2131 my $path = $vol->{path};
2132
2133 if ($in_use) {
2134 $refpath->{$path} = $key;
2135 delete $orphans->{$path};
2136 } else {
2137 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
2138 $orphans->{$path} = $key;
2139 }
2140 }
2141 }
2142
2143 for my $key (keys %$orphans) {
2144 my $disk = $orphans->{$key};
2145 my $unused = PVE::LXC::Config->add_unused_volume($conf, $disk);
2146
2147 if ($unused) {
2148 $changes = 1;
2149 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
2150 }
2151 }
2152
2153 return $changes;
2154}
2155
2156sub scan_volids {
2157 my ($cfg, $vmid) = @_;
2158
5a0db48a 2159 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid, undef, 'rootdir');
6827e44d
AA
2160
2161 my $all_volumes = {};
2162 foreach my $storeid (keys %$info) {
2163 foreach my $item (@{$info->{$storeid}}) {
2164 my $volid = $item->{volid};
2165 next if !($volid && $item->{size});
2166 $item->{path} = PVE::Storage::path($cfg, $volid);
2167 $all_volumes->{$volid} = $item;
2168 }
2169 }
2170
2171 return $all_volumes;
2172}
2173
2174sub rescan {
2175 my ($vmid, $nolock, $dryrun) = @_;
2176
2177 my $cfg = PVE::Storage::config();
2178
6827e44d
AA
2179 print "rescan volumes...\n";
2180 my $all_volumes = scan_volids($cfg, $vmid);
2181
2182 my $updatefn = sub {
2183 my ($vmid) = @_;
2184
2185 my $changes;
2186 my $conf = PVE::LXC::Config->load_config($vmid);
2187
2188 PVE::LXC::Config->check_lock($conf);
2189
2190 my $vm_volids = {};
2191 foreach my $volid (keys %$all_volumes) {
2192 my $info = $all_volumes->{$volid};
2193 $vm_volids->{$volid} = $info if $info->{vmid} == $vmid;
2194 }
2195
2196 my $upu = update_unused($vmid, $conf, $vm_volids);
2197 my $upd = update_disksize($vmid, $conf, $vm_volids);
2198 $changes = $upu || $upd;
2199
2200 PVE::LXC::Config->write_config($vmid, $conf) if $changes && !$dryrun;
2201 };
2202
2203 if (defined($vmid)) {
2204 if ($nolock) {
2205 &$updatefn($vmid);
2206 } else {
2207 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2208 }
2209 } else {
2210 my $vmlist = config_list();
2211 foreach my $vmid (keys %$vmlist) {
2212 if ($nolock) {
2213 &$updatefn($vmid);
2214 } else {
2215 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2216 }
2217 }
2218 }
2219}
2220
2221
68e8f3c5
DM
2222# bash completion helper
2223
2224sub complete_os_templates {
2225 my ($cmdname, $pname, $cvalue) = @_;
2226
2227 my $cfg = PVE::Storage::config();
2228
9e9bc3a6 2229 my $storeid;
68e8f3c5
DM
2230
2231 if ($cvalue =~ m/^([^:]+):/) {
2232 $storeid = $1;
2233 }
2234
2235 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
2236 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
2237
2238 my $res = [];
2239 foreach my $id (keys %$data) {
2240 foreach my $item (@{$data->{$id}}) {
2241 push @$res, $item->{volid} if defined($item->{volid});
2242 }
2243 }
2244
2245 return $res;
2246}
2247
68e8f3c5
DM
2248my $complete_ctid_full = sub {
2249 my ($running) = @_;
2250
2251 my $idlist = vmstatus();
2252
2253 my $active_hash = list_active_containers();
2254
2255 my $res = [];
2256
2257 foreach my $id (keys %$idlist) {
2258 my $d = $idlist->{$id};
2259 if (defined($running)) {
2260 next if $d->{template};
2261 next if $running && !$active_hash->{$id};
2262 next if !$running && $active_hash->{$id};
2263 }
2264 push @$res, $id;
2265
2266 }
2267 return $res;
2268};
2269
2270sub complete_ctid {
2271 return &$complete_ctid_full();
2272}
2273
2274sub complete_ctid_stopped {
2275 return &$complete_ctid_full(0);
2276}
2277
2278sub complete_ctid_running {
2279 return &$complete_ctid_full(1);
2280}
2281
c6a605f9
WB
2282sub parse_id_maps {
2283 my ($conf) = @_;
2284
2285 my $id_map = [];
2286 my $rootuid = 0;
2287 my $rootgid = 0;
2288
2289 my $lxc = $conf->{lxc};
2290 foreach my $entry (@$lxc) {
2291 my ($key, $value) = @$entry;
108c6cab
WB
2292 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
2293 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
c6a605f9
WB
2294 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2295 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2296 push @$id_map, [$type, $ct, $host, $length];
2297 if ($ct == 0) {
2298 $rootuid = $host if $type eq 'u';
2299 $rootgid = $host if $type eq 'g';
2300 }
2301 } else {
108c6cab 2302 die "failed to parse idmap: $value\n";
c6a605f9
WB
2303 }
2304 }
2305
2306 if (!@$id_map && $conf->{unprivileged}) {
2307 # Should we read them from /etc/subuid?
2308 $id_map = [ ['u', '0', '100000', '65536'],
2309 ['g', '0', '100000', '65536'] ];
2310 $rootuid = $rootgid = 100000;
2311 }
2312
2313 return ($id_map, $rootuid, $rootgid);
2314}
2315
01dce99b
WB
2316sub userns_command {
2317 my ($id_map) = @_;
2318 if (@$id_map) {
2319 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2320 }
2321 return [];
2322}
2323
572efee1
TL
2324my sub print_ct_stderr_log {
2325 my ($vmid) = @_;
2326 my $log = eval { file_get_contents("/run/pve/ct-$vmid.stderr") };
2327 return if !$log;
2328
2329 while ($log =~ /^\h*(lxc-start:?\s+$vmid:?\s*\S+\s*)?(.*?)\h*$/gm) {
2330 my $line = $2;
2331 print STDERR "$line\n";
2332 }
2333}
c717bffb
TL
2334my sub print_ct_warn_log {
2335 my ($vmid) = @_;
2336 my $log_fn = "/run/pve/ct-$vmid.warnings";
2337 my $log = eval { file_get_contents($log_fn) };
2338 return if !$log;
2339
c717bffb 2340 while ($log =~ /^\h*\s*(.*?)\h*$/gm) {
0e0ae7e0 2341 PVE::RESTEnvironment::log_warn($1);
c717bffb
TL
2342 }
2343 unlink $log_fn or warn "could not unlink '$log_fn' - $!\n";
2344}
572efee1 2345
6e42d509
TL
2346my sub monitor_state_change($$) {
2347 my ($monitor_socket, $vmid) = @_;
2348 die "no monitor socket\n" if !defined($monitor_socket);
2349
2350 while (1) {
2351 my ($type, $name, $value) = PVE::LXC::Monitor::read_lxc_message($monitor_socket);
2352
2353 die "monitor socket: got EOF\n" if !defined($type);
2354
2355 next if $name ne "$vmid" || $type ne 'STATE';
2356
2357 if ($value eq PVE::LXC::Monitor::STATE_STARTING) {
2358 alarm(0); # don't timeout after seeing the starting state
2359 } elsif ($value eq PVE::LXC::Monitor::STATE_ABORTING ||
2360 $value eq PVE::LXC::Monitor::STATE_STOPPING ||
2361 $value eq PVE::LXC::Monitor::STATE_STOPPED) {
2362 return 0;
2363 } elsif ($value eq PVE::LXC::Monitor::STATE_RUNNING) {
2364 return 1;
2365 } else {
2366 warn "unexpected message from monitor socket - " .
2367 "type: '$type' - value: '$value'\n";
2368 }
2369 }
2370}
2371my sub monitor_start($$) {
2372 my ($monitor_socket, $vmid) = @_;
2373
2374 my $success = eval {
2375 PVE::Tools::run_with_timeout(10, \&monitor_state_change, $monitor_socket, $vmid)
2376 };
2377 if (my $err = $@) {
2378 warn "problem with monitor socket, but continuing anyway: $err\n";
2379 } elsif (!$success) {
572efee1 2380 print_ct_stderr_log($vmid);
6e42d509
TL
2381 die "startup for container '$vmid' failed\n";
2382 }
2383}
2384
6725e93c 2385sub vm_start {
cc9967d2 2386 my ($vmid, $conf, $skiplock, $debug) = @_;
6725e93c 2387
60b3c5e4
OB
2388 # apply pending changes while starting
2389 if (scalar(keys %{$conf->{pending}})) {
2390 my $storecfg = PVE::Storage::config();
2391 PVE::LXC::Config->vmconfig_apply_pending($vmid, $conf, $storecfg);
87c36547 2392 PVE::LXC::Config->write_config($vmid, $conf);
60b3c5e4
OB
2393 $conf = PVE::LXC::Config->load_config($vmid); # update/reload
2394 }
2395
6725e93c
AA
2396 update_lxc_config($vmid, $conf);
2397
2e64f057
AA
2398 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2399
2400 if ($skiplock) {
2401 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2402 close($fh);
2403 }
6725e93c 2404
e8bb92bd
SI
2405 my $storage_cfg = PVE::Storage::config();
2406 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
2407
2408 PVE::Storage::activate_volumes($storage_cfg, $vollist);
2409
6e42d509 2410 my $monitor_socket = eval { PVE::LXC::Monitor::get_monitor_socket() };
abaa24bd
FE
2411 warn $@ if $@;
2412
572efee1
TL
2413 unlink "/run/pve/ct-$vmid.stderr"; # systemd does not truncate log files
2414
cc9967d2
TL
2415 my $is_debug = $debug || (!defined($debug) && $conf->{debug});
2416 my $base_unit = $is_debug ? 'pve-container-debug' : 'pve-container';
abaa24bd 2417
cc9967d2 2418 my $cmd = ['systemctl', 'start', "$base_unit\@$vmid"];
6725e93c 2419
1a416433 2420 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
abaa24bd 2421 eval {
10937f87 2422 run_command($cmd);
abaa24bd 2423
6e42d509 2424 monitor_start($monitor_socket, $vmid) if defined($monitor_socket);
cc9967d2
TL
2425
2426 # if debug is requested, print the log it also when the start succeeded
2427 print_ct_stderr_log($vmid) if $is_debug;
c717bffb
TL
2428
2429 print_ct_warn_log($vmid); # always print warn log, if any
abaa24bd 2430 };
2e64f057
AA
2431 if (my $err = $@) {
2432 unlink $skiplock_flag_fn;
1322f50d 2433 die $err;
2e64f057 2434 }
1a416433 2435 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
6725e93c
AA
2436
2437 return;
2438}
2439
b1bad293
WB
2440# Helper to stop a container completely and make sure it has stopped completely.
2441# This is necessary because we want the post-stop hook to have completed its
2442# unmount-all step, but post-stop happens after lxc puts the container into the
2443# STOPPED state.
e0e29818
TL
2444# $kill - if true it will always do an immediate hard-stop
2445# $shutdown_timeout - the timeout to wait for a gracefull shutdown
2446# $kill_after_timeout - if true, send a hardstop if shutdown timed out
b1bad293 2447sub vm_stop {
e0e29818 2448 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
b1bad293
WB
2449
2450 # Open the container's command socket.
2451 my $path = "\0/var/lib/lxc/$vmid/command";
2452 my $sock = IO::Socket::UNIX->new(
2453 Type => SOCK_STREAM(),
2454 Peer => $path,
2455 );
2456 if (!$sock) {
2457 return if $! == ECONNREFUSED; # The container is not running
2458 die "failed to open container ${vmid}'s command socket: $!\n";
2459 }
2460
1a416433
DC
2461 my $conf = PVE::LXC::Config->load_config($vmid);
2462 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
2463
b1bad293
WB
2464 # Stop the container:
2465
2466 my $cmd = ['lxc-stop', '-n', $vmid];
2467
2468 if ($kill) {
2469 push @$cmd, '--kill'; # doesn't allow timeouts
e0e29818
TL
2470 } else {
2471 # lxc-stop uses a default timeout
2472 push @$cmd, '--nokill' if !$kill_after_timeout;
2473
2474 if (defined($shutdown_timeout)) {
2475 push @$cmd, '--timeout', $shutdown_timeout;
2476 # Give run_command 5 extra seconds
2477 $shutdown_timeout += 5;
2478 }
b1bad293
WB
2479 }
2480
10937f87 2481 eval { run_command($cmd, timeout => $shutdown_timeout) };
0d1d137e
FW
2482
2483 # Wait until the command socket is closed.
2484 # In case the lxc-stop call failed, reading from the command socket may block forever,
2485 # so poll with another timeout to avoid freezing the shutdown task.
b1bad293 2486 if (my $err = $@) {
0d1d137e 2487 warn $err if $err;
b1bad293 2488
0d1d137e
FW
2489 my $poll = IO::Poll->new();
2490 $poll->mask($sock => POLLIN | POLLHUP); # watch for input and EOF events
2491 $poll->poll($shutdown_timeout); # IO::Poll timeout is in seconds
2492 return if ($poll->events($sock) & POLLHUP);
2493 } else {
2494 my $result = <$sock>;
2495 return if !defined $result; # monitor is gone and the ct has stopped.
2496 }
b1bad293 2497
b1bad293
WB
2498 die "container did not stop\n";
2499}
846a66b0 2500
f5fe1125
OB
2501sub vm_reboot {
2502 my ($vmid, $timeout, $skiplock) = @_;
2503
2504 PVE::LXC::Config->lock_config($vmid, sub {
2505 return if !check_running($vmid);
2506
2507 vm_stop($vmid, 0, $timeout, 1); # kill if timeout exceeds
2508
2509 my $conf = PVE::LXC::Config->load_config($vmid);
2510 vm_start($vmid, $conf);
2511 });
2512}
2513
00501642
WB
2514sub run_unshared {
2515 my ($code) = @_;
2516
2517 return PVE::Tools::run_fork(sub {
2518 # Unshare the mount namespace
2519 die "failed to unshare mount namespace: $!\n"
2520 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
10937f87 2521 run_command(['mount', '--make-rslave', '/']);
00501642
WB
2522 return $code->();
2523 });
2524}
2525
2526my $copy_volume = sub {
4c98d66c 2527 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
00501642 2528
fd8cab92 2529 my $src_mp = { volume => $src_volid, mp => '/', ro => 1 };
00501642
WB
2530 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
2531
fd8cab92 2532 my $dst_mp = { volume => $dst_volid, mp => '/', ro => 0 };
00501642
WB
2533 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
2534
2535 my @mounted;
2536 eval {
2537 # mount and copy
2538 mkdir $src;
4c98d66c 2539 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
00501642
WB
2540 push @mounted, $src;
2541 mkdir $dest;
4c98d66c 2542 mountpoint_mount($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
00501642
WB
2543 push @mounted, $dest;
2544
08540353
SI
2545 $bwlimit //= 0;
2546
10937f87
TL
2547 run_command([
2548 'rsync',
2549 '--stats',
2550 '-X',
2551 '-A',
2552 '--numeric-ids',
2553 '-aH',
2554 '--whole-file',
2555 '--sparse',
2556 '--one-file-system',
2557 "--bwlimit=$bwlimit",
2558 "$src/",
2559 $dest
2560 ]);
00501642
WB
2561 };
2562 my $err = $@;
75c2677f
DJ
2563
2564 # Wait for rsync's children to release dest so that
2565 # consequent file operations (umount, remove) are possible
2566 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2567
00501642 2568 foreach my $mount (reverse @mounted) {
10937f87 2569 eval { run_command(['/bin/umount', $mount], errfunc => sub{})};
00501642
WB
2570 warn "Can't umount $mount\n" if $@;
2571 }
2572
2573 # If this fails they're used as mount points in a concurrent operation
2574 # (which should not happen but there's also no real need to get rid of them).
2575 rmdir $dest;
2576 rmdir $src;
2577
2578 die $err if $err;
2579};
2580
2581# Should not be called after unsharing the mount namespace!
2582sub copy_volume {
08540353 2583 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
00501642
WB
2584
2585 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
2586 File::Path::make_path("/var/lib/lxc/$vmid");
2587 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2588 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2589
2590 # get id's for unprivileged container
2591 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
2592
2593 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2594 # are visible in this namespace, otherwise the host only sees the empty
2595 # (not-mounted) directory.
2596 my $new_volid;
2597 eval {
5154e3e9
WB
2598 # Make sure $mp contains a correct size.
2599 $mp->{size} = PVE::Storage::volume_size_info($storage_cfg, $mp->{volume});
00501642
WB
2600 my $needs_chown;
2601 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
2602 if ($needs_chown) {
2603 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
2604 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
2605 chown($rootuid, $rootgid, $path);
2606 }
2607
2608 run_unshared(sub {
4c98d66c 2609 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
00501642
WB
2610 });
2611 };
2612 if (my $err = $@) {
2613 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
2614 if defined($new_volid);
2615 die $err;
2616 }
2617
2618 return $new_volid;
2619}
2620
022a70ff
WB
2621sub get_lxc_version() {
2622 my $version;
10937f87 2623 run_command([qw(lxc-start --version)], outfunc => sub {
022a70ff
WB
2624 my ($line) = @_;
2625 # We only parse out major & minor version numbers.
2626 if ($line =~ /^(\d+)\.(\d+)(?:\D.*)?$/) {
2627 $version = [$1, $2];
2628 }
2629 });
2630
2631 die "failed to get lxc version\n" if !defined($version);
2632
2633 # return as a list:
2634 return $version->@*;
2635}
2636
89424a8b
TL
2637sub freeze($) {
2638 my ($vmid) = @_;
396a9122
WB
2639 if (PVE::CGroup::cgroup_mode() == 2) {
2640 PVE::LXC::Command::freeze($vmid, 30);
2641 } else {
2642 PVE::LXC::CGroup->new($vmid)->freeze_thaw(1);
2643 }
89424a8b 2644}
c9b25dfd 2645
89424a8b
TL
2646sub thaw($) {
2647 my ($vmid) = @_;
396a9122
WB
2648 if (PVE::CGroup::cgroup_mode() == 2) {
2649 PVE::LXC::Command::unfreeze($vmid, 30);
2650 } else {
2651 PVE::LXC::CGroup->new($vmid)->freeze_thaw(0);
2652 }
c9b25dfd
WB
2653}
2654
f76a2828 26551;