]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC/Setup/Base.pm
7bf66ca81d62de49c0b0dd06723dfc3a2ba7479b
[pve-container.git] / src / PVE / LXC / Setup / Base.pm
1 package PVE::LXC::Setup::Base;
2
3 use strict;
4 use warnings;
5
6 use File::stat;
7 use Digest::SHA;
8 use IO::File;
9 use Encode;
10 use Fcntl;
11 use File::Path;
12 use File::Spec;
13 use File::Basename;
14
15 use PVE::INotify;
16 use PVE::Tools;
17 use PVE::Network;
18
19 sub new {
20 my ($class, $conf, $rootdir) = @_;
21
22 return bless { conf => $conf, rootdir => $rootdir }, $class;
23 }
24
25 sub lookup_dns_conf {
26 my ($self, $conf) = @_;
27
28 my $nameserver = $conf->{nameserver};
29 my $searchdomains = $conf->{searchdomain};
30
31 if (!($nameserver && $searchdomains)) {
32
33 if ($conf->{'testmode'}) {
34
35 $nameserver = "8.8.8.8 8.8.8.9";
36 $searchdomains = "proxmox.com";
37
38 } else {
39
40 my $host_resolv_conf = $self->{host_resolv_conf};
41
42 $searchdomains = $host_resolv_conf->{search};
43
44 my @list = ();
45 foreach my $k ("dns1", "dns2", "dns3") {
46 if (my $ns = $host_resolv_conf->{$k}) {
47 push @list, $ns;
48 }
49 }
50 $nameserver = join(' ', @list);
51 }
52 }
53
54 return ($searchdomains, $nameserver);
55 }
56
57 sub update_etc_hosts {
58 my ($self, $hostip, $oldname, $newname, $searchdomains) = @_;
59
60 my $done = 0;
61
62 my $namepart = ($newname =~ s/\..*$//r);
63
64 my $all_names = '';
65 if ($newname =~ /\./) {
66 $all_names .= "$newname $namepart";
67 } else {
68 foreach my $domain (PVE::Tools::split_list($searchdomains)) {
69 $all_names .= ' ' if $all_names;
70 $all_names .= "$newname.$domain";
71 }
72 $all_names .= ' ' if $all_names;
73 $all_names .= $newname;
74 }
75
76 # Prepare section:
77 my $section = '';
78 my $hosts_fn = '/etc/hosts';
79
80 my $lo4 = "127.0.0.1 localhost.localnet localhost\n";
81 my $lo6 = "::1 localhost.localnet localhost\n";
82 if ($self->ct_file_exists($hosts_fn)) {
83 my $data = $self->ct_file_get_contents($hosts_fn);
84 # don't take localhost entries within our hosts sections into account
85 $data = remove_pve_sections($data);
86
87 # check for existing localhost entries
88 $section .= $lo4 if $data !~ /^\h*127\.0\.0\.1\h+/m;
89 $section .= $lo6 if $data !~ /^\h*::1\h+/m;
90 } else {
91 $section .= $lo4 . $lo6;
92 }
93
94 if (defined($hostip)) {
95 $section .= "$hostip $all_names\n";
96 } else {
97 $section .= "127.0.1.1 $namepart\n";
98 }
99
100 $self->ct_modify_file($hosts_fn, $section);
101 }
102
103 sub template_fixup {
104 my ($self, $conf) = @_;
105
106 # do nothing by default
107 }
108
109 sub set_dns {
110 my ($self, $conf) = @_;
111
112 my ($searchdomains, $nameserver) = $self->lookup_dns_conf($conf);
113
114 my $data = '';
115
116 $data .= "search " . join(' ', PVE::Tools::split_list($searchdomains)) . "\n"
117 if $searchdomains;
118
119 foreach my $ns ( PVE::Tools::split_list($nameserver)) {
120 $data .= "nameserver $ns\n";
121 }
122
123 $self->ct_modify_file("/etc/resolv.conf", $data, replace => 1);
124 }
125
126 sub set_hostname {
127 my ($self, $conf) = @_;
128
129 my $hostname = $conf->{hostname} || 'localhost';
130
131 my $namepart = ($hostname =~ s/\..*$//r);
132
133 my $hostname_fn = "/etc/hostname";
134
135 my $oldname = $self->ct_file_read_firstline($hostname_fn) || 'localhost';
136
137 my ($ipv4, $ipv6) = PVE::LXC::get_primary_ips($conf);
138 my $hostip = $ipv4 || $ipv6;
139
140 my ($searchdomains) = $self->lookup_dns_conf($conf);
141
142 $self->update_etc_hosts($hostip, $oldname, $hostname, $searchdomains);
143
144 $self->ct_file_set_contents($hostname_fn, "$namepart\n");
145 }
146
147 sub setup_network {
148 my ($self, $conf) = @_;
149
150 die "please implement this inside subclass"
151 }
152
153 sub setup_init {
154 my ($self, $conf) = @_;
155
156 die "please implement this inside subclass"
157 }
158
159 sub setup_systemd_console {
160 my ($self, $conf) = @_;
161
162 my $systemd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
163 "/lib/systemd/system" : "/usr/lib/systemd/system";
164
165 my $systemd_getty_service_rel = "$systemd_dir_rel/getty\@.service";
166
167 return if !$self->ct_file_exists($systemd_getty_service_rel);
168
169 my $raw = $self->ct_file_get_contents($systemd_getty_service_rel);
170
171 my $systemd_container_getty_service_rel = "$systemd_dir_rel/container-getty\@.service";
172
173 # systemd on CenoOS 7.1 is too old (version 205), so there is no
174 # container-getty service
175 if (!$self->ct_file_exists($systemd_container_getty_service_rel)) {
176 if ($raw =~ s!^ConditionPathExists=/dev/tty0$!ConditionPathExists=/dev/tty!m) {
177 $self->ct_file_set_contents($systemd_getty_service_rel, $raw);
178 }
179 } else {
180 # undo above change (in case someone updated systemd)
181 if ($raw =~ s!^ConditionPathExists=/dev/tty$!ConditionPathExists=/dev/tty0!m) {
182 $self->ct_file_set_contents($systemd_getty_service_rel, $raw);
183 }
184 }
185
186 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
187
188 for (my $i = 1; $i < 7; $i++) {
189 my $tty_service_lnk = "/etc/systemd/system/getty.target.wants/getty\@tty$i.service";
190 if ($i > $ttycount) {
191 $self->ct_unlink($tty_service_lnk);
192 } else {
193 if (!$self->ct_is_symlink($tty_service_lnk)) {
194 $self->ct_unlink($tty_service_lnk);
195 $self->ct_symlink($systemd_getty_service_rel, $tty_service_lnk);
196 }
197 }
198 }
199 }
200
201 # A few distros as well as unprivileged containers cannot deal with the
202 # /dev/lxc/ tty subdirectory.
203 sub devttydir {
204 my ($self, $conf) = @_;
205 return $conf->{unprivileged} ? '' : 'lxc/';
206 }
207
208 sub setup_container_getty_service {
209 my ($self, $conf) = @_;
210
211 my $systemd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
212 "/lib/systemd/system" : "/usr/lib/systemd/system";
213 my $servicefile = "$systemd_dir_rel/container-getty\@.service";
214 my $raw = $self->ct_file_get_contents($servicefile);
215 my $ttyname = $self->devttydir($conf) . 'tty%I';
216 if ($raw =~ s@pts/%I|lxc/tty%I@$ttyname@g) {
217 $self->ct_file_set_contents($servicefile, $raw);
218 }
219 }
220
221 sub setup_systemd_networkd {
222 my ($self, $conf) = @_;
223
224 foreach my $k (keys %$conf) {
225 next if $k !~ m/^net(\d+)$/;
226 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
227 next if !$d->{name};
228
229 my $filename = "/etc/systemd/network/$d->{name}.network";
230
231 my $data = <<"DATA";
232 [Match]
233 Name = $d->{name}
234
235 [Network]
236 Description = Interface $d->{name} autoconfigured by PVE
237 DATA
238
239 my $routes = '';
240 my ($has_ipv4, $has_ipv6);
241
242 # DHCP bitflags:
243 my @DHCPMODES = ('none', 'v4', 'v6', 'both');
244 my ($NONE, $DHCP4, $DHCP6, $BOTH) = (0, 1, 2, 3);
245 my $dhcp = $NONE;
246
247 if (defined(my $ip = $d->{ip})) {
248 if ($ip eq 'dhcp') {
249 $dhcp |= $DHCP4;
250 } elsif ($ip ne 'manual') {
251 $has_ipv4 = 1;
252 $data .= "Address = $ip\n";
253 }
254 }
255 if (defined(my $gw = $d->{gw})) {
256 $data .= "Gateway = $gw\n";
257 if ($has_ipv4 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip}, 4)) {
258 $routes .= "\n[Route]\nDestination = $gw/32\nScope = link\n";
259 }
260 }
261
262 if (defined(my $ip = $d->{ip6})) {
263 if ($ip eq 'dhcp') {
264 $dhcp |= $DHCP6;
265 } elsif ($ip ne 'manual') {
266 $has_ipv6 = 1;
267 $data .= "Address = $ip\n";
268 }
269 }
270 if (defined(my $gw = $d->{gw6})) {
271 $data .= "Gateway = $gw\n";
272 if ($has_ipv6 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip6}, 6) &&
273 !PVE::Network::is_ip_in_cidr($gw, 'fe80::/10', 6)) {
274 $routes .= "\n[Route]\nDestination = $gw/128\nScope = link\n";
275 }
276 }
277
278 $data .= "DHCP = $DHCPMODES[$dhcp]\n";
279 $data .= $routes if $routes;
280
281 $self->ct_file_set_contents($filename, $data);
282 }
283 }
284
285 sub setup_securetty {
286 my ($self, $conf, @add) = @_;
287
288 my $filename = "/etc/securetty";
289 # root login is already allowed on every device if no securetty present
290 return if !$self->ct_file_exists($filename);
291
292 if (!scalar(@add)) {
293 @add = qw(console tty1 tty2 tty3 tty4);
294 if (my $dir = $self->devttydir($conf)) {
295 @add = map { "${dir}$_" } @add;
296 }
297 }
298
299 my $data = $self->ct_file_get_contents($filename);
300 chomp $data; $data .= "\n";
301 foreach my $dev (@add) {
302 if ($data !~ m!^\Q$dev\E\s*$!m) {
303 $data .= "$dev\n";
304 }
305 }
306 $self->ct_file_set_contents($filename, $data);
307 }
308
309 my $replacepw = sub {
310 my ($self, $file, $user, $epw, $shadow) = @_;
311
312 my $tmpfile = "$file.$$";
313
314 eval {
315 my $src = $self->ct_open_file_read($file) ||
316 die "unable to open file '$file' - $!";
317
318 my $st = $self->ct_stat($src) ||
319 die "unable to stat file - $!";
320
321 my $dst = $self->ct_open_file_write($tmpfile) ||
322 die "unable to open file '$tmpfile' - $!";
323
324 # copy owner and permissions
325 chmod $st->mode, $dst;
326 chown $st->uid, $st->gid, $dst;
327
328 my $last_change = int(time()/(60*60*24));
329
330 if ($epw =~ m/^\$TEST\$/) { # for regression tests
331 $last_change = 12345;
332 }
333
334 while (defined (my $line = <$src>)) {
335 if ($shadow) {
336 $line =~ s/^${user}:[^:]*:[^:]*:/${user}:${epw}:${last_change}:/;
337 } else {
338 $line =~ s/^${user}:[^:]*:/${user}:${epw}:/;
339 }
340 print $dst $line;
341 }
342
343 $src->close() || die "close '$file' failed - $!\n";
344 $dst->close() || die "close '$tmpfile' failed - $!\n";
345 };
346 if (my $err = $@) {
347 $self->ct_unlink($tmpfile);
348 } else {
349 $self->ct_rename($tmpfile, $file);
350 $self->ct_unlink($tmpfile); # in case rename fails
351 }
352 };
353
354 sub set_user_password {
355 my ($self, $conf, $user, $opt_password) = @_;
356
357 my $pwfile = "/etc/passwd";
358
359 return if !$self->ct_file_exists($pwfile);
360
361 my $shadow = "/etc/shadow";
362
363 if (defined($opt_password)) {
364 if ($opt_password !~ m/^\$/) {
365 my $time = substr (Digest::SHA::sha1_base64 (time), 0, 8);
366 $opt_password = crypt(encode("utf8", $opt_password), "\$1\$$time\$");
367 };
368 } else {
369 $opt_password = '*';
370 }
371
372 if ($self->ct_file_exists($shadow)) {
373 &$replacepw ($self, $shadow, $user, $opt_password, 1);
374 &$replacepw ($self, $pwfile, $user, 'x');
375 } else {
376 &$replacepw ($self, $pwfile, $user, $opt_password);
377 }
378 }
379
380 my $parse_home_dir = sub {
381 my ($self, $passwdfile, $user) = @_;
382
383 my $fh = $self->ct_open_file_read($passwdfile);
384 while (defined (my $line = <$fh>)) {
385 return $2
386 if $line =~ m/^${user}:([^:]*:){4}([^:]*):/;
387 }
388 };
389
390 sub set_user_authorized_ssh_keys {
391 my ($self, $conf, $user, $ssh_keys) = @_;
392
393 my $passwd = "/etc/passwd";
394 my $home = $user eq "root" ? "/root/" : "/home/$user/";
395
396 $home = &$parse_home_dir($self, $passwd, $user)
397 if $self->ct_file_exists($passwd);
398
399 die "home directory '$home' of $user does not exist!"
400 if ! ($self->ct_is_directory($home) || $self->ct_is_symlink($home));
401
402 $self->ct_mkdir("$home/.ssh", 0700)
403 if ! $self->ct_is_directory("$home/.ssh");
404
405 $self->ct_modify_file("$home/.ssh/authorized_keys", $ssh_keys, perms => 0700);
406 }
407
408 my $randomize_crontab = sub {
409 my ($self, $conf) = @_;
410
411 my @files;
412 # Note: dir_glob_foreach() untaints filenames!
413 PVE::Tools::dir_glob_foreach("/etc/cron.d", qr/[A-Z\-\_a-z0-9]+/, sub {
414 my ($name) = @_;
415 push @files, "/etc/cron.d/$name";
416 });
417
418 my $crontab_fn = "/etc/crontab";
419 unshift @files, $crontab_fn if $self->ct_file_exists($crontab_fn);
420
421 foreach my $filename (@files) {
422 my $data = $self->ct_file_get_contents($filename);
423 my $new = '';
424 foreach my $line (split(/\n/, $data)) {
425 # we only randomize minutes for root crontab entries
426 if ($line =~ m/^\d+(\s+\S+\s+\S+\s+\S+\s+\S+\s+root\s+\S.*)$/) {
427 my $rest = $1;
428 my $min = int(rand()*59);
429 $new .= "$min$rest\n";
430 } else {
431 $new .= "$line\n";
432 }
433 }
434 $self->ct_file_set_contents($filename, $new);
435 }
436 };
437
438 sub pre_start_hook {
439 my ($self, $conf) = @_;
440
441 $self->setup_init($conf);
442 $self->setup_network($conf);
443 $self->set_hostname($conf);
444 $self->set_dns($conf);
445
446 # fixme: what else ?
447 }
448
449 sub post_create_hook {
450 my ($self, $conf, $root_password, $ssh_keys) = @_;
451
452 $self->template_fixup($conf);
453
454 &$randomize_crontab($self, $conf);
455
456 $self->set_user_password($conf, 'root', $root_password);
457 $self->set_user_authorized_ssh_keys($conf, 'root', $ssh_keys) if $ssh_keys;
458 $self->setup_init($conf);
459 $self->setup_network($conf);
460 $self->set_hostname($conf);
461 $self->set_dns($conf);
462
463 # fixme: what else ?
464 }
465
466 # File access wrappers for container setup code.
467 # For user-namespace support these might need to take uid and gid maps into account.
468
469 sub ct_is_file_ignored {
470 my ($self, $file) = @_;
471 my ($name, $path) = fileparse($file);
472 return -f "$path/.pve-ignore.$name";
473 }
474
475 sub ct_reset_ownership {
476 my ($self, @files) = @_;
477 my $conf = $self->{conf};
478 return if !$self->{id_map};
479
480 @files = grep { !$self->ct_is_file_ignored($_) } @files;
481 return if !@files;
482
483 my $uid = $self->{rootuid};
484 my $gid = $self->{rootgid};
485 chown($uid, $gid, @files);
486 }
487
488 sub ct_mkdir {
489 my ($self, $file, $mask) = @_;
490 # mkdir goes by parameter count - an `undef' mode acts like a mode of 0000
491 if (defined($mask)) {
492 return CORE::mkdir($file, $mask) && $self->ct_reset_ownership($file);
493 } else {
494 return CORE::mkdir($file) && $self->ct_reset_ownership($file);
495 }
496 }
497
498 sub ct_unlink {
499 my ($self, @files) = @_;
500 foreach my $file (@files) {
501 next if $self->ct_is_file_ignored($file);
502 CORE::unlink($file);
503 }
504 }
505
506 sub ct_rename {
507 my ($self, $old, $new) = @_;
508 return if $self->ct_is_file_ignored($new);
509 CORE::rename($old, $new);
510 }
511
512 sub ct_open_file_read {
513 my $self = shift;
514 my $file = shift;
515 return IO::File->new($file, O_RDONLY, @_);
516 }
517
518 sub ct_open_file_write {
519 my $self = shift;
520 my $file = shift;
521 $file = '/dev/null' if $self->ct_is_file_ignored($file);
522 my $fh = IO::File->new($file, O_WRONLY | O_CREAT, @_);
523 $self->ct_reset_ownership($fh);
524 return $fh;
525 }
526
527 sub ct_make_path {
528 my $self = shift;
529 if ($self->{id_map}) {
530 my $opts = pop;
531 if (ref($opts) eq 'HASH') {
532 $opts->{owner} = $self->{rootuid} if !defined($self->{owner});
533 $opts->{group} = $self->{rootgid} if !defined($self->{group});
534 }
535 File::Path::make_path(@_, $opts);
536 } else {
537 File::Path::make_path(@_);
538 }
539 }
540
541 sub ct_symlink {
542 my ($self, $old, $new) = @_;
543 return if $self->ct_is_file_ignored($new);
544 return CORE::symlink($old, $new);
545 }
546
547 sub ct_readlink {
548 my ($self, $name) = @_;
549 return CORE::readlink($name);
550 }
551
552 sub ct_file_exists {
553 my ($self, $file) = @_;
554 return -f $file;
555 }
556
557 sub ct_is_directory {
558 my ($self, $file) = @_;
559 return -d $file;
560 }
561
562 sub ct_is_symlink {
563 my ($self, $file) = @_;
564 return -l $file;
565 }
566
567 sub ct_is_executable {
568 my ($self, $file) = @_;
569 return -x $file
570 }
571
572 sub ct_stat {
573 my ($self, $file) = @_;
574 return File::stat::stat($file);
575 }
576
577 sub ct_file_read_firstline {
578 my ($self, $file) = @_;
579 return PVE::Tools::file_read_firstline($file);
580 }
581
582 sub ct_file_get_contents {
583 my ($self, $file) = @_;
584 return PVE::Tools::file_get_contents($file);
585 }
586
587 sub ct_file_set_contents {
588 my ($self, $file, $data, $perms) = @_;
589 return if $self->ct_is_file_ignored($file);
590 PVE::Tools::file_set_contents($file, $data, $perms);
591 $self->ct_reset_ownership($file);
592 }
593
594 # Modify a marked portion of a file.
595 # Optionally if the file becomes empty it will be deleted.
596 sub ct_modify_file {
597 my ($self, $file, $data, %options) = @_;
598 return if $self->ct_is_file_ignored($file);
599
600 my $head = "# --- BEGIN PVE ---\n";
601 my $tail = "# --- END PVE ---\n";
602 my $perms = $options{perms};
603 $data .= "\n" if $data && $data !~ /\n$/;
604
605 if (!$self->ct_file_exists($file)) {
606 $self->ct_file_set_contents($file, $head.$data.$tail, $perms) if $data;
607 return;
608 }
609
610 my $old = $self->ct_file_get_contents($file);
611 my @lines = split(/\n/, $old);
612
613 my ($beg, $end);
614 foreach my $i (0..(@lines-1)) {
615 my $line = $lines[$i];
616 $beg = $i if !defined($beg) &&
617 $line =~ /^#\s*---\s*BEGIN\s*PVE\s*/;
618 $end = $i if !defined($end) && defined($beg) &&
619 $line =~ /^#\s*---\s*END\s*PVE\s*/i;
620 last if defined($beg) && defined($end);
621 }
622
623 if (defined($beg) && defined($end)) {
624 # Found a section
625 if ($data) {
626 chomp $tail;
627 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
628 } else {
629 if ($beg == 0 && $end == (@lines-1)) {
630 $self->ct_unlink($file) if $options{delete};
631 return;
632 }
633 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
634 }
635 $self->ct_file_set_contents($file, join("\n", @lines) . "\n");
636 } elsif ($data) {
637 # No section found
638 my $content = join("\n", @lines);
639 chomp $content;
640 if (!$content && !$data && $options{delete}) {
641 $self->ct_unlink($file);
642 return;
643 }
644 $content .= "\n";
645 $data = $head.$data.$tail;
646 if ($options{replace}) {
647 $self->ct_file_set_contents($file, $data, $perms);
648 } elsif ($options{prepend}) {
649 $self->ct_file_set_contents($file, $data . $content, $perms);
650 } else { # append
651 $self->ct_file_set_contents($file, $content . $data, $perms);
652 }
653 }
654 }
655
656 sub remove_pve_sections {
657 my ($data) = @_;
658
659 my $head = "# --- BEGIN PVE ---";
660 my $tail = "# --- END PVE ---";
661
662 # Remove the sections enclosed with the above headers and footers.
663 # from a line (^) starting with '\h*$head'
664 # to a line (the other ^) starting with '\h*$tail' up to including that
665 # line's end (.*?$).
666 return $data =~ s/^\h*\Q$head\E.*^\h*\Q$tail\E.*?$//rgms;
667 }
668
669 1;