]> git.proxmox.com Git - pve-container.git/blob - src/PVE/LXC/Setup/Base.pm
add support for ubuntu xenial
[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 = -x "/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 sub setup_container_getty_service {
202 my ($self, $nosubdir) = @_;
203 my $systemd_dir_rel = -x "/lib/systemd/systemd" ?
204 "/lib/systemd/system" : "/usr/lib/systemd/system";
205 my $servicefile = "$systemd_dir_rel/container-getty\@.service";
206 my $raw = $self->ct_file_get_contents($servicefile);
207 my $ttyname = ($nosubdir ? '' : 'lxc/') . 'tty%I';
208 if ($raw =~ s@pts/%I@$ttyname@g) {
209 $self->ct_file_set_contents($servicefile, $raw);
210 }
211 }
212
213 sub setup_systemd_networkd {
214 my ($self, $conf) = @_;
215
216 foreach my $k (keys %$conf) {
217 next if $k !~ m/^net(\d+)$/;
218 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
219 next if !$d->{name};
220
221 my $filename = "/etc/systemd/network/$d->{name}.network";
222
223 my $data = <<"DATA";
224 [Match]
225 Name = $d->{name}
226
227 [Network]
228 Description = Interface $d->{name} autoconfigured by PVE
229 DATA
230
231 my $routes = '';
232 my ($has_ipv4, $has_ipv6);
233
234 # DHCP bitflags:
235 my @DHCPMODES = ('none', 'v4', 'v6', 'both');
236 my ($NONE, $DHCP4, $DHCP6, $BOTH) = (0, 1, 2, 3);
237 my $dhcp = $NONE;
238
239 if (defined(my $ip = $d->{ip})) {
240 if ($ip eq 'dhcp') {
241 $dhcp |= $DHCP4;
242 } elsif ($ip ne 'manual') {
243 $has_ipv4 = 1;
244 $data .= "Address = $ip\n";
245 }
246 }
247 if (defined(my $gw = $d->{gw})) {
248 $data .= "Gateway = $gw\n";
249 if ($has_ipv4 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip}, 4)) {
250 $routes .= "\n[Route]\nDestination = $gw/32\nScope = link\n";
251 }
252 }
253
254 if (defined(my $ip = $d->{ip6})) {
255 if ($ip eq 'dhcp') {
256 $dhcp |= $DHCP6;
257 } elsif ($ip ne 'manual') {
258 $has_ipv6 = 1;
259 $data .= "Address = $ip\n";
260 }
261 }
262 if (defined(my $gw = $d->{gw6})) {
263 $data .= "Gateway = $gw\n";
264 if ($has_ipv6 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip6}, 6)) {
265 $routes .= "\n[Route]\nDestination = $gw/128\nScope = link\n";
266 }
267 }
268
269 $data .= "DHCP = $DHCPMODES[$dhcp]\n";
270 $data .= $routes if $routes;
271
272 $self->ct_file_set_contents($filename, $data);
273 }
274 }
275
276 sub setup_securetty {
277 my ($self, $conf, @add) = @_;
278
279 my $filename = "/etc/securetty";
280 my $data = $self->ct_file_get_contents($filename);
281 chomp $data; $data .= "\n";
282 foreach my $dev (@add) {
283 if ($data !~ m!^\Q$dev\E\s*$!m) {
284 $data .= "$dev\n";
285 }
286 }
287 $self->ct_file_set_contents($filename, $data);
288 }
289
290 my $replacepw = sub {
291 my ($self, $file, $user, $epw, $shadow) = @_;
292
293 my $tmpfile = "$file.$$";
294
295 eval {
296 my $src = $self->ct_open_file_read($file) ||
297 die "unable to open file '$file' - $!";
298
299 my $st = $self->ct_stat($src) ||
300 die "unable to stat file - $!";
301
302 my $dst = $self->ct_open_file_write($tmpfile) ||
303 die "unable to open file '$tmpfile' - $!";
304
305 # copy owner and permissions
306 chmod $st->mode, $dst;
307 chown $st->uid, $st->gid, $dst;
308
309 my $last_change = int(time()/(60*60*24));
310
311 if ($epw =~ m/^\$TEST\$/) { # for regression tests
312 $last_change = 12345;
313 }
314
315 while (defined (my $line = <$src>)) {
316 if ($shadow) {
317 $line =~ s/^${user}:[^:]*:[^:]*:/${user}:${epw}:${last_change}:/;
318 } else {
319 $line =~ s/^${user}:[^:]*:/${user}:${epw}:/;
320 }
321 print $dst $line;
322 }
323
324 $src->close() || die "close '$file' failed - $!\n";
325 $dst->close() || die "close '$tmpfile' failed - $!\n";
326 };
327 if (my $err = $@) {
328 $self->ct_unlink($tmpfile);
329 } else {
330 $self->ct_rename($tmpfile, $file);
331 $self->ct_unlink($tmpfile); # in case rename fails
332 }
333 };
334
335 sub set_user_password {
336 my ($self, $conf, $user, $opt_password) = @_;
337
338 my $pwfile = "/etc/passwd";
339
340 return if !$self->ct_file_exists($pwfile);
341
342 my $shadow = "/etc/shadow";
343
344 if (defined($opt_password)) {
345 if ($opt_password !~ m/^\$/) {
346 my $time = substr (Digest::SHA::sha1_base64 (time), 0, 8);
347 $opt_password = crypt(encode("utf8", $opt_password), "\$1\$$time\$");
348 };
349 } else {
350 $opt_password = '*';
351 }
352
353 if ($self->ct_file_exists($shadow)) {
354 &$replacepw ($self, $shadow, $user, $opt_password, 1);
355 &$replacepw ($self, $pwfile, $user, 'x');
356 } else {
357 &$replacepw ($self, $pwfile, $user, $opt_password);
358 }
359 }
360
361 my $parse_home_dir = sub {
362 my ($self, $passwdfile, $user) = @_;
363
364 my $fh = $self->ct_open_file_read($passwdfile);
365 while (defined (my $line = <$fh>)) {
366 return $2
367 if $line =~ m/^${user}:([^:]*:){4}([^:]*):/;
368 }
369 };
370
371 sub set_user_authorized_ssh_keys {
372 my ($self, $conf, $user, $ssh_keys) = @_;
373
374 my $passwd = "/etc/passwd";
375 my $home = $user eq "root" ? "/root/" : "/home/$user/";
376
377 $home = &$parse_home_dir($self, $passwd, $user)
378 if $self->ct_file_exists($passwd);
379
380 die "home directory '$home' of $user does not exist!"
381 if ! ($self->ct_is_directory($home) || $self->ct_is_symlink($home));
382
383 $self->ct_mkdir("$home/.ssh", 0700)
384 if ! $self->ct_is_directory("$home/.ssh");
385
386 $self->ct_modify_file("$home/.ssh/authorized_keys", $ssh_keys, perms => 0700);
387 }
388
389 my $randomize_crontab = sub {
390 my ($self, $conf) = @_;
391
392 my @files;
393 # Note: dir_glob_foreach() untaints filenames!
394 PVE::Tools::dir_glob_foreach("/etc/cron.d", qr/[A-Z\-\_a-z0-9]+/, sub {
395 my ($name) = @_;
396 push @files, "/etc/cron.d/$name";
397 });
398
399 my $crontab_fn = "/etc/crontab";
400 unshift @files, $crontab_fn if $self->ct_file_exists($crontab_fn);
401
402 foreach my $filename (@files) {
403 my $data = $self->ct_file_get_contents($filename);
404 my $new = '';
405 foreach my $line (split(/\n/, $data)) {
406 # we only randomize minutes for root crontab entries
407 if ($line =~ m/^\d+(\s+\S+\s+\S+\s+\S+\s+\S+\s+root\s+\S.*)$/) {
408 my $rest = $1;
409 my $min = int(rand()*59);
410 $new .= "$min$rest\n";
411 } else {
412 $new .= "$line\n";
413 }
414 }
415 $self->ct_file_set_contents($filename, $new);
416 }
417 };
418
419 sub pre_start_hook {
420 my ($self, $conf) = @_;
421
422 $self->setup_init($conf);
423 $self->setup_network($conf);
424 $self->set_hostname($conf);
425 $self->set_dns($conf);
426
427 # fixme: what else ?
428 }
429
430 sub post_create_hook {
431 my ($self, $conf, $root_password, $ssh_keys) = @_;
432
433 $self->template_fixup($conf);
434
435 &$randomize_crontab($self, $conf);
436
437 $self->set_user_password($conf, 'root', $root_password);
438 $self->set_user_authorized_ssh_keys($conf, 'root', $ssh_keys) if $ssh_keys;
439 $self->setup_init($conf);
440 $self->setup_network($conf);
441 $self->set_hostname($conf);
442 $self->set_dns($conf);
443
444 # fixme: what else ?
445 }
446
447 # File access wrappers for container setup code.
448 # For user-namespace support these might need to take uid and gid maps into account.
449
450 sub ct_is_file_ignored {
451 my ($self, $file) = @_;
452 my ($name, $path) = fileparse($file);
453 return -f "$path/.pve-ignore.$name";
454 }
455
456 sub ct_reset_ownership {
457 my ($self, @files) = @_;
458 my $conf = $self->{conf};
459 return if !$self->{id_map};
460
461 @files = grep { !$self->ct_is_file_ignored($_) } @files;
462 return if !@files;
463
464 my $uid = $self->{rootuid};
465 my $gid = $self->{rootgid};
466 chown($uid, $gid, @files);
467 }
468
469 sub ct_mkdir {
470 my ($self, $file, $mask) = @_;
471 # mkdir goes by parameter count - an `undef' mode acts like a mode of 0000
472 if (defined($mask)) {
473 return CORE::mkdir($file, $mask) && $self->ct_reset_ownership($file);
474 } else {
475 return CORE::mkdir($file) && $self->ct_reset_ownership($file);
476 }
477 }
478
479 sub ct_unlink {
480 my ($self, @files) = @_;
481 foreach my $file (@files) {
482 next if $self->ct_is_file_ignored($file);
483 CORE::unlink($file);
484 }
485 }
486
487 sub ct_rename {
488 my ($self, $old, $new) = @_;
489 return if $self->ct_is_file_ignored($new);
490 CORE::rename($old, $new);
491 }
492
493 sub ct_open_file_read {
494 my $self = shift;
495 my $file = shift;
496 return IO::File->new($file, O_RDONLY, @_);
497 }
498
499 sub ct_open_file_write {
500 my $self = shift;
501 my $file = shift;
502 $file = '/dev/null' if $self->ct_is_file_ignored($file);
503 my $fh = IO::File->new($file, O_WRONLY | O_CREAT, @_);
504 $self->ct_reset_ownership($fh);
505 return $fh;
506 }
507
508 sub ct_make_path {
509 my $self = shift;
510 if ($self->{id_map}) {
511 my $opts = pop;
512 if (ref($opts) eq 'HASH') {
513 $opts->{owner} = $self->{rootuid} if !defined($self->{owner});
514 $opts->{group} = $self->{rootgid} if !defined($self->{group});
515 }
516 File::Path::make_path(@_, $opts);
517 } else {
518 File::Path::make_path(@_);
519 }
520 }
521
522 sub ct_symlink {
523 my ($self, $old, $new) = @_;
524 return if $self->ct_is_file_ignored($new);
525 return CORE::symlink($old, $new);
526 }
527
528 sub ct_readlink {
529 my ($self, $name) = @_;
530 return CORE::readlink($name);
531 }
532
533 sub ct_file_exists {
534 my ($self, $file) = @_;
535 return -f $file;
536 }
537
538 sub ct_is_directory {
539 my ($self, $file) = @_;
540 return -d $file;
541 }
542
543 sub ct_is_symlink {
544 my ($self, $file) = @_;
545 return -l $file;
546 }
547
548 sub ct_stat {
549 my ($self, $file) = @_;
550 return File::stat::stat($file);
551 }
552
553 sub ct_file_read_firstline {
554 my ($self, $file) = @_;
555 return PVE::Tools::file_read_firstline($file);
556 }
557
558 sub ct_file_get_contents {
559 my ($self, $file) = @_;
560 return PVE::Tools::file_get_contents($file);
561 }
562
563 sub ct_file_set_contents {
564 my ($self, $file, $data, $perms) = @_;
565 return if $self->ct_is_file_ignored($file);
566 PVE::Tools::file_set_contents($file, $data, $perms);
567 $self->ct_reset_ownership($file);
568 }
569
570 # Modify a marked portion of a file.
571 # Optionally if the file becomes empty it will be deleted.
572 sub ct_modify_file {
573 my ($self, $file, $data, %options) = @_;
574 return if $self->ct_is_file_ignored($file);
575
576 my $head = "# --- BEGIN PVE ---\n";
577 my $tail = "# --- END PVE ---\n";
578 my $perms = $options{perms};
579 $data .= "\n" if $data && $data !~ /\n$/;
580
581 if (!$self->ct_file_exists($file)) {
582 $self->ct_file_set_contents($file, $head.$data.$tail, $perms) if $data;
583 return;
584 }
585
586 my $old = $self->ct_file_get_contents($file);
587 my @lines = split(/\n/, $old);
588
589 my ($beg, $end);
590 foreach my $i (0..(@lines-1)) {
591 my $line = $lines[$i];
592 $beg = $i if !defined($beg) &&
593 $line =~ /^#\s*---\s*BEGIN\s*PVE\s*/;
594 $end = $i if !defined($end) && defined($beg) &&
595 $line =~ /^#\s*---\s*END\s*PVE\s*/i;
596 last if defined($beg) && defined($end);
597 }
598
599 if (defined($beg) && defined($end)) {
600 # Found a section
601 if ($data) {
602 chomp $tail;
603 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
604 } else {
605 if ($beg == 0 && $end == (@lines-1)) {
606 $self->ct_unlink($file) if $options{delete};
607 return;
608 }
609 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
610 }
611 $self->ct_file_set_contents($file, join("\n", @lines) . "\n");
612 } elsif ($data) {
613 # No section found
614 my $content = join("\n", @lines);
615 chomp $content;
616 if (!$content && !$data && $options{delete}) {
617 $self->ct_unlink($file);
618 return;
619 }
620 $content .= "\n";
621 $data = $head.$data.$tail;
622 if ($options{replace}) {
623 $self->ct_file_set_contents($file, $data, $perms);
624 } elsif ($options{prepend}) {
625 $self->ct_file_set_contents($file, $data . $content, $perms);
626 } else { # append
627 $self->ct_file_set_contents($file, $content . $data, $perms);
628 }
629 }
630 }
631
632 sub remove_pve_sections {
633 my ($data) = @_;
634
635 my $head = "# --- BEGIN PVE ---";
636 my $tail = "# --- END PVE ---";
637
638 # Remove the sections enclosed with the above headers and footers.
639 # from a line (^) starting with '\h*$head'
640 # to a line (the other ^) starting with '\h*$tail' up to including that
641 # line's end (.*?$).
642 return $data =~ s/^\h*\Q$head\E.*^\h*\Q$tail\E.*?$//rgms;
643 }
644
645 1;