]> git.proxmox.com Git - pve-container.git/blame - src/PVE/LXC.pm
document bind/device mp permissions better
[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();
ab3722b3 13use Fcntl qw(O_RDONLY O_NOFOLLOW O_DIRECTORY);
619f27b4 14use Errno qw(ELOOP EROFS);
f76a2828 15
f1ba1a4b 16use PVE::Exception qw(raise_perm_exc);
c65e0a6d 17use PVE::Storage;
f76a2828
DM
18use PVE::SafeSyslog;
19use PVE::INotify;
ab3722b3 20use PVE::Tools qw($IPV6RE $IPV4RE dir_glob_foreach lock_file lock_file_full O_PATH);
92902047 21use PVE::CpuSet;
68fba17b 22use PVE::Network;
52389a07 23use PVE::AccessControl;
228a5a1d 24use PVE::ProcFSTools;
67afe46e 25use PVE::LXC::Config;
688afc63 26use Time::HiRes qw (gettimeofday);
f76a2828
DM
27
28use Data::Dumper;
29
27916659
DM
30my $nodename = PVE::INotify::nodename();
31
688afc63
WL
32my $cpuinfo= PVE::ProcFSTools::read_cpuinfo();
33
f9897acd 34our $COMMON_TAR_FLAGS = [ '--sparse', '--numeric-owner', '--acls',
fc4e132e
WB
35 '--xattrs',
36 '--xattrs-include=user.*',
4132377b
WB
37 '--xattrs-include=security.capability',
38 '--warning=no-xattr-write' ];
fc4e132e 39
f76a2828
DM
40sub config_list {
41 my $vmlist = PVE::Cluster::get_vmlist();
42 my $res = {};
43 return $res if !$vmlist || !$vmlist->{ids};
44 my $ids = $vmlist->{ids};
45
46 foreach my $vmid (keys %$ids) {
47 next if !$vmid; # skip CT0
48 my $d = $ids->{$vmid};
49 next if !$d->{node} || $d->{node} ne $nodename;
50 next if !$d->{type} || $d->{type} ne 'lxc';
51 $res->{$vmid}->{type} = 'lxc';
52 }
53 return $res;
54}
55
5b4657d0
DM
56sub destroy_config {
57 my ($vmid) = @_;
58
67afe46e 59 unlink PVE::LXC::Config->config_file($vmid, $nodename);
3cc56749
FG
60}
61
822de0c3
DM
62# container status helpers
63
64sub list_active_containers {
cbb03fea 65
822de0c3
DM
66 my $filename = "/proc/net/unix";
67
68 # similar test is used by lcxcontainers.c: list_active_containers
69 my $res = {};
cbb03fea 70
822de0c3
DM
71 my $fh = IO::File->new ($filename, "r");
72 return $res if !$fh;
73
74 while (defined(my $line = <$fh>)) {
28df2cde 75 if ($line =~ m/^[a-f0-9]+:\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\d+\s+(\S+)$/) {
822de0c3 76 my $path = $1;
27916659 77 if ($path =~ m!^@/var/lib/lxc/(\d+)/command$!) {
822de0c3
DM
78 $res->{$1} = 1;
79 }
80 }
81 }
82
83 close($fh);
cbb03fea 84
822de0c3
DM
85 return $res;
86}
f76a2828 87
5c752bbf
DM
88# warning: this is slow
89sub check_running {
90 my ($vmid) = @_;
91
92 my $active_hash = list_active_containers();
93
94 return 1 if defined($active_hash->{$vmid});
cbb03fea 95
5c752bbf
DM
96 return undef;
97}
98
10fc3ba5 99sub get_container_disk_usage {
73e03cb7 100 my ($vmid, $pid) = @_;
10fc3ba5 101
73e03cb7 102 return PVE::Tools::df("/proc/$pid/root/", 1);
10fc3ba5
DM
103}
104
688afc63
WL
105my $last_proc_vmid_stat;
106
107my $parse_cpuacct_stat = sub {
108 my ($vmid) = @_;
109
110 my $raw = read_cgroup_value('cpuacct', $vmid, 'cpuacct.stat', 1);
111
112 my $stat = {};
113
114 if ($raw =~ m/^user (\d+)\nsystem (\d+)\n/) {
115
116 $stat->{utime} = $1;
117 $stat->{stime} = $2;
118
119 }
120
121 return $stat;
122};
123
f76a2828
DM
124sub vmstatus {
125 my ($opt_vmid) = @_;
126
127 my $list = $opt_vmid ? { $opt_vmid => { type => 'lxc' }} : config_list();
128
822de0c3 129 my $active_hash = list_active_containers();
cbb03fea 130
688afc63
WL
131 my $cpucount = $cpuinfo->{cpus} || 1;
132
133 my $cdtime = gettimeofday;
134
135 my $uptime = (PVE::ProcFSTools::read_proc_uptime(1))[0];
136
f76a2828 137 foreach my $vmid (keys %$list) {
f76a2828 138 my $d = $list->{$vmid};
10fc3ba5 139
d5588ee3
DM
140 eval { $d->{pid} = find_lxc_pid($vmid) if defined($active_hash->{$vmid}); };
141 warn $@ if $@; # ignore errors (consider them stopped)
cbb03fea 142
d5588ee3 143 $d->{status} = $d->{pid} ? 'running' : 'stopped';
f76a2828 144
67afe46e 145 my $cfspath = PVE::LXC::Config->cfs_config_path($vmid);
238a56cb 146 my $conf = PVE::Cluster::cfs_read_file($cfspath) || {};
cbb03fea 147
27916659 148 $d->{name} = $conf->{'hostname'} || "CT$vmid";
238a56cb 149 $d->{name} =~ s/[\s]//g;
cbb03fea 150
f2357408
DM
151 $d->{cpus} = $conf->{cores} || $conf->{cpulimit};
152 $d->{cpus} = $cpucount if !$d->{cpus};
44da0641 153
d0226204
WB
154 $d->{lock} = $conf->{lock} || '';
155
d5588ee3
DM
156 if ($d->{pid}) {
157 my $res = get_container_disk_usage($vmid, $d->{pid});
27916659
DM
158 $d->{disk} = $res->{used};
159 $d->{maxdisk} = $res->{total};
160 } else {
161 $d->{disk} = 0;
162 # use 4GB by default ??
163 if (my $rootfs = $conf->{rootfs}) {
1b4cf758 164 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($rootfs);
af02245c 165 $d->{maxdisk} = $rootinfo->{size} || (4*1024*1024*1024);
27916659
DM
166 } else {
167 $d->{maxdisk} = 4*1024*1024*1024;
10fc3ba5 168 }
238a56cb 169 }
cbb03fea 170
238a56cb
DM
171 $d->{mem} = 0;
172 $d->{swap} = 0;
95df9a12
DM
173 $d->{maxmem} = ($conf->{memory}||512)*1024*1024;
174 $d->{maxswap} = ($conf->{swap}//0)*1024*1024;
e901d418 175
238a56cb
DM
176 $d->{uptime} = 0;
177 $d->{cpu} = 0;
e901d418 178
238a56cb
DM
179 $d->{netout} = 0;
180 $d->{netin} = 0;
f76a2828 181
238a56cb
DM
182 $d->{diskread} = 0;
183 $d->{diskwrite} = 0;
bb1ac2de 184
67afe46e 185 $d->{template} = PVE::LXC::Config->is_template($conf);
f76a2828 186 }
cbb03fea 187
238a56cb
DM
188 foreach my $vmid (keys %$list) {
189 my $d = $list->{$vmid};
d5588ee3
DM
190 my $pid = $d->{pid};
191
192 next if !$pid; # skip stopped CTs
f76a2828 193
88a8696b
TL
194 my $ctime = (stat("/proc/$pid"))[10]; # 10 = ctime
195 $d->{uptime} = time - $ctime; # the method lxcfs uses
22a77285 196
b3059d35
TL
197 my $memory_stat = read_cgroup_list('memory', $vmid, 'memory.stat');
198 my $mem_usage_in_bytes = read_cgroup_value('memory', $vmid, 'memory.usage_in_bytes');
199
200 $d->{mem} = $mem_usage_in_bytes - $memory_stat->{cache};
201 $d->{swap} = read_cgroup_value('memory', $vmid, 'memory.memsw.usage_in_bytes') - $mem_usage_in_bytes;
b5289322
AD
202
203 my $blkio_bytes = read_cgroup_value('blkio', $vmid, 'blkio.throttle.io_service_bytes', 1);
1e647c7c 204 my @bytes = split(/\n/, $blkio_bytes);
b5289322 205 foreach my $byte (@bytes) {
1e647c7c
DM
206 if (my ($key, $value) = $byte =~ /(Read|Write)\s+(\d+)/) {
207 $d->{diskread} = $2 if $key eq 'Read';
208 $d->{diskwrite} = $2 if $key eq 'Write';
209 }
b5289322 210 }
688afc63
WL
211
212 my $pstat = &$parse_cpuacct_stat($vmid);
213
214 my $used = $pstat->{utime} + $pstat->{stime};
215
216 my $old = $last_proc_vmid_stat->{$vmid};
217 if (!$old) {
218 $last_proc_vmid_stat->{$vmid} = {
219 time => $cdtime,
220 used => $used,
221 cpu => 0,
222 };
223 next;
224 }
225
226 my $dtime = ($cdtime - $old->{time}) * $cpucount * $cpuinfo->{user_hz};
227
228 if ($dtime > 1000) {
229 my $dutime = $used - $old->{used};
230
231 $d->{cpu} = (($dutime/$dtime)* $cpucount) / $d->{cpus};
232 $last_proc_vmid_stat->{$vmid} = {
233 time => $cdtime,
234 used => $used,
235 cpu => $d->{cpu},
236 };
237 } else {
238 $d->{cpu} = $old->{cpu};
239 }
238a56cb 240 }
cbb03fea 241
68b8f4d1
WL
242 my $netdev = PVE::ProcFSTools::read_proc_net_dev();
243
244 foreach my $dev (keys %$netdev) {
245 next if $dev !~ m/^veth([1-9]\d*)i/;
246 my $vmid = $1;
247 my $d = $list->{$vmid};
248
249 next if !$d;
250
251 $d->{netout} += $netdev->{$dev}->{receive};
252 $d->{netin} += $netdev->{$dev}->{transmit};
253
254 }
255
f76a2828
DM
256 return $list;
257}
258
b3059d35
TL
259sub read_cgroup_list {
260 my ($group, $vmid, $name) = @_;
261
262 my $content = read_cgroup_value($group, $vmid, $name, 1);
263
264 return { split(/\s+/, $content) };
265}
266
238a56cb
DM
267sub read_cgroup_value {
268 my ($group, $vmid, $name, $full) = @_;
269
270 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
271
272 return PVE::Tools::file_get_contents($path) if $full;
273
274 return PVE::Tools::file_read_firstline($path);
275}
276
bf0b8c43
AD
277sub write_cgroup_value {
278 my ($group, $vmid, $name, $value) = @_;
279
280 my $path = "/sys/fs/cgroup/$group/lxc/$vmid/$name";
281 PVE::ProcFSTools::write_proc_entry($path, $value) if -e $path;
282
283}
284
52f1d76b
DM
285sub find_lxc_console_pids {
286
287 my $res = {};
288
289 PVE::Tools::dir_glob_foreach('/proc', '\d+', sub {
290 my ($pid) = @_;
291
292 my $cmdline = PVE::Tools::file_read_firstline("/proc/$pid/cmdline");
293 return if !$cmdline;
294
295 my @args = split(/\0/, $cmdline);
296
c31ad455 297 # search for lxc-console -n <vmid>
cbb03fea 298 return if scalar(@args) != 3;
52f1d76b
DM
299 return if $args[1] ne '-n';
300 return if $args[2] !~ m/^\d+$/;
301 return if $args[0] !~ m|^(/usr/bin/)?lxc-console$|;
cbb03fea 302
52f1d76b 303 my $vmid = $args[2];
cbb03fea 304
52f1d76b
DM
305 push @{$res->{$vmid}}, $pid;
306 });
307
308 return $res;
309}
310
bedeaaf1
AD
311sub find_lxc_pid {
312 my ($vmid) = @_;
313
314 my $pid = undef;
315 my $parser = sub {
316 my $line = shift;
8b25977f 317 $pid = $1 if $line =~ m/^PID:\s+(\d+)$/;
bedeaaf1 318 };
c39aa40a 319 PVE::Tools::run_command(['lxc-info', '-n', $vmid, '-p'], outfunc => $parser);
bedeaaf1 320
8b25977f 321 die "unable to get PID for CT $vmid (not running?)\n" if !$pid;
cbb03fea 322
8b25977f 323 return $pid;
bedeaaf1
AD
324}
325
cbb03fea 326# Note: we cannot use Net:IP, because that only allows strict
55fa4e09
DM
327# CIDR networks
328sub parse_ipv4_cidr {
329 my ($cidr, $noerr) = @_;
330
f7a7b413
WB
331 if ($cidr =~ m!^($IPV4RE)(?:/(\d+))$! && ($2 > 7) && ($2 <= 32)) {
332 return { address => $1, netmask => $PVE::Network::ipv4_reverse_mask->[$2] };
55fa4e09 333 }
cbb03fea 334
55fa4e09 335 return undef if $noerr;
cbb03fea 336
55fa4e09
DM
337 die "unable to parse ipv4 address/mask\n";
338}
93285df8 339
e22af68f 340
27916659 341sub update_lxc_config {
f91f3669 342 my ($vmid, $conf) = @_;
b80dd50a 343
bb1ac2de
DM
344 my $dir = "/var/lib/lxc/$vmid";
345
346 if ($conf->{template}) {
347
348 unlink "$dir/config";
349
350 return;
351 }
352
27916659 353 my $raw = '';
b80dd50a 354
27916659
DM
355 die "missing 'arch' - internal error" if !$conf->{arch};
356 $raw .= "lxc.arch = $conf->{arch}\n";
b80dd50a 357
425b62cb
WB
358 my $unprivileged = $conf->{unprivileged};
359 my $custom_idmap = grep { $_->[0] eq 'lxc.id_map' } @{$conf->{lxc}};
360
27916659 361 my $ostype = $conf->{ostype} || die "missing 'ostype' - internal error";
ed027b58 362 if ($ostype =~ /^(?:debian | ubuntu | centos | fedora | opensuse | archlinux | alpine | gentoo | unmanaged)$/x) {
c34f7efe
WB
363 my $inc ="/usr/share/lxc/config/$ostype.common.conf";
364 $inc ="/usr/share/lxc/config/common.conf" if !-f $inc;
365 $raw .= "lxc.include = $inc\n";
425b62cb 366 if ($unprivileged || $custom_idmap) {
c34f7efe
WB
367 $inc = "/usr/share/lxc/config/$ostype.userns.conf";
368 $inc = "/usr/share/lxc/config/userns.conf" if !-f $inc;
369 $raw .= "lxc.include = $inc\n"
425b62cb 370 }
27916659 371 } else {
9a7a910b 372 die "implement me (ostype $ostype)";
27916659 373 }
b80dd50a 374
50df544c
WB
375 # WARNING: DO NOT REMOVE this without making sure that loop device nodes
376 # cannot be exposed to the container with r/w access (cgroup perms).
377 # When this is enabled mounts will still remain in the monitor's namespace
378 # after the container unmounted them and thus will not detach from their
379 # files while the container is running!
c16b8890 380 $raw .= "lxc.monitor.unshare = 1\n";
58cc92a9 381
425b62cb
WB
382 # Should we read them from /etc/subuid?
383 if ($unprivileged && !$custom_idmap) {
384 $raw .= "lxc.id_map = u 0 100000 65536\n";
385 $raw .= "lxc.id_map = g 0 100000 65536\n";
386 }
387
d250604f 388 if (!PVE::LXC::Config->has_dev_console($conf)) {
eeaea429
DM
389 $raw .= "lxc.console = none\n";
390 $raw .= "lxc.cgroup.devices.deny = c 5:1 rwm\n";
391 }
4f958489 392
1b4cf758 393 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
27916659 394 $raw .= "lxc.tty = $ttycount\n";
cbb03fea 395
c31ad455 396 # some init scripts expect a linux terminal (turnkey).
a691a5a3
DM
397 $raw .= "lxc.environment = TERM=linux\n";
398
27916659
DM
399 my $utsname = $conf->{hostname} || "CT$vmid";
400 $raw .= "lxc.utsname = $utsname\n";
cbb03fea 401
27916659
DM
402 my $memory = $conf->{memory} || 512;
403 my $swap = $conf->{swap} // 0;
404
405 my $lxcmem = int($memory*1024*1024);
406 $raw .= "lxc.cgroup.memory.limit_in_bytes = $lxcmem\n";
a12a36e0 407
27916659
DM
408 my $lxcswap = int(($memory + $swap)*1024*1024);
409 $raw .= "lxc.cgroup.memory.memsw.limit_in_bytes = $lxcswap\n";
410
411 if (my $cpulimit = $conf->{cpulimit}) {
412 $raw .= "lxc.cgroup.cpu.cfs_period_us = 100000\n";
413 my $value = int(100000*$cpulimit);
414 $raw .= "lxc.cgroup.cpu.cfs_quota_us = $value\n";
a12a36e0
WL
415 }
416
27916659
DM
417 my $shares = $conf->{cpuunits} || 1024;
418 $raw .= "lxc.cgroup.cpu.shares = $shares\n";
419
fddaa91b
DM
420 die "missing 'rootfs' configuration\n"
421 if !defined($conf->{rootfs});
422
1b4cf758 423 my $mountpoint = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
a3076d81 424
c9a5774b 425 $raw .= "lxc.rootfs = $dir/rootfs\n";
27916659
DM
426
427 my $netcount = 0;
e756bdd6 428 foreach my $k (sort keys %$conf) {
27916659
DM
429 next if $k !~ m/^net(\d+)$/;
430 my $ind = $1;
1b4cf758 431 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
27916659
DM
432 $netcount++;
433 $raw .= "lxc.network.type = veth\n";
18862537 434 $raw .= "lxc.network.veth.pair = veth${vmid}i${ind}\n";
27916659
DM
435 $raw .= "lxc.network.hwaddr = $d->{hwaddr}\n" if defined($d->{hwaddr});
436 $raw .= "lxc.network.name = $d->{name}\n" if defined($d->{name});
437 $raw .= "lxc.network.mtu = $d->{mtu}\n" if defined($d->{mtu});
a12a36e0
WL
438 }
439
92902047 440 my $had_cpuset = 0;
e576f689
DM
441 if (my $lxcconf = $conf->{lxc}) {
442 foreach my $entry (@$lxcconf) {
443 my ($k, $v) = @$entry;
444 $netcount++ if $k eq 'lxc.network.type';
92902047 445 $had_cpuset = 1 if $k eq 'lxc.cgroup.cpuset.cpus';
e576f689
DM
446 $raw .= "$k = $v\n";
447 }
448 }
27916659 449
e576f689 450 $raw .= "lxc.network.type = empty\n" if !$netcount;
92902047
WB
451
452 my $cores = $conf->{cores};
453 if (!$had_cpuset && $cores) {
6560ce0f
WB
454 my $cpuset = eval { PVE::CpuSet->new_from_cgroup('lxc', 'effective_cpus') };
455 $cpuset = PVE::CpuSet->new_from_cgroup('', 'effective_cpus') if !$cpuset;
92902047
WB
456 my @members = $cpuset->members();
457 while (scalar(@members) > $cores) {
458 my $randidx = int(rand(scalar(@members)));
459 $cpuset->delete($members[$randidx]);
460 splice(@members, $randidx, 1); # keep track of the changes
461 }
462 $raw .= "lxc.cgroup.cpuset.cpus = ".$cpuset->short_string()."\n";
463 }
e576f689 464
27916659
DM
465 File::Path::mkpath("$dir/rootfs");
466
467 PVE::Tools::file_set_contents("$dir/config", $raw);
b80dd50a
DM
468}
469
117636e5
DM
470# verify and cleanup nameserver list (replace \0 with ' ')
471sub verify_nameserver_list {
472 my ($nameserver_list) = @_;
473
474 my @list = ();
475 foreach my $server (PVE::Tools::split_list($nameserver_list)) {
476 PVE::JSONSchema::pve_verify_ip($server);
477 push @list, $server;
478 }
479
480 return join(' ', @list);
481}
482
483sub verify_searchdomain_list {
484 my ($searchdomain_list) = @_;
485
486 my @list = ();
487 foreach my $server (PVE::Tools::split_list($searchdomain_list)) {
488 # todo: should we add checks for valid dns domains?
489 push @list, $server;
490 }
491
492 return join(' ', @list);
493}
494
aca816ad
DM
495sub get_console_command {
496 my ($vmid, $conf) = @_;
497
1b4cf758 498 my $cmode = PVE::LXC::Config->get_cmode($conf);
aca816ad
DM
499
500 if ($cmode eq 'console') {
501 return ['lxc-console', '-n', $vmid, '-t', 0];
502 } elsif ($cmode eq 'tty') {
503 return ['lxc-console', '-n', $vmid];
504 } elsif ($cmode eq 'shell') {
505 return ['lxc-attach', '--clear-env', '-n', $vmid];
506 } else {
507 die "internal error";
508 }
509}
510
c325b32f
DM
511sub get_primary_ips {
512 my ($conf) = @_;
513
514 # return data from net0
cbb03fea 515
27916659 516 return undef if !defined($conf->{net0});
1b4cf758 517 my $net = PVE::LXC::Config->parse_lxc_network($conf->{net0});
c325b32f
DM
518
519 my $ipv4 = $net->{ip};
db78a181
WB
520 if ($ipv4) {
521 if ($ipv4 =~ /^(dhcp|manual)$/) {
522 $ipv4 = undef
523 } else {
524 $ipv4 =~ s!/\d+$!!;
525 }
526 }
65e5eaa3 527 my $ipv6 = $net->{ip6};
db78a181 528 if ($ipv6) {
5f291c7d 529 if ($ipv6 =~ /^(auto|dhcp|manual)$/) {
db78a181
WB
530 $ipv6 = undef;
531 } else {
532 $ipv6 =~ s!/\d+$!!;
533 }
534 }
cbb03fea 535
c325b32f
DM
536 return ($ipv4, $ipv6);
537}
148d1cb4 538
b407293b
WB
539sub delete_mountpoint_volume {
540 my ($storage_cfg, $vmid, $volume) = @_;
541
d250604f 542 return if PVE::LXC::Config->classify_mountpoint($volume) ne 'volume';
b407293b
WB
543
544 my ($vtype, $name, $owner) = PVE::Storage::parse_volname($storage_cfg, $volume);
545 PVE::Storage::vdisk_free($storage_cfg, $volume) if $vmid == $owner;
546}
ef241384 547
27916659 548sub destroy_lxc_container {
bccaa371 549 my ($storage_cfg, $vmid, $conf, $replacement_conf) = @_;
148d1cb4 550
d250604f 551 PVE::LXC::Config->foreach_mountpoint($conf, sub {
db8989e1 552 my ($ms, $mountpoint) = @_;
b407293b 553 delete_mountpoint_volume($storage_cfg, $vmid, $mountpoint->{volume});
db8989e1
WB
554 });
555
27916659
DM
556 rmdir "/var/lib/lxc/$vmid/rootfs";
557 unlink "/var/lib/lxc/$vmid/config";
558 rmdir "/var/lib/lxc/$vmid";
bccaa371
FG
559 if (defined $replacement_conf) {
560 PVE::LXC::Config->write_config($vmid, $replacement_conf);
561 } else {
562 destroy_config($vmid);
563 }
27916659
DM
564
565 #my $cmd = ['lxc-destroy', '-n', $vmid ];
566 #PVE::Tools::run_command($cmd);
148d1cb4 567}
68fba17b 568
ef241384 569sub vm_stop_cleanup {
5fa890f0 570 my ($storage_cfg, $vmid, $conf, $keepActive) = @_;
ef241384
DM
571
572 eval {
573 if (!$keepActive) {
bf9d912c 574
d250604f 575 my $vollist = PVE::LXC::Config->get_vm_volumes($conf);
a8b6b8a7 576 PVE::Storage::deactivate_volumes($storage_cfg, $vollist);
ef241384
DM
577 }
578 };
579 warn $@ if $@; # avoid errors - just warn
580}
581
93cdbbfb
AD
582my $safe_num_ne = sub {
583 my ($a, $b) = @_;
584
585 return 0 if !defined($a) && !defined($b);
586 return 1 if !defined($a);
587 return 1 if !defined($b);
588
589 return $a != $b;
590};
591
592my $safe_string_ne = sub {
593 my ($a, $b) = @_;
594
595 return 0 if !defined($a) && !defined($b);
596 return 1 if !defined($a);
597 return 1 if !defined($b);
598
599 return $a ne $b;
600};
601
602sub update_net {
bedeaaf1 603 my ($vmid, $conf, $opt, $newnet, $netid, $rootdir) = @_;
93cdbbfb 604
18862537
WB
605 if ($newnet->{type} ne 'veth') {
606 # for when there are physical interfaces
607 die "cannot update interface of type $newnet->{type}";
608 }
609
610 my $veth = "veth${vmid}i${netid}";
93cdbbfb
AD
611 my $eth = $newnet->{name};
612
18862537 613 if (my $oldnetcfg = $conf->{$opt}) {
1b4cf758 614 my $oldnet = PVE::LXC::Config->parse_lxc_network($oldnetcfg);
18862537
WB
615
616 if (&$safe_string_ne($oldnet->{hwaddr}, $newnet->{hwaddr}) ||
617 &$safe_string_ne($oldnet->{name}, $newnet->{name})) {
93cdbbfb 618
18862537 619 PVE::Network::veth_delete($veth);
bedeaaf1 620 delete $conf->{$opt};
67afe46e 621 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb 622
18862537 623 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
bedeaaf1 624
380962c7
WB
625 } else {
626 if (&$safe_string_ne($oldnet->{bridge}, $newnet->{bridge}) ||
627 &$safe_num_ne($oldnet->{tag}, $newnet->{tag}) ||
628 &$safe_num_ne($oldnet->{firewall}, $newnet->{firewall})) {
bedeaaf1 629
18862537 630 if ($oldnet->{bridge}) {
bedeaaf1 631 PVE::Network::tap_unplug($veth);
18862537
WB
632 foreach (qw(bridge tag firewall)) {
633 delete $oldnet->{$_};
634 }
1b4cf758 635 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
67afe46e 636 PVE::LXC::Config->write_config($vmid, $conf);
bedeaaf1 637 }
93cdbbfb 638
380962c7
WB
639 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
640 # This includes the rate:
641 foreach (qw(bridge tag firewall rate)) {
18862537
WB
642 $oldnet->{$_} = $newnet->{$_} if $newnet->{$_};
643 }
380962c7
WB
644 } elsif (&$safe_string_ne($oldnet->{rate}, $newnet->{rate})) {
645 # Rate can be applied on its own but any change above needs to
646 # include the rate in tap_plug since OVS resets everything.
647 PVE::Network::tap_rate_limit($veth, $newnet->{rate});
648 $oldnet->{rate} = $newnet->{rate}
649 }
650 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($oldnet);
651 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
652 }
653 } else {
18862537 654 hotplug_net($vmid, $conf, $opt, $newnet, $netid);
93cdbbfb
AD
655 }
656
bedeaaf1 657 update_ipconfig($vmid, $conf, $opt, $eth, $newnet, $rootdir);
93cdbbfb
AD
658}
659
660sub hotplug_net {
18862537 661 my ($vmid, $conf, $opt, $newnet, $netid) = @_;
93cdbbfb 662
18862537 663 my $veth = "veth${vmid}i${netid}";
cbb03fea 664 my $vethpeer = $veth . "p";
93cdbbfb
AD
665 my $eth = $newnet->{name};
666
667 PVE::Network::veth_create($veth, $vethpeer, $newnet->{bridge}, $newnet->{hwaddr});
380962c7 668 PVE::Network::tap_plug($veth, $newnet->{bridge}, $newnet->{tag}, $newnet->{firewall}, $newnet->{trunks}, $newnet->{rate});
93cdbbfb 669
cbb03fea 670 # attach peer in container
93cdbbfb
AD
671 my $cmd = ['lxc-device', '-n', $vmid, 'add', $vethpeer, "$eth" ];
672 PVE::Tools::run_command($cmd);
673
cbb03fea 674 # link up peer in container
93cdbbfb
AD
675 $cmd = ['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', '/sbin/ip', 'link', 'set', $eth ,'up' ];
676 PVE::Tools::run_command($cmd);
bedeaaf1 677
18862537
WB
678 my $done = { type => 'veth' };
679 foreach (qw(bridge tag firewall hwaddr name)) {
680 $done->{$_} = $newnet->{$_} if $newnet->{$_};
681 }
1b4cf758 682 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($done);
bedeaaf1 683
67afe46e 684 PVE::LXC::Config->write_config($vmid, $conf);
93cdbbfb
AD
685}
686
68a05bb3 687sub update_ipconfig {
bedeaaf1
AD
688 my ($vmid, $conf, $opt, $eth, $newnet, $rootdir) = @_;
689
f2104b80 690 my $lxc_setup = PVE::LXC::Setup->new($conf, $rootdir);
bedeaaf1 691
1b4cf758 692 my $optdata = PVE::LXC::Config->parse_lxc_network($conf->{$opt});
84e0c123
WB
693 my $deleted = [];
694 my $added = [];
8d723477
WB
695 my $nscmd = sub {
696 my $cmdargs = shift;
697 PVE::Tools::run_command(['lxc-attach', '-n', $vmid, '-s', 'NETWORK', '--', @_], %$cmdargs);
84e0c123 698 };
8d723477 699 my $ipcmd = sub { &$nscmd({}, '/sbin/ip', @_) };
2bfd1615 700
84e0c123 701 my $change_ip_config = sub {
f39002a6
DM
702 my ($ipversion) = @_;
703
704 my $family_opt = "-$ipversion";
705 my $suffix = $ipversion == 4 ? '' : $ipversion;
84e0c123
WB
706 my $gw= "gw$suffix";
707 my $ip= "ip$suffix";
bedeaaf1 708
6178b0dd
WB
709 my $newip = $newnet->{$ip};
710 my $newgw = $newnet->{$gw};
711 my $oldip = $optdata->{$ip};
712
713 my $change_ip = &$safe_string_ne($oldip, $newip);
714 my $change_gw = &$safe_string_ne($optdata->{$gw}, $newgw);
bedeaaf1 715
84e0c123 716 return if !$change_ip && !$change_gw;
68a05bb3 717
84e0c123 718 # step 1: add new IP, if this fails we cancel
292aff54
WB
719 my $is_real_ip = ($newip && $newip !~ /^(?:auto|dhcp|manual)$/);
720 if ($change_ip && $is_real_ip) {
8d723477 721 eval { &$ipcmd($family_opt, 'addr', 'add', $newip, 'dev', $eth); };
84e0c123
WB
722 if (my $err = $@) {
723 warn $err;
724 return;
725 }
bedeaaf1 726 }
bedeaaf1 727
84e0c123
WB
728 # step 2: replace gateway
729 # If this fails we delete the added IP and cancel.
730 # If it succeeds we save the config and delete the old IP, ignoring
731 # errors. The config is then saved.
732 # Note: 'ip route replace' can add
733 if ($change_gw) {
6178b0dd 734 if ($newgw) {
292aff54
WB
735 eval {
736 if ($is_real_ip && !PVE::Network::is_ip_in_cidr($newgw, $newip, $ipversion)) {
737 &$ipcmd($family_opt, 'route', 'add', $newgw, 'dev', $eth);
738 }
739 &$ipcmd($family_opt, 'route', 'replace', 'default', 'via', $newgw);
740 };
84e0c123
WB
741 if (my $err = $@) {
742 warn $err;
743 # the route was not replaced, the old IP is still available
744 # rollback (delete new IP) and cancel
745 if ($change_ip) {
8d723477 746 eval { &$ipcmd($family_opt, 'addr', 'del', $newip, 'dev', $eth); };
84e0c123
WB
747 warn $@ if $@; # no need to die here
748 }
749 return;
750 }
751 } else {
8d723477 752 eval { &$ipcmd($family_opt, 'route', 'del', 'default'); };
84e0c123
WB
753 # if the route was not deleted, the guest might have deleted it manually
754 # warn and continue
755 warn $@ if $@;
756 }
2bfd1615 757 }
2bfd1615 758
6178b0dd 759 # from this point on we save the configuration
84e0c123 760 # step 3: delete old IP ignoring errors
6178b0dd 761 if ($change_ip && $oldip && $oldip !~ /^(?:auto|dhcp)$/) {
8d723477
WB
762 # We need to enable promote_secondaries, otherwise our newly added
763 # address will be removed along with the old one.
764 my $promote = 0;
765 eval {
766 if ($ipversion == 4) {
767 &$nscmd({ outfunc => sub { $promote = int(shift) } },
768 'cat', "/proc/sys/net/ipv4/conf/$eth/promote_secondaries");
769 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=1");
770 }
771 &$ipcmd($family_opt, 'addr', 'del', $oldip, 'dev', $eth);
772 };
84e0c123 773 warn $@ if $@; # no need to die here
8d723477
WB
774
775 if ($ipversion == 4) {
776 &$nscmd({}, 'sysctl', "net.ipv4.conf.$eth.promote_secondaries=$promote");
777 }
bedeaaf1
AD
778 }
779
84e0c123
WB
780 foreach my $property ($ip, $gw) {
781 if ($newnet->{$property}) {
782 $optdata->{$property} = $newnet->{$property};
783 } else {
784 delete $optdata->{$property};
785 }
bedeaaf1 786 }
1b4cf758 787 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($optdata);
67afe46e 788 PVE::LXC::Config->write_config($vmid, $conf);
84e0c123
WB
789 $lxc_setup->setup_network($conf);
790 };
bedeaaf1 791
f39002a6
DM
792 &$change_ip_config(4);
793 &$change_ip_config(6);
489e960d
WL
794
795}
796
34fdb3d7
WB
797my $enter_namespace = sub {
798 my ($vmid, $pid, $which, $type) = @_;
799 sysopen my $fd, "/proc/$pid/ns/$which", O_RDONLY
800 or die "failed to open $which namespace of container $vmid: $!\n";
801 PVE::Tools::setns(fileno($fd), $type)
802 or die "failed to enter $which namespace of container $vmid: $!\n";
803 close $fd;
804};
805
806my $do_syncfs = sub {
807 my ($vmid, $pid, $socket) = @_;
808
809 &$enter_namespace($vmid, $pid, 'mnt', PVE::Tools::CLONE_NEWNS);
810
811 # Tell the parent process to start reading our /proc/mounts
812 print {$socket} "go\n";
813 $socket->flush();
814
815 # Receive /proc/self/mounts
816 my $mountdata = do { local $/ = undef; <$socket> };
817 close $socket;
818
819 # Now sync all mountpoints...
820 my $mounts = PVE::ProcFSTools::parse_mounts($mountdata);
821 foreach my $mp (@$mounts) {
822 my ($what, $dir, $fs) = @$mp;
823 next if $fs eq 'fuse.lxcfs';
824 eval { PVE::Tools::sync_mountpoint($dir); };
825 warn $@ if $@;
826 }
827};
828
829sub sync_container_namespace {
830 my ($vmid) = @_;
831 my $pid = find_lxc_pid($vmid);
832
833 # SOCK_DGRAM is nicer for barriers but cannot be slurped
834 socketpair my $pfd, my $cfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC
835 or die "failed to create socketpair: $!\n";
836
837 my $child = fork();
838 die "fork failed: $!\n" if !defined($child);
839
840 if (!$child) {
841 eval {
842 close $pfd;
843 &$do_syncfs($vmid, $pid, $cfd);
844 };
845 if (my $err = $@) {
846 warn $err;
847 POSIX::_exit(1);
848 }
849 POSIX::_exit(0);
850 }
851 close $cfd;
852 my $go = <$pfd>;
853 die "failed to enter container namespace\n" if $go ne "go\n";
854
855 open my $mounts, '<', "/proc/$child/mounts"
856 or die "failed to open container's /proc/mounts: $!\n";
857 my $mountdata = do { local $/ = undef; <$mounts> };
858 close $mounts;
859 print {$pfd} $mountdata;
860 close $pfd;
861
862 while (waitpid($child, 0) != $child) {}
863 die "failed to sync container namespace\n" if $? != 0;
864}
865
bb1ac2de
DM
866sub template_create {
867 my ($vmid, $conf) = @_;
868
869 my $storecfg = PVE::Storage::config();
870
1b4cf758 871 my $rootinfo = PVE::LXC::Config->parse_ct_rootfs($conf->{rootfs});
bb1ac2de
DM
872 my $volid = $rootinfo->{volume};
873
874 die "Template feature is not available for '$volid'\n"
875 if !PVE::Storage::volume_has_feature($storecfg, 'template', $volid);
876
877 PVE::Storage::activate_volumes($storecfg, [$volid]);
878
879 my $template_volid = PVE::Storage::vdisk_create_base($storecfg, $volid);
880 $rootinfo->{volume} = $template_volid;
1b4cf758 881 $conf->{rootfs} = PVE::LXC::Config->print_ct_mountpoint($rootinfo, 1);
bb1ac2de 882
67afe46e 883 PVE::LXC::Config->write_config($vmid, $conf);
bb1ac2de
DM
884}
885
52389a07 886sub check_ct_modify_config_perm {
f1ba1a4b 887 my ($rpcenv, $authuser, $vmid, $pool, $newconf, $delete) = @_;
52389a07 888
c81f19d1 889 return 1 if $authuser eq 'root@pam';
52389a07 890
f1ba1a4b
WB
891 my $check = sub {
892 my ($opt, $delete) = @_;
f2357408 893 if ($opt eq 'cores' || $opt eq 'cpuunits' || $opt eq 'cpulimit') {
52389a07 894 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.CPU']);
e59a61ed 895 } elsif ($opt eq 'rootfs' || $opt =~ /^mp\d+$/) {
52389a07 896 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Disk']);
f1ba1a4b 897 return if $delete;
1b4cf758
FG
898 my $data = $opt eq 'rootfs' ? PVE::LXC::Config->parse_ct_rootfs($newconf->{$opt})
899 : PVE::LXC::Config->parse_ct_mountpoint($newconf->{$opt});
9d294016
FG
900 raise_perm_exc("mount point type $data->{type} is only allowed for root\@pam")
901 if $data->{type} ne 'volume';
52389a07
DM
902 } elsif ($opt eq 'memory' || $opt eq 'swap') {
903 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Memory']);
904 } elsif ($opt =~ m/^net\d+$/ || $opt eq 'nameserver' ||
905 $opt eq 'searchdomain' || $opt eq 'hostname') {
906 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Network']);
907 } else {
908 $rpcenv->check_vm_perm($authuser, $vmid, $pool, ['VM.Config.Options']);
909 }
f1ba1a4b
WB
910 };
911
912 foreach my $opt (keys %$newconf) {
913 &$check($opt, 0);
914 }
915 foreach my $opt (@$delete) {
916 &$check($opt, 1);
52389a07
DM
917 }
918
919 return 1;
920}
921
9622e848 922sub umount_all {
da629848 923 my ($vmid, $storage_cfg, $conf, $noerr) = @_;
9622e848
DM
924
925 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
d250604f 926 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848 927
d250604f 928 PVE::LXC::Config->foreach_mountpoint_reverse($conf, sub {
9622e848
DM
929 my ($ms, $mountpoint) = @_;
930
931 my $volid = $mountpoint->{volume};
932 my $mount = $mountpoint->{mp};
933
934 return if !$volid || !$mount;
935
d18f96b4 936 my $mount_path = "$rootdir/$mount";
f845a93d 937 $mount_path =~ s!/+!/!g;
9622e848 938
228a5a1d
WL
939 return if !PVE::ProcFSTools::is_mounted($mount_path);
940
9622e848 941 eval {
d18f96b4 942 PVE::Tools::run_command(['umount', '-d', $mount_path]);
9622e848
DM
943 };
944 if (my $err = $@) {
945 if ($noerr) {
946 warn $err;
947 } else {
948 die $err;
949 }
950 }
951 });
9622e848
DM
952}
953
954sub mount_all {
25321b68 955 my ($vmid, $storage_cfg, $conf, $ignore_ro) = @_;
9622e848
DM
956
957 my $rootdir = "/var/lib/lxc/$vmid/rootfs";
1adc7e53 958 File::Path::make_path($rootdir);
9622e848 959
d250604f 960 my $volid_list = PVE::LXC::Config->get_vm_volumes($conf);
9622e848
DM
961 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
962
963 eval {
d250604f 964 PVE::LXC::Config->foreach_mountpoint($conf, sub {
9622e848
DM
965 my ($ms, $mountpoint) = @_;
966
25321b68
FG
967 $mountpoint->{ro} = 0 if $ignore_ro;
968
da629848 969 mountpoint_mount($mountpoint, $rootdir, $storage_cfg);
9622e848
DM
970 });
971 };
972 if (my $err = $@) {
e2007ac2 973 warn "mounting container failed\n";
9622e848 974 umount_all($vmid, $storage_cfg, $conf, 1);
e2007ac2 975 die $err;
9622e848
DM
976 }
977
da629848 978 return $rootdir;
9622e848
DM
979}
980
981
b15c75fc 982sub mountpoint_mount_path {
da629848 983 my ($mountpoint, $storage_cfg, $snapname) = @_;
b15c75fc 984
da629848 985 return mountpoint_mount($mountpoint, undef, $storage_cfg, $snapname);
b15c75fc 986}
cc6b0307 987
21f292ff
WB
988sub query_loopdev {
989 my ($path) = @_;
990 my $found;
991 my $parser = sub {
992 my $line = shift;
993 if ($line =~ m@^(/dev/loop\d+):@) {
994 $found = $1;
995 }
996 };
997 my $cmd = ['losetup', '--associated', $path];
998 PVE::Tools::run_command($cmd, outfunc => $parser);
999 return $found;
1000}
1001
50df544c
WB
1002# Run a function with a file attached to a loop device.
1003# The loop device is always detached afterwards (or set to autoclear).
1004# Returns the loop device.
1005sub run_with_loopdev {
1006 my ($func, $file) = @_;
54d11e5c
WB
1007 my $device = query_loopdev($file);
1008 # Try to reuse an existing device
1009 if ($device) {
1010 # We assume that whoever setup the loop device is responsible for
1011 # detaching it.
1012 &$func($device);
1013 return $device;
1014 }
1015
50df544c
WB
1016 my $parser = sub {
1017 my $line = shift;
1018 if ($line =~ m@^(/dev/loop\d+)$@) {
1019 $device = $1;
1020 }
1021 };
1022 PVE::Tools::run_command(['losetup', '--show', '-f', $file], outfunc => $parser);
1023 die "failed to setup loop device for $file\n" if !$device;
1024 eval { &$func($device); };
1025 my $err = $@;
1026 PVE::Tools::run_command(['losetup', '-d', $device]);
1027 die $err if $err;
1028 return $device;
1029}
1030
ab3722b3
WB
1031# In scalar mode: returns a file handle to the deepest directory node.
1032# In list context: returns a list of:
1033# * the deepest directory node
1034# * the 2nd deepest directory (parent of the above)
1035# * directory name of the last directory
1036# So that the path $2/$3 should lead to $1 afterwards.
1037sub walk_tree_nofollow($$$) {
1038 my ($start, $subdir, $mkdir) = @_;
1039
1040 # splitdir() returns '' for empty components including the leading /
1041 my @comps = grep { length($_)>0 } File::Spec->splitdir($subdir);
1042
1043 sysopen(my $fd, $start, O_PATH | O_DIRECTORY)
1044 or die "failed to open start directory $start: $!\n";
1045
1046 my $dir = $start;
1047 my $last_component = undef;
1048 my $second = $fd;
1049 foreach my $component (@comps) {
1050 $dir .= "/$component";
1051 my $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1052
1053 if (!$next) {
1054 # failed, check for symlinks and try to create the path
1055 die "symlink encountered at: $dir\n" if $! == ELOOP;
1056 die "cannot open directory $dir: $!\n" if !$mkdir;
1057
1058 # We don't check for errors on mkdirat() here and just try to
1059 # openat() again, since at least one error (EEXIST) is an
1060 # expected possibility if multiple containers start
1061 # simultaneously. If someone else injects a symlink now then
1062 # the subsequent openat() will fail due to O_NOFOLLOW anyway.
1063 PVE::Tools::mkdirat(fileno($fd), $component, 0755);
1064
1065 $next = PVE::Tools::openat(fileno($fd), $component, O_NOFOLLOW | O_DIRECTORY);
1066 die "failed to create path: $dir: $!\n" if !$next;
1067 }
1068
1069 close $second if defined($last_component);
1070 $last_component = $component;
1071 $second = $fd;
1072 $fd = $next;
1073 }
1074
1075 return ($fd, defined($last_component) && $second, $last_component) if wantarray;
1076 close $second if defined($last_component);
1077 return $fd;
1078}
1079
619f27b4
WB
1080# To guard against symlink attack races against other currently running
1081# containers with shared recursive bind mount hierarchies we prepare a
1082# directory handle for the directory we're mounting over to verify the
1083# mountpoint afterwards.
1084sub __bindmount_prepare {
1085 my ($hostroot, $dir) = @_;
1086 my $srcdh = walk_tree_nofollow($hostroot, $dir, 0);
1087 return $srcdh;
1088}
ab3722b3 1089
619f27b4
WB
1090# Assuming we mount to rootfs/a/b/c, verify with the directory handle to 'b'
1091# ($parentfd) that 'b/c' (openat($parentfd, 'c')) really leads to the directory
1092# we intended to bind mount.
1093sub __bindmount_verify {
1094 my ($srcdh, $parentfd, $last_dir, $ro) = @_;
ab3722b3
WB
1095 my $destdh;
1096 if ($parentfd) {
1097 # Open the mount point path coming from the parent directory since the
1098 # filehandle we would have gotten as first result of walk_tree_nofollow
1099 # earlier is still a handle to the underlying directory instead of the
1100 # mounted path.
619f27b4
WB
1101 $destdh = PVE::Tools::openat(fileno($parentfd), $last_dir, PVE::Tools::O_PATH | O_NOFOLLOW | O_DIRECTORY);
1102 die "failed to open mount point: $!\n" if !$destdh;
1103 if ($ro) {
1104 my $dot = '.';
1105 # 269: faccessat()
1106 # no separate function because 99% of the time it's the wrong thing to use.
1107 if (syscall(269, fileno($destdh), $dot, &POSIX::W_OK, 0) != -1) {
1108 die "failed to mark bind mount read only\n";
1109 }
1110 die "read-only check failed: $!\n" if $! != EROFS;
1111 }
ab3722b3
WB
1112 } else {
1113 # For the rootfs we don't have a parentfd so we open the path directly.
1114 # Note that this means bindmounting any prefix of the host's
1115 # /var/lib/lxc/$vmid path into another container is considered a grave
1116 # security error.
1117 sysopen $destdh, $last_dir, O_PATH | O_DIRECTORY;
619f27b4 1118 die "failed to open mount point: $!\n" if !$destdh;
ab3722b3 1119 }
ab3722b3
WB
1120
1121 my ($srcdev, $srcinode) = stat($srcdh);
1122 my ($dstdev, $dstinode) = stat($destdh);
1123 close $srcdh;
1124 close $destdh;
1125
619f27b4
WB
1126 return ($srcdev == $dstdev && $srcinode == $dstinode);
1127}
1128
1129# Perform the actual bind mounting:
1130sub __bindmount_do {
1131 my ($dir, $dest, $ro, @extra_opts) = @_;
1132 PVE::Tools::run_command(['mount', '-o', 'bind', @extra_opts, $dir, $dest]);
1133 if ($ro) {
1134 eval { PVE::Tools::run_command(['mount', '-o', 'bind,remount,ro', $dest]); };
1135 if (my $err = $@) {
1136 warn "bindmount error\n";
1137 # don't leave writable bind-mounts behind...
1138 PVE::Tools::run_command(['umount', $dest]);
1139 die $err;
1140 }
1141 }
1142}
1143
1144sub bindmount {
1145 my ($dir, $parentfd, $last_dir, $dest, $ro, @extra_opts) = @_;
1146
1147 my $srcdh = __bindmount_prepare('/', $dir);
1148
1149 __bindmount_do($dir, $dest, $ro, @extra_opts);
1150
1151 if (!__bindmount_verify($srcdh, $parentfd, $last_dir, $ro)) {
ab3722b3
WB
1152 PVE::Tools::run_command(['umount', $dest]);
1153 die "detected mount path change at: $dir\n";
1154 }
c2744c97
WB
1155}
1156
619f27b4
WB
1157# Cleanup $rootdir a bit (double and trailing slashes), build the mount path
1158# from $rootdir and $mount and walk the path from $rootdir to the final
1159# directory to check for symlinks.
1160sub __mount_prepare_rootdir {
1161 my ($rootdir, $mount) = @_;
1162 $rootdir =~ s!/+!/!g;
1163 $rootdir =~ s!/+$!!;
1164 my $mount_path = "$rootdir/$mount";
1165 my ($mpfd, $parentfd, $last_dir) = walk_tree_nofollow($rootdir, $mount, 1);
1166 return ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir);
1167}
1168
b15c75fc 1169# use $rootdir = undef to just return the corresponding mount path
cc6b0307 1170sub mountpoint_mount {
da629848 1171 my ($mountpoint, $rootdir, $storage_cfg, $snapname) = @_;
cc6b0307
AD
1172
1173 my $volid = $mountpoint->{volume};
1174 my $mount = $mountpoint->{mp};
7c921c80 1175 my $type = $mountpoint->{type};
50df544c
WB
1176 my $quota = !$snapname && !$mountpoint->{ro} && $mountpoint->{quota};
1177 my $mounted_dev;
b15c75fc 1178
cc6b0307
AD
1179 return if !$volid || !$mount;
1180
ab3722b3
WB
1181 $mount =~ s!/+!/!g;
1182
b15c75fc 1183 my $mount_path;
ab3722b3 1184 my ($mpfd, $parentfd, $last_dir);
b15c75fc
DM
1185
1186 if (defined($rootdir)) {
619f27b4
WB
1187 ($rootdir, $mount_path, $mpfd, $parentfd, $last_dir) =
1188 __mount_prepare_rootdir($rootdir, $mount);
116ce06f 1189 }
b15c75fc
DM
1190
1191 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
cc6b0307 1192
b15c75fc 1193 die "unknown snapshot path for '$volid'" if !$storage && defined($snapname);
cc6b0307 1194
471dd315 1195 my $optstring = '';
719129ea
WB
1196 my $acl = $mountpoint->{acl};
1197 if (defined($acl)) {
1198 $optstring .= ($acl ? 'acl' : 'noacl');
471dd315 1199 }
c2744c97 1200 my $readonly = $mountpoint->{ro};
471dd315 1201
c019c56a 1202 my @extra_opts = ('-o', $optstring) if $optstring;
471dd315 1203
b15c75fc
DM
1204 if ($storage) {
1205
1206 my $scfg = PVE::Storage::storage_config($storage_cfg, $storage);
7c138f58
WB
1207
1208 # early sanity checks:
1209 # we otherwise call realpath on the rbd url
1210 die "containers on rbd storage without krbd are not supported\n"
1211 if $scfg->{type} eq 'rbd' && !$scfg->{krbd};
1212
b15c75fc
DM
1213 my $path = PVE::Storage::path($storage_cfg, $volid, $snapname);
1214
1215 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1216 PVE::Storage::parse_volname($storage_cfg, $volid);
1217
c87b9dd8
DM
1218 $format = 'iso' if $vtype eq 'iso'; # allow to handle iso files
1219
b15c75fc 1220 if ($format eq 'subvol') {
30de33be
DM
1221 if ($mount_path) {
1222 if ($snapname) {
e84f7f5d
DM
1223 if ($scfg->{type} eq 'zfspool') {
1224 my $path_arg = $path;
1225 $path_arg =~ s!^/+!!;
471dd315 1226 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, '-t', 'zfs', $path_arg, $mount_path]);
e84f7f5d 1227 } else {
30de33be
DM
1228 die "cannot mount subvol snapshots for storage type '$scfg->{type}'\n";
1229 }
e84f7f5d 1230 } else {
719129ea
WB
1231 if (defined($acl) && $scfg->{type} eq 'zfspool') {
1232 my $acltype = ($acl ? 'acltype=posixacl' : 'acltype=noacl');
1233 my (undef, $name) = PVE::Storage::parse_volname($storage_cfg, $volid);
1234 $name .= "\@$snapname" if defined($snapname);
1235 PVE::Tools::run_command(['zfs', 'set', $acltype, "$scfg->{pool}/$name"]);
1236 }
ab3722b3 1237 bindmount($path, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts);
50df544c 1238 warn "cannot enable quota control for bind mounted subvolumes\n" if $quota;
30de33be 1239 }
b15c75fc 1240 }
5f6280cf 1241 return wantarray ? ($path, 0, undef) : $path;
c87b9dd8 1242 } elsif ($format eq 'raw' || $format eq 'iso') {
ada088e6
WB
1243 # NOTE: 'mount' performs canonicalization without the '-c' switch, which for
1244 # device-mapper devices is special-cased to use the /dev/mapper symlinks.
1245 # Our autodev hook expects the /dev/dm-* device currently
1246 # and will create the /dev/mapper symlink accordingly
e439a713
WB
1247 $path = Cwd::realpath($path);
1248 die "failed to get device path\n" if !$path;
1249 ($path) = ($path =~ /^(.*)$/s); #untaint
50df544c
WB
1250 my $domount = sub {
1251 my ($path) = @_;
1252 if ($mount_path) {
1253 if ($format eq 'iso') {
1254 PVE::Tools::run_command(['mount', '-o', 'ro', @extra_opts, $path, $mount_path]);
1255 } elsif ($isBase || defined($snapname)) {
1256 PVE::Tools::run_command(['mount', '-o', 'ro,noload', @extra_opts, $path, $mount_path]);
1257 } else {
1258 if ($quota) {
1259 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0';
1260 }
c2744c97 1261 push @extra_opts, '-o', 'ro' if $readonly;
50df544c
WB
1262 PVE::Tools::run_command(['mount', @extra_opts, $path, $mount_path]);
1263 }
1264 }
1265 };
30de33be 1266 my $use_loopdev = 0;
b15c75fc 1267 if ($scfg->{path}) {
50df544c 1268 $mounted_dev = run_with_loopdev($domount, $path);
30de33be 1269 $use_loopdev = 1;
2e879877
DM
1270 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' ||
1271 $scfg->{type} eq 'rbd' || $scfg->{type} eq 'lvmthin') {
50df544c
WB
1272 $mounted_dev = $path;
1273 &$domount($path);
b15c75fc
DM
1274 } else {
1275 die "unsupported storage type '$scfg->{type}'\n";
1276 }
50df544c 1277 return wantarray ? ($path, $use_loopdev, $mounted_dev) : $path;
b15c75fc
DM
1278 } else {
1279 die "unsupported image format '$format'\n";
1280 }
7c921c80 1281 } elsif ($type eq 'device') {
c9bc95a1 1282 push @extra_opts, '-o', 'ro' if $readonly;
0d449e38
WB
1283 push @extra_opts, '-o', 'usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0' if $quota;
1284 # See the NOTE above about devicemapper canonicalization
1285 my ($devpath) = (Cwd::realpath($volid) =~ /^(.*)$/s); # realpath() taints
471dd315 1286 PVE::Tools::run_command(['mount', @extra_opts, $volid, $mount_path]) if $mount_path;
0d449e38 1287 return wantarray ? ($volid, 0, $devpath) : $volid;
e2007ac2
DM
1288 } elsif ($type eq 'bind') {
1289 die "directory '$volid' does not exist\n" if ! -d $volid;
ab3722b3 1290 bindmount($volid, $parentfd, $last_dir//$rootdir, $mount_path, $readonly, @extra_opts) if $mount_path;
50df544c
WB
1291 warn "cannot enable quota control for bind mounts\n" if $quota;
1292 return wantarray ? ($volid, 0, undef) : $volid;
b15c75fc
DM
1293 }
1294
1295 die "unsupported storage";
cc6b0307
AD
1296}
1297
6c871c36 1298sub mkfs {
d216e891 1299 my ($dev, $rootuid, $rootgid) = @_;
6c871c36 1300
d216e891
WB
1301 PVE::Tools::run_command(['mkfs.ext4', '-O', 'mmp',
1302 '-E', "root_owner=$rootuid:$rootgid",
1303 $dev]);
6c871c36
DM
1304}
1305
1306sub format_disk {
d216e891 1307 my ($storage_cfg, $volid, $rootuid, $rootgid) = @_;
6c871c36
DM
1308
1309 if ($volid =~ m!^/dev/.+!) {
1310 mkfs($volid);
1311 return;
1312 }
1313
1314 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1315
1316 die "cannot format volume '$volid' with no storage\n" if !$storage;
1317
08ca136d
DM
1318 PVE::Storage::activate_volumes($storage_cfg, [$volid]);
1319
6c871c36
DM
1320 my $path = PVE::Storage::path($storage_cfg, $volid);
1321
1322 my ($vtype, undef, undef, undef, undef, $isBase, $format) =
1323 PVE::Storage::parse_volname($storage_cfg, $volid);
1324
1325 die "cannot format volume '$volid' (format == $format)\n"
1326 if $format ne 'raw';
1327
d216e891 1328 mkfs($path, $rootuid, $rootgid);
6c871c36
DM
1329}
1330
1331sub destroy_disks {
1332 my ($storecfg, $vollist) = @_;
1333
1334 foreach my $volid (@$vollist) {
1335 eval { PVE::Storage::vdisk_free($storecfg, $volid); };
1336 warn $@ if $@;
1337 }
1338}
1339
1340sub create_disks {
1341 my ($storecfg, $vmid, $settings, $conf) = @_;
1342
1343 my $vollist = [];
1344
1345 eval {
d216e891
WB
1346 my (undef, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
1347 my $chown_vollist = [];
1348
d250604f 1349 PVE::LXC::Config->foreach_mountpoint($settings, sub {
6c871c36
DM
1350 my ($ms, $mountpoint) = @_;
1351
1352 my $volid = $mountpoint->{volume};
1353 my $mp = $mountpoint->{mp};
1354
1355 my ($storage, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1356
e2007ac2 1357 if ($storage && ($volid =~ m/^([^:\s]+):(\d+(\.\d+)?)$/)) {
8ed5ff9d 1358 my ($storeid, $size_gb) = ($1, $2);
6c871c36 1359
8ed5ff9d 1360 my $size_kb = int(${size_gb}*1024) * 1024;
6c871c36
DM
1361
1362 my $scfg = PVE::Storage::storage_config($storecfg, $storage);
1363 # fixme: use better naming ct-$vmid-disk-X.raw?
1364
1365 if ($scfg->{type} eq 'dir' || $scfg->{type} eq 'nfs') {
8ed5ff9d 1366 if ($size_kb > 0) {
6c871c36 1367 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw',
8ed5ff9d 1368 undef, $size_kb);
d216e891 1369 format_disk($storecfg, $volid, $rootuid, $rootgid);
6c871c36
DM
1370 } else {
1371 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
1372 undef, 0);
d216e891 1373 push @$chown_vollist, $volid;
6c871c36
DM
1374 }
1375 } elsif ($scfg->{type} eq 'zfspool') {
1376
1377 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'subvol',
8ed5ff9d 1378 undef, $size_kb);
d216e891 1379 push @$chown_vollist, $volid;
2e879877 1380 } elsif ($scfg->{type} eq 'drbd' || $scfg->{type} eq 'lvm' || $scfg->{type} eq 'lvmthin') {
6c871c36 1381
8ed5ff9d 1382 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
d216e891 1383 format_disk($storecfg, $volid, $rootuid, $rootgid);
6c871c36
DM
1384
1385 } elsif ($scfg->{type} eq 'rbd') {
1386
1387 die "krbd option must be enabled on storage type '$scfg->{type}'\n" if !$scfg->{krbd};
8ed5ff9d 1388 $volid = PVE::Storage::vdisk_alloc($storecfg, $storage, $vmid, 'raw', undef, $size_kb);
d216e891 1389 format_disk($storecfg, $volid, $rootuid, $rootgid);
6c871c36
DM
1390 } else {
1391 die "unable to create containers on storage type '$scfg->{type}'\n";
1392 }
1393 push @$vollist, $volid;
71c780b9
WB
1394 $mountpoint->{volume} = $volid;
1395 $mountpoint->{size} = $size_kb * 1024;
1b4cf758 1396 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36 1397 } else {
e2007ac2 1398 # use specified/existing volid/dir/device
1b4cf758 1399 $conf->{$ms} = PVE::LXC::Config->print_ct_mountpoint($mountpoint, $ms eq 'rootfs');
6c871c36
DM
1400 }
1401 });
d216e891
WB
1402
1403 PVE::Storage::activate_volumes($storecfg, $chown_vollist, undef);
1404 foreach my $volid (@$chown_vollist) {
1405 my $path = PVE::Storage::path($storecfg, $volid, undef);
1406 chown($rootuid, $rootgid, $path);
1407 }
1408 PVE::Storage::deactivate_volumes($storecfg, $chown_vollist, undef);
6c871c36
DM
1409 };
1410 # free allocated images on error
1411 if (my $err = $@) {
1412 destroy_disks($storecfg, $vollist);
1413 die $err;
1414 }
1415 return $vollist;
1416}
1417
68e8f3c5
DM
1418# bash completion helper
1419
1420sub complete_os_templates {
1421 my ($cmdname, $pname, $cvalue) = @_;
1422
1423 my $cfg = PVE::Storage::config();
1424
9e9bc3a6 1425 my $storeid;
68e8f3c5
DM
1426
1427 if ($cvalue =~ m/^([^:]+):/) {
1428 $storeid = $1;
1429 }
1430
1431 my $vtype = $cmdname eq 'restore' ? 'backup' : 'vztmpl';
1432 my $data = PVE::Storage::template_list($cfg, $storeid, $vtype);
1433
1434 my $res = [];
1435 foreach my $id (keys %$data) {
1436 foreach my $item (@{$data->{$id}}) {
1437 push @$res, $item->{volid} if defined($item->{volid});
1438 }
1439 }
1440
1441 return $res;
1442}
1443
68e8f3c5
DM
1444my $complete_ctid_full = sub {
1445 my ($running) = @_;
1446
1447 my $idlist = vmstatus();
1448
1449 my $active_hash = list_active_containers();
1450
1451 my $res = [];
1452
1453 foreach my $id (keys %$idlist) {
1454 my $d = $idlist->{$id};
1455 if (defined($running)) {
1456 next if $d->{template};
1457 next if $running && !$active_hash->{$id};
1458 next if !$running && $active_hash->{$id};
1459 }
1460 push @$res, $id;
1461
1462 }
1463 return $res;
1464};
1465
1466sub complete_ctid {
1467 return &$complete_ctid_full();
1468}
1469
1470sub complete_ctid_stopped {
1471 return &$complete_ctid_full(0);
1472}
1473
1474sub complete_ctid_running {
1475 return &$complete_ctid_full(1);
1476}
1477
c6a605f9
WB
1478sub parse_id_maps {
1479 my ($conf) = @_;
1480
1481 my $id_map = [];
1482 my $rootuid = 0;
1483 my $rootgid = 0;
1484
1485 my $lxc = $conf->{lxc};
1486 foreach my $entry (@$lxc) {
1487 my ($key, $value) = @$entry;
1488 next if $key ne 'lxc.id_map';
1489 if ($value =~ /^([ug])\s+(\d+)\s+(\d+)\s+(\d+)\s*$/) {
1490 my ($type, $ct, $host, $length) = ($1, $2, $3, $4);
1491 push @$id_map, [$type, $ct, $host, $length];
1492 if ($ct == 0) {
1493 $rootuid = $host if $type eq 'u';
1494 $rootgid = $host if $type eq 'g';
1495 }
1496 } else {
1497 die "failed to parse id_map: $value\n";
1498 }
1499 }
1500
1501 if (!@$id_map && $conf->{unprivileged}) {
1502 # Should we read them from /etc/subuid?
1503 $id_map = [ ['u', '0', '100000', '65536'],
1504 ['g', '0', '100000', '65536'] ];
1505 $rootuid = $rootgid = 100000;
1506 }
1507
1508 return ($id_map, $rootuid, $rootgid);
1509}
1510
01dce99b
WB
1511sub userns_command {
1512 my ($id_map) = @_;
1513 if (@$id_map) {
1514 return ['lxc-usernsexec', (map { ('-m', join(':', @$_)) } @$id_map), '--'];
1515 }
1516 return [];
1517}
1518
846a66b0 1519
f76a2828 15201;