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