]> git.proxmox.com Git - pve-container.git/blobdiff - src/PVE/LXC/Setup/Base.pm
use /etc/os-release
[pve-container.git] / src / PVE / LXC / Setup / Base.pm
index 857835d17f6af7cc72798c8415a90a8ca5800c7f..0228fe7655b1d59721503431c1d31a2fafe5a038 100644 (file)
@@ -10,19 +10,20 @@ use Encode;
 use Fcntl;
 use File::Path;
 use File::Spec;
+use File::Basename;
 
 use PVE::INotify;
 use PVE::Tools;
 use PVE::Network;
 
 sub new {
-    my ($class, $conf, $rootdir) = @_;
+    my ($class, $conf, $rootdir, $os_release) = @_;
 
-    return bless { conf => $conf, rootdir => $rootdir }, $class;
+    return bless { conf => $conf, rootdir => $rootdir, os_release => $os_release }, $class;
 }
 
 sub lookup_dns_conf {
-    my ($conf) = @_;
+    my ($self, $conf) = @_;
 
     my $nameserver = $conf->{nameserver};
     my $searchdomains = $conf->{searchdomain};
@@ -36,7 +37,7 @@ sub lookup_dns_conf {
        
        } else {
 
-           my $host_resolv_conf = PVE::INotify::read_file('resolvconf');
+           my $host_resolv_conf = $self->{host_resolv_conf};
 
            $searchdomains = $host_resolv_conf->{search};
 
@@ -54,78 +55,49 @@ sub lookup_dns_conf {
 }
 
 sub update_etc_hosts {
-    my ($etc_hosts_data, $hostip, $oldname, $newname, $searchdomains) = @_;
+    my ($self, $hostip, $oldname, $newname, $searchdomains) = @_;
 
     my $done = 0;
 
-    my @lines;
+    my $namepart = ($newname =~ s/\..*$//r);
 
-    my $extra_names = '';
-    foreach my $domain (PVE::Tools::split_list($searchdomains)) {
-       $extra_names .= ' ' if $extra_names;
-       $extra_names .= "$newname.$domain";
-    }
-    
-    foreach my $line (split(/\n/, $etc_hosts_data)) {
-       if ($line =~ m/^#/ || $line =~ m/^\s*$/) {
-           push @lines, $line;
-           next;
+    my $all_names = '';
+    if ($newname =~ /\./) {
+       $all_names .= "$newname $namepart";
+    } else {
+       foreach my $domain (PVE::Tools::split_list($searchdomains)) {
+           $all_names .= ' ' if $all_names;
+           $all_names .= "$newname.$domain";
        }
+       $all_names .= ' ' if $all_names;
+       $all_names .= $newname;
+    }
 
-       my ($ip, @names) = split(/\s+/, $line);
-       if (($ip eq '127.0.0.1') || ($ip eq '::1')) {
-           push @lines, $line;
-           next;
-       }
+    # Prepare section:
+    my $section = '';
+    my $hosts_fn = '/etc/hosts';
 
-       my $found = 0;
-       foreach my $name (@names) {
-           if ($name eq $oldname || $name eq $newname) {
-               $found = 1;
-           } else {
-               # fixme: record extra names?
-           }
-       }
-       $found = 1 if defined($hostip) && ($ip eq $hostip);
-       
-       if ($found) {
-           if (!$done) {
-               if (defined($hostip)) {
-                   push @lines, "$hostip $extra_names $newname";
-               } else {
-                   push @lines, "127.0.1.1 $newname";
-               }
-               $done = 1;
-           }
-           next;
-       } else {
-           push @lines, $line;
-       }
-    }
+    my $lo4 = "127.0.0.1 localhost.localnet localhost\n";
+    my $lo6 = "::1 localhost.localnet localhost\n";
+    if ($self->ct_file_exists($hosts_fn)) {
+       my $data = $self->ct_file_get_contents($hosts_fn);
+       # don't take localhost entries within our hosts sections into account
+       $data = remove_pve_sections($data);
 
-    if (!$done) {
-       if (defined($hostip)) {
-           push @lines, "$hostip $extra_names $newname";
-       } else {
-           push @lines, "127.0.1.1 $newname";
-       }       
+       # check for existing localhost entries
+       $section .= $lo4 if $data !~ /^\h*127\.0\.0\.1\h+/m;
+       $section .= $lo6 if $data !~ /^\h*::1\h+/m;
+    } else {
+       $section .= $lo4 . $lo6;
     }
 
-    my $found_localhost = 0;
-    foreach my $line (@lines) {
-       if ($line =~ m/^127.0.0.1\s/) {
-           $found_localhost = 1;
-           last;
-       }
+    if (defined($hostip)) {
+       $section .= "$hostip $all_names\n";
+    } else {
+       $section .= "127.0.1.1 $namepart\n";
     }
 
-    if (!$found_localhost) {
-       unshift @lines, "127.0.0.1 localhost.localnet localhost";
-    }
-    
-    $etc_hosts_data = join("\n", @lines) . "\n";
-    
-    return $etc_hosts_data;
+    $self->ct_modify_file($hosts_fn, $section);
 }
 
 sub template_fixup {
@@ -137,7 +109,7 @@ sub template_fixup {
 sub set_dns {
     my ($self, $conf) = @_;
 
-    my ($searchdomains, $nameserver) = lookup_dns_conf($conf);
+    my ($searchdomains, $nameserver) = $self->lookup_dns_conf($conf);
     
     my $data = '';
 
@@ -148,7 +120,7 @@ sub set_dns {
        $data .= "nameserver $ns\n";
     }
 
-    $self->ct_file_set_contents("/etc/resolv.conf", $data);
+    $self->ct_modify_file("/etc/resolv.conf", $data, replace => 1);
 }
 
 sub set_hostname {
@@ -156,29 +128,20 @@ sub set_hostname {
     
     my $hostname = $conf->{hostname} || 'localhost';
 
-    $hostname =~ s/\..*$//;
+    my $namepart = ($hostname =~ s/\..*$//r);
 
     my $hostname_fn = "/etc/hostname";
     
     my $oldname = $self->ct_file_read_firstline($hostname_fn) || 'localhost';
 
-    my $hosts_fn = "/etc/hosts";
-    my $etc_hosts_data = '';
-    
-    if ($self->ct_file_exists($hosts_fn)) {
-       $etc_hosts_data =  $self->ct_file_get_contents($hosts_fn);
-    }
-
     my ($ipv4, $ipv6) = PVE::LXC::get_primary_ips($conf);
     my $hostip = $ipv4 || $ipv6;
 
-    my ($searchdomains) = lookup_dns_conf($conf);
+    my ($searchdomains) = $self->lookup_dns_conf($conf);
 
-    $etc_hosts_data = update_etc_hosts($etc_hosts_data, $hostip, $oldname, 
-                                      $hostname, $searchdomains);
+    $self->update_etc_hosts($hostip, $oldname, $hostname, $searchdomains);
     
-    $self->ct_file_set_contents($hostname_fn, "$hostname\n");
-    $self->ct_file_set_contents($hosts_fn, $etc_hosts_data);
+    $self->ct_file_set_contents($hostname_fn, "$namepart\n");
 }
 
 sub setup_network {
@@ -196,7 +159,7 @@ sub setup_init {
 sub setup_systemd_console {
     my ($self, $conf) = @_;
 
-    my $systemd_dir_rel = -x "/lib/systemd/systemd" ?
+    my $systemd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
        "/lib/systemd/system" : "/usr/lib/systemd/system";
 
     my $systemd_getty_service_rel = "$systemd_dir_rel/getty\@.service";
@@ -220,7 +183,7 @@ sub setup_systemd_console {
        }
     }
 
-    my $ttycount = PVE::LXC::get_tty_count($conf);
+    my $ttycount = PVE::LXC::Config->get_tty_count($conf);
 
     for (my $i = 1; $i < 7; $i++) {
        my $tty_service_lnk = "/etc/systemd/system/getty.target.wants/getty\@tty$i.service";
@@ -235,12 +198,32 @@ sub setup_systemd_console {
     }
 }
 
+# A few distros as well as unprivileged containers cannot deal with the
+# /dev/lxc/ tty subdirectory.
+sub devttydir {
+    my ($self, $conf) = @_;
+    return $conf->{unprivileged} ? '' : 'lxc/';
+}
+
+sub setup_container_getty_service {
+    my ($self, $conf) = @_;
+
+    my $systemd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
+       "/lib/systemd/system" : "/usr/lib/systemd/system";
+    my $servicefile = "$systemd_dir_rel/container-getty\@.service";
+    my $raw = $self->ct_file_get_contents($servicefile);
+    my $ttyname = $self->devttydir($conf) . 'tty%I';
+    if ($raw =~ s@pts/%I|lxc/tty%I@$ttyname@g) {
+       $self->ct_file_set_contents($servicefile, $raw);
+    }
+}
+
 sub setup_systemd_networkd {
     my ($self, $conf) = @_;
 
     foreach my $k (keys %$conf) {
        next if $k !~ m/^net(\d+)$/;
-       my $d = PVE::LXC::parse_lxc_network($conf->{$k});
+       my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
        next if !$d->{name};
 
        my $filename = "/etc/systemd/network/$d->{name}.network";
@@ -286,7 +269,8 @@ DATA
        }
        if (defined(my $gw = $d->{gw6})) {
            $data .= "Gateway = $gw\n";
-           if ($has_ipv6 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip6}, 6)) {
+           if ($has_ipv6 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip6}, 6) &&
+               !PVE::Network::is_ip_in_cidr($gw, 'fe80::/10', 6)) {
                $routes .= "\n[Route]\nDestination = $gw/128\nScope = link\n";
            }
        }
@@ -302,6 +286,16 @@ sub setup_securetty {
     my ($self, $conf, @add) = @_;
 
     my $filename = "/etc/securetty";
+    # root login is already allowed on every device if no securetty present
+    return if !$self->ct_file_exists($filename);
+
+    if (!scalar(@add)) {
+       @add = qw(console tty1 tty2 tty3 tty4);
+       if (my $dir = $self->devttydir($conf)) {
+           @add = map { "${dir}$_" } @add;
+       }
+    }
+
     my $data = $self->ct_file_get_contents($filename);
     chomp $data; $data .= "\n";
     foreach my $dev (@add) {
@@ -383,6 +377,34 @@ sub set_user_password {
     }
 }
 
+my $parse_home_dir = sub {
+    my ($self, $passwdfile, $user) = @_;
+
+    my $fh = $self->ct_open_file_read($passwdfile);
+    while (defined (my $line = <$fh>)) {
+       return $2
+           if $line =~ m/^${user}:([^:]*:){4}([^:]*):/;
+    }
+};
+
+sub set_user_authorized_ssh_keys {
+    my ($self, $conf, $user, $ssh_keys) = @_;
+
+    my $passwd = "/etc/passwd";
+    my $home = $user eq "root" ? "/root/" : "/home/$user/";
+
+    $home = &$parse_home_dir($self, $passwd, $user)
+       if $self->ct_file_exists($passwd);
+
+    die "home directory '$home' of $user does not exist!"
+       if ! ($self->ct_is_directory($home) || $self->ct_is_symlink($home));
+
+    $self->ct_mkdir("$home/.ssh", 0700)
+       if ! $self->ct_is_directory("$home/.ssh");
+
+    $self->ct_modify_file("$home/.ssh/authorized_keys", $ssh_keys, perms => 0700);
+}
+
 my $randomize_crontab = sub {
     my ($self, $conf) = @_;
 
@@ -413,36 +435,6 @@ my $randomize_crontab = sub {
    }
 };
 
-sub rewrite_ssh_host_keys {
-    my ($self, $conf) = @_;
-
-    return if !$self->ct_is_directory('/etc/ssh');
-    
-    my $keynames = {
-       rsa1 => 'ssh_host_key',
-       rsa => 'ssh_host_rsa_key',
-       dsa => 'ssh_host_dsa_key',
-       ecdsa => 'ssh_host_ecdsa_key', 
-       ed25519 => 'ssh_host_ed25519_key',
-    };
-
-    my $hostname = $conf->{hostname} || 'localhost';
-    $hostname =~ s/\..*$//;
-
-    # Since we don't want to replace host keys let's make sure in_chroot is set
-    die "internal error: not protected" if !$self->{in_chroot};
-
-    foreach my $keytype (keys %$keynames) {
-       my $basename = $keynames->{$keytype};
-       $self->ct_unlink("/etc/ssh/$basename");
-       $self->ct_unlink("/etc/ssh/$basename.pub");
-       print "Creating SSH host key '$basename' - this may take some time ...\n";
-       my $cmd = ['ssh-keygen', '-q', '-f', "/etc/ssh/$basename", '-t', $keytype,
-                  '-N', '', '-C', "root\@$hostname"];
-       PVE::Tools::run_command($cmd);
-    }
-}
-
 sub pre_start_hook {
     my ($self, $conf) = @_;
 
@@ -455,18 +447,18 @@ sub pre_start_hook {
 }
 
 sub post_create_hook {
-    my ($self, $conf, $root_password) = @_;
+    my ($self, $conf, $root_password, $ssh_keys) = @_;
 
     $self->template_fixup($conf);
     
     &$randomize_crontab($self, $conf);
     
     $self->set_user_password($conf, 'root', $root_password);
+    $self->set_user_authorized_ssh_keys($conf, 'root', $ssh_keys) if $ssh_keys;
     $self->setup_init($conf);
     $self->setup_network($conf);
     $self->set_hostname($conf);
     $self->set_dns($conf);
-    $self->rewrite_ssh_host_keys($conf);
     
     # fixme: what else ?
 }
@@ -474,22 +466,46 @@ sub post_create_hook {
 # File access wrappers for container setup code.
 # For user-namespace support these might need to take uid and gid maps into account.
 
+sub ct_is_file_ignored {
+    my ($self, $file) = @_;
+    my ($name, $path) = fileparse($file);
+    return -f "$path/.pve-ignore.$name";
+}
+
+sub ct_reset_ownership {
+    my ($self, @files) = @_;
+    my $conf = $self->{conf};
+    return if !$self->{id_map};
+
+    @files = grep { !$self->ct_is_file_ignored($_) } @files;
+    return if !@files;
+
+    my $uid = $self->{rootuid};
+    my $gid = $self->{rootgid};
+    chown($uid, $gid, @files);
+}
+
 sub ct_mkdir {
     my ($self, $file, $mask) = @_;
     # mkdir goes by parameter count - an `undef' mode acts like a mode of 0000
-    return CORE::mkdir($file, $mask) if defined ($mask);
-    return CORE::mkdir($file);
+    if (defined($mask)) {
+       return CORE::mkdir($file, $mask) && $self->ct_reset_ownership($file);
+    } else {
+       return CORE::mkdir($file) && $self->ct_reset_ownership($file);
+    }
 }
 
 sub ct_unlink {
     my ($self, @files) = @_;
     foreach my $file (@files) {
+       next if $self->ct_is_file_ignored($file);
        CORE::unlink($file);
     }
 }
 
 sub ct_rename {
     my ($self, $old, $new) = @_;
+    return if $self->ct_is_file_ignored($new);
     CORE::rename($old, $new);
 }
 
@@ -502,19 +518,37 @@ sub ct_open_file_read {
 sub ct_open_file_write {
     my $self = shift;
     my $file = shift;
-    return IO::File->new($file, O_WRONLY | O_CREAT, @_);
+    $file = '/dev/null' if $self->ct_is_file_ignored($file);
+    my $fh = IO::File->new($file, O_WRONLY | O_CREAT, @_);
+    $self->ct_reset_ownership($fh);
+    return $fh;
 }
 
 sub ct_make_path {
     my $self = shift;
-    File::Path::make_path(@_);
+    if ($self->{id_map}) {
+       my $opts = pop;
+       if (ref($opts) eq 'HASH') {
+           $opts->{owner} = $self->{rootuid} if !defined($self->{owner});
+           $opts->{group} = $self->{rootgid} if !defined($self->{group});
+       }
+       File::Path::make_path(@_, $opts);
+    } else {
+       File::Path::make_path(@_);
+    }
 }
 
 sub ct_symlink {
     my ($self, $old, $new) = @_;
+    return if $self->ct_is_file_ignored($new);
     return CORE::symlink($old, $new);
 }
 
+sub ct_readlink {
+    my ($self, $name) = @_;
+    return CORE::readlink($name);
+}
+
 sub ct_file_exists {
     my ($self, $file) = @_;
     return -f $file;
@@ -530,6 +564,11 @@ sub ct_is_symlink {
     return -l $file;
 }
 
+sub ct_is_executable {
+    my ($self, $file) = @_;
+    return -x $file
+}
+
 sub ct_stat {
     my ($self, $file) = @_;
     return File::stat::stat($file);
@@ -546,8 +585,85 @@ sub ct_file_get_contents {
 }
 
 sub ct_file_set_contents {
-    my ($self, $file, $data) = @_;
-    return PVE::Tools::file_set_contents($file, $data);
+    my ($self, $file, $data, $perms) = @_;
+    return if $self->ct_is_file_ignored($file);
+    PVE::Tools::file_set_contents($file, $data, $perms);
+    $self->ct_reset_ownership($file);
+}
+
+# Modify a marked portion of a file.
+# Optionally if the file becomes empty it will be deleted.
+sub ct_modify_file {
+    my ($self, $file, $data, %options) = @_;
+    return if $self->ct_is_file_ignored($file);
+
+    my $head = "# --- BEGIN PVE ---\n";
+    my $tail = "# --- END PVE ---\n";
+    my $perms = $options{perms};
+    $data .= "\n" if $data && $data !~ /\n$/;
+
+    if (!$self->ct_file_exists($file)) {
+       $self->ct_file_set_contents($file, $head.$data.$tail, $perms) if $data;
+       return;
+    }
+
+    my $old = $self->ct_file_get_contents($file);
+    my @lines = split(/\n/, $old);
+
+    my ($beg, $end);
+    foreach my $i (0..(@lines-1)) {
+       my $line = $lines[$i];
+       $beg = $i if !defined($beg) &&
+           $line =~ /^#\s*---\s*BEGIN\s*PVE\s*/;
+       $end = $i if !defined($end) && defined($beg) &&
+           $line =~ /^#\s*---\s*END\s*PVE\s*/i;
+       last if defined($beg) && defined($end);
+    }
+
+    if (defined($beg) && defined($end)) {
+       # Found a section
+       if ($data) {
+           chomp $tail;
+           splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
+       } else {
+           if ($beg == 0 && $end == (@lines-1)) {
+               $self->ct_unlink($file) if $options{delete};
+               return;
+           }
+           splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
+       }
+       $self->ct_file_set_contents($file, join("\n", @lines) . "\n");
+    } elsif ($data) {
+       # No section found
+       my $content = join("\n", @lines);
+       chomp $content;
+       if (!$content && !$data && $options{delete}) {
+           $self->ct_unlink($file);
+           return;
+       }
+       $content .= "\n";
+       $data = $head.$data.$tail;
+       if ($options{replace}) {
+           $self->ct_file_set_contents($file, $data, $perms);
+       } elsif ($options{prepend}) {
+           $self->ct_file_set_contents($file, $data . $content, $perms);
+       } else { # append
+           $self->ct_file_set_contents($file, $content . $data, $perms);
+       }
+    }
+}
+
+sub remove_pve_sections {
+    my ($data) = @_;
+
+    my $head = "# --- BEGIN PVE ---";
+    my $tail = "# --- END PVE ---";
+
+    # Remove the sections enclosed with the above headers and footers.
+    # from a line (^) starting with '\h*$head'
+    # to a line (the other ^) starting with '\h*$tail' up to including that
+    # line's end (.*?$).
+    return $data =~ s/^\h*\Q$head\E.*^\h*\Q$tail\E.*?$//rgms;
 }
 
 1;