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