]> git.proxmox.com Git - pve-container.git/blame - src/PVE/LXC/Setup/Base.pm
d/control: bump versioned dependency for guest-common
[pve-container.git] / src / PVE / LXC / Setup / Base.pm
CommitLineData
7af97ad5 1package PVE::LXC::Setup::Base;
1c7f4f65
DM
2
3use strict;
4use warnings;
5
e6e308ae 6use Cwd 'abs_path';
168d6b07
DM
7use File::stat;
8use Digest::SHA;
9use IO::File;
10use Encode;
f08b2779 11use Fcntl;
2063d380 12use File::Path;
f08b2779 13use File::Spec;
bd1dc8d1 14use File::Basename;
464452c0 15use POSIX ();
168d6b07 16
b9cd9975 17use PVE::INotify;
55fa4e09 18use PVE::Tools;
4401b7d4 19use PVE::Network;
55fa4e09 20
4526287a 21use PVE::LXC::Setup::Plugin;
1de92199
CH
22use PVE::LXC::Tools;
23
4526287a
TL
24use base qw(PVE::LXC::Setup::Plugin);
25
633a7bd8 26sub new {
153747ff 27 my ($class, $conf, $rootdir, $os_release) = @_;
633a7bd8 28
153747ff 29 return bless { conf => $conf, rootdir => $rootdir, os_release => $os_release }, $class;
633a7bd8 30}
b9cd9975 31
c0eae401 32sub lookup_dns_conf {
23d928a1 33 my ($self, $conf) = @_;
b9cd9975 34
27916659
DM
35 my $nameserver = $conf->{nameserver};
36 my $searchdomains = $conf->{searchdomain};
b9cd9975 37
ffc468ee 38 if ($conf->{'testmode'}) {
bb7f97cd
TL
39 $nameserver //= '8.8.8.8 8.8.8.9';
40 $searchdomains //= 'proxmox.com';
ffc468ee 41 }
b9cd9975 42
ffc468ee 43 my $host_resolv_conf = $self->{host_resolv_conf};
b9cd9975 44
ffc468ee
DC
45 if (!defined($nameserver)) {
46 my @list = ();
47 foreach my $k ("dns1", "dns2", "dns3") {
48 if (my $ns = $host_resolv_conf->{$k}) {
49 push @list, $ns;
b9cd9975 50 }
b9cd9975 51 }
ffc468ee
DC
52 $nameserver = join(' ', @list);
53 }
54
55 if (!defined($searchdomains)) {
56 $searchdomains = $host_resolv_conf->{search};
b9cd9975
DM
57 }
58
59 return ($searchdomains, $nameserver);
c0eae401 60}
b9cd9975 61
c0eae401 62sub update_etc_hosts {
9096a91d 63 my ($self, $hostip, $oldname, $newname, $searchdomains) = @_;
1c7f4f65 64
1b3cffda
WB
65 my $hosts_fn = '/etc/hosts';
66 return if $self->ct_is_file_ignored($hosts_fn);
67
ce289e3c
WB
68 my $namepart = ($newname =~ s/\..*$//r);
69
005f91ad 70 my $all_names = '';
ce289e3c 71 if ($newname =~ /\./) {
005f91ad 72 $all_names .= "$newname $namepart";
ce289e3c
WB
73 } else {
74 foreach my $domain (PVE::Tools::split_list($searchdomains)) {
005f91ad
WB
75 $all_names .= ' ' if $all_names;
76 $all_names .= "$newname.$domain";
ce289e3c 77 }
005f91ad
WB
78 $all_names .= ' ' if $all_names;
79 $all_names .= $newname;
e4929e97 80 }
1c7f4f65 81
9096a91d
WB
82 # Prepare section:
83 my $section = '';
c325b32f 84
9096a91d
WB
85 my $lo4 = "127.0.0.1 localhost.localnet localhost\n";
86 my $lo6 = "::1 localhost.localnet localhost\n";
87 if ($self->ct_file_exists($hosts_fn)) {
88 my $data = $self->ct_file_get_contents($hosts_fn);
89 # don't take localhost entries within our hosts sections into account
90 $data = remove_pve_sections($data);
1c7f4f65 91
9096a91d
WB
92 # check for existing localhost entries
93 $section .= $lo4 if $data !~ /^\h*127\.0\.0\.1\h+/m;
94 $section .= $lo6 if $data !~ /^\h*::1\h+/m;
95 } else {
96 $section .= $lo4 . $lo6;
1c7f4f65
DM
97 }
98
9096a91d
WB
99 if (defined($hostip)) {
100 $section .= "$hostip $all_names\n";
63ec4b3b
DC
101 } elsif ($namepart ne 'localhost') {
102 $section .= "127.0.1.1 $all_names\n";
9096a91d
WB
103 } else {
104 $section .= "127.0.1.1 $namepart\n";
1e180f97
DM
105 }
106
9096a91d 107 $self->ct_modify_file($hosts_fn, $section);
c0eae401 108}
1c7f4f65 109
142444d5
DM
110sub template_fixup {
111 my ($self, $conf) = @_;
112
113 # do nothing by default
114}
115
c325b32f 116sub set_dns {
633a7bd8 117 my ($self, $conf) = @_;
c325b32f 118
23d928a1 119 my ($searchdomains, $nameserver) = $self->lookup_dns_conf($conf);
c325b32f 120
c325b32f
DM
121 my $data = '';
122
123 $data .= "search " . join(' ', PVE::Tools::split_list($searchdomains)) . "\n"
124 if $searchdomains;
125
126 foreach my $ns ( PVE::Tools::split_list($nameserver)) {
127 $data .= "nameserver $ns\n";
128 }
129
2edb50e5 130 $self->ct_modify_file("/etc/resolv.conf", $data, replace => 1);
c325b32f
DM
131}
132
1c7f4f65 133sub set_hostname {
633a7bd8 134 my ($self, $conf) = @_;
1c7f4f65 135
27916659 136 my $hostname = $conf->{hostname} || 'localhost';
1c7f4f65 137
ce289e3c 138 my $namepart = ($hostname =~ s/\..*$//r);
1c7f4f65 139
f08b2779 140 my $hostname_fn = "/etc/hostname";
1c7f4f65 141
f08b2779 142 my $oldname = $self->ct_file_read_firstline($hostname_fn) || 'localhost';
1c7f4f65 143
c325b32f
DM
144 my ($ipv4, $ipv6) = PVE::LXC::get_primary_ips($conf);
145 my $hostip = $ipv4 || $ipv6;
b9cd9975 146
23d928a1 147 my ($searchdomains) = $self->lookup_dns_conf($conf);
b9cd9975 148
9096a91d 149 $self->update_etc_hosts($hostip, $oldname, $hostname, $searchdomains);
b9cd9975 150
ce289e3c 151 $self->ct_file_set_contents($hostname_fn, "$namepart\n");
1c7f4f65
DM
152}
153
55fa4e09 154sub setup_network {
633a7bd8 155 my ($self, $conf) = @_;
55fa4e09
DM
156
157 die "please implement this inside subclass"
158}
159
d66768a2 160sub setup_init {
633a7bd8 161 my ($self, $conf) = @_;
1c7f4f65 162
d66768a2
DM
163 die "please implement this inside subclass"
164}
165
5e84bdc8
DM
166# A few distros as well as unprivileged containers cannot deal with the
167# /dev/lxc/ tty subdirectory.
168sub devttydir {
169 my ($self, $conf) = @_;
170 return $conf->{unprivileged} ? '' : 'lxc/';
171}
172
dd7a436b
TL
173sub fixup_old_getty {
174 my ($self) = @_;
175
176 my $sd_dir_rel = $self->ct_is_executable("/lib/systemd/systemd") ?
177 "/lib/systemd/system" : "/usr/lib/systemd/system";
178
179 my $sd_getty_service_rel = "$sd_dir_rel/getty\@.service";
180 return if !$self->ct_file_exists($sd_getty_service_rel);
181
182 my $raw = $self->ct_file_get_contents($sd_getty_service_rel);
183
184 my $sd_container_getty_service_rel = "$sd_dir_rel/container-getty\@.service";
185 # systemd on CenoOS 7.1 is too old (version 205), so there is no
186 # container-getty service
187 if (!$self->ct_file_exists($sd_container_getty_service_rel)) {
188 if ($raw =~ s!^ConditionPathExists=/dev/tty0$!ConditionPathExists=/dev/tty!m) {
189 $self->ct_file_set_contents($sd_getty_service_rel, $raw);
190 }
191 } else {
192 # undo above change (in case someone updated systemd)
193 if ($raw =~ s!^ConditionPathExists=/dev/tty$!ConditionPathExists=/dev/tty0!m) {
194 $self->ct_file_set_contents($sd_getty_service_rel, $raw);
195 }
196 }
197}
198
90b21cdc 199sub setup_container_getty_service {
5e84bdc8
DM
200 my ($self, $conf) = @_;
201
bfe63c1a 202 my $sd_dir = $self->ct_is_executable("/lib/systemd/systemd") ?
8f115f7c 203 "/lib/systemd/system" : "/usr/lib/systemd/system";
bfe63c1a
TL
204
205 # prefer container-getty.service shipped by newer systemd versions
206 # fallback to getty.service and just return if that doesn't exists either..
207 my $template_base = "container-getty\@";
208 my $template_path = "${sd_dir}/${template_base}.service";
209 my $instance_base = $template_base;
210
211 if (!$self->ct_file_exists($template_path)) {
212 $template_base = "getty\@";
213 $template_path = "${template_base}.service";
214 $instance_base = "{$template_base}tty";
215 return if !$self->ct_file_exists($template_path);
216 }
217
218 my $raw = $self->ct_file_get_contents($template_path);
5e84bdc8 219 my $ttyname = $self->devttydir($conf) . 'tty%I';
418ec240 220 if ($raw =~ s@pts/%I|lxc/tty%I@$ttyname@g) {
bfe63c1a 221 $self->ct_file_set_contents($template_path, $raw);
90b21cdc 222 }
73aa033d 223
bfe63c1a 224 my $getty_target_fn = "/etc/systemd/system/getty.target.wants/";
73aa033d 225 my $ttycount = PVE::LXC::Config->get_tty_count($conf);
73aa033d 226
bfe63c1a 227 for (my $i = 1; $i < 7; $i++) {
73aa033d
TL
228 # ensure that not two gettys are using the same tty!
229 $self->ct_unlink("$getty_target_fn/getty\@tty$i.service");
bfe63c1a 230 $self->ct_unlink("$getty_target_fn/container-getty\@$i.service");
73aa033d 231
bfe63c1a 232 # re-enable only those requested
73aa033d 233 if ($i <= $ttycount) {
bfe63c1a
TL
234 my $tty_service = "${instance_base}${i}.service";
235
236 $self->ct_symlink($template_path, "$getty_target_fn/$tty_service");
73aa033d
TL
237 }
238 }
570798fa
TL
239
240 # ensure getty.target is not masked
241 $self->ct_unlink("/etc/systemd/system/getty.target");
90b21cdc
WB
242}
243
c1d32b55
WB
244sub setup_systemd_networkd {
245 my ($self, $conf) = @_;
246
c1d32b55
WB
247 foreach my $k (keys %$conf) {
248 next if $k !~ m/^net(\d+)$/;
1b4cf758 249 my $d = PVE::LXC::Config->parse_lxc_network($conf->{$k});
c1d32b55
WB
250 next if !$d->{name};
251
f08b2779 252 my $filename = "/etc/systemd/network/$d->{name}.network";
c1d32b55
WB
253
254 my $data = <<"DATA";
255[Match]
256Name = $d->{name}
257
258[Network]
259Description = Interface $d->{name} autoconfigured by PVE
260DATA
4401b7d4
WB
261
262 my $routes = '';
263 my ($has_ipv4, $has_ipv6);
264
c1d32b55 265 # DHCP bitflags:
5614a02f 266 my @DHCPMODES = ('no', 'ipv4', 'ipv6', 'yes');
c1d32b55
WB
267 my ($NONE, $DHCP4, $DHCP6, $BOTH) = (0, 1, 2, 3);
268 my $dhcp = $NONE;
bb7f06ef 269 my $accept_ra = 'false';
c1d32b55
WB
270
271 if (defined(my $ip = $d->{ip})) {
272 if ($ip eq 'dhcp') {
273 $dhcp |= $DHCP4;
274 } elsif ($ip ne 'manual') {
4401b7d4 275 $has_ipv4 = 1;
c1d32b55
WB
276 $data .= "Address = $ip\n";
277 }
278 }
279 if (defined(my $gw = $d->{gw})) {
280 $data .= "Gateway = $gw\n";
4401b7d4
WB
281 if ($has_ipv4 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip}, 4)) {
282 $routes .= "\n[Route]\nDestination = $gw/32\nScope = link\n";
283 }
c1d32b55
WB
284 }
285
286 if (defined(my $ip = $d->{ip6})) {
287 if ($ip eq 'dhcp') {
288 $dhcp |= $DHCP6;
bb7f06ef
WB
289 } elsif ($ip eq 'auto') {
290 $accept_ra = 'true';
c1d32b55 291 } elsif ($ip ne 'manual') {
4401b7d4 292 $has_ipv6 = 1;
c1d32b55
WB
293 $data .= "Address = $ip\n";
294 }
295 }
296 if (defined(my $gw = $d->{gw6})) {
bb7f06ef 297 $accept_ra = 'false';
c1d32b55 298 $data .= "Gateway = $gw\n";
d13fd23a
WB
299 if ($has_ipv6 && !PVE::Network::is_ip_in_cidr($gw, $d->{ip6}, 6) &&
300 !PVE::Network::is_ip_in_cidr($gw, 'fe80::/10', 6)) {
4401b7d4
WB
301 $routes .= "\n[Route]\nDestination = $gw/128\nScope = link\n";
302 }
c1d32b55
WB
303 }
304
305 $data .= "DHCP = $DHCPMODES[$dhcp]\n";
bb7f06ef 306 $data .= "IPv6AcceptRA = $accept_ra\n";
4401b7d4 307 $data .= $routes if $routes;
c1d32b55 308
f08b2779 309 $self->ct_file_set_contents($filename, $data);
c1d32b55 310 }
b7cd927f
WB
311}
312
65a9b7be 313# At first boot (/etc/machine-id not existing), systemd goes through a set of `presets` to bring the
e11806e0 314# enable/disable state of services to a default.
65a9b7be
TL
315# Meaning for newer templates we should use this instead of manually creating enable/disable
316# symlinks.
e11806e0 317#
65a9b7be
TL
318# Disables some common problematic and/or useless units by default.
319#
320# `$extra_preset` should map service names to a bool-ish. It can also hold overrides for the default
321# presets.
e11806e0 322sub setup_systemd_preset {
65a9b7be
TL
323 my ($self, $extra_preset) = @_;
324
325 # some don't make sense in CTs, child-plugins can still override through extra_presets
326 my $preset = {
327 'sys-kernel-config.mount' => 0,
328 'sys-kernel-debug.mount' => 0,
d4c76917
TL
329 # NOTE: some older distro releases (e.g., centos 7.0) had no container-getty, which itself
330 # is not an issue for presets, but disabling getty@ then could cause issues.
ea98dcd2
TL
331 'getty@.service' => 0,
332 'container-getty@.service' => 1,
65a9b7be 333 };
e11806e0 334
65a9b7be
TL
335 if (defined($extra_preset)) {
336 $preset->{$_} = $extra_preset->{$_} for keys $extra_preset->%*;
337 }
e11806e0 338
65a9b7be 339 my $preset_data = "# Added by PVE at create-time for first-boot configuration.\n";
e11806e0
WB
340 for my $service (sort keys %$preset) {
341 if ($preset->{$service}) {
342 $preset_data .= "enable $service\n";
343 } else {
344 $preset_data .= "disable $service\n";
345 }
346 }
347
348 $self->ct_mkdir('/etc/systemd/system-preset', 0755);
349 $self->ct_file_set_contents(
350 '/etc/systemd/system-preset/00-pve.preset',
351 $preset_data,
352 );
353}
354
b7cd927f
WB
355sub setup_securetty {
356 my ($self, $conf, @add) = @_;
c1d32b55 357
f08b2779 358 my $filename = "/etc/securetty";
bd3093ef
TL
359 # root login is already allowed on every device if no securetty present
360 return if !$self->ct_file_exists($filename);
361
5e84bdc8
DM
362 if (!scalar(@add)) {
363 @add = qw(console tty1 tty2 tty3 tty4);
364 if (my $dir = $self->devttydir($conf)) {
365 @add = map { "${dir}$_" } @add;
366 }
367 }
368
f08b2779 369 my $data = $self->ct_file_get_contents($filename);
b7cd927f
WB
370 chomp $data; $data .= "\n";
371 foreach my $dev (@add) {
372 if ($data !~ m!^\Q$dev\E\s*$!m) {
373 $data .= "$dev\n";
374 }
375 }
f08b2779 376 $self->ct_file_set_contents($filename, $data);
c1d32b55
WB
377}
378
168d6b07 379my $replacepw = sub {
f08b2779 380 my ($self, $file, $user, $epw, $shadow) = @_;
168d6b07
DM
381
382 my $tmpfile = "$file.$$";
383
384 eval {
f08b2779 385 my $src = $self->ct_open_file_read($file) ||
168d6b07
DM
386 die "unable to open file '$file' - $!";
387
f08b2779 388 my $st = $self->ct_stat($src) ||
168d6b07
DM
389 die "unable to stat file - $!";
390
f08b2779 391 my $dst = $self->ct_open_file_write($tmpfile) ||
168d6b07
DM
392 die "unable to open file '$tmpfile' - $!";
393
394 # copy owner and permissions
395 chmod $st->mode, $dst;
396 chown $st->uid, $st->gid, $dst;
367a7c18
DM
397
398 my $last_change = int(time()/(60*60*24));
399
168d6b07 400 while (defined (my $line = <$src>)) {
367a7c18
DM
401 if ($shadow) {
402 $line =~ s/^${user}:[^:]*:[^:]*:/${user}:${epw}:${last_change}:/;
403 } else {
404 $line =~ s/^${user}:[^:]*:/${user}:${epw}:/;
405 }
168d6b07
DM
406 print $dst $line;
407 }
408
409 $src->close() || die "close '$file' failed - $!\n";
410 $dst->close() || die "close '$tmpfile' failed - $!\n";
411 };
412 if (my $err = $@) {
f08b2779 413 $self->ct_unlink($tmpfile);
168d6b07 414 } else {
f08b2779
WB
415 $self->ct_rename($tmpfile, $file);
416 $self->ct_unlink($tmpfile); # in case rename fails
168d6b07
DM
417 }
418};
419
420sub set_user_password {
633a7bd8 421 my ($self, $conf, $user, $opt_password) = @_;
168d6b07 422
f08b2779 423 my $pwfile = "/etc/passwd";
168d6b07 424
f08b2779 425 return if !$self->ct_file_exists($pwfile);
168d6b07 426
f08b2779 427 my $shadow = "/etc/shadow";
168d6b07
DM
428
429 if (defined($opt_password)) {
a46b2fb3 430 if ($opt_password !~ m/^\$(?:1|2[axy]?|5|6)\$[a-zA-Z0-9.\/]{1,16}\$[a-zA-Z0-9.\/]+$/) {
168d6b07 431 my $time = substr (Digest::SHA::sha1_base64 (time), 0, 8);
f55589da 432 $opt_password = crypt(encode("utf8", $opt_password), "\$6\$$time\$");
168d6b07
DM
433 };
434 } else {
435 $opt_password = '*';
436 }
437
f08b2779
WB
438 if ($self->ct_file_exists($shadow)) {
439 &$replacepw ($self, $shadow, $user, $opt_password, 1);
440 &$replacepw ($self, $pwfile, $user, 'x');
168d6b07 441 } else {
f08b2779 442 &$replacepw ($self, $pwfile, $user, $opt_password);
168d6b07
DM
443 }
444}
445
f36ce482
FG
446my $parse_home_dir = sub {
447 my ($self, $passwdfile, $user) = @_;
448
449 my $fh = $self->ct_open_file_read($passwdfile);
450 while (defined (my $line = <$fh>)) {
451 return $2
452 if $line =~ m/^${user}:([^:]*:){4}([^:]*):/;
453 }
454};
455
456sub set_user_authorized_ssh_keys {
457 my ($self, $conf, $user, $ssh_keys) = @_;
458
459 my $passwd = "/etc/passwd";
460 my $home = $user eq "root" ? "/root/" : "/home/$user/";
461
462 $home = &$parse_home_dir($self, $passwd, $user)
463 if $self->ct_file_exists($passwd);
464
465 die "home directory '$home' of $user does not exist!"
466 if ! ($self->ct_is_directory($home) || $self->ct_is_symlink($home));
467
468 $self->ct_mkdir("$home/.ssh", 0700)
469 if ! $self->ct_is_directory("$home/.ssh");
470
471 $self->ct_modify_file("$home/.ssh/authorized_keys", $ssh_keys, perms => 0700);
472}
473
4727bd09
DM
474my $randomize_crontab = sub {
475 my ($self, $conf) = @_;
476
b5e62cd0
DM
477 my @files;
478 # Note: dir_glob_foreach() untaints filenames!
f08b2779 479 PVE::Tools::dir_glob_foreach("/etc/cron.d", qr/[A-Z\-\_a-z0-9]+/, sub {
b5e62cd0 480 my ($name) = @_;
f08b2779 481 push @files, "/etc/cron.d/$name";
b5e62cd0 482 });
4727bd09 483
f08b2779
WB
484 my $crontab_fn = "/etc/crontab";
485 unshift @files, $crontab_fn if $self->ct_file_exists($crontab_fn);
4727bd09
DM
486
487 foreach my $filename (@files) {
f08b2779 488 my $data = $self->ct_file_get_contents($filename);
4727bd09
DM
489 my $new = '';
490 foreach my $line (split(/\n/, $data)) {
491 # we only randomize minutes for root crontab entries
492 if ($line =~ m/^\d+(\s+\S+\s+\S+\s+\S+\s+\S+\s+root\s+\S.*)$/) {
493 my $rest = $1;
494 my $min = int(rand()*59);
495 $new .= "$min$rest\n";
496 } else {
497 $new .= "$line\n";
498 }
499 }
f08b2779 500 $self->ct_file_set_contents($filename, $new);
4727bd09
DM
501 }
502};
503
e6e308ae
OB
504sub set_timezone {
505 my ($self, $conf) = @_;
506
507 my $zoneinfo = $conf->{timezone};
508
509 return if !defined($zoneinfo);
510
511 my $tz_path = "/usr/share/zoneinfo/$zoneinfo";
512
513 if ($zoneinfo eq 'host') {
514 $tz_path = $self->{host_localtime};
515 }
516
e6e308ae 517 if ($self->ct_file_exists($tz_path)) {
6007e81b
FE
518 if (abs_path('/etc/localtime') ne $tz_path) {
519 my $tmpfile = "localtime.$$.new.tmpfile";
520 $self->ct_symlink($tz_path, $tmpfile);
521 $self->ct_rename($tmpfile, "/etc/localtime");
522 }
523
524 # not all distributions have /etc/timezone
525 if ($self->ct_file_exists('/etc/timezone')) {
526 my $contents = $zoneinfo eq 'host' ? $self->{host_timezone} : $zoneinfo;
527 $self->ct_file_set_contents('/etc/timezone', "$contents\n");
528 }
e6e308ae
OB
529 } else {
530 warn "container does not have $tz_path, timezone can not be modified\n";
531 }
532}
533
64d4c144
OB
534sub clear_machine_id {
535 my ($self, $conf, $clone) = @_;
536
537 my $uses_systemd = $self->ct_is_executable("/lib/systemd/systemd")
538 || $self->ct_is_executable("/usr/lib/systemd/systemd");
539
540 my $dbus_machine_id_path = "/var/lib/dbus/machine-id";
541 my $machine_id_path = "/etc/machine-id";
b2c3706f
TL
542
543 my $machine_id_existed = $self->ct_file_exists($machine_id_path);
544
64d4c144
OB
545 if (
546 $self->ct_file_exists($dbus_machine_id_path)
547 && !$self->ct_is_symlink($dbus_machine_id_path)
548 && $uses_systemd
549 ) {
550 $self->ct_unlink($dbus_machine_id_path);
551 }
552
a72424ba
TL
553 if ($machine_id_existed) {
554 # truncate exiting ones on clone to avoid FirstBoot condition. admins can override this by
555 # removing the machine-id file or setting it to uninitialized before creating a template, or
556 # cloning a guest - as per machine-id(5) man page. TODO: add explicit switch to API?
557 if ($clone) {
558 my $old_machine_id = $self->ct_file_read_firstline($machine_id_path) // '';
559 if ($uses_systemd && $old_machine_id ne 'uninitialized') {
560 $self->ct_file_set_contents($machine_id_path, "\n") if $uses_systemd;
561 }
562 } else {
563 $self->ct_unlink($machine_id_path);
564 }
64d4c144
OB
565 }
566}
567
917f7ae3
LN
568# tries to guess the systemd (major) version based on the
569# libsystemd-shared<version>.so linked with /sbin/init
f7073b99 570sub get_systemd_version {
917f7ae3
LN
571 my ($self, $init) = @_;
572
573 my $version = undef;
574 PVE::Tools::run_command(
575 ['objdump', '-p', $self->{rootdir}.$init],
576 outfunc => sub {
577 my $line = shift;
863ebe36 578 if ($line =~ /libsystemd-shared-(\d+)(?:[-.][a-zA-Z0-9]+)*\.so:?$/) {
917f7ae3 579 $version = $1;
69121dd2
TL
580 }
581 },
917f7ae3
LN
582 errmsg => "objdump on $init failed",
583 );
584
585 return $version;
f7073b99
SI
586}
587
588sub unified_cgroupv2_support {
917f7ae3 589 my ($self, $init) = @_;
f7073b99
SI
590
591 # https://www.freedesktop.org/software/systemd/man/systemd.html
592 # systemd is installed as symlink to /sbin/init
f7073b99 593 # assume non-systemd init will run with unified cgroupv2
917f7ae3 594 if (!defined($init) || $init !~ m@/systemd$@) {
f7073b99
SI
595 return 1;
596 }
597
598 # systemd version 232 (e.g. debian stretch) supports the unified hierarchy
917f7ae3 599 my $sdver = $self->get_systemd_version($init);
f7073b99
SI
600 if (!defined($sdver) || $sdver < 232) {
601 return 0;
602 }
603
917f7ae3 604 return 1;
f7073b99
SI
605}
606
6e8457d5
TL
607sub get_ct_init_path {
608 my ($self) = @_;
609
610 my $init_path = "/sbin/init";
611 if ($self->ct_is_symlink($init_path)) {
612 $init_path = $self->ct_readlink_recursive($init_path);
613 }
614 return $init_path;
615}
616
bc5b7618
TL
617sub ssh_host_key_types_to_generate {
618 my ($self) = @_;
619
620 return {
621 rsa => 'ssh_host_rsa_key',
622 dsa => 'ssh_host_dsa_key',
623 ecdsa => 'ssh_host_ecdsa_key',
624 ed25519 => 'ssh_host_ed25519_key',
625 };
626}
627
1de92199
CH
628sub detect_architecture {
629 my ($self) = @_;
630
631 # '/bin/sh' is POSIX mandatory
632 return PVE::LXC::Tools::detect_elf_architecture('/bin/sh');
633}
634
d66768a2 635sub pre_start_hook {
633a7bd8 636 my ($self, $conf) = @_;
d66768a2 637
33b53903
TL
638 $self->ct_file_set_contents('/fastboot', ''); # skips fsck, among other things
639
633a7bd8
DM
640 $self->setup_init($conf);
641 $self->setup_network($conf);
642 $self->set_hostname($conf);
643 $self->set_dns($conf);
e6e308ae 644 $self->set_timezone($conf);
d66768a2
DM
645
646 # fixme: what else ?
647}
648
64d4c144
OB
649sub post_clone_hook {
650 my ($self, $conf) = @_;
651
652 $self->clear_machine_id($conf, 1);
653}
654
d66768a2 655sub post_create_hook {
f36ce482 656 my ($self, $conf, $root_password, $ssh_keys) = @_;
d66768a2 657
64d4c144 658 $self->clear_machine_id($conf);
142444d5 659 $self->template_fixup($conf);
e6e308ae 660
4727bd09 661 &$randomize_crontab($self, $conf);
e6e308ae 662
633a7bd8 663 $self->set_user_password($conf, 'root', $root_password);
f36ce482 664 $self->set_user_authorized_ssh_keys($conf, 'root', $ssh_keys) if $ssh_keys;
633a7bd8
DM
665 $self->setup_init($conf);
666 $self->setup_network($conf);
667 $self->set_hostname($conf);
668 $self->set_dns($conf);
e6e308ae
OB
669 $self->set_timezone($conf);
670
55fa4e09 671 # fixme: what else ?
1c7f4f65
DM
672}
673
f08b2779 674# File access wrappers for container setup code.
4526287a 675# NOTE: those are not direct part of the Plugin API (yet), avoid using them outside the child plugins
f08b2779
WB
676# For user-namespace support these might need to take uid and gid maps into account.
677
bd1dc8d1
WB
678sub ct_is_file_ignored {
679 my ($self, $file) = @_;
680 my ($name, $path) = fileparse($file);
681 return -f "$path/.pve-ignore.$name";
682}
683
c6a605f9
WB
684sub ct_reset_ownership {
685 my ($self, @files) = @_;
686 my $conf = $self->{conf};
687 return if !$self->{id_map};
bd1dc8d1
WB
688
689 @files = grep { !$self->ct_is_file_ignored($_) } @files;
690 return if !@files;
691
eda68a08
TL
692 my $uid = $self->{root_uid};
693 my $gid = $self->{root_gid};
c6a605f9
WB
694 chown($uid, $gid, @files);
695}
696
2063d380
WB
697sub ct_mkdir {
698 my ($self, $file, $mask) = @_;
f08b2779 699 # mkdir goes by parameter count - an `undef' mode acts like a mode of 0000
c6a605f9
WB
700 if (defined($mask)) {
701 return CORE::mkdir($file, $mask) && $self->ct_reset_ownership($file);
702 } else {
703 return CORE::mkdir($file) && $self->ct_reset_ownership($file);
704 }
2063d380
WB
705}
706
707sub ct_unlink {
f08b2779
WB
708 my ($self, @files) = @_;
709 foreach my $file (@files) {
bd1dc8d1 710 next if $self->ct_is_file_ignored($file);
f08b2779
WB
711 CORE::unlink($file);
712 }
713}
714
715sub ct_rename {
716 my ($self, $old, $new) = @_;
bd1dc8d1 717 return if $self->ct_is_file_ignored($new);
f08b2779 718 CORE::rename($old, $new);
2063d380
WB
719}
720
f08b2779 721sub ct_open_file_read {
2063d380 722 my $self = shift;
f08b2779
WB
723 my $file = shift;
724 return IO::File->new($file, O_RDONLY, @_);
2063d380
WB
725}
726
f08b2779 727sub ct_open_file_write {
2063d380 728 my $self = shift;
f08b2779 729 my $file = shift;
bd1dc8d1 730 $file = '/dev/null' if $self->ct_is_file_ignored($file);
c6a605f9
WB
731 my $fh = IO::File->new($file, O_WRONLY | O_CREAT, @_);
732 $self->ct_reset_ownership($fh);
733 return $fh;
2063d380
WB
734}
735
f08b2779 736sub ct_make_path {
2063d380 737 my $self = shift;
464452c0
FG
738
739 my $opts = {};
740 if (defined($self->{id_map})) {
eda68a08
TL
741 $opts->{owner} = $self->{root_uid};
742 $opts->{group} = $self->{root_gid};
c6a605f9 743 }
464452c0 744 File::Path::make_path(@_, $opts);
2063d380
WB
745}
746
747sub ct_symlink {
748 my ($self, $old, $new) = @_;
bd1dc8d1 749 return if $self->ct_is_file_ignored($new);
464452c0
FG
750 if (CORE::symlink($old, $new)) {
751 if (defined($self->{id_map})) {
eda68a08 752 POSIX::lchown($self->{root_uid}, $self->{root_gid}, $new);
464452c0
FG
753 }
754 return 1;
755 } else {
756 return 0;
757 }
2063d380
WB
758}
759
8f115f7c
WB
760sub ct_readlink {
761 my ($self, $name) = @_;
762 return CORE::readlink($name);
763}
764
41835686
TL
765sub ct_readlink_recursive {
766 my ($self, $name) = @_;
767
768 my $res = $name;
769 for (my $i = 0; $self->ct_is_symlink($res); $i++) {
770 # arbitrary limit, but should be enough for all for our management relevant things
771 die "maximal link depth of 10 for resolving '$name' reached, abort\n" if $i >= 10;
772 $res = $self->ct_readlink($res);
773 $res = abs_path($res);
774 }
775 return $res;
776}
777
2063d380
WB
778sub ct_file_exists {
779 my ($self, $file) = @_;
f08b2779
WB
780 return -f $file;
781}
782
783sub ct_is_directory {
784 my ($self, $file) = @_;
785 return -d $file;
786}
787
788sub ct_is_symlink {
789 my ($self, $file) = @_;
790 return -l $file;
791}
792
e7deac01
WB
793sub ct_is_executable {
794 my ($self, $file) = @_;
795 return -x $file
796}
797
f08b2779
WB
798sub ct_stat {
799 my ($self, $file) = @_;
800 return File::stat::stat($file);
2063d380
WB
801}
802
803sub ct_file_read_firstline {
804 my ($self, $file) = @_;
f08b2779 805 return PVE::Tools::file_read_firstline($file);
2063d380
WB
806}
807
808sub ct_file_get_contents {
809 my ($self, $file) = @_;
f08b2779 810 return PVE::Tools::file_get_contents($file);
2063d380
WB
811}
812
813sub ct_file_set_contents {
39243220 814 my ($self, $file, $data, $perms) = @_;
bd1dc8d1 815 return if $self->ct_is_file_ignored($file);
c6a605f9
WB
816 PVE::Tools::file_set_contents($file, $data, $perms);
817 $self->ct_reset_ownership($file);
2063d380
WB
818}
819
2edb50e5
WB
820# Modify a marked portion of a file.
821# Optionally if the file becomes empty it will be deleted.
822sub ct_modify_file {
823 my ($self, $file, $data, %options) = @_;
bd1dc8d1 824 return if $self->ct_is_file_ignored($file);
2edb50e5
WB
825
826 my $head = "# --- BEGIN PVE ---\n";
827 my $tail = "# --- END PVE ---\n";
be7ee97a 828 my $perms = $options{perms};
a5a4b5aa 829 $data .= "\n" if $data && $data !~ /\n$/;
2edb50e5
WB
830
831 if (!$self->ct_file_exists($file)) {
be7ee97a 832 $self->ct_file_set_contents($file, $head.$data.$tail, $perms) if $data;
2edb50e5
WB
833 return;
834 }
835
836 my $old = $self->ct_file_get_contents($file);
837 my @lines = split(/\n/, $old);
838
839 my ($beg, $end);
840 foreach my $i (0..(@lines-1)) {
841 my $line = $lines[$i];
842 $beg = $i if !defined($beg) &&
843 $line =~ /^#\s*---\s*BEGIN\s*PVE\s*/;
844 $end = $i if !defined($end) && defined($beg) &&
845 $line =~ /^#\s*---\s*END\s*PVE\s*/i;
846 last if defined($beg) && defined($end);
847 }
848
849 if (defined($beg) && defined($end)) {
850 # Found a section
851 if ($data) {
852 chomp $tail;
853 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
fa7cb12b 854 } else {
2edb50e5
WB
855 if ($beg == 0 && $end == (@lines-1)) {
856 $self->ct_unlink($file) if $options{delete};
857 return;
858 }
859 splice @lines, $beg, $end-$beg+1, $head.$data.$tail;
860 }
861 $self->ct_file_set_contents($file, join("\n", @lines) . "\n");
862 } elsif ($data) {
863 # No section found
864 my $content = join("\n", @lines);
865 chomp $content;
866 if (!$content && !$data && $options{delete}) {
fa7cb12b 867 $self->ct_unlink($file);
2edb50e5
WB
868 return;
869 }
870 $content .= "\n";
871 $data = $head.$data.$tail;
872 if ($options{replace}) {
be7ee97a 873 $self->ct_file_set_contents($file, $data, $perms);
2edb50e5 874 } elsif ($options{prepend}) {
be7ee97a 875 $self->ct_file_set_contents($file, $data . $content, $perms);
2edb50e5 876 } else { # append
be7ee97a 877 $self->ct_file_set_contents($file, $content . $data, $perms);
fa7cb12b 878 }
fa7cb12b
WB
879 }
880}
881
9096a91d
WB
882sub remove_pve_sections {
883 my ($data) = @_;
884
885 my $head = "# --- BEGIN PVE ---";
886 my $tail = "# --- END PVE ---";
887
888 # Remove the sections enclosed with the above headers and footers.
889 # from a line (^) starting with '\h*$head'
890 # to a line (the other ^) starting with '\h*$tail' up to including that
891 # line's end (.*?$).
892 return $data =~ s/^\h*\Q$head\E.*^\h*\Q$tail\E.*?$//rgms;
893}
894
8f56203b
SI
895# templates from images.linuxcontainers.org have a bogus LXC_NAME line in /etc/hosts
896sub remove_lxc_name_from_etc_hosts {
897 my ($self) = @_;
db95dea4
TL
898
899 return if ! -e '/etc/hosts';
900
8f56203b
SI
901 my $hosts = $self->ct_file_get_contents('/etc/hosts');
902 my @lines = grep { !/^127.0.1.1\s+LXC_NAME$/ } split(/\n/, $hosts);
903
904 $hosts = join("\n", @lines). "\n";
905
906 $self->ct_file_set_contents('/etc/hosts', $hosts);
907}
908
1c7f4f65 9091;