1 package PVE
::LXC
::Setup
::Base
;
21 my ($class, $conf, $rootdir, $os_release) = @_;
23 return bless { conf
=> $conf, rootdir
=> $rootdir, os_release
=> $os_release }, $class;
27 my ($self, $conf) = @_;
29 my $nameserver = $conf->{nameserver
};
30 my $searchdomains = $conf->{searchdomain
};
32 if ($conf->{'testmode'}) {
33 return ('proxmox.com', '8.8.8.8 8.8.8.9');
36 my $host_resolv_conf = $self->{host_resolv_conf
};
38 if (!defined($nameserver)) {
40 foreach my $k ("dns1", "dns2", "dns3") {
41 if (my $ns = $host_resolv_conf->{$k}) {
45 $nameserver = join(' ', @list);
48 if (!defined($searchdomains)) {
49 $searchdomains = $host_resolv_conf->{search
};
52 return ($searchdomains, $nameserver);
55 sub update_etc_hosts
{
56 my ($self, $hostip, $oldname, $newname, $searchdomains) = @_;
58 my $hosts_fn = '/etc/hosts';
59 return if $self->ct_is_file_ignored($hosts_fn);
61 my $namepart = ($newname =~ s/\..*$//r);
64 if ($newname =~ /\./) {
65 $all_names .= "$newname $namepart";
67 foreach my $domain (PVE
::Tools
::split_list
($searchdomains)) {
68 $all_names .= ' ' if $all_names;
69 $all_names .= "$newname.$domain";
71 $all_names .= ' ' if $all_names;
72 $all_names .= $newname;
78 my $lo4 = "127.0.0.1 localhost.localnet localhost\n";
79 my $lo6 = "::1 localhost.localnet localhost\n";
80 if ($self->ct_file_exists($hosts_fn)) {
81 my $data = $self->ct_file_get_contents($hosts_fn);
82 # don't take localhost entries within our hosts sections into account
83 $data = remove_pve_sections
($data);
85 # check for existing localhost entries
86 $section .= $lo4 if $data !~ /^\h*127\.0\.0\.1\h+/m;
87 $section .= $lo6 if $data !~ /^\h*::1\h+/m;
89 $section .= $lo4 . $lo6;
92 if (defined($hostip)) {
93 $section .= "$hostip $all_names\n";
94 } elsif ($namepart ne 'localhost') {
95 $section .= "127.0.1.1 $all_names\n";
97 $section .= "127.0.1.1 $namepart\n";
100 $self->ct_modify_file($hosts_fn, $section);
104 my ($self, $conf) = @_;
106 # do nothing by default
110 my ($self, $conf) = @_;
112 my ($searchdomains, $nameserver) = $self->lookup_dns_conf($conf);
116 $data .= "search " . join(' ', PVE
::Tools
::split_list
($searchdomains)) . "\n"
119 foreach my $ns ( PVE
::Tools
::split_list
($nameserver)) {
120 $data .= "nameserver $ns\n";
123 $self->ct_modify_file("/etc/resolv.conf", $data, replace
=> 1);
127 my ($self, $conf) = @_;
129 my $hostname = $conf->{hostname
} || 'localhost';
131 my $namepart = ($hostname =~ s/\..*$//r);
133 my $hostname_fn = "/etc/hostname";
135 my $oldname = $self->ct_file_read_firstline($hostname_fn) || 'localhost';
137 my ($ipv4, $ipv6) = PVE
::LXC
::get_primary_ips
($conf);
138 my $hostip = $ipv4 || $ipv6;
140 my ($searchdomains) = $self->lookup_dns_conf($conf);
142 $self->update_etc_hosts($hostip, $oldname, $hostname, $searchdomains);
144 $self->ct_file_set_contents($hostname_fn, "$namepart\n");
148 my ($self, $conf) = @_;
150 die "please implement this inside subclass"
154 my ($self, $conf) = @_;
156 die "please implement this inside subclass"
159 # A few distros as well as unprivileged containers cannot deal with the
160 # /dev/lxc/ tty subdirectory.
162 my ($self, $conf) = @_;
163 return $conf->{unprivileged
} ?
'' : 'lxc/';
166 sub fixup_old_getty
{
169 my $sd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
170 "/lib/systemd/system" : "/usr/lib/systemd/system";
172 my $sd_getty_service_rel = "$sd_dir_rel/getty\@.service";
173 return if !$self->ct_file_exists($sd_getty_service_rel);
175 my $raw = $self->ct_file_get_contents($sd_getty_service_rel);
177 my $sd_container_getty_service_rel = "$sd_dir_rel/container-getty\@.service";
178 # systemd on CenoOS 7.1 is too old (version 205), so there is no
179 # container-getty service
180 if (!$self->ct_file_exists($sd_container_getty_service_rel)) {
181 if ($raw =~ s!^ConditionPathExists=/dev/tty0$!ConditionPathExists=/dev/tty!m) {
182 $self->ct_file_set_contents($sd_getty_service_rel, $raw);
185 # undo above change (in case someone updated systemd)
186 if ($raw =~ s!^ConditionPathExists=/dev/tty$!ConditionPathExists=/dev/tty0!m) {
187 $self->ct_file_set_contents($sd_getty_service_rel, $raw);
192 sub setup_container_getty_service
{
193 my ($self, $conf) = @_;
195 my $sd_dir = $self->ct_is_executable("/lib/systemd/systemd") ?
196 "/lib/systemd/system" : "/usr/lib/systemd/system";
198 # prefer container-getty.service shipped by newer systemd versions
199 # fallback to getty.service and just return if that doesn't exists either..
200 my $template_base = "container-getty\@";
201 my $template_path = "${sd_dir}/${template_base}.service";
202 my $instance_base = $template_base;
204 if (!$self->ct_file_exists($template_path)) {
205 $template_base = "getty\@";
206 $template_path = "${template_base}.service";
207 $instance_base = "{$template_base}tty";
208 return if !$self->ct_file_exists($template_path);
211 my $raw = $self->ct_file_get_contents($template_path);
212 my $ttyname = $self->devttydir($conf) . 'tty%I';
213 if ($raw =~ s
@pts/%I|lxc
/tty
%I@$ttyname@g) {
214 $self->ct_file_set_contents($template_path, $raw);
217 my $getty_target_fn = "/etc/systemd/system/getty.target.wants/";
218 my $ttycount = PVE
::LXC
::Config-
>get_tty_count($conf);
220 for (my $i = 1; $i < 7; $i++) {
221 # ensure that not two gettys are using the same tty!
222 $self->ct_unlink("$getty_target_fn/getty\@tty$i.service");
223 $self->ct_unlink("$getty_target_fn/container-getty\@$i.service");
225 # re-enable only those requested
226 if ($i <= $ttycount) {
227 my $tty_service = "${instance_base}${i}.service";
229 $self->ct_symlink($template_path, "$getty_target_fn/$tty_service");
233 # ensure getty.target is not masked
234 $self->ct_unlink("/etc/systemd/system/getty.target");
237 sub setup_systemd_networkd
{
238 my ($self, $conf) = @_;
240 foreach my $k (keys %$conf) {
241 next if $k !~ m/^net(\d+)$/;
242 my $d = PVE
::LXC
::Config-
>parse_lxc_network($conf->{$k});
245 my $filename = "/etc/systemd/network/$d->{name}.network";
252 Description = Interface $d->{name} autoconfigured by PVE
256 my ($has_ipv4, $has_ipv6);
259 my @DHCPMODES = ('no', 'v4', 'v6', 'both');
260 my ($NONE, $DHCP4, $DHCP6, $BOTH) = (0, 1, 2, 3);
262 my $accept_ra = 'false';
264 if (defined(my $ip = $d->{ip
})) {
267 } elsif ($ip ne 'manual') {
269 $data .= "Address = $ip\n";
272 if (defined(my $gw = $d->{gw
})) {
273 $data .= "Gateway = $gw\n";
274 if ($has_ipv4 && !PVE
::Network
::is_ip_in_cidr
($gw, $d->{ip
}, 4)) {
275 $routes .= "\n[Route]\nDestination = $gw/32\nScope = link\n";
279 if (defined(my $ip = $d->{ip6
})) {
282 } elsif ($ip eq 'auto') {
284 } elsif ($ip ne 'manual') {
286 $data .= "Address = $ip\n";
289 if (defined(my $gw = $d->{gw6
})) {
290 $accept_ra = 'false';
291 $data .= "Gateway = $gw\n";
292 if ($has_ipv6 && !PVE
::Network
::is_ip_in_cidr
($gw, $d->{ip6
}, 6) &&
293 !PVE
::Network
::is_ip_in_cidr
($gw, 'fe80::/10', 6)) {
294 $routes .= "\n[Route]\nDestination = $gw/128\nScope = link\n";
298 $data .= "DHCP = $DHCPMODES[$dhcp]\n";
299 $data .= "IPv6AcceptRA = $accept_ra\n";
300 $data .= $routes if $routes;
302 $self->ct_file_set_contents($filename, $data);
306 sub setup_securetty
{
307 my ($self, $conf, @add) = @_;
309 my $filename = "/etc/securetty";
310 # root login is already allowed on every device if no securetty present
311 return if !$self->ct_file_exists($filename);
314 @add = qw(console tty1 tty2 tty3 tty4);
315 if (my $dir = $self->devttydir($conf)) {
316 @add = map { "${dir}$_" } @add;
320 my $data = $self->ct_file_get_contents($filename);
321 chomp $data; $data .= "\n";
322 foreach my $dev (@add) {
323 if ($data !~ m!^\Q$dev\E\s*$!m) {
327 $self->ct_file_set_contents($filename, $data);
330 my $replacepw = sub {
331 my ($self, $file, $user, $epw, $shadow) = @_;
333 my $tmpfile = "$file.$$";
336 my $src = $self->ct_open_file_read($file) ||
337 die "unable to open file '$file' - $!";
339 my $st = $self->ct_stat($src) ||
340 die "unable to stat file - $!";
342 my $dst = $self->ct_open_file_write($tmpfile) ||
343 die "unable to open file '$tmpfile' - $!";
345 # copy owner and permissions
346 chmod $st->mode, $dst;
347 chown $st->uid, $st->gid, $dst;
349 my $last_change = int(time()/(60*60*24));
351 while (defined (my $line = <$src>)) {
353 $line =~ s/^${user}:[^:]*:[^:]*:/${user}:${epw}:${last_change}:/;
355 $line =~ s/^${user}:[^:]*:/${user}:${epw}:/;
360 $src->close() || die "close '$file' failed - $!\n";
361 $dst->close() || die "close '$tmpfile' failed - $!\n";
364 $self->ct_unlink($tmpfile);
366 $self->ct_rename($tmpfile, $file);
367 $self->ct_unlink($tmpfile); # in case rename fails
371 sub set_user_password
{
372 my ($self, $conf, $user, $opt_password) = @_;
374 my $pwfile = "/etc/passwd";
376 return if !$self->ct_file_exists($pwfile);
378 my $shadow = "/etc/shadow";
380 if (defined($opt_password)) {
381 if ($opt_password !~ m/^\$(?:1|2[axy]?|5|6)\$[a-zA-Z0-9.\/]{1,16}\
$[a-zA-Z0-9
.\
/]+$/) {
382 my $time = substr (Digest
::SHA
::sha1_base64
(time), 0, 8);
383 $opt_password = crypt(encode
("utf8", $opt_password), "\$6\$$time\$");
389 if ($self->ct_file_exists($shadow)) {
390 &$replacepw ($self, $shadow, $user, $opt_password, 1);
391 &$replacepw ($self, $pwfile, $user, 'x');
393 &$replacepw ($self, $pwfile, $user, $opt_password);
397 my $parse_home_dir = sub {
398 my ($self, $passwdfile, $user) = @_;
400 my $fh = $self->ct_open_file_read($passwdfile);
401 while (defined (my $line = <$fh>)) {
403 if $line =~ m/^${user}:([^:]*:){4}([^:]*):/;
407 sub set_user_authorized_ssh_keys
{
408 my ($self, $conf, $user, $ssh_keys) = @_;
410 my $passwd = "/etc/passwd";
411 my $home = $user eq "root" ?
"/root/" : "/home/$user/";
413 $home = &$parse_home_dir($self, $passwd, $user)
414 if $self->ct_file_exists($passwd);
416 die "home directory '$home' of $user does not exist!"
417 if ! ($self->ct_is_directory($home) || $self->ct_is_symlink($home));
419 $self->ct_mkdir("$home/.ssh", 0700)
420 if ! $self->ct_is_directory("$home/.ssh");
422 $self->ct_modify_file("$home/.ssh/authorized_keys", $ssh_keys, perms
=> 0700);
425 my $randomize_crontab = sub {
426 my ($self, $conf) = @_;
429 # Note: dir_glob_foreach() untaints filenames!
430 PVE
::Tools
::dir_glob_foreach
("/etc/cron.d", qr/[A-Z\-\_a-z0-9]+/, sub {
432 push @files, "/etc/cron.d/$name";
435 my $crontab_fn = "/etc/crontab";
436 unshift @files, $crontab_fn if $self->ct_file_exists($crontab_fn);
438 foreach my $filename (@files) {
439 my $data = $self->ct_file_get_contents($filename);
441 foreach my $line (split(/\n/, $data)) {
442 # we only randomize minutes for root crontab entries
443 if ($line =~ m/^\d+(\s+\S+\s+\S+\s+\S+\s+\S+\s+root\s+\S.*)$/) {
445 my $min = int(rand()*59);
446 $new .= "$min$rest\n";
451 $self->ct_file_set_contents($filename, $new);
456 my ($self, $conf) = @_;
458 my $zoneinfo = $conf->{timezone
};
460 return if !defined($zoneinfo);
462 my $tz_path = "/usr/share/zoneinfo/$zoneinfo";
464 if ($zoneinfo eq 'host') {
465 $tz_path = $self->{host_localtime
};
468 return if abs_path
('/etc/localtime') eq $tz_path;
470 if ($self->ct_file_exists($tz_path)) {
471 my $tmpfile = "localtime.$$.new.tmpfile";
472 $self->ct_symlink($tz_path, $tmpfile);
473 $self->ct_rename($tmpfile, "/etc/localtime");
475 warn "container does not have $tz_path, timezone can not be modified\n";
479 sub clear_machine_id
{
480 my ($self, $conf, $clone) = @_;
482 my $uses_systemd = $self->ct_is_executable("/lib/systemd/systemd")
483 || $self->ct_is_executable("/usr/lib/systemd/systemd");
485 my $dbus_machine_id_path = "/var/lib/dbus/machine-id";
486 my $machine_id_path = "/etc/machine-id";
488 my $machine_id_existed = $self->ct_file_exists($machine_id_path);
491 $self->ct_file_exists($dbus_machine_id_path)
492 && !$self->ct_is_symlink($dbus_machine_id_path)
495 $self->ct_unlink($dbus_machine_id_path);
498 # truncate on clone to avoid that FirstBoot condition is set
499 if ($clone && ($uses_systemd || $machine_id_existed)) {
500 $self->ct_file_set_contents($machine_id_path, "\n");
501 } elsif (!$clone && $machine_id_existed) {
502 $self->ct_unlink($machine_id_path);
507 my ($self, $conf) = @_;
509 $self->setup_init($conf);
510 $self->setup_network($conf);
511 $self->set_hostname($conf);
512 $self->set_dns($conf);
513 $self->set_timezone($conf);
518 sub post_clone_hook
{
519 my ($self, $conf) = @_;
521 $self->clear_machine_id($conf, 1);
524 sub post_create_hook
{
525 my ($self, $conf, $root_password, $ssh_keys) = @_;
527 $self->clear_machine_id($conf);
528 $self->template_fixup($conf);
530 &$randomize_crontab($self, $conf);
532 $self->set_user_password($conf, 'root', $root_password);
533 $self->set_user_authorized_ssh_keys($conf, 'root', $ssh_keys) if $ssh_keys;
534 $self->setup_init($conf);
535 $self->setup_network($conf);
536 $self->set_hostname($conf);
537 $self->set_dns($conf);
538 $self->set_timezone($conf);
543 # File access wrappers for container setup code.
544 # For user-namespace support these might need to take uid and gid maps into account.
546 sub ct_is_file_ignored
{
547 my ($self, $file) = @_;
548 my ($name, $path) = fileparse
($file);
549 return -f
"$path/.pve-ignore.$name";
552 sub ct_reset_ownership
{
553 my ($self, @files) = @_;
554 my $conf = $self->{conf
};
555 return if !$self->{id_map
};
557 @files = grep { !$self->ct_is_file_ignored($_) } @files;
560 my $uid = $self->{rootuid
};
561 my $gid = $self->{rootgid
};
562 chown($uid, $gid, @files);
566 my ($self, $file, $mask) = @_;
567 # mkdir goes by parameter count - an `undef' mode acts like a mode of 0000
568 if (defined($mask)) {
569 return CORE
::mkdir($file, $mask) && $self->ct_reset_ownership($file);
571 return CORE
::mkdir($file) && $self->ct_reset_ownership($file);
576 my ($self, @files) = @_;
577 foreach my $file (@files) {
578 next if $self->ct_is_file_ignored($file);
584 my ($self, $old, $new) = @_;
585 return if $self->ct_is_file_ignored($new);
586 CORE
::rename($old, $new);
589 sub ct_open_file_read
{
592 return IO
::File-
>new($file, O_RDONLY
, @_);
595 sub ct_open_file_write
{
598 $file = '/dev/null' if $self->ct_is_file_ignored($file);
599 my $fh = IO
::File-
>new($file, O_WRONLY
| O_CREAT
, @_);
600 $self->ct_reset_ownership($fh);
606 if ($self->{id_map
}) {
608 if (ref($opts) eq 'HASH') {
609 $opts->{owner
} = $self->{rootuid
} if !defined($self->{owner
});
610 $opts->{group
} = $self->{rootgid
} if !defined($self->{group
});
612 File
::Path
::make_path
(@_, $opts);
614 File
::Path
::make_path
(@_);
619 my ($self, $old, $new) = @_;
620 return if $self->ct_is_file_ignored($new);
621 return CORE
::symlink($old, $new);
625 my ($self, $name) = @_;
626 return CORE
::readlink($name);
630 my ($self, $file) = @_;
634 sub ct_is_directory
{
635 my ($self, $file) = @_;
640 my ($self, $file) = @_;
644 sub ct_is_executable
{
645 my ($self, $file) = @_;
650 my ($self, $file) = @_;
651 return File
::stat::stat($file);
654 sub ct_file_read_firstline
{
655 my ($self, $file) = @_;
656 return PVE
::Tools
::file_read_firstline
($file);
659 sub ct_file_get_contents
{
660 my ($self, $file) = @_;
661 return PVE
::Tools
::file_get_contents
($file);
664 sub ct_file_set_contents
{
665 my ($self, $file, $data, $perms) = @_;
666 return if $self->ct_is_file_ignored($file);
667 PVE
::Tools
::file_set_contents
($file, $data, $perms);
668 $self->ct_reset_ownership($file);
671 # Modify a marked portion of a file.
672 # Optionally if the file becomes empty it will be deleted.
674 my ($self, $file, $data, %options) = @_;
675 return if $self->ct_is_file_ignored($file);
677 my $head = "# --- BEGIN PVE ---\n";
678 my $tail = "# --- END PVE ---\n";
679 my $perms = $options{perms
};
680 $data .= "\n" if $data && $data !~ /\n$/;
682 if (!$self->ct_file_exists($file)) {
683 $self->ct_file_set_contents($file, $head.$data.$tail, $perms) if $data;
687 my $old = $self->ct_file_get_contents($file);
688 my @lines = split(/\n/, $old);
691 foreach my $i (0..(@lines-1)) {
692 my $line = $lines[$i];
693 $beg = $i if !defined($beg) &&
694 $line =~ /^#\s*---\s*BEGIN\s*PVE\s*/;
695 $end = $i if !defined($end) && defined($beg) &&
696 $line =~ /^#\s*---\s*END\s*PVE\s*/i;
697 last if defined($beg) && defined($end);
700 if (defined($beg) && defined($end)) {
704 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
706 if ($beg == 0 && $end == (@lines-1)) {
707 $self->ct_unlink($file) if $options{delete};
710 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
712 $self->ct_file_set_contents($file, join("\n", @lines) . "\n");
715 my $content = join("\n", @lines);
717 if (!$content && !$data && $options{delete}) {
718 $self->ct_unlink($file);
722 $data = $head.$data.$tail;
723 if ($options{replace
}) {
724 $self->ct_file_set_contents($file, $data, $perms);
725 } elsif ($options{prepend
}) {
726 $self->ct_file_set_contents($file, $data . $content, $perms);
728 $self->ct_file_set_contents($file, $content . $data, $perms);
733 sub remove_pve_sections
{
736 my $head = "# --- BEGIN PVE ---";
737 my $tail = "# --- END PVE ---";
739 # Remove the sections enclosed with the above headers and footers.
740 # from a line (^) starting with '\h*$head'
741 # to a line (the other ^) starting with '\h*$tail' up to including that
743 return $data =~ s/^\h*\Q$head\E.*^\h*\Q$tail\E.*?$//rgms;