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