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