]> git.proxmox.com Git - pve-container.git/blame - src/PVE/LXC.pm
mask 'mknod' feature by kernel version
[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;
f76a2828 16
f1ba1a4b 17use PVE::Exception qw(raise_perm_exc);
c65e0a6d 18use PVE::Storage;
f76a2828
DM
19use PVE::SafeSyslog;
20use PVE::INotify;
8233d33d 21use PVE::JSONSchema qw(get_standard_option);
2df08734
WB
22use PVE::Tools qw(
23 dir_glob_foreach file_get_contents file_set_contents lock_file
24 lock_file_full AT_FDCWD O_PATH $IPV4RE $IPV6RE
25);
92902047 26use PVE::CpuSet;
68fba17b 27use PVE::Network;
52389a07 28use PVE::AccessControl;
228a5a1d 29use PVE::ProcFSTools;
ef447944 30use PVE::Syscall qw(:fsmount);
67afe46e 31use PVE::LXC::Config;
1a416433 32use PVE::GuestHelpers;
ef447944 33use PVE::LXC::Tools;
8233d33d 34
688afc63 35use Time::HiRes qw (gettimeofday);
f76a2828 36
5a63f1c5
WB
37my $LXC_CONFIG_PATH = '/usr/share/lxc/config';
38
27916659
DM
39my $nodename = PVE::INotify::nodename();
40
688afc63
WL
41my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
42
f76a2828
DM
43sub config_list {
44 my $vmlist = PVE::Cluster::get_vmlist();
45 my $res = {};
46 return $res if !$vmlist || !$vmlist->{ids};
47 my $ids = $vmlist->{ids};
48
49 foreach my $vmid (keys %$ids) {
50 next if !$vmid; # skip CT0
51 my $d = $ids->{$vmid};
52 next if !$d->{node} || $d->{node} ne $nodename;
53 next if !$d->{type} || $d->{type} ne 'lxc';
8233d33d 54 $res->{$vmid} = { type => 'lxc', vmid => $vmid };
f76a2828
DM
55 }
56 return $res;
57}
58
822de0c3
DM
59# container status helpers
60
61sub list_active_containers {
cbb03fea 62
822de0c3
DM
63 my $filename = "/proc/net/unix";
64
65 # similar test is used by lcxcontainers.c: list_active_containers
66 my $res = {};
cbb03fea 67
822de0c3
DM
68 my $fh = IO::File->new ($filename, "r");
69 return $res if !$fh;
70
71 while (defined(my $line = <$fh>)) {
28df2cde 72 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
822de0c3 73 my $path = $1;
27916659 74 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
822de0c3
DM
75 $res->{$1} = 1;
76 }
77 }
78 }
79
80 close($fh);
cbb03fea 81
822de0c3
DM
82 return $res;
83}
f76a2828 84
5c752bbf
DM
85# warning: this is slow
86sub check_running {
87 my ($vmid) = @_;
88
89 my $active_hash = list_active_containers();
90
91 return 1 if defined($active_hash->{$vmid});
cbb03fea 92
5c752bbf
DM
93 return undef;
94}
95
10fc3ba5 96sub get_container_disk_usage {
73e03cb7 97 my ($vmid, $pid) = @_;
10fc3ba5 98
73e03cb7 99 return PVE::Tools::df("/proc/$pid/root/", 1);
10fc3ba5
DM
100}
101
688afc63
WL
102my $last_proc_vmid_stat;
103
104my $parse_cpuacct_stat = sub {
3b5070d4 105 my ($vmid, $unprivileged) = @_;
688afc63 106
3b5070d4 107 my $raw = read_cgroup_value('cpuacct', $vmid, $unprivileged, 'cpuacct.stat', 1);
688afc63
WL
108
109 my $stat = {};
110
111 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
112
113 $stat->{utime} = $1;
114 $stat->{stime} = $2;
115
116 }
117
118 return $stat;
119};
120
8233d33d
DM
121our $vmstatus_return_properties = {
122 vmid => get_standard_option('pve-vmid'),
123 status => {
124 description => "LXC Container status.",
125 type => 'string',
126 enum => ['stopped', 'running'],
127 },
128 maxmem => {
129 description => "Maximum memory in bytes.",
130 type => 'integer',
131 optional => 1,
132 renderer => 'bytes',
133 },
134 maxswap => {
135 description => "Maximum SWAP memory in bytes.",
136 type => 'integer',
137 optional => 1,
138 renderer => 'bytes',
139 },
140 maxdisk => {
141 description => "Root disk size in bytes.",
142 type => 'integer',
143 optional => 1,
144 renderer => 'bytes',
145 },
146 name => {
147 description => "Container name.",
148 type => 'string',
149 optional => 1,
150 },
151 uptime => {
152 description => "Uptime.",
153 type => 'integer',
154 optional => 1,
155 renderer => 'duration',
156 },
157 cpus => {
158 description => "Maximum usable CPUs.",
159 type => 'number',
160 optional => 1,
161 },
440b6427 162 lock => {
87c5dc96 163 description => "The current config lock, if any.",
440b6427
DC
164 type => 'string',
165 optional => 1,
733e52ec
DC
166 },
167 tags => {
168 description => "The current configured tags, if any.",
169 type => 'string',
170 optional => 1,
440b6427 171 }
8233d33d
DM
172};
173
f76a2828
DM
174sub vmstatus {
175 my ($opt_vmid) = @_;
176
8233d33d 177 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc', vmid => $opt_vmid }} : config_list();
f76a2828 178
822de0c3 179 my $active_hash = list_active_containers();
cbb03fea 180
688afc63
WL
181 my $cpucount = $cpuinfo->{cpus} || 1;
182
183 my $cdtime = gettimeofday;
184
185 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
80d56111 186 my $clock_ticks = POSIX::sysconf(&POSIX::_SC_CLK_TCK);
688afc63 187
3b5070d4
WB
188 my $unprivileged = {};
189
f76a2828 190 foreach my $vmid (keys %$list) {
f76a2828 191 my $d = $list->{$vmid};
10fc3ba5 192
d5588ee3
DM
193 eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
194 warn $@ if $@; # ignore errors (consider them stopped)
cbb03fea 195
2ff1c49c 196 $d->{status} = $active_hash->{$vmid} ? 'running' : 'stopped';
f76a2828 197
67afe46e 198 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
238a56cb 199 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
cbb03fea 200
3b5070d4
WB
201 $unprivileged->{$vmid} = $conf->{unprivileged};
202
aec218c7 203 $d->{name} = $conf->{'hostname'} || "CT$vmid";
238a56cb 204 $d->{name} =~ s/[\s]//g;
cbb03fea 205
f2357408
DM
206 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
207 $d->{cpus} = $cpucount if !$d->{cpus};
44da0641 208
d0226204 209 $d->{lock} = $conf->{lock} || '';
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});
27916659
DM
214 $d->{disk} = $res->{used};
215 $d->{maxdisk} = $res->{total};
216 } else {
217 $d->{disk} = 0;
218 # use 4GB by default ??
219 if (my $rootfs = $conf->{rootfs}) {
1b4cf758 220 my $rootinfo = PVE::LXC::Config->parse_ct_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
67afe46e 241 $d->{template} = 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
0b6a2f0e
WB
256 if (-d '/sys/fs/cgroup/memory') {
257 my $memory_stat = read_cgroup_list('memory', $vmid, $unpriv, 'memory.stat');
258 my $mem_usage_in_bytes = read_cgroup_value('memory', $vmid, $unpriv, 'memory.usage_in_bytes');
259
260 $d->{mem} = $mem_usage_in_bytes - $memory_stat->{total_cache};
261 $d->{swap} = read_cgroup_value('memory', $vmid, $unpriv, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
262 } else {
263 $d->{mem} = 0;
264 $d->{swap} = 0;
265 }
266
267 if (-d '/sys/fs/cgroup/blkio') {
0defbe08 268 my $blkio_bytes = read_cgroup_value('blkio', $vmid, 0, 'blkio.throttle.io_service_bytes', 1); # don't check if unpriv
0b6a2f0e
WB
269 my @bytes = split(/\n/, $blkio_bytes);
270 foreach my $byte (@bytes) {
271 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
272 $d->{diskread} += $2 if $key eq 'Read';
273 $d->{diskwrite} += $2 if $key eq 'Write';
274 }
1e647c7c 275 }
0b6a2f0e
WB
276 } else {
277 $d->{diskread} = 0;
278 $d->{diskwrite} = 0;
b5289322 279 }
688afc63 280
0b6a2f0e
WB
281 if (-d '/sys/fs/cgroup/cpuacct') {
282 my $pstat = $parse_cpuacct_stat->($vmid, $unpriv);
688afc63 283
0b6a2f0e 284 my $used = $pstat->{utime} + $pstat->{stime};
688afc63 285
0b6a2f0e
WB
286 my $old = $last_proc_vmid_stat->{$vmid};
287 if (!$old) {
288 $last_proc_vmid_stat->{$vmid} = {
289 time => $cdtime,
290 used => $used,
291 cpu => 0,
292 };
293 next;
294 }
688afc63 295
0b6a2f0e 296 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
688afc63 297
0b6a2f0e
WB
298 if ($dtime > 1000) {
299 my $dutime = $used - $old->{used};
688afc63 300
0b6a2f0e
WB
301 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
302 $last_proc_vmid_stat->{$vmid} = {
303 time => $cdtime,
304 used => $used,
305 cpu => $d->{cpu},
306 };
307 } else {
308 $d->{cpu} = $old->{cpu};
309 }
688afc63 310 } else {
0b6a2f0e 311 $d->{cpu} = 0;
688afc63 312 }
238a56cb 313 }
cbb03fea 314
68b8f4d1
WL
315 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
316
317 foreach my $dev (keys %$netdev) {
318 next if $dev !~ m/^veth([1-9]\d*)i/;
319 my $vmid = $1;
320 my $d = $list->{$vmid};
321
322 next if !$d;
323
324 $d->{netout} += $netdev->{$dev}->{receive};
325 $d->{netin} += $netdev->{$dev}->{transmit};
326
327 }
328
f76a2828
DM
329 return $list;
330}
331
3b5070d4
WB
332sub read_cgroup_list($$$$) {
333 my ($group, $vmid, $unprivileged, $name) = @_;
b3059d35 334
3b5070d4 335 my $content = read_cgroup_value($group, $vmid, $unprivileged, $name, 1);
b3059d35
TL
336
337 return { split(/\s+/, $content) };
338}
339
3b5070d4
WB
340sub read_cgroup_value($$$$$) {
341 my ($group, $vmid, $unprivileged, $name, $full) = @_;
238a56cb 342
3b5070d4
WB
343 my $nsdir = $unprivileged ? '' : 'ns/';
344 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/${nsdir}$name";
238a56cb
DM
345
346 return PVE::Tools::file_get_contents($path) if $full;
347
348 return PVE::Tools::file_read_firstline($path);
349}
350
bf0b8c43
AD
351sub write_cgroup_value {
352 my ($group, $vmid, $name, $value) = @_;
353
354 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
355 PVE::ProcFSTools::write_proc_entry($path, $value) if -e $path;
356
357}
358
52f1d76b
DM
359sub find_lxc_console_pids {
360
361 my $res = {};
362
363 PVE::Tools::dir_glob_foreach('/proc', '\d+', sub {
364 my ($pid) = @_;
365
366 my $cmdline = PVE::Tools::file_read_firstline("/proc/$pid/cmdline");
367 return if !$cmdline;
368
369 my @args = split(/\0/, $cmdline);
370
c31ad455 371 # search for lxc-console -n <vmid>
cbb03fea 372 return if scalar(@args) != 3;
52f1d76b
DM
373 return if $args[1] ne '-n';
374 return if $args[2] !~ m/^\d+$/;
375 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
cbb03fea 376
52f1d76b 377 my $vmid = $args[2];
cbb03fea 378
52f1d76b
DM
379 push @{$res->{$vmid}}, $pid;
380 });
381
382 return $res;
383}
384
bedeaaf1
AD
385sub find_lxc_pid {
386 my ($vmid) = @_;
387
388 my $pid = undef;
389 my $parser = sub {
390 my $line = shift;
8b25977f 391 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
bedeaaf1 392 };
c39aa40a 393 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
bedeaaf1 394
8b25977f 395 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
cbb03fea 396
8b25977f 397 return $pid;
bedeaaf1
AD
398}
399
ab74a9ba
WB
400sub open_pid_fd($) {
401 my ($pid) = @_;
402 sysopen(my $fd, "/proc/$pid", O_RDONLY | O_DIRECTORY)
403 or die "failed to open /proc/$pid pid fd\n";
404 return $fd;
405}
406
407sub open_lxc_pid {
408 my ($vmid) = @_;
409
410 # Find the pid and open:
411 my $pid = find_lxc_pid($vmid);
412 my $fd = open_pid_fd($pid);
413
414 # Verify:
415 my $pid2 = find_lxc_pid($vmid);
416
417 return () if $pid != $pid2;
418 return ($pid, $fd);
419}
420
421sub open_ppid {
422 my ($pid) = @_;
423
424 # Find the parent pid via proc and open it:
425 my $stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
426 my $ppid = $stat->{ppid} // die "failed to get parent pid\n";
427
428 my $fd = open_pid_fd($ppid);
429
430 # Verify:
431 $stat = PVE::ProcFSTools::read_proc_pid_stat($pid);
432 my $ppid2 = $stat->{ppid} // die "failed to get parent pid for verification\n";
433
434 return () if $ppid != $ppid2;
435 return ($ppid, $fd);
436}
437
cbb03fea 438# Note: we cannot use Net:IP, because that only allows strict
55fa4e09
DM
439# CIDR networks
440sub parse_ipv4_cidr {
441 my ($cidr, $noerr) = @_;
442
f7a7b413
WB
443 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
444 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
55fa4e09 445 }
cbb03fea 446
55fa4e09 447 return undef if $noerr;
cbb03fea 448
55fa4e09
DM
449 die "unable to parse ipv4 address/mask\n";
450}
93285df8 451
0b6a2f0e
WB
452sub get_cgroup_subsystems {
453 my $v1 = {};
454 my $v2 = 0;
455 my $data = PVE::Tools::file_get_contents('/proc/self/cgroup');
456 while ($data =~ /^\d+:([^:\n]*):.*$/gm) {
457 my $type = $1;
458 if (length($type)) {
459 $v1->{$_} = 1 foreach split(/,/, $type);
460 } else {
461 $v2 = 1;
462 }
463 }
464 return wantarray ? ($v1, $v2) : $v1;
465}
e22af68f 466
2df08734
WB
467# With seccomp trap to userspace we now have the ability to optionally forward
468# certain syscalls to the "host" to handle (via our pve-lxc-syscalld daemon).
5a63f1c5 469#
2df08734
WB
470# This means that there are cases where we need to create an extra seccomp
471# profile for the container to load.
472#
473# This returns a configuration snippet added to the raw lxc config.
5a63f1c5 474sub make_seccomp_config {
2df08734 475 my ($conf, $conf_dir, $unprivileged, $features) = @_;
5a63f1c5
WB
476 # User-configured profile has precedence, note that the user's entry would
477 # be written 'after' this line anyway...
478 if (PVE::LXC::Config->has_lxc_entry($conf, 'lxc.seccomp.profile')) {
479 # Warn the user if this conflicts with a feature:
2df08734
WB
480 my $warn = join(', ', grep { $features->{$_} } qw(keyctl mknod));
481 warn "explicitly configured lxc.seccomp.profile overrides the following settings: $warn\n"
482 if length($warn) > 0;
5a63f1c5
WB
483 return '';
484 }
485
486 # Privileged containers keep using the default (which is already part of
487 # the files included via lxc.include, so we don't need to write it out,
488 # that way it stays admin-configurable via /usr/share/lxc/config/... as
489 # well)
490 return '' if !$unprivileged;
491
2df08734
WB
492 my $rules = {
493 keyctl => ['errno 38'],
494 };
495
496 my $raw_conf = '';
497
5a63f1c5
WB
498 # Unprivileged containers will get keyctl() disabled by default as a
499 # workaround for systemd-networkd behavior. But we have an option to
500 # explicitly enable it:
2df08734
WB
501 if ($features->{keyctl}) {
502 delete $rules->{keyctl};
503 }
504
505 # By default, unprivileged containers cannot use `mknod` at all.
506 # Since lxc 3.2, we can use seccomp's trap to userspace feature for this,
507 # but for now this is experimental, so it has to be enabled via a feature
508 # flag.
509 # Note that we only handle block and char devices (like lxd), the rest we
510 # leave up to the kernel. We may in the future remove this if seccomp gets
511 # a way to tell the kernel to "continue" a syscall.
512 if ($features->{mknod}) {
b6bbd32c
WB
513 my ($ok, $kernel) = PVE::ProcFSTools::check_kernel_release(5, 3);
514 if (!$ok) {
515 die "'mknod' feature requested, but kernel too old (found $kernel, required >= 5.3)\n";
516 }
517
2df08734
WB
518 $raw_conf .= "lxc.seccomp.notify.proxy = unix:/run/pve/lxc-syscalld.sock\n";
519
520 $rules->{mknod} = [
521 # condition: (mode & S_IFMT) == S_IFCHR
522 'notify [1,8192,SCMP_CMP_MASKED_EQ,61440]',
523 # condition: (mode & S_IFMT) == S_IFBLK
524 'notify [1,24576,SCMP_CMP_MASKED_EQ,61440]',
525 ];
526 $rules->{mknodat} = [
527 # condition: (mode & S_IFMT) == S_IFCHR
528 'notify [2,8192,SCMP_CMP_MASKED_EQ,61440]',
529 # condition: (mode & S_IFMT) == S_IFBLK
530 'notify [2,24576,SCMP_CMP_MASKED_EQ,61440]',
531 ];
532 }
533
534 # Now build the custom seccomp rule text...
535 my $extra_rules = join("\n", map {
536 my $syscall = $_;
537 map { "$syscall $_" } $rules->{$syscall}->@*
538 } sort keys %$rules) . "\n";
539
540 return $raw_conf if $extra_rules eq "\n";
541
542 # We still have the "most common" config readily available, so don't write
543 # out that one:
544 if ($raw_conf eq '' && $extra_rules eq "keyctl errno 38\n") {
545 # we have no extra $raw_conf and use the same we had in pve 6.1:
546 return "lxc.seccomp.profile = $LXC_CONFIG_PATH/pve-userns.seccomp\n";
547 }
548
549 # Write the rule file to the container's config path:
550 my $rule_file = "$conf_dir/rules.seccomp";
551 my $rule_data = file_get_contents("$LXC_CONFIG_PATH/common.seccomp")
552 . $extra_rules;
553 file_set_contents($rule_file, $rule_data);
554 $raw_conf .= "lxc.seccomp.profile = $rule_file\n";
5a63f1c5 555
2df08734 556 return $raw_conf;
5a63f1c5
WB
557}
558
559# Since lxc-3.0.2 we can have lxc generate a profile for the container
560# automatically. The default should be equivalent to the old
561# `lxc-container-default-cgns` profile.
562#
563# Additionally this also added `lxc.apparmor.raw` which can be used to inject
564# additional lines into the profile. We can use that to allow mounting specific
565# file systems.
566sub make_apparmor_config {
567 my ($conf, $unprivileged, $features) = @_;
568
569 # user-configured profile has precedence, but first we go through our own
570 # code to figure out whether we should warn the user:
571
572 my $raw = "lxc.apparmor.profile = generated\n";
573 my @profile_uses;
574
96f8d2a2
WB
575 if ($features->{fuse}) {
576 # For the informational warning:
577 push @profile_uses, 'features:fuse';
578 }
579
5a63f1c5
WB
580 # There's lxc.apparmor.allow_nesting now, which will add the necessary
581 # apparmor lines, create an apparmor namespace for the container, but also
582 # adds proc and sysfs mounts to /dev/.lxc/{proc,sys}. These do not have
583 # lxcfs mounted over them, because that would prevent the container from
584 # mounting new instances of them for nested containers.
585 if ($features->{nesting}) {
586 push @profile_uses, 'features:nesting';
587 $raw .= "lxc.apparmor.allow_nesting = 1\n"
588 } else {
589 # In the default profile in /etc/apparmor.d we patch this in because
590 # otherwise a container can for example run `chown` on /sys, breaking
591 # access to it for non-CAP_DAC_OVERRIDE tools on the host:
592 $raw .= "lxc.apparmor.raw = deny mount -> /proc/,\n";
593 $raw .= "lxc.apparmor.raw = deny mount -> /sys/,\n";
594 # Preferably we could use the 'remount' flag but this does not sit well
595 # with apparmor_parser currently:
596 # mount options=(rw, nosuid, nodev, noexec, remount) -> /sys/,
597 }
598
599 if (my $mount = $features->{mount}) {
600 push @profile_uses, 'features:mount';
601 foreach my $fs (PVE::Tools::split_list($mount)) {
602 $raw .= "lxc.apparmor.raw = mount fstype=$fs,\n";
603 }
604 }
605
606 # More to come?
607
608 if (PVE::LXC::Config->has_lxc_entry($conf, 'lxc.apparmor.profile')) {
609 if (length(my $used = join(', ', @profile_uses))) {
610 warn "explicitly configured lxc.apparmor.profile overrides the following settings: $used\n";
611 }
612 return '';
613 }
614
615 return $raw;
616}
617
27916659 618sub update_lxc_config {
f91f3669 619 my ($vmid, $conf) = @_;
b80dd50a 620
bb1ac2de
DM
621 my $dir = "/var/lib/lxc/$vmid";
622
623 if ($conf->{template}) {
624
625 unlink "$dir/config";
626
627 return;
628 }
629
27916659 630 my $raw = '';
b80dd50a 631
27916659
DM
632 die "missing 'arch' - internal error" if !$conf->{arch};
633 $raw .= "lxc.arch = $conf->{arch}\n";
b80dd50a 634
5a63f1c5
WB
635 my $custom_idmap = PVE::LXC::Config->has_lxc_entry($conf, 'lxc.idmap');
636 my $unprivileged = $conf->{unprivileged} || $custom_idmap;
425b62cb 637
27916659 638 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
866e0611 639
059f7bb4
WB
640 my $cfgpath = '/usr/share/lxc/config';
641 my $inc = "$cfgpath/$ostype.common.conf";
642 $inc ="$cfgpath/common.conf" if !-f $inc;
866e0611 643 $raw .= "lxc.include = $inc\n";
5a63f1c5 644 if ($unprivileged) {
059f7bb4
WB
645 $inc = "$cfgpath/$ostype.userns.conf";
646 $inc = "$cfgpath/userns.conf" if !-f $inc;
647 $raw .= "lxc.include = $inc\n";
27916659 648 }
b80dd50a 649
5a63f1c5
WB
650 my $features = PVE::LXC::Config->parse_features($conf->{features});
651
2df08734 652 $raw .= make_seccomp_config($conf, $dir, $unprivileged, $features);
5a63f1c5 653 $raw .= make_apparmor_config($conf, $unprivileged, $features);
96f8d2a2
WB
654 if ($features->{fuse}) {
655 $raw .= "lxc.apparmor.raw = mount fstype=fuse,\n";
656 $raw .= "lxc.mount.entry = /dev/fuse dev/fuse none bind,create=file 0 0\n";
657 }
5a63f1c5 658
50df544c
WB
659 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
660 # cannot be exposed to the container with r/w access (cgroup perms).
661 # When this is enabled mounts will still remain in the monitor's namespace
662 # after the container unmounted them and thus will not detach from their
663 # files while the container is running!
c16b8890 664 $raw .= "lxc.monitor.unshare = 1\n";
58cc92a9 665
0b6a2f0e
WB
666 my $cgv1 = get_cgroup_subsystems();
667
425b62cb
WB
668 # Should we read them from /etc/subuid?
669 if ($unprivileged && !$custom_idmap) {
108c6cab
WB
670 $raw .= "lxc.idmap = u 0 100000 65536\n";
671 $raw .= "lxc.idmap = g 0 100000 65536\n";
425b62cb
WB
672 }
673
d250604f 674 if (!PVE::LXC::Config->has_dev_console($conf)) {
108c6cab 675 $raw .= "lxc.console.path = none\n";
0b6a2f0e 676 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n" if $cgv1->{devices};
eeaea429 677 }
4f958489 678
1b4cf758 679 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
108c6cab 680 $raw .= "lxc.tty.max = $ttycount\n";
cbb03fea 681
c31ad455 682 # some init scripts expect a linux terminal (turnkey).
a691a5a3
DM
683 $raw .= "lxc.environment = TERM=linux\n";
684
27916659 685 my $utsname = $conf->{hostname} || "CT$vmid";
108c6cab 686 $raw .= "lxc.uts.name = $utsname\n";
cbb03fea 687
0b6a2f0e
WB
688 if ($cgv1->{memory}) {
689 my $memory = $conf->{memory} || 512;
690 my $swap = $conf->{swap} // 0;
a12a36e0 691
0b6a2f0e
WB
692 my $lxcmem = int($memory*1024*1024);
693 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
27916659 694
0b6a2f0e
WB
695 my $lxcswap = int(($memory + $swap)*1024*1024);
696 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
a12a36e0
WL
697 }
698
0b6a2f0e
WB
699 if ($cgv1->{cpu}) {
700 if (my $cpulimit = $conf->{cpulimit}) {
701 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
702 my $value = int(100000*$cpulimit);
703 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
704 }
705
706 my $shares = $conf->{cpuunits} || 1024;
707 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
708 }
27916659 709
fddaa91b
DM
710 die "missing 'rootfs' configuration\n"
711 if !defined($conf->{rootfs});
712
1b4cf758 713 my $mountpoint = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
a3076d81 714
108c6cab 715 $raw .= "lxc.rootfs.path = $dir/rootfs\n";
27916659 716
e756bdd6 717 foreach my $k (sort keys %$conf) {
27916659
DM
718 next if $k !~ m/^net(\d+)$/;
719 my $ind = $1;
1b4cf758 720 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
108c6cab
WB
721 $raw .= "lxc.net.$ind.type = veth\n";
722 $raw .= "lxc.net.$ind.veth.pair = veth${vmid}i${ind}\n";
723 $raw .= "lxc.net.$ind.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
724 $raw .= "lxc.net.$ind.name = $d->{name}\n" if defined($d->{name});
725 $raw .= "lxc.net.$ind.mtu = $d->{mtu}\n" if defined($d->{mtu});
a12a36e0
WL
726 }
727
0b6a2f0e
WB
728 if ($cgv1->{cpuset}) {
729 my $had_cpuset = 0;
730 if (my $lxcconf = $conf->{lxc}) {
731 foreach my $entry (@$lxcconf) {
732 my ($k, $v) = @$entry;
733 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
734 $raw .= "$k = $v\n";
735 }
e576f689 736 }
27916659 737
0b6a2f0e
WB
738 my $cores = $conf->{cores};
739 if (!$had_cpuset && $cores) {
740 my $cpuset = eval { PVE::CpuSet->new_from_cgroup('lxc', 'effective_cpus') };
741 $cpuset = PVE::CpuSet->new_from_cgroup('', 'effective_cpus') if !$cpuset;
742 my @members = $cpuset->members();
743 while (scalar(@members) > $cores) {
744 my $randidx = int(rand(scalar(@members)));
745 $cpuset->delete($members[$randidx]);
746 splice(@members, $randidx, 1); # keep track of the changes
747 }
748 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
92902047 749 }
92902047 750 }
0b6a2f0e 751
27916659
DM
752 File::Path::mkpath("$dir/rootfs");
753
754 PVE::Tools::file_set_contents("$dir/config", $raw);
b80dd50a
DM
755}
756
117636e5
DM
757# verify and cleanup nameserver list (replace \0 with ' ')
758sub verify_nameserver_list {
759 my ($nameserver_list) = @_;
760
761 my @list = ();
762 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
763 PVE::JSONSchema::pve_verify_ip($server);
764 push @list, $server;
765 }
766
767 return join(' ', @list);
768}
769
770sub verify_searchdomain_list {
771 my ($searchdomain_list) = @_;
772
773 my @list = ();
774 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
775 # todo: should we add checks for valid dns domains?
776 push @list, $server;
777 }
778
779 return join(' ', @list);
780}
781
aca816ad 782sub get_console_command {
65213b67 783 my ($vmid, $conf, $escapechar) = @_;
39413635 784
65213b67
TM
785 # '-1' as $escapechar disables keyboard escape sequence
786 # any other passed char (a-z) will result in <Ctrl+$escapechar q>
aca816ad 787
1b4cf758 788 my $cmode = PVE::LXC::Config->get_cmode($conf);
aca816ad 789
4d494664 790 my $cmd = [];
aca816ad 791 if ($cmode eq 'console') {
4d494664 792 push @$cmd, 'lxc-console', '-n', $vmid, '-t', 0;
65213b67 793 push @$cmd, '-e', $escapechar if $escapechar;
aca816ad 794 } elsif ($cmode eq 'tty') {
4d494664 795 push @$cmd, 'lxc-console', '-n', $vmid;
65213b67 796 push @$cmd, '-e', $escapechar if $escapechar;
aca816ad 797 } elsif ($cmode eq 'shell') {
4d494664 798 push @$cmd, 'lxc-attach', '--clear-env', '-n', $vmid;
aca816ad
DM
799 } else {
800 die "internal error";
801 }
4d494664
DC
802
803 return $cmd;
aca816ad
DM
804}
805
c325b32f
DM
806sub get_primary_ips {
807 my ($conf) = @_;
808
809 # return data from net0
cbb03fea 810
27916659 811 return undef if !defined($conf->{net0});
1b4cf758 812 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
c325b32f
DM
813
814 my $ipv4 = $net->{ip};
db78a181
WB
815 if ($ipv4) {
816 if ($ipv4 =~ /^(dhcp|manual)$/) {
817 $ipv4 = undef
818 } else {
819 $ipv4 =~ s!/\d+$!!;
820 }
821 }
65e5eaa3 822 my $ipv6 = $net->{ip6};
db78a181 823 if ($ipv6) {
5f291c7d 824 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
db78a181
WB
825 $ipv6 = undef;
826 } else {
827 $ipv6 =~ s!/\d+$!!;
828 }
829 }
cbb03fea 830
c325b32f
DM
831 return ($ipv4, $ipv6);
832}
148d1cb4 833
b407293b
WB
834sub delete_mountpoint_volume {
835 my ($storage_cfg, $vmid, $volume) = @_;
836
d250604f 837 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
b407293b
WB
838
839 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
6b81ef77
TL
840
841 if ($vmid == $owner) {
842 PVE::Storage::vdisk_free($storage_cfg, $volume);
843 } else {
844 warn "ignore deletion of '$volume', CT $vmid isn't the owner!\n";
845 }
b407293b 846}
ef241384 847
27916659 848sub destroy_lxc_container {
bccaa371 849 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
148d1cb4 850
d250604f 851 PVE::LXC::Config->foreach_mountpoint($conf, sub {
db8989e1 852 my ($ms, $mountpoint) = @_;
b407293b 853 delete_mountpoint_volume($storage_cfg, $vmid, $mountpoint->{volume});
db8989e1
WB
854 });
855
27916659
DM
856 rmdir "/var/lib/lxc/$vmid/rootfs";
857 unlink "/var/lib/lxc/$vmid/config";
858 rmdir "/var/lib/lxc/$vmid";
bccaa371
FG
859 if (defined $replacement_conf) {
860 PVE::LXC::Config->write_config($vmid, $replacement_conf);
861 } else {
4eeb9af1 862 PVE::LXC::Config->destroy_config($vmid);
bccaa371 863 }
148d1cb4 864}
68fba17b 865
ef241384 866sub vm_stop_cleanup {
5fa890f0 867 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
bf9d912c 868
38e7891a
TL
869 return if $keepActive;
870
871 eval {
872 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
873 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
ef241384
DM
874 };
875 warn $@ if $@; # avoid errors - just warn
876}
877
93cdbbfb
AD
878my $safe_num_ne = sub {
879 my ($a, $b) = @_;
880
881 return 0 if !defined($a) && !defined($b);
882 return 1 if !defined($a);
883 return 1 if !defined($b);
884
885 return $a != $b;
886};
887
888my $safe_string_ne = sub {
889 my ($a, $b) = @_;
890
891 return 0 if !defined($a) && !defined($b);
892 return 1 if !defined($a);
893 return 1 if !defined($b);
894
895 return $a ne $b;
896};
897
898sub update_net {
bedeaaf1 899 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
93cdbbfb 900
18862537
WB
901 if ($newnet->{type} ne 'veth') {
902 # for when there are physical interfaces
903 die "cannot update interface of type $newnet->{type}";
904 }
905
906 my $veth = "veth${vmid}i${netid}";
93cdbbfb
AD
907 my $eth = $newnet->{name};
908
18862537 909 if (my $oldnetcfg = $conf->{$opt}) {
1b4cf758 910 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
18862537
WB
911
912 if (&$safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
913 &$safe_string_ne($oldnet->{name}, $newnet->{name})) {
93cdbbfb 914
18862537 915 PVE::Network::veth_delete($veth);
bedeaaf1 916 delete $conf->{$opt};
67afe46e 917 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb 918
18862537 919 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
bedeaaf1 920
380962c7
WB
921 } else {
922 if (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
923 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
924 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
bedeaaf1 925
18862537 926 if ($oldnet->{bridge}) {
bedeaaf1 927 PVE::Network::tap_unplug($veth);
18862537
WB
928 foreach (qw(bridge tag firewall)) {
929 delete $oldnet->{$_};
930 }
1b4cf758 931 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
67afe46e 932 PVE::LXC::Config->write_config($vmid, $conf);
bedeaaf1 933 }
93cdbbfb 934
380962c7
WB
935 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
936 # This includes the rate:
937 foreach (qw(bridge tag firewall rate)) {
18862537
WB
938 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
939 }
380962c7
WB
940 } elsif (&$safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
941 # Rate can be applied on its own but any change above needs to
942 # include the rate in tap_plug since OVS resets everything.
943 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
944 $oldnet->{rate} = $newnet->{rate}
945 }
946 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
947 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
948 }
949 } else {
18862537 950 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
93cdbbfb
AD
951 }
952
bedeaaf1 953 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
93cdbbfb
AD
954}
955
956sub hotplug_net {
18862537 957 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
93cdbbfb 958
18862537 959 my $veth = "veth${vmid}i${netid}";
cbb03fea 960 my $vethpeer = $veth . "p";
93cdbbfb
AD
961 my $eth = $newnet->{name};
962
963 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
380962c7 964 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
93cdbbfb 965
cbb03fea 966 # attach peer in container
93cdbbfb
AD
967 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
968 PVE::Tools::run_command($cmd);
969
cbb03fea 970 # link up peer in container
93cdbbfb
AD
971 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
972 PVE::Tools::run_command($cmd);
bedeaaf1 973
18862537
WB
974 my $done = { type => 'veth' };
975 foreach (qw(bridge tag firewall hwaddr name)) {
976 $done->{$_} = $newnet->{$_} if $newnet->{$_};
977 }
1b4cf758 978 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
bedeaaf1 979
67afe46e 980 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
981}
982
68a05bb3 983sub update_ipconfig {
bedeaaf1
AD
984 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
985
f2104b80 986 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
bedeaaf1 987
1b4cf758 988 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
84e0c123
WB
989 my $deleted = [];
990 my $added = [];
8d723477
WB
991 my $nscmd = sub {
992 my $cmdargs = shift;
993 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
84e0c123 994 };
8d723477 995 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
2bfd1615 996
84e0c123 997 my $change_ip_config = sub {
f39002a6
DM
998 my ($ipversion) = @_;
999
1000 my $family_opt = "-$ipversion";
1001 my $suffix = $ipversion == 4 ? '' : $ipversion;
84e0c123
WB
1002 my $gw= "gw$suffix";
1003 my $ip= "ip$suffix";
bedeaaf1 1004
6178b0dd
WB
1005 my $newip = $newnet->{$ip};
1006 my $newgw = $newnet->{$gw};
1007 my $oldip = $optdata->{$ip};
ded5d25a 1008 my $oldgw = $optdata->{$gw};
6178b0dd
WB
1009
1010 my $change_ip = &$safe_string_ne($oldip, $newip);
ded5d25a 1011 my $change_gw = &$safe_string_ne($oldgw, $newgw);
bedeaaf1 1012
84e0c123 1013 return if !$change_ip && !$change_gw;
68a05bb3 1014
84e0c123 1015 # step 1: add new IP, if this fails we cancel
292aff54
WB
1016 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
1017 if ($change_ip && $is_real_ip) {
8d723477 1018 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
84e0c123
WB
1019 if (my $err = $@) {
1020 warn $err;
1021 return;
1022 }
bedeaaf1 1023 }
bedeaaf1 1024
84e0c123
WB
1025 # step 2: replace gateway
1026 # If this fails we delete the added IP and cancel.
1027 # If it succeeds we save the config and delete the old IP, ignoring
1028 # errors. The config is then saved.
1029 # Note: 'ip route replace' can add
1030 if ($change_gw) {
6178b0dd 1031 if ($newgw) {
292aff54
WB
1032 eval {
1033 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
1034 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
1035 }
1036 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
1037 };
84e0c123
WB
1038 if (my $err = $@) {
1039 warn $err;
1040 # the route was not replaced, the old IP is still available
1041 # rollback (delete new IP) and cancel
1042 if ($change_ip) {
8d723477 1043 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
84e0c123
WB
1044 warn $@ if $@; # no need to die here
1045 }
1046 return;
1047 }
1048 } else {
8d723477 1049 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
84e0c123
WB
1050 # if the route was not deleted, the guest might have deleted it manually
1051 # warn and continue
1052 warn $@ if $@;
1053 }
ded5d25a
DL
1054 if ($oldgw && $oldip && !PVE::Network::is_ip_in_cidr($oldgw, $oldip)) {
1055 eval { &$ipcmd($family_opt, 'route', 'del', $oldgw, 'dev', $eth); };
1056 # warn if the route was deleted manually
1057 warn $@ if $@;
1058 }
2bfd1615 1059 }
2bfd1615 1060
6178b0dd 1061 # from this point on we save the configuration
84e0c123 1062 # step 3: delete old IP ignoring errors
6178b0dd 1063 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
8d723477
WB
1064 # We need to enable promote_secondaries, otherwise our newly added
1065 # address will be removed along with the old one.
1066 my $promote = 0;
1067 eval {
1068 if ($ipversion == 4) {
1069 &$nscmd({ outfunc => sub { $promote = int(shift) } },
1070 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
1071 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
1072 }
1073 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
1074 };
84e0c123 1075 warn $@ if $@; # no need to die here
8d723477
WB
1076
1077 if ($ipversion == 4) {
1078 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
1079 }
bedeaaf1
AD
1080 }
1081
84e0c123
WB
1082 foreach my $property ($ip, $gw) {
1083 if ($newnet->{$property}) {
1084 $optdata->{$property} = $newnet->{$property};
1085 } else {
1086 delete $optdata->{$property};
1087 }
bedeaaf1 1088 }
1b4cf758 1089 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
67afe46e 1090 PVE::LXC::Config->write_config($vmid, $conf);
84e0c123
WB
1091 $lxc_setup->setup_network($conf);
1092 };
bedeaaf1 1093
f39002a6
DM
1094 &$change_ip_config(4);
1095 &$change_ip_config(6);
489e960d
WL
1096
1097}
1098
9a14c1fa
WB
1099my $open_namespace = sub {
1100 my ($vmid, $pid, $kind) = @_;
1101 sysopen my $fd, "/proc/$pid/ns/$kind", O_RDONLY
1102 or die "failed to open $kind namespace of container $vmid: $!\n";
1103 return $fd;
1104};
1105
34fdb3d7 1106my $enter_namespace = sub {
9a14c1fa
WB
1107 my ($vmid, $pid, $kind, $type) = @_;
1108 my $fd = $open_namespace->($vmid, $pid, $kind);
34fdb3d7 1109 PVE::Tools::setns(fileno($fd), $type)
9a14c1fa 1110 or die "failed to enter $kind namespace of container $vmid: $!\n";
34fdb3d7
WB
1111 close $fd;
1112};
1113
418b94fe
WB
1114my $get_container_namespace = sub {
1115 my ($vmid, $pid, $kind) = @_;
1116
1117 my $pidfd;
1118 if (!defined($pid)) {
1119 # Pin the pid while we're grabbing its stuff from /proc
1120 ($pid, $pidfd) = open_lxc_pid($vmid)
1121 or die "failed to open pidfd of container $vmid\'s init process\n";
1122 }
1123
1124 return $open_namespace->($vmid, $pid, $kind);
1125};
1126
34fdb3d7
WB
1127my $do_syncfs = sub {
1128 my ($vmid, $pid, $socket) = @_;
1129
1130 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
1131
1132 # Tell the parent process to start reading our /proc/mounts
1133 print {$socket} "go\n";
1134 $socket->flush();
1135
1136 # Receive /proc/self/mounts
1137 my $mountdata = do { local $/ = undef; <$socket> };
1138 close $socket;
1139
1140 # Now sync all mountpoints...
1141 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
1142 foreach my $mp (@$mounts) {
1143 my ($what, $dir, $fs) = @$mp;
1144 next if $fs eq 'fuse.lxcfs';
1145 eval { PVE::Tools::sync_mountpoint($dir); };
1146 warn $@ if $@;
1147 }
1148};
1149
1150sub sync_container_namespace {
1151 my ($vmid) = @_;
1152 my $pid = find_lxc_pid($vmid);
1153
1154 # SOCK_DGRAM is nicer for barriers but cannot be slurped
1155 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
1156 or die "failed to create socketpair: $!\n";
1157
1158 my $child = fork();
1159 die "fork failed: $!\n" if !defined($child);
1160
1161 if (!$child) {
1162 eval {
1163 close $pfd;
1164 &$do_syncfs($vmid, $pid, $cfd);
1165 };
1166 if (my $err = $@) {
1167 warn $err;
1168 POSIX::_exit(1);
1169 }
1170 POSIX::_exit(0);
1171 }
1172 close $cfd;
1173 my $go = <$pfd>;
1174 die "failed to enter container namespace\n" if $go ne "go\n";
1175
1176 open my $mounts, '<', "/proc/$child/mounts"
1177 or die "failed to open container's /proc/mounts: $!\n";
1178 my $mountdata = do { local $/ = undef; <$mounts> };
1179 close $mounts;
1180 print {$pfd} $mountdata;
1181 close $pfd;
1182
1183 while (waitpid($child, 0) != $child) {}
1184 die "failed to sync container namespace\n" if $? != 0;
1185}
1186
bb1ac2de
DM
1187sub template_create {
1188 my ($vmid, $conf) = @_;
1189
1190 my $storecfg = PVE::Storage::config();
1191
9d1cb46b
WL
1192 PVE::LXC::Config->foreach_mountpoint($conf, sub {
1193 my ($ms, $mountpoint) = @_;
bb1ac2de 1194
9d1cb46b 1195 my $volid = $mountpoint->{volume};
bb1ac2de 1196
9d1cb46b
WL
1197 die "Template feature is not available for '$volid'\n"
1198 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
1199 });
bb1ac2de 1200
9d1cb46b
WL
1201 PVE::LXC::Config->foreach_mountpoint($conf, sub {
1202 my ($ms, $mountpoint) = @_;
1203
1204 my $volid = $mountpoint->{volume};
1205
1206 PVE::Storage::activate_volumes($storecfg, [$volid]);
1207
1208 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
1209 $mountpoint->{volume} = $template_volid;
1210 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq "rootfs");
1211 });
bb1ac2de 1212
67afe46e 1213 PVE::LXC::Config->write_config($vmid, $conf);
bb1ac2de
DM
1214}
1215
52389a07 1216sub check_ct_modify_config_perm {
f1ba1a4b 1217 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
52389a07 1218
c81f19d1 1219 return 1 if $authuser eq 'root@pam';
52389a07 1220
f1ba1a4b
WB
1221 my $check = sub {
1222 my ($opt, $delete) = @_;
f2357408 1223 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
52389a07 1224 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
e59a61ed 1225 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
52389a07 1226 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
f1ba1a4b 1227 return if $delete;
1b4cf758
FG
1228 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
1229 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
9d294016
FG
1230 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
1231 if $data->{type} ne 'volume';
52389a07
DM
1232 } elsif ($opt eq 'memory' || $opt eq 'swap') {
1233 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
1234 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
1235 $opt eq 'searchdomain' || $opt eq 'hostname') {
1236 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
5a63f1c5
WB
1237 } elsif ($opt eq 'features') {
1238 # For now this is restricted to root@pam
1239 raise_perm_exc("changing feature flags is only allowed for root\@pam");
1a416433
DC
1240 } elsif ($opt eq 'hookscript') {
1241 # For now this is restricted to root@pam
1242 raise_perm_exc("changing the hookscript is only allowed for root\@pam");
52389a07
DM
1243 } else {
1244 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
1245 }
f1ba1a4b
WB
1246 };
1247
1248 foreach my $opt (keys %$newconf) {
1249 &$check($opt, 0);
1250 }
1251 foreach my $opt (@$delete) {
1252 &$check($opt, 1);
52389a07
DM
1253 }
1254
1255 return 1;
1256}
1257
9622e848 1258sub umount_all {
da629848 1259 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
9622e848
DM
1260
1261 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
d250604f 1262 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848 1263
73058b84
TL
1264 my $res = 1;
1265
d250604f 1266 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
9622e848
DM
1267 my ($ms, $mountpoint) = @_;
1268
1269 my $volid = $mountpoint->{volume};
1270 my $mount = $mountpoint->{mp};
1271
1272 return if !$volid || !$mount;
1273
d18f96b4 1274 my $mount_path = "$rootdir/$mount";
f845a93d 1275 $mount_path =~ s!/+!/!g;
9622e848 1276
228a5a1d
WL
1277 return if !PVE::ProcFSTools::is_mounted($mount_path);
1278
9622e848 1279 eval {
d18f96b4 1280 PVE::Tools::run_command(['umount', '-d', $mount_path]);
9622e848
DM
1281 };
1282 if (my $err = $@) {
1283 if ($noerr) {
73058b84 1284 $res = 0;
9622e848
DM
1285 warn $err;
1286 } else {
1287 die $err;
1288 }
1289 }
1290 });
73058b84
TL
1291
1292 return $res; # tell caller if (some) umounts failed for the noerr case
9622e848
DM
1293}
1294
1295sub mount_all {
25321b68 1296 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
9622e848
DM
1297
1298 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1adc7e53 1299 File::Path::make_path($rootdir);
9622e848 1300
d250604f 1301 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848
DM
1302 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
1303
4c98d66c
FG
1304 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
1305
9622e848 1306 eval {
d250604f 1307 PVE::LXC::Config->foreach_mountpoint($conf, sub {
9622e848
DM
1308 my ($ms, $mountpoint) = @_;
1309
25321b68
FG
1310 $mountpoint->{ro} = 0 if $ignore_ro;
1311
4c98d66c 1312 mountpoint_mount($mountpoint, $rootdir, $storage_cfg, undef, $rootuid, $rootgid);
9622e848
DM
1313 });
1314 };
1315 if (my $err = $@) {
e2007ac2 1316 warn "mounting container failed\n";
9622e848 1317 umount_all($vmid, $storage_cfg, $conf, 1);
e2007ac2 1318 die $err;
9622e848
DM
1319 }
1320
da629848 1321 return $rootdir;
9622e848
DM
1322}
1323
1324
b15c75fc 1325sub mountpoint_mount_path {
da629848 1326 my ($mountpoint, $storage_cfg, $snapname) = @_;
b15c75fc 1327
da629848 1328 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
b15c75fc 1329}
cc6b0307 1330
21f292ff
WB
1331sub query_loopdev {
1332 my ($path) = @_;
1333 my $found;
1334 my $parser = sub {
1335 my $line = shift;
1336 if ($line =~ m@^(/dev/loop\d+):@) {
1337 $found = $1;
1338 }
1339 };
1340 my $cmd = ['losetup', '--associated', $path];
1341 PVE::Tools::run_command($cmd, outfunc => $parser);
1342 return $found;
1343}
1344
50df544c
WB
1345# Run a function with a file attached to a loop device.
1346# The loop device is always detached afterwards (or set to autoclear).
1347# Returns the loop device.
1348sub run_with_loopdev {
fd8cab92 1349 my ($func, $file, $readonly) = @_;
54d11e5c
WB
1350 my $device = query_loopdev($file);
1351 # Try to reuse an existing device
1352 if ($device) {
1353 # We assume that whoever setup the loop device is responsible for
1354 # detaching it.
1355 &$func($device);
1356 return $device;
1357 }
1358
50df544c
WB
1359 my $parser = sub {
1360 my $line = shift;
1361 if ($line =~ m@^(/dev/loop\d+)$@) {
1362 $device = $1;
1363 }
1364 };
fd8cab92
DL
1365 my $losetup_cmd = [
1366 'losetup',
1367 '--show',
1368 '-f',
1369 $file,
1370 ];
1371 push @$losetup_cmd, '-r' if $readonly;
1372 PVE::Tools::run_command($losetup_cmd, outfunc => $parser);
50df544c
WB
1373 die "failed to setup loop device for $file\n" if !$device;
1374 eval { &$func($device); };
1375 my $err = $@;
1376 PVE::Tools::run_command(['losetup', '-d', $device]);
1377 die $err if $err;
1378 return $device;
1379}
1380
ab3722b3
WB
1381# In scalar mode: returns a file handle to the deepest directory node.
1382# In list context: returns a list of:
1383# * the deepest directory node
1384# * the 2nd deepest directory (parent of the above)
1385# * directory name of the last directory
1386# So that the path $2/$3 should lead to $1 afterwards.
4c98d66c
FG
1387sub walk_tree_nofollow($$$;$$) {
1388 my ($start, $subdir, $mkdir, $rootuid, $rootgid) = @_;
ab3722b3 1389
ab3722b3
WB
1390 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1391 or die "failed to open start directory $start: $!\n";
1392
2c6830d5
WB
1393 return walk_tree_nofollow_fd($start, $fd, $subdir, $mkdir, $rootuid, $rootgid);
1394}
1395
1396
1397sub walk_tree_nofollow_fd($$$$;$$) {
1398 my ($start_dirname, $start_fd, $subdir, $mkdir, $rootuid, $rootgid) = @_;
1399
1400 # splitdir() returns '' for empty components including the leading /
1401 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1402
1403 my $fd = $start_fd;
1404 my $dir = $start_dirname;
ab3722b3
WB
1405 my $last_component = undef;
1406 my $second = $fd;
1407 foreach my $component (@comps) {
1408 $dir .= "/$component";
1409 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1410
1411 if (!$next) {
1412 # failed, check for symlinks and try to create the path
3eb5f47b 1413 die "symlink encountered at: $dir\n" if $! == ELOOP || $! == ENOTDIR;
ab3722b3
WB
1414 die "cannot open directory $dir: $!\n" if !$mkdir;
1415
1416 # We don't check for errors on mkdirat() here and just try to
1417 # openat() again, since at least one error (EEXIST) is an
1418 # expected possibility if multiple containers start
1419 # simultaneously. If someone else injects a symlink now then
1420 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1421 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1422
1423 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1424 die "failed to create path: $dir: $!\n" if !$next;
4c98d66c
FG
1425
1426 PVE::Tools::fchownat(fileno($next), '', $rootuid, $rootgid, PVE::Tools::AT_EMPTY_PATH)
1427 if defined($rootuid) && defined($rootgid);
ab3722b3
WB
1428 }
1429
2c6830d5 1430 close $second if defined($last_component) && $second != $start_fd;
ab3722b3
WB
1431 $last_component = $component;
1432 $second = $fd;
1433 $fd = $next;
1434 }
1435
1436 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
2c6830d5 1437 close $second if defined($last_component) && $second != $start_fd;
ab3722b3
WB
1438 return $fd;
1439}
1440
619f27b4
WB
1441# To guard against symlink attack races against other currently running
1442# containers with shared recursive bind mount hierarchies we prepare a
1443# directory handle for the directory we're mounting over to verify the
1444# mountpoint afterwards.
1445sub __bindmount_prepare {
1446 my ($hostroot, $dir) = @_;
1447 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1448 return $srcdh;
1449}
ab3722b3 1450
619f27b4
WB
1451# Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1452# ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1453# we intended to bind mount.
1454sub __bindmount_verify {
1455 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
ab3722b3
WB
1456 my $destdh;
1457 if ($parentfd) {
1458 # Open the mount point path coming from the parent directory since the
1459 # filehandle we would have gotten as first result of walk_tree_nofollow
1460 # earlier is still a handle to the underlying directory instead of the
1461 # mounted path.
619f27b4
WB
1462 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1463 die "failed to open mount point: $!\n" if !$destdh;
1464 if ($ro) {
1465 my $dot = '.';
619f27b4 1466 # no separate function because 99% of the time it's the wrong thing to use.
0389da0d 1467 if (syscall(PVE::Syscall::faccessat, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
619f27b4
WB
1468 die "failed to mark bind mount read only\n";
1469 }
1470 die "read-only check failed: $!\n" if $! != EROFS;
1471 }
ab3722b3
WB
1472 } else {
1473 # For the rootfs we don't have a parentfd so we open the path directly.
1474 # Note that this means bindmounting any prefix of the host's
1475 # /var/lib/lxc/$vmid path into another container is considered a grave
1476 # security error.
1477 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
619f27b4 1478 die "failed to open mount point: $!\n" if !$destdh;
ab3722b3 1479 }
ab3722b3
WB
1480
1481 my ($srcdev, $srcinode) = stat($srcdh);
1482 my ($dstdev, $dstinode) = stat($destdh);
1483 close $srcdh;
1484 close $destdh;
1485
619f27b4
WB
1486 return ($srcdev == $dstdev && $srcinode == $dstinode);
1487}
1488
1489# Perform the actual bind mounting:
1490sub __bindmount_do {
1491 my ($dir, $dest, $ro, @extra_opts) = @_;
1492 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1493 if ($ro) {
1494 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1495 if (my $err = $@) {
1496 warn "bindmount error\n";
1497 # don't leave writable bind-mounts behind...
1498 PVE::Tools::run_command(['umount', $dest]);
1499 die $err;
1500 }
1501 }
1502}
1503
1504sub bindmount {
1505 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1506
1507 my $srcdh = __bindmount_prepare('/', $dir);
1508
1509 __bindmount_do($dir, $dest, $ro, @extra_opts);
1510
1511 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
ab3722b3
WB
1512 PVE::Tools::run_command(['umount', $dest]);
1513 die "detected mount path change at: $dir\n";
1514 }
c2744c97
WB
1515}
1516
619f27b4
WB
1517# Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1518# from $rootdir and $mount and walk the path from $rootdir to the final
1519# directory to check for symlinks.
1520sub __mount_prepare_rootdir {
4c98d66c 1521 my ($rootdir, $mount, $rootuid, $rootgid) = @_;
619f27b4
WB
1522 $rootdir =~ s!/+!/!g;
1523 $rootdir =~ s!/+$!!;
1524 my $mount_path = "$rootdir/$mount";
4c98d66c 1525 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1, $rootuid, $rootgid);
619f27b4
WB
1526 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1527}
1528
b15c75fc 1529# use $rootdir = undef to just return the corresponding mount path
cc6b0307 1530sub mountpoint_mount {
4c98d66c 1531 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
ef447944
WB
1532 return __mountpoint_mount($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, undef);
1533}
1534
1535sub mountpoint_stage {
1536 my ($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid) = @_;
1537 my ($path, $loop, $dev) =
1538 __mountpoint_mount($mountpoint, $stage_dir, $storage_cfg, $snapname, $rootuid, $rootgid, 1);
1539
1540 if (!defined($path)) {
1541 return undef if $! == ENOSYS;
1542 die "failed to mount subvolume: $!\n";
1543 }
1544
87962670
WB
1545 # We clone the mount point and leave it there in order to keep them connected to eg. loop
1546 # devices in case we're hotplugging (which would allow contaienrs to unmount the new mount
1547 # point).
ef447944
WB
1548 my $err;
1549 my $fd = PVE::Tools::open_tree(&AT_FDCWD, $stage_dir, &OPEN_TREE_CLOEXEC | &OPEN_TREE_CLONE)
1550 or die "open_tree() on mount point failed: $!\n";
1551
1552 return wantarray ? ($path, $loop, $dev, $fd) : $fd;
1553}
1554
aee0902b
WB
1555sub mountpoint_insert_staged {
1556 my ($mount_fd, $rootdir_fd, $mp_dir, $opt, $rootuid, $rootgid) = @_;
1557
1558 if (!defined($rootdir_fd)) {
1559 sysopen($rootdir_fd, '.', O_PATH | O_DIRECTORY)
1560 or die "failed to open '.': $!\n";
1561 }
1562
1563 my $dest_fd = walk_tree_nofollow_fd('/', $rootdir_fd, $mp_dir, 1, $rootuid, $rootgid);
1564
1565 PVE::Tools::move_mount(
1566 fileno($mount_fd),
1567 '',
1568 fileno($dest_fd),
1569 '',
1570 &MOVE_MOUNT_F_EMPTY_PATH | &MOVE_MOUNT_T_EMPTY_PATH,
1571 ) or die "failed to move '$opt' into container hierarchy: $!\n";
1572}
1573
ef447944
WB
1574# Use $stage_mount, $rootdir is treated as a temporary path to "stage" the file system. The user
1575# can then open a file descriptor to it which can be used with the `move_mount` syscall.
1576# Note that if the kernel does not support the new mount API, this will not perform any action
1577# and return `undef` with $! = ENOSYS.
1578sub __mountpoint_mount {
1579 my ($mountpoint, $rootdir, $storage_cfg, $snapname, $rootuid, $rootgid, $stage_mount) = @_;
1580
1581 if (defined($stage_mount) && !PVE::LXC::Tools::can_use_new_mount_api()) {
1582 $! = ENOSYS;
1583 return undef;
1584 }
cc6b0307 1585
48e36ac2
WB
1586 # When staging mount points we always mount to $rootdir directly (iow. as if `mp=/`).
1587 # This is required since __mount_prepare_rootdir() will return handles to the parent directory
1588 # which we use in __bindmount_verify()!
1589 my $mount = $stage_mount ? '/': $mountpoint->{mp};
1590
cc6b0307 1591 my $volid = $mountpoint->{volume};
7c921c80 1592 my $type = $mountpoint->{type};
50df544c
WB
1593 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1594 my $mounted_dev;
b15c75fc 1595
cc6b0307
AD
1596 return if !$volid || !$mount;
1597
ab3722b3
WB
1598 $mount =~ s!/+!/!g;
1599
b15c75fc 1600 my $mount_path;
ab3722b3 1601 my ($mpfd, $parentfd, $last_dir);
b15c75fc
DM
1602
1603 if (defined($rootdir)) {
619f27b4 1604 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
4c98d66c 1605 __mount_prepare_rootdir($rootdir, $mount, $rootuid, $rootgid);
116ce06f 1606 }
ef447944
WB
1607
1608 if (defined($stage_mount)) {
1609 $mount_path = $rootdir;
1610 }
b15c75fc
DM
1611
1612 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
cc6b0307 1613
b15c75fc 1614 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
cc6b0307 1615
2bf24eb3 1616 my $optlist = [];
e80cb0cd
TL
1617
1618 if (my $mountopts = $mountpoint->{mountoptions}) {
1619 my @opts = split(/;/, $mountpoint->{mountoptions});
1620 push @$optlist, grep { PVE::LXC::Config::is_valid_mount_option($_) } @opts;
2bf24eb3
OB
1621 }
1622
719129ea
WB
1623 my $acl = $mountpoint->{acl};
1624 if (defined($acl)) {
2bf24eb3 1625 push @$optlist, ($acl ? 'acl' : 'noacl');
471dd315 1626 }
2bf24eb3
OB
1627
1628 my $optstring = join(',', @$optlist);
c2744c97 1629 my $readonly = $mountpoint->{ro};
471dd315 1630
9de0505c
WL
1631 my @extra_opts;
1632 @extra_opts = ('-o', $optstring) if $optstring;
471dd315 1633
b15c75fc
DM
1634 if ($storage) {
1635
1636 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
7c138f58 1637
841fba68 1638 my $path = PVE::Storage::map_volume($storage_cfg, $volid, $snapname);
7c138f58 1639
841fba68 1640 $path = PVE::Storage::path($storage_cfg, $volid, $snapname) if !defined($path);
b15c75fc
DM
1641
1642 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1643 PVE::Storage::parse_volname($storage_cfg, $volid);
1644
c87b9dd8
DM
1645 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1646
b15c75fc 1647 if ($format eq 'subvol') {
30de33be
DM
1648 if ($mount_path) {
1649 if ($snapname) {
e84f7f5d
DM
1650 if ($scfg->{type} eq 'zfspool') {
1651 my $path_arg = $path;
1652 $path_arg =~ s!^/+!!;
471dd315 1653 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
e84f7f5d 1654 } else {
30de33be
DM
1655 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1656 }
e84f7f5d 1657 } else {
719129ea
WB
1658 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1659 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1660 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1661 $name .= "\@$snapname" if defined($snapname);
1662 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1663 }
ab3722b3 1664 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
50df544c 1665 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
30de33be 1666 }
b15c75fc 1667 }
5f6280cf 1668 return wantarray ? ($path, 0, undef) : $path;
c87b9dd8 1669 } elsif ($format eq 'raw' || $format eq 'iso') {
ada088e6
WB
1670 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1671 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1672 # Our autodev hook expects the /dev/dm-* device currently
1673 # and will create the /dev/mapper symlink accordingly
e439a713
WB
1674 $path = Cwd::realpath($path);
1675 die "failed to get device path\n" if !$path;
1676 ($path) = ($path =~ /^(.*)$/s); #untaint
50df544c
WB
1677 my $domount = sub {
1678 my ($path) = @_;
1679 if ($mount_path) {
1680 if ($format eq 'iso') {
1681 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1682 } elsif ($isBase || defined($snapname)) {
1683 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1684 } else {
1685 if ($quota) {
1686 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1687 }
c2744c97 1688 push @extra_opts, '-o', 'ro' if $readonly;
50df544c
WB
1689 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1690 }
1691 }
1692 };
30de33be 1693 my $use_loopdev = 0;
b15c75fc 1694 if ($scfg->{path}) {
fd8cab92 1695 $mounted_dev = run_with_loopdev($domount, $path, $readonly);
30de33be 1696 $use_loopdev = 1;
2e879877
DM
1697 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1698 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
50df544c
WB
1699 $mounted_dev = $path;
1700 &$domount($path);
b15c75fc
DM
1701 } else {
1702 die "unsupported storage type '$scfg->{type}'\n";
1703 }
50df544c 1704 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
b15c75fc
DM
1705 } else {
1706 die "unsupported image format '$format'\n";
1707 }
7c921c80 1708 } elsif ($type eq 'device') {
c9bc95a1 1709 push @extra_opts, '-o', 'ro' if $readonly;
0d449e38
WB
1710 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1711 # See the NOTE above about devicemapper canonicalization
1712 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
471dd315 1713 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
0d449e38 1714 return wantarray ? ($volid, 0, $devpath) : $volid;
e2007ac2
DM
1715 } elsif ($type eq 'bind') {
1716 die "directory '$volid' does not exist\n" if ! -d $volid;
ab3722b3 1717 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
50df544c
WB
1718 warn "cannot enable quota control for bind mounts\n" if $quota;
1719 return wantarray ? ($volid, 0, undef) : $volid;
b15c75fc
DM
1720 }
1721
1722 die "unsupported storage";
cc6b0307
AD
1723}
1724
b2de4c04
WB
1725sub mountpoint_hotplug($$$) {
1726 my ($vmid, $conf, $opt, $mp, $storage_cfg) = @_;
1727
1728 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1729
172ea186
WB
1730 # We do the rest in a fork with an unshared mount namespace, because:
1731 # -) change our papparmor profile to that of /usr/bin/lxc-start
1732 # -) we're now going to 'stage' # the mountpoint, then grab it, then move into the
1733 # container's namespace, then mount it.
b2de4c04
WB
1734
1735 PVE::Tools::run_fork(sub {
1736 # Pin the container pid longer, we also need to get its monitor/parent:
1737 my ($ct_pid, $ct_pidfd) = open_lxc_pid($vmid)
1738 or die "failed to open pidfd of container $vmid\'s init process\n";
1739
1740 my ($monitor_pid, $monitor_pidfd) = open_ppid($ct_pid)
1741 or die "failed to open pidfd of container $vmid\'s monitor process\n";
1742
1743 my $ct_mnt_ns = $get_container_namespace->($vmid, $ct_pid, 'mnt');
1744 my $monitor_mnt_ns = $get_container_namespace->($vmid, $monitor_pid, 'mnt');
1745
172ea186
WB
1746 # Grab a file descriptor to our apparmor label file so we can change into the 'lxc-start'
1747 # profile to lower our privileges to the same level we have in the start hook:
1748 sysopen(my $aa_fd, "/proc/self/attr/current", O_WRONLY)
1749 or die "failed to open '/proc/self/attr/current' for writing: $!\n";
1750 # But switch namespaces first, to make sure the namespace switches aren't blocked by
1751 # apparmor.
1752
b2de4c04
WB
1753 # Change into the monitor's mount namespace. We "pin" the mount into the monitor's
1754 # namespace for it to remain active there since the container will be able to unmount
1755 # hotplugged mount points and thereby potentially free up loop devices, which is a security
1756 # concern.
1757 PVE::Tools::setns(fileno($monitor_mnt_ns), PVE::Tools::CLONE_NEWNS);
1758 chdir('/')
1759 or die "failed to change root directory within the monitor's mount namespace: $!\n";
1760
1761 my $dir = get_staging_mount_path($opt);
172ea186
WB
1762
1763 # Now switch our apparmor profile before mounting:
1764 my $data = 'changeprofile /usr/bin/lxc-start';
1765 if (syswrite($aa_fd, $data, length($data)) != length($data)) {
1766 die "failed to change apparmor profile: $!\n";
1767 }
1768 # Check errors on close as well:
1769 close($aa_fd)
1770 or die "failed to change apparmor profile (close() failed): $!\n";
1771
b2de4c04
WB
1772 my $mount_fd = mountpoint_stage($mp, $dir, $storage_cfg, undef, $rootuid, $rootgid);
1773
1774 PVE::Tools::setns(fileno($ct_mnt_ns), PVE::Tools::CLONE_NEWNS);
1775 chdir('/')
1776 or die "failed to change root directory within the container's mount namespace: $!\n";
1777
1778 mountpoint_insert_staged($mount_fd, undef, $mp->{mp}, $opt, $rootuid, $rootgid);
1779 });
1780}
1781
180c05c5
WB
1782# Create a directory in the mountpoint staging tempfs.
1783sub get_staging_mount_path($) {
1784 my ($opt) = @_;
1785
1786 my $target = get_staging_tempfs() . "/$opt";
1787 if (!mkdir($target) && $! != EEXIST) {
1788 die "failed to create directory $target: $!\n";
1789 }
1790
1791 return $target;
1792}
1793
1794# Mount /run/pve/mountpoints as tmpfs
1795sub get_staging_tempfs() {
1796 # We choose a path in /var/lib/lxc/ here because the lxc-start apparmor profile restricts most
1797 # mounts to that.
1798 my $target = '/var/lib/lxc/.pve-staged-mounts';
1799 if (!mkdir($target)) {
1800 return $target if $! == EEXIST;
1801 die "failed to create directory $target: $!\n";
1802 }
1803
1804 PVE::Tools::mount("none", $target, 'tmpfs', 0, "size=8k,mode=755")
1805 or die "failed to mount $target as tmpfs: $!\n";
1806
1807 return $target;
1808}
1809
6c871c36 1810sub mkfs {
d216e891 1811 my ($dev, $rootuid, $rootgid) = @_;
6c871c36 1812
d216e891
WB
1813 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1814 '-E', "root_owner=$rootuid:$rootgid",
1815 $dev]);
6c871c36
DM
1816}
1817
1818sub format_disk {
d216e891 1819 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
6c871c36
DM
1820
1821 if ($volid =~ m!^/dev/.+!) {
1822 mkfs($volid);
1823 return;
1824 }
1825
1826 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1827
1828 die "cannot format volume '$volid' with no storage\n" if !$storage;
1829
08ca136d
DM
1830 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1831
841fba68
DM
1832 my $path = PVE::Storage::map_volume($storage_cfg, $volid);
1833
1834 $path = PVE::Storage::path($storage_cfg, $volid) if !defined($path);
6c871c36
DM
1835
1836 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1837 PVE::Storage::parse_volname($storage_cfg, $volid);
1838
1839 die "cannot format volume '$volid' (format == $format)\n"
1840 if $format ne 'raw';
1841
d216e891 1842 mkfs($path, $rootuid, $rootgid);
6c871c36
DM
1843}
1844
1845sub destroy_disks {
1846 my ($storecfg, $vollist) = @_;
1847
1848 foreach my $volid (@$vollist) {
1849 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1850 warn $@ if $@;
1851 }
1852}
1853
c9cf8008
WB
1854sub alloc_disk {
1855 my ($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid) = @_;
1856
1857 my $needs_chown = 0;
1858 my $volid;
1859
1860 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1861 # fixme: use better naming ct-$vmid-disk-X.raw?
1862
1863 eval {
1864 my $do_format = 0;
be6c3dfa 1865 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs' || $scfg->{type} eq 'cifs' ) {
c9cf8008
WB
1866 if ($size_kb > 0) {
1867 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
1868 undef, $size_kb);
1869 $do_format = 1;
1870 } else {
1871 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1872 undef, 0);
1873 $needs_chown = 1;
1874 }
1875 } elsif ($scfg->{type} eq 'zfspool') {
1876
1877 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1878 undef, $size_kb);
1879 $needs_chown = 1;
1880 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
1881
1882 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1883 $do_format = 1;
1884
1885 } elsif ($scfg->{type} eq 'rbd') {
1886
c9cf8008
WB
1887 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
1888 $do_format = 1;
1889 } else {
1890 die "unable to create containers on storage type '$scfg->{type}'\n";
1891 }
1892 format_disk($storecfg, $volid, $rootuid, $rootgid) if $do_format;
1893 };
1894 if (my $err = $@) {
1895 # in case formatting got interrupted:
1896 if (defined($volid)) {
1897 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1898 warn $@ if $@;
1899 }
1900 die $err;
1901 }
1902
1903 return ($volid, $needs_chown);
1904}
1905
2aee38e5 1906our $NEW_DISK_RE = qr/^([^:\s]+):(\d+(\.\d+)?)$/;
6c871c36 1907sub create_disks {
32e15a2b 1908 my ($storecfg, $vmid, $settings, $conf, $pending) = @_;
6c871c36
DM
1909
1910 my $vollist = [];
1911
1912 eval {
d216e891
WB
1913 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1914 my $chown_vollist = [];
1915
d250604f 1916 PVE::LXC::Config->foreach_mountpoint($settings, sub {
6c871c36
DM
1917 my ($ms, $mountpoint) = @_;
1918
1919 my $volid = $mountpoint->{volume};
1920 my $mp = $mountpoint->{mp};
1921
1922 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1923
2aee38e5 1924 if ($storage && ($volid =~ $NEW_DISK_RE)) {
8ed5ff9d 1925 my ($storeid, $size_gb) = ($1, $2);
6c871c36 1926
8ed5ff9d 1927 my $size_kb = int(${size_gb}*1024) * 1024;
6c871c36 1928
c9cf8008
WB
1929 my $needs_chown = 0;
1930 ($volid, $needs_chown) = alloc_disk($storecfg, $vmid, $storage, $size_kb, $rootuid, $rootgid);
1931 push @$chown_vollist, $volid if $needs_chown;
6c871c36 1932 push @$vollist, $volid;
71c780b9
WB
1933 $mountpoint->{volume} = $volid;
1934 $mountpoint->{size} = $size_kb * 1024;
32e15a2b
OB
1935 if ($pending) {
1936 $conf->{pending}->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1937 } else {
1938 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
1939 }
6c871c36 1940 } else {
32e15a2b
OB
1941 # use specified/existing volid/dir/device
1942 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36
DM
1943 }
1944 });
d216e891
WB
1945
1946 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1947 foreach my $volid (@$chown_vollist) {
1948 my $path = PVE::Storage::path($storecfg, $volid, undef);
1949 chown($rootuid, $rootgid, $path);
1950 }
1951 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
6c871c36
DM
1952 };
1953 # free allocated images on error
1954 if (my $err = $@) {
1955 destroy_disks($storecfg, $vollist);
32e15a2b 1956 die $err;
6c871c36
DM
1957 }
1958 return $vollist;
1959}
1960
6827e44d
AA
1961sub update_disksize {
1962 my ($vmid, $conf, $all_volumes) = @_;
1963
1964 my $changes;
1965 my $prefix = "CT $vmid:";
1966
1967 my $update_mp = sub {
1968 my ($key, $mp, @param) = @_;
1969 my $size = $all_volumes->{$mp->{volume}}->{size} // 0;
1970
1971 if (!defined($mp->{size}) || $size != $mp->{size}) {
1972 $changes = 1;
1973 print "$prefix updated volume size of '$mp->{volume}' in config.\n";
1974 $mp->{size} = $size;
1975 my $nomp = 1 if ($key eq 'rootfs');
1976 $conf->{$key} = PVE::LXC::Config->print_ct_mountpoint($mp, $nomp);
1977 }
1978 };
1979
1980 PVE::LXC::Config->foreach_mountpoint($conf, $update_mp);
1981
1982 return $changes;
1983}
1984
1985sub update_unused {
1986 my ($vmid, $conf, $all_volumes) = @_;
1987
1988 my $changes;
1989 my $prefix = "CT $vmid:";
1990
1991 # Note: it is allowed to define multiple storage entries with the same path
1992 # (alias), so we need to check both 'volid' and real 'path' (two different
1993 # volid can point to the same path).
1994
1995 # used and unused disks
1996 my $refpath = {};
1997 my $orphans = {};
1998
1999 foreach my $opt (keys %$conf) {
2000 next if ($opt !~ m/^unused\d+$/);
2001 my $vol = $all_volumes->{$conf->{$opt}};
2002 $refpath->{$vol->{path}} = $vol->{volid};
2003 }
2004
2005 foreach my $key (keys %$all_volumes) {
2006 my $vol = $all_volumes->{$key};
2007 my $in_use = PVE::LXC::Config->is_volume_in_use($conf, $vol->{volid});
2008 my $path = $vol->{path};
2009
2010 if ($in_use) {
2011 $refpath->{$path} = $key;
2012 delete $orphans->{$path};
2013 } else {
2014 if ((!$orphans->{$path}) && (!$refpath->{$path})) {
2015 $orphans->{$path} = $key;
2016 }
2017 }
2018 }
2019
2020 for my $key (keys %$orphans) {
2021 my $disk = $orphans->{$key};
2022 my $unused = PVE::LXC::Config->add_unused_volume($conf, $disk);
2023
2024 if ($unused) {
2025 $changes = 1;
2026 print "$prefix add unreferenced volume '$disk' as '$unused' to config.\n";
2027 }
2028 }
2029
2030 return $changes;
2031}
2032
2033sub scan_volids {
2034 my ($cfg, $vmid) = @_;
2035
2036 my $info = PVE::Storage::vdisk_list($cfg, undef, $vmid);
2037
2038 my $all_volumes = {};
2039 foreach my $storeid (keys %$info) {
2040 foreach my $item (@{$info->{$storeid}}) {
2041 my $volid = $item->{volid};
2042 next if !($volid && $item->{size});
2043 $item->{path} = PVE::Storage::path($cfg, $volid);
2044 $all_volumes->{$volid} = $item;
2045 }
2046 }
2047
2048 return $all_volumes;
2049}
2050
2051sub rescan {
2052 my ($vmid, $nolock, $dryrun) = @_;
2053
2054 my $cfg = PVE::Storage::config();
2055
2056 # FIXME: Remove once our RBD plugin can handle CT and VM on a single storage
2057 # see: https://pve.proxmox.com/pipermail/pve-devel/2018-July/032900.html
2058 foreach my $stor (keys %{$cfg->{ids}}) {
2059 delete($cfg->{ids}->{$stor}) if !$cfg->{ids}->{$stor}->{content}->{rootdir};
2060 }
2061
2062 print "rescan volumes...\n";
2063 my $all_volumes = scan_volids($cfg, $vmid);
2064
2065 my $updatefn = sub {
2066 my ($vmid) = @_;
2067
2068 my $changes;
2069 my $conf = PVE::LXC::Config->load_config($vmid);
2070
2071 PVE::LXC::Config->check_lock($conf);
2072
2073 my $vm_volids = {};
2074 foreach my $volid (keys %$all_volumes) {
2075 my $info = $all_volumes->{$volid};
2076 $vm_volids->{$volid} = $info if $info->{vmid} == $vmid;
2077 }
2078
2079 my $upu = update_unused($vmid, $conf, $vm_volids);
2080 my $upd = update_disksize($vmid, $conf, $vm_volids);
2081 $changes = $upu || $upd;
2082
2083 PVE::LXC::Config->write_config($vmid, $conf) if $changes && !$dryrun;
2084 };
2085
2086 if (defined($vmid)) {
2087 if ($nolock) {
2088 &$updatefn($vmid);
2089 } else {
2090 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2091 }
2092 } else {
2093 my $vmlist = config_list();
2094 foreach my $vmid (keys %$vmlist) {
2095 if ($nolock) {
2096 &$updatefn($vmid);
2097 } else {
2098 PVE::LXC::Config->lock_config($vmid, $updatefn, $vmid);
2099 }
2100 }
2101 }
2102}
2103
2104
68e8f3c5
DM
2105# bash completion helper
2106
2107sub complete_os_templates {
2108 my ($cmdname, $pname, $cvalue) = @_;
2109
2110 my $cfg = PVE::Storage::config();
2111
9e9bc3a6 2112 my $storeid;
68e8f3c5
DM
2113
2114 if ($cvalue =~ m/^([^:]+):/) {
2115 $storeid = $1;
2116 }
2117
2118 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
2119 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
2120
2121 my $res = [];
2122 foreach my $id (keys %$data) {
2123 foreach my $item (@{$data->{$id}}) {
2124 push @$res, $item->{volid} if defined($item->{volid});
2125 }
2126 }
2127
2128 return $res;
2129}
2130
68e8f3c5
DM
2131my $complete_ctid_full = sub {
2132 my ($running) = @_;
2133
2134 my $idlist = vmstatus();
2135
2136 my $active_hash = list_active_containers();
2137
2138 my $res = [];
2139
2140 foreach my $id (keys %$idlist) {
2141 my $d = $idlist->{$id};
2142 if (defined($running)) {
2143 next if $d->{template};
2144 next if $running && !$active_hash->{$id};
2145 next if !$running && $active_hash->{$id};
2146 }
2147 push @$res, $id;
2148
2149 }
2150 return $res;
2151};
2152
2153sub complete_ctid {
2154 return &$complete_ctid_full();
2155}
2156
2157sub complete_ctid_stopped {
2158 return &$complete_ctid_full(0);
2159}
2160
2161sub complete_ctid_running {
2162 return &$complete_ctid_full(1);
2163}
2164
c6a605f9
WB
2165sub parse_id_maps {
2166 my ($conf) = @_;
2167
2168 my $id_map = [];
2169 my $rootuid = 0;
2170 my $rootgid = 0;
2171
2172 my $lxc = $conf->{lxc};
2173 foreach my $entry (@$lxc) {
2174 my ($key, $value) = @$entry;
108c6cab
WB
2175 # FIXME: remove the 'id_map' variant when lxc-3.0 arrives
2176 next if $key ne 'lxc.idmap' && $key ne 'lxc.id_map';
c6a605f9
WB
2177 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
2178 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
2179 push @$id_map, [$type, $ct, $host, $length];
2180 if ($ct == 0) {
2181 $rootuid = $host if $type eq 'u';
2182 $rootgid = $host if $type eq 'g';
2183 }
2184 } else {
108c6cab 2185 die "failed to parse idmap: $value\n";
c6a605f9
WB
2186 }
2187 }
2188
2189 if (!@$id_map && $conf->{unprivileged}) {
2190 # Should we read them from /etc/subuid?
2191 $id_map = [ ['u', '0', '100000', '65536'],
2192 ['g', '0', '100000', '65536'] ];
2193 $rootuid = $rootgid = 100000;
2194 }
2195
2196 return ($id_map, $rootuid, $rootgid);
2197}
2198
01dce99b
WB
2199sub userns_command {
2200 my ($id_map) = @_;
2201 if (@$id_map) {
2202 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
2203 }
2204 return [];
2205}
2206
6725e93c
AA
2207sub vm_start {
2208 my ($vmid, $conf, $skiplock) = @_;
2209
60b3c5e4
OB
2210 # apply pending changes while starting
2211 if (scalar(keys %{$conf->{pending}})) {
2212 my $storecfg = PVE::Storage::config();
2213 PVE::LXC::Config->vmconfig_apply_pending($vmid, $conf, $storecfg);
2214 $conf = PVE::LXC::Config->load_config($vmid); # update/reload
2215 }
2216
6725e93c
AA
2217 update_lxc_config($vmid, $conf);
2218
2e64f057
AA
2219 my $skiplock_flag_fn = "/run/lxc/skiplock-$vmid";
2220
2221 if ($skiplock) {
2222 open(my $fh, '>', $skiplock_flag_fn) || die "failed to open $skiplock_flag_fn for writing: $!\n";
2223 close($fh);
2224 }
6725e93c
AA
2225
2226 my $cmd = ['systemctl', 'start', "pve-container\@$vmid"];
2227
1a416433 2228 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-start', 1);
2e64f057
AA
2229 eval { PVE::Tools::run_command($cmd); };
2230 if (my $err = $@) {
2231 unlink $skiplock_flag_fn;
1322f50d 2232 die $err;
2e64f057 2233 }
1a416433 2234 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-start');
6725e93c
AA
2235
2236 return;
2237}
2238
b1bad293
WB
2239# Helper to stop a container completely and make sure it has stopped completely.
2240# This is necessary because we want the post-stop hook to have completed its
2241# unmount-all step, but post-stop happens after lxc puts the container into the
2242# STOPPED state.
e0e29818
TL
2243# $kill - if true it will always do an immediate hard-stop
2244# $shutdown_timeout - the timeout to wait for a gracefull shutdown
2245# $kill_after_timeout - if true, send a hardstop if shutdown timed out
b1bad293 2246sub vm_stop {
e0e29818 2247 my ($vmid, $kill, $shutdown_timeout, $kill_after_timeout) = @_;
b1bad293
WB
2248
2249 # Open the container's command socket.
2250 my $path = "\0/var/lib/lxc/$vmid/command";
2251 my $sock = IO::Socket::UNIX->new(
2252 Type => SOCK_STREAM(),
2253 Peer => $path,
2254 );
2255 if (!$sock) {
2256 return if $! == ECONNREFUSED; # The container is not running
2257 die "failed to open container ${vmid}'s command socket: $!\n";
2258 }
2259
1a416433
DC
2260 my $conf = PVE::LXC::Config->load_config($vmid);
2261 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'pre-stop');
2262
b1bad293
WB
2263 # Stop the container:
2264
2265 my $cmd = ['lxc-stop', '-n', $vmid];
2266
2267 if ($kill) {
2268 push @$cmd, '--kill'; # doesn't allow timeouts
e0e29818
TL
2269 } else {
2270 # lxc-stop uses a default timeout
2271 push @$cmd, '--nokill' if !$kill_after_timeout;
2272
2273 if (defined($shutdown_timeout)) {
2274 push @$cmd, '--timeout', $shutdown_timeout;
2275 # Give run_command 5 extra seconds
2276 $shutdown_timeout += 5;
2277 }
b1bad293
WB
2278 }
2279
2280 eval { PVE::Tools::run_command($cmd, timeout => $shutdown_timeout) };
2281 if (my $err = $@) {
2282 warn $@ if $@;
2283 }
2284
8d41edef 2285 my $result = <$sock>;
b1bad293
WB
2286
2287 return if !defined $result; # monitor is gone and the ct has stopped.
2288 die "container did not stop\n";
2289}
846a66b0 2290
f5fe1125
OB
2291sub vm_reboot {
2292 my ($vmid, $timeout, $skiplock) = @_;
2293
2294 PVE::LXC::Config->lock_config($vmid, sub {
2295 return if !check_running($vmid);
2296
2297 vm_stop($vmid, 0, $timeout, 1); # kill if timeout exceeds
2298
2299 my $conf = PVE::LXC::Config->load_config($vmid);
2300 vm_start($vmid, $conf);
2301 });
2302}
2303
00501642
WB
2304sub run_unshared {
2305 my ($code) = @_;
2306
2307 return PVE::Tools::run_fork(sub {
2308 # Unshare the mount namespace
2309 die "failed to unshare mount namespace: $!\n"
2310 if !PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
2311 PVE::Tools::run_command(['mount', '--make-rslave', '/']);
2312 return $code->();
2313 });
2314}
2315
2316my $copy_volume = sub {
4c98d66c 2317 my ($src_volid, $src, $dst_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid) = @_;
00501642 2318
fd8cab92 2319 my $src_mp = { volume => $src_volid, mp => '/', ro => 1 };
00501642
WB
2320 $src_mp->{type} = PVE::LXC::Config->classify_mountpoint($src_volid);
2321
fd8cab92 2322 my $dst_mp = { volume => $dst_volid, mp => '/', ro => 0 };
00501642
WB
2323 $dst_mp->{type} = PVE::LXC::Config->classify_mountpoint($dst_volid);
2324
2325 my @mounted;
2326 eval {
2327 # mount and copy
2328 mkdir $src;
4c98d66c 2329 mountpoint_mount($src_mp, $src, $storage_cfg, $snapname, $rootuid, $rootgid);
00501642
WB
2330 push @mounted, $src;
2331 mkdir $dest;
4c98d66c 2332 mountpoint_mount($dst_mp, $dest, $storage_cfg, undef, $rootuid, $rootgid);
00501642
WB
2333 push @mounted, $dest;
2334
08540353
SI
2335 $bwlimit //= 0;
2336
00501642
WB
2337 PVE::Tools::run_command(['/usr/bin/rsync', '--stats', '-X', '-A', '--numeric-ids',
2338 '-aH', '--whole-file', '--sparse', '--one-file-system',
08540353 2339 "--bwlimit=$bwlimit", "$src/", $dest]);
00501642
WB
2340 };
2341 my $err = $@;
75c2677f
DJ
2342
2343 # Wait for rsync's children to release dest so that
2344 # consequent file operations (umount, remove) are possible
2345 while ((system {"fuser"} "fuser", "-s", $dest) == 0) {sleep 1};
2346
00501642 2347 foreach my $mount (reverse @mounted) {
75c2677f 2348 eval { PVE::Tools::run_command(['/bin/umount', $mount], errfunc => sub{})};
00501642
WB
2349 warn "Can't umount $mount\n" if $@;
2350 }
2351
2352 # If this fails they're used as mount points in a concurrent operation
2353 # (which should not happen but there's also no real need to get rid of them).
2354 rmdir $dest;
2355 rmdir $src;
2356
2357 die $err if $err;
2358};
2359
2360# Should not be called after unsharing the mount namespace!
2361sub copy_volume {
08540353 2362 my ($mp, $vmid, $storage, $storage_cfg, $conf, $snapname, $bwlimit) = @_;
00501642
WB
2363
2364 die "cannot copy volumes of type $mp->{type}\n" if $mp->{type} ne 'volume';
2365 File::Path::make_path("/var/lib/lxc/$vmid");
2366 my $dest = "/var/lib/lxc/$vmid/.copy-volume-1";
2367 my $src = "/var/lib/lxc/$vmid/.copy-volume-2";
2368
2369 # get id's for unprivileged container
2370 my (undef, $rootuid, $rootgid) = parse_id_maps($conf);
2371
2372 # Allocate the disk before unsharing in order to make sure zfs subvolumes
2373 # are visible in this namespace, otherwise the host only sees the empty
2374 # (not-mounted) directory.
2375 my $new_volid;
2376 eval {
5154e3e9
WB
2377 # Make sure $mp contains a correct size.
2378 $mp->{size} = PVE::Storage::volume_size_info($storage_cfg, $mp->{volume});
00501642
WB
2379 my $needs_chown;
2380 ($new_volid, $needs_chown) = alloc_disk($storage_cfg, $vmid, $storage, $mp->{size}/1024, $rootuid, $rootgid);
2381 if ($needs_chown) {
2382 PVE::Storage::activate_volumes($storage_cfg, [$new_volid], undef);
2383 my $path = PVE::Storage::path($storage_cfg, $new_volid, undef);
2384 chown($rootuid, $rootgid, $path);
2385 }
2386
2387 run_unshared(sub {
4c98d66c 2388 $copy_volume->($mp->{volume}, $src, $new_volid, $dest, $storage_cfg, $snapname, $bwlimit, $rootuid, $rootgid);
00501642
WB
2389 });
2390 };
2391 if (my $err = $@) {
2392 PVE::Storage::vdisk_free($storage_cfg, $new_volid)
2393 if defined($new_volid);
2394 die $err;
2395 }
2396
2397 return $new_volid;
2398}
2399
f76a2828 24001;