]> git.proxmox.com Git - dab.git/blob - DAB.pm
allow compressing final archive with zstd
[dab.git] / DAB.pm
1 package PVE::DAB;
2
3 use strict;
4 use warnings;
5 use IO::File;
6 use File::Path;
7 use File::Basename;
8 use IO::Select;
9 use IPC::Open2;
10 use IPC::Open3;
11 use POSIX qw (LONG_MAX);
12 use UUID;
13 use Cwd;
14
15 # fixme: lock container ?
16
17 my $dablibdir = "/usr/lib/dab";
18 my $devicetar = "$dablibdir/devices.tar.gz";
19 my $default_env = "$dablibdir/scripts/defenv";
20 my $fake_init = "$dablibdir/scripts/init.pl";
21 my $script_ssh_init = "$dablibdir/scripts/ssh_gen_host_keys";
22 my $script_mysql_randompw = "$dablibdir/scripts/mysql_randompw";
23 my $script_init_urandom = "$dablibdir/scripts/init_urandom";
24
25 my $postfix_main_cf = <<EOD;
26 # See /usr/share/postfix/main.cf.dist for a commented, more complete version
27
28 smtpd_banner = \$myhostname ESMTP \$mail_name (Debian/GNU)
29 biff = no
30
31 # appending .domain is the MUA's job.
32 append_dot_mydomain = no
33
34 # Uncomment the next line to generate "delayed mail" warnings
35 #delay_warning_time = 4h
36
37 alias_maps = hash:/etc/aliases
38 alias_database = hash:/etc/aliases
39 mydestination = \$myhostname, localhost.\$mydomain, localhost
40 relayhost =
41 mynetworks = 127.0.0.0/8
42 inet_interfaces = loopback-only
43 recipient_delimiter = +
44
45 compatibility_level = 2
46
47 EOD
48
49 # produce apt compatible filenames (/var/lib/apt/lists)
50 sub __url_to_filename {
51 my $url = shift;
52
53 $url =~ s|^\S+://||;
54 $url =~ s|_|%5f|g;
55 $url =~ s|/|_|g;
56
57 return $url;
58 }
59
60 # defaults:
61 # origin: debian
62 my $supported_suites = {
63 'bullseye' => {
64 ostype => "debian-11.0",
65 },
66 'buster' => {
67 ostype => "debian-10",
68 },
69 'stretch' => {
70 ostype => "debian-9.0",
71 },
72 'jessie' => {
73 ostype => "debian-8.0",
74 },
75 'wheezy' => {
76 ostype => "debian-7.0",
77 },
78 'squeeze' => {
79 ostype => "debian-6.0",
80 },
81 'lenny' => {
82 ostype => "debian-5.0",
83 },
84 'etch' => {
85 ostype => "debian-4.0",
86 },
87
88 # DEVUAN
89 'devuan-jessie' => {
90 suite => 'jessie',
91 ostype => "devuan-1.0",
92 },
93 'devuan-ascii' => {
94 suite => 'ascii',
95 ostype => "devuan-2.0",
96 },
97 'ascii' => {
98 ostype => "devuan-2.0",
99 },
100
101 # UBUNTU
102 'hardy' => {
103 ostype => "ubuntu-8.04",
104 origin => 'ubuntu',
105 },
106 'intrepid' => {
107 ostype => "ubuntu-8.10",
108 origin => 'ubuntu',
109 },
110 'jaunty' => {
111 ostype => "ubuntu-9.04",
112 origin => 'ubuntu',
113 },
114 'precise' => {
115 ostype => "ubuntu-12.04",
116 origin => 'ubuntu',
117 },
118 'trusty' => {
119 ostype => "ubuntu-14.04",
120 origin => 'ubuntu',
121 },
122 'vivid' => {
123 ostype => "ubuntu-15.04",
124 origin => 'ubuntu',
125 },
126 'wily' => {
127 ostype => "ubuntu-15.10",
128 origin => 'ubuntu',
129 },
130 'xenial' => {
131 ostype => "ubuntu-16.04",
132 origin => 'ubuntu',
133 },
134 'yakkety' => {
135 ostype => "ubuntu-16.10",
136 origin => 'ubuntu',
137 },
138 'zesty' => {
139 ostype => "ubuntu-17.04",
140 origin => 'ubuntu',
141 },
142 'artful' => {
143 ostype => "ubuntu-17.10",
144 origin => 'ubuntu',
145 },
146 'bionic' => {
147 ostype => "ubuntu-18.04",
148 origin => 'ubuntu',
149 },
150 'cosmic' => {
151 ostype => "ubuntu-18.10",
152 origin => 'ubuntu',
153 },
154 'disco' => {
155 ostype => "ubuntu-19.04",
156 origin => 'ubuntu',
157 },
158 'eoan' => {
159 ostype => "ubuntu-19.10",
160 origin => 'ubuntu',
161 },
162 'focal' => {
163 ostype => "ubuntu-20.04",
164 origin => 'ubuntu',
165 },
166 };
167
168 sub get_suite_info {
169 my ($suite) = @_;
170
171 my $suiteinfo = $supported_suites->{$suite} || die "unsupported suite '$suite'!\n";
172
173 # set defaults
174 $suiteinfo->{origin} //= 'debian';
175 $suiteinfo->{suite} //= $suite;
176
177 return $suiteinfo;
178 }
179
180 sub download {
181 my ($self, $url, $path) = @_;
182
183 $self->logmsg ("download: $url\n");
184 my $tmpfn = "$path.tmp$$";
185 eval {
186 $self->run_command ("wget -q '$url' -O '$tmpfn'");
187 };
188
189 my $err = $@;
190 if ($err) {
191 unlink $tmpfn;
192 die $err;
193 }
194
195 rename ($tmpfn, $path);
196 }
197
198 sub write_file {
199 my ($data, $file, $perm) = @_;
200
201 die "no filename" if !$file;
202
203 unlink $file;
204
205 my $fh = IO::File->new ($file, O_WRONLY | O_CREAT, $perm) ||
206 die "unable to open file '$file'";
207
208 print $fh $data;
209
210 $fh->close;
211 }
212
213 sub read_file {
214 my ($file) = @_;
215
216 die "no filename" if !$file;
217
218 my $fh = IO::File->new ($file) ||
219 die "unable to open file '$file'";
220
221 local $/; # slurp mode
222
223 my $data = <$fh>;
224
225 $fh->close;
226
227 return $data;
228 }
229
230 sub read_config {
231 my ($filename) = @_;
232
233 my $res = {};
234
235 my $fh = IO::File->new ("<$filename") || return $res;
236 my $rec = '';
237
238 while (defined (my $line = <$fh>)) {
239 next if $line =~ m/^\#/;
240 next if $line =~ m/^\s*$/;
241 $rec .= $line;
242 };
243
244 close ($fh);
245
246 chomp $rec;
247 $rec .= "\n";
248
249 while ($rec) {
250 if ($rec =~ s/^Description:\s*([^\n]*)(\n\s+.*)*$//si) {
251 $res->{headline} = $1;
252 chomp $res->{headline};
253 my $long = $2;
254 $long =~ s/^\s+/ /;
255 $res->{description} = $long;
256 chomp $res->{description};
257 } elsif ($rec =~ s/^([^:]+):\s*(.*\S)\s*\n//) {
258 my ($key, $value) = (lc ($1), $2);
259 if ($key eq 'source' || $key eq 'mirror') {
260 push @{$res->{$key}}, $value;
261 } else {
262 die "duplicate key '$key'\n" if defined ($res->{$key});
263 $res->{$key} = $value;
264 }
265 } else {
266 die "unable to parse config file: $rec";
267 }
268 }
269
270 die "unable to parse config file" if $rec;
271
272 return $res;
273 }
274
275 sub run_command {
276 my ($self, $cmd, $input, $getoutput) = @_;
277
278 my $reader = IO::File->new();
279 my $writer = IO::File->new();
280 my $error = IO::File->new();
281
282 my $orig_pid = $$;
283
284 my $cmdstr = ref ($cmd) eq 'ARRAY' ? join (' ', @$cmd) : $cmd;
285
286 my $pid;
287 eval {
288 if (ref ($cmd) eq 'ARRAY') {
289 $pid = open3 ($writer, $reader, $error, @$cmd) || die $!;
290 } else {
291 $pid = open3 ($writer, $reader, $error, $cmdstr) || die $!;
292 }
293 };
294
295 my $err = $@;
296
297 # catch exec errors
298 if ($orig_pid != $$) {
299 $self->logmsg ("ERROR: command '$cmdstr' failed - fork failed\n");
300 POSIX::_exit (1);
301 kill ('KILL', $$);
302 }
303
304 die $err if $err;
305
306 print $writer $input if defined $input;
307 close $writer;
308
309 my $select = new IO::Select;
310 $select->add ($reader);
311 $select->add ($error);
312
313 my $res = '';
314 my $logfd = $self->{logfd};
315
316 while ($select->count) {
317 my @handles = $select->can_read ();
318
319 foreach my $h (@handles) {
320 my $buf = '';
321 my $count = sysread ($h, $buf, 4096);
322 if (!defined ($count)) {
323 waitpid ($pid, 0);
324 die "command '$cmdstr' failed: $!";
325 }
326 $select->remove ($h) if !$count;
327
328 print $logfd $buf;
329
330 $res .= $buf if $getoutput;
331 }
332 }
333
334 waitpid ($pid, 0);
335 my $ec = ($? >> 8);
336
337 die "command '$cmdstr' failed with exit code $ec\n" if $ec;
338
339 return $res;
340 }
341
342 sub logmsg {
343 my $self = shift;
344 print STDERR @_;
345 $self->writelog (@_);
346 }
347
348 sub writelog {
349 my $self = shift;
350 my $fd = $self->{logfd};
351 print $fd @_;
352 }
353
354 sub __sample_config {
355 my ($self) = @_;
356
357 my $data = '';
358 my $arch = $self->{config}->{architecture};
359
360 my $ostype = $self->{config}->{ostype};
361
362 if ($ostype =~ m/^de(bi|vu)an-/) {
363 $data .= "lxc.include = /usr/share/lxc/config/debian.common.conf\n";
364 } elsif ($ostype =~ m/^ubuntu-/) {
365 $data .= "lxc.include = /usr/share/lxc/config/ubuntu.common.conf\n";
366 } else {
367 die "unknown os type '$ostype'\n";
368 }
369 $data .= "lxc.uts.name = localhost\n";
370 $data .= "lxc.rootfs.path = $self->{rootfs}\n";
371
372 return $data;
373 }
374
375 sub __allocate_ve {
376 my ($self) = @_;
377
378 my $cid;
379 if (my $fd = IO::File->new (".veid")) {
380 $cid = <$fd>;
381 chomp $cid;
382 close ($fd);
383 }
384
385
386 $self->{working_dir} = getcwd;
387 $self->{veconffile} = "$self->{working_dir}/config";
388 $self->{rootfs} = "$self->{working_dir}/rootfs";
389
390 if ($cid) {
391 $self->{veid} = $cid;
392 return $cid;
393 }
394
395 my $uuid;
396 my $uuid_str;
397 UUID::generate($uuid);
398 UUID::unparse($uuid, $uuid_str);
399 $self->{veid} = $uuid_str;
400
401 my $fd = IO::File->new (">.veid") ||
402 die "unable to write '.veid'\n";
403 print $fd "$self->{veid}\n";
404 close ($fd);
405
406 my $cdata = $self->__sample_config();
407
408 my $fh = IO::File->new ($self->{veconffile}, O_WRONLY|O_CREAT|O_EXCL) ||
409 die "unable to write lxc config file '$self->{veconffile}' - $!";
410 print $fh $cdata;
411 close ($fh);
412
413 mkdir $self->{rootfs} || die "unable to create rootfs - $!";
414
415 $self->logmsg ("allocated VE $self->{veid}\n");
416
417 return $self->{veid};
418 }
419
420 sub new {
421 my ($class, $config) = @_;
422
423 $class = ref ($class) || $class;
424
425 my $self = {};
426
427 $config = read_config ('dab.conf') if !$config;
428
429 $self->{config} = $config;
430
431 bless $self, $class;
432
433 $self->{logfile} = "logfile";
434 $self->{logfd} = IO::File->new (">>$self->{logfile}") ||
435 die "unable to open log file";
436
437 my $arch = $config->{architecture};
438 die "no 'architecture' specified\n" if !$arch;
439
440 die "unsupported architecture '$arch'\n"
441 if $arch !~ m/^(i386|amd64)$/;
442
443 my $suite = $config->{suite} || die "no 'suite' specified\n";
444
445 my $suiteinfo = get_suite_info($suite);
446 $suite = $suiteinfo->{suite};
447 $config->{ostype} = $suiteinfo->{ostype};
448
449 my $name = $config->{name} || die "no 'name' specified\n";
450
451 $name =~ m/^[a-z][0-9a-z\-\*\.]+$/ ||
452 die "illegal characters in name '$name'\n";
453
454 my $version = $config->{version};
455 die "no 'version' specified\n" if !$version;
456 die "no 'section' specified\n" if !$config->{section};
457 die "no 'description' specified\n" if !$config->{headline};
458 die "no 'maintainer' specified\n" if !$config->{maintainer};
459
460 if ($name =~ m/^$config->{ostype}/) {
461 $self->{targetname} = "${name}_${version}_$config->{architecture}";
462 } else {
463 $self->{targetname} = "$config->{ostype}-${name}_" .
464 "${version}_$config->{architecture}";
465 }
466
467 if (!$config->{source}) {
468 if (lc($suiteinfo->{origin}) eq 'debian') {
469 if ($suite eq 'etch' || $suite eq 'lenny') {
470 push @{$config->{source}}, (
471 'http://ftp.debian.org/debian SUITE main contrib',
472 'http://security.debian.org SUITE/updates main contrib',
473 );
474 } elsif ($suite eq 'bullseye') {
475 push @{$config->{source}}, (
476 "http://ftp.debian.org/debian SUITE main contrib",
477 "http://ftp.debian.org/debian SUITE-updates main contrib",
478 "http://security.debian.org SUITE-security main contrib",
479 );
480 } else {
481 push @{$config->{source}}, (
482 "http://ftp.debian.org/debian SUITE main contrib",
483 "http://ftp.debian.org/debian SUITE-updates main contrib",
484 "http://security.debian.org SUITE/updates main contrib",
485 );
486 }
487 } elsif (lc($suiteinfo->{origin}) eq 'ubuntu') {
488 my $comp = "main restricted universe multiverse";
489 push @{$config->{source}}, (
490 "http://archive.ubuntu.com/ubuntu SUITE $comp",
491 "http://archive.ubuntu.com/ubuntu SUITE-updates $comp",
492 "http://archive.ubuntu.com/ubuntu SUITE-security $comp",
493 );
494 } else {
495 die "implement me";
496 }
497 }
498
499 my $sources = undef;
500
501 foreach my $s (@{$config->{source}}) {
502 if ($s =~ m@^\s*((http|ftp)://\S+)\s+(\S+)((\s+(\S+))+)$@) {
503 my ($url, $su, $components) = ($1, $3, $4);
504 $su =~ s/SUITE/$suite/;
505 $components =~ s/^\s+//;
506 $components =~ s/\s+$//;
507 my $ca;
508 foreach my $co (split (/\s+/, $components)) {
509 push @$ca, $co;
510 }
511 $ca = ['main'] if !$ca;
512
513 push @$sources, {
514 source => $url,
515 comp => $ca,
516 suite => $su,
517 };
518 } else {
519 die "syntax error in source spezification '$s'\n";
520 }
521 }
522
523 foreach my $m (@{$config->{mirror}}) {
524 if ($m =~ m@^\s*((http|ftp)://\S+)\s*=>\s*((http|ftp)://\S+)\s*$@) {
525 my ($ms, $md) = ($1, $3);
526 my $found;
527 foreach my $ss (@$sources) {
528 if ($ss->{source} eq $ms) {
529 $found = 1;
530 $ss->{mirror} = $md;
531 last;
532 }
533 }
534 die "unusable mirror $ms\n" if !$found;
535 } else {
536 die "syntax error in mirror spezification '$m'\n";
537 }
538 }
539
540 $self->{sources} = $sources;
541
542 $self->{infodir} = "info";
543
544 $self->__allocate_ve ();
545
546 $self->{cachedir} = ($config->{cachedir} || 'cache') . "/$suite";;
547
548 my $incl = [qw (less ssh openssh-server logrotate)];
549
550 my $excl = [qw (modutils reiserfsprogs ppp pppconfig pppoe
551 pppoeconf nfs-common mtools ntp)];
552
553 # ubuntu has too many dependencies on udev, so
554 # we cannot exclude it (instead we disable udevd)
555
556 if ($suite eq 'vivid' || $suite eq 'wily' || $suite eq 'xenial' ||
557 $suite eq 'yakkety' || $suite eq 'zesty' || $suite eq 'artful' ||
558 $suite eq 'bionic' || $suite eq 'cosmic' || $suite eq 'disco' ||
559 $suite eq 'eoan' || $suite eq 'focal') {
560 push @$incl, 'isc-dhcp-client';
561 push @$excl, qw(libmodule-build-perl);
562 } elsif ($suite eq 'trusty') {
563 push @$excl, qw(systemd systemd-services libpam-systemd libsystemd-daemon0 memtest86+);
564 } elsif ($suite eq 'precise') {
565 push @$excl, qw(systemd systemd-services libpam-systemd libsystemd-daemon0 memtest86+ ubuntu-standard);
566 } elsif ($suite eq 'hardy') {
567 push @$excl, qw(kbd);
568 push @$excl, qw(apparmor apparmor-utils ntfs-3g
569 friendly-recovery);
570 } elsif ($suite eq 'intrepid' || $suite eq 'jaunty') {
571 push @$excl, qw(apparmor apparmor-utils libapparmor1 libapparmor-perl
572 libntfs-3g28 ntfs-3g friendly-recovery);
573 } elsif ($suite eq 'jessie') {
574 push @$incl, 'sysvinit-core'; # avoid systemd and udev
575 push @$incl, 'libperl4-corelibs-perl'; # to make lsof happy
576 push @$excl, qw(systemd systemd-sysv udev module-init-tools pciutils hdparm
577 memtest86+ parted);
578 } elsif ($suite eq 'stretch' || $suite eq 'buster' || $suite eq 'bullseye') {
579 push @$excl, qw(module-init-tools pciutils hdparm
580 memtest86+ parted);
581 } else {
582 push @$excl, qw(udev module-init-tools pciutils hdparm
583 memtest86+ parted);
584 }
585
586 $self->{incl} = $incl;
587 $self->{excl} = $excl;
588
589 return $self;
590 }
591
592 sub initialize {
593 my ($self) = @_;
594
595 my $infodir = $self->{infodir};
596 my $arch = $self->{config}->{architecture};
597
598 rmtree $infodir;
599 mkpath $infodir;
600
601 # truncate log
602 my $logfd = $self->{logfd} = IO::File->new (">$self->{logfile}") ||
603 die "unable to open log file";
604
605 # FIXME: seems a bit like a hacky way??
606 my $COMPRESSOR = {
607 ext => 'gz',
608 decomp => 'gzip -d',
609 };
610 if ($self->{config}->{suite} eq 'bullseye') {
611 $COMPRESSOR = {
612 ext => 'xz',
613 decomp => 'xz -d',
614 };
615 }
616
617 foreach my $ss (@{$self->{sources}}) {
618 my $src = $ss->{mirror} || $ss->{source};
619 my $path = "dists/$ss->{suite}/Release";
620 my $url = "$src/$path";
621 my $target = __url_to_filename ("$ss->{source}/$path");
622 eval {
623 $self->download ($url, "$infodir/$target");
624 $self->download ("$url.gpg", "$infodir/$target.gpg");
625 # fixme: impl. verify (needs --keyring option)
626 };
627 if (my $err = $@) {
628 print $logfd $@;
629 warn "Release info ignored\n";
630 };
631
632 foreach my $comp (@{$ss->{comp}}) {
633 $path = "dists/$ss->{suite}/$comp/binary-$arch/Packages.$COMPRESSOR->{ext}";
634 $target = "$infodir/" . __url_to_filename ("$ss->{source}/$path");
635 my $pkgsrc = "$src/$path";
636 $self->download ($pkgsrc, $target);
637 $self->run_command ("$COMPRESSOR->{decomp} '$target'");
638 }
639 }
640 }
641
642 sub write_config {
643 my ($self, $filename, $size) = @_;
644
645 my $config = $self->{config};
646
647 my $data = '';
648
649 $data .= "Name: $config->{name}\n";
650 $data .= "Version: $config->{version}\n";
651 $data .= "Type: lxc\n";
652 $data .= "OS: $config->{ostype}\n";
653 $data .= "Section: $config->{section}\n";
654 $data .= "Maintainer: $config->{maintainer}\n";
655 $data .= "Architecture: $config->{architecture}\n";
656 $data .= "Installed-Size: $size\n";
657
658 # optional
659 $data .= "Infopage: $config->{infopage}\n" if $config->{infopage};
660 $data .= "ManageUrl: $config->{manageurl}\n" if $config->{manageurl};
661 $data .= "Certified: $config->{certified}\n" if $config->{certified};
662
663 # description
664 $data .= "Description: $config->{headline}\n";
665 $data .= "$config->{description}\n" if $config->{description};
666
667 write_file ($data, $filename, 0644);
668 }
669
670 sub finalize {
671 my ($self, $opts) = @_;
672
673 my $suite = $self->{config}->{suite};
674 my $infodir = $self->{infodir};
675 my $arch = $self->{config}->{architecture};
676
677 my $instpkgs = $self->read_installed ();
678 my $pkginfo = $self->pkginfo();
679 my $veid = $self->{veid};
680 my $conffile = $self->{veconffile};
681 my $rootdir = $self->{rootfs};
682
683 my $vestat = $self->ve_status();
684 die "ve not running - unable to finalize\n" if !$vestat->{running};
685
686 # cleanup mysqld
687 if (-f "$rootdir/etc/init.d/mysql") {
688 $self->ve_command ("/etc/init.d/mysql stop");
689 }
690
691 if (!($opts->{keepmycnf} || (-f "$rootdir/etc/init.d/mysql_randompw"))) {
692 unlink "$rootdir/root/.my.cnf";
693 }
694
695 if ($suite eq 'etch') {
696 # enable apache2 startup
697 if ($instpkgs->{apache2}) {
698 write_file ("NO_START=0\n", "$rootdir/etc/default/apache2");
699 } else {
700 unlink "$rootdir/etc/default/apache2";
701 }
702 }
703 $self->logmsg ("cleanup package status\n");
704 # prevent auto selection of all standard, required or important
705 # packages which are not installed
706 foreach my $pkg (keys %$pkginfo) {
707 my $pri = $pkginfo->{$pkg}->{priority};
708 if ($pri && ($pri eq 'required' || $pri eq 'important'
709 || $pri eq 'standard')) {
710 if (!$instpkgs->{$pkg}) {
711 $self->ve_dpkg_set_selection ($pkg, 'purge');
712 }
713 }
714 }
715
716 $self->ve_command ("apt-get clean");
717
718 $self->logmsg ("update available package list\n");
719
720 $self->ve_command ("dpkg --clear-avail");
721 foreach my $ss (@{$self->{sources}}) {
722 my $relsrc = __url_to_filename ("$ss->{source}/dists/$ss->{suite}/Release");
723 if (-f "$infodir/$relsrc" && -f "$infodir/$relsrc.gpg") {
724 $self->run_command ("cp '$infodir/$relsrc' '$rootdir/var/lib/apt/lists/$relsrc'");
725 $self->run_command ("cp '$infodir/$relsrc.gpg' '$rootdir/var/lib/apt/lists/$relsrc.gpg'");
726 }
727 foreach my $comp (@{$ss->{comp}}) {
728 my $src = __url_to_filename ("$ss->{source}/dists/$ss->{suite}/" .
729 "$comp/binary-$arch/Packages");
730 my $target = "/var/lib/apt/lists/$src";
731 $self->run_command ("cp '$infodir/$src' '$rootdir/$target'");
732 $self->ve_command ("dpkg --merge-avail '$target'");
733 }
734 }
735
736 # set dselect default method
737 write_file ("apt apt\n", "$rootdir/var/lib/dpkg/cmethopt");
738
739 $self->ve_divert_remove ("/usr/sbin/policy-rc.d");
740
741 $self->ve_divert_remove ("/sbin/start-stop-daemon");
742
743 $self->ve_divert_remove ("/sbin/init");
744
745 # finally stop the VE
746 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
747
748 unlink "$rootdir/sbin/defenv";
749
750 unlink <$rootdir/root/dead.letter*>;
751
752 unlink "$rootdir/var/log/init.log";
753
754 unlink "$rootdir/aquota.group";
755
756 unlink "$rootdir/aquota.user";
757
758 write_file ("", "$rootdir/var/log/syslog");
759
760 my $get_path_size = sub {
761 my ($path) = @_;
762 my $sizestr = $self->run_command ("du -sm $path", undef, 1);
763 if ($sizestr =~ m/^(\d+)\s+\Q$path\E$/) {
764 return int($1);
765 } else {
766 die "unable to detect size for '$path'\n";
767 }
768 };
769
770 $self->logmsg ("detecting final appliance size: ");
771 my $size = $get_path_size->($rootdir);
772 $self->logmsg ("$size MB\n");
773
774 $self->write_config ("$rootdir/etc/appliance.info", $size);
775
776 $self->logmsg ("creating final appliance archive\n");
777
778 my $target = "$self->{targetname}.tar";
779
780 my $compressor = $opts->{compressor} // 'gz';
781 my $compressor2cmd_map = {
782 gz => 'gzip',
783 zst => 'zstd',
784 };
785 my $compressor_cmd = $compressor2cmd_map->{$compressor};
786 die "unkown compressor '$compressor', use one of: ". join(', ', sort keys %$compressor2cmd_map)
787 if !defined($compressor_cmd);
788
789 my $final_archive = "${target}.${compressor}";
790 unlink $target;
791 unlink $final_archive;
792
793 $self->run_command ("tar cpf $target --numeric-owner -C '$rootdir' ./etc/appliance.info");
794 $self->run_command ("tar rpf $target --numeric-owner -C '$rootdir' --exclude ./etc/appliance.info .");
795 $self->run_command ("$compressor_cmd $target");
796
797 $self->logmsg ("detecting final commpressed appliance size: ");
798 $size = $get_path_size->($final_archive);
799 $self->logmsg ("$size MB\n");
800
801 $self->logmsg ("appliance archive: $final_archive\n");
802 }
803
804 sub read_installed {
805 my ($self) = @_;
806
807 my $rootdir = $self->{rootfs};
808
809 my $pkgfilelist = "$rootdir/var/lib/dpkg/status";
810 local $/ = '';
811 open (PKGLST, "<$pkgfilelist") ||
812 die "unable to open '$pkgfilelist'";
813
814 my $pkglist = {};
815
816 while (my $rec = <PKGLST>) {
817 chomp $rec;
818 $rec =~ s/\n\s+/ /g;
819 $rec .= "\n";
820 my $res = {};
821
822 while ($rec =~ s/^([^:]+):\s+(.*)\s*\n//) {
823 $res->{lc $1} = $2;
824 }
825
826 my $pkg = $res->{'package'};
827 if (my $status = $res->{status}) {
828 my @sa = split (/\s+/, $status);
829 my $stat = $sa[0];
830 if ($stat && ($stat ne 'purge')) {
831 $pkglist->{$pkg} = $res;
832 }
833 }
834 }
835
836 close (PKGLST);
837
838 return $pkglist;
839 }
840
841 sub ve_status {
842 my ($self) = @_;
843
844 my $veid = $self->{veid};
845
846 my $res = { running => 0 };
847
848 $res->{exist} = 1 if -d "$self->{rootfs}/usr";
849
850 my $filename = "/proc/net/unix";
851
852 # similar test is used by lcxcontainers.c: list_active_containers
853 my $fh = IO::File->new ($filename, "r");
854 return $res if !$fh;
855
856 while (defined(my $line = <$fh>)) {
857 if ($line =~ m/^[a-f0-9]+:\s\S+\s\S+\s\S+\s\S+\s\S+\s\d+\s(\S+)$/) {
858 my $path = $1;
859 if ($path =~ m!^@/\S+/$veid/command$!) {
860 $res->{running} = 1;
861 }
862 }
863 }
864 close($fh);
865
866 return $res;
867 }
868
869 sub ve_command {
870 my ($self, $cmd, $input) = @_;
871
872 my $veid = $self->{veid};
873 my $conffile = $self->{veconffile};
874
875 if (ref ($cmd) eq 'ARRAY') {
876 unshift @$cmd, 'lxc-attach', '-n', $veid, '--rcfile', $conffile, '--clear-env', '--', 'defenv';
877 $self->run_command ($cmd, $input);
878 } else {
879 $self->run_command ("lxc-attach -n $veid --rcfile $conffile --clear-env -- defenv $cmd", $input);
880 }
881 }
882
883 # like ve_command, but pipes stdin correctly
884 sub ve_exec {
885 my ($self, @cmd) = @_;
886
887 my $veid = $self->{veid};
888 my $conffile = $self->{veconffile};
889
890 my $reader;
891 my $pid = open2($reader, "<&STDIN", 'lxc-attach', '-n', $veid, '--rcfile', $conffile, '--',
892 'defenv', @cmd) || die "unable to exec command";
893
894 while (defined (my $line = <$reader>)) {
895 $self->logmsg ($line);
896 }
897
898 waitpid ($pid, 0);
899 my $rc = $? >> 8;
900
901 die "ve_exec failed - status $rc\n" if $rc != 0;
902 }
903
904 sub ve_divert_add {
905 my ($self, $filename) = @_;
906
907 $self->ve_command ("dpkg-divert --add --divert '$filename.distrib' " .
908 "--rename '$filename'");
909 }
910 sub ve_divert_remove {
911 my ($self, $filename) = @_;
912
913 my $rootdir = $self->{rootfs};
914
915 unlink "$rootdir/$filename";
916 $self->ve_command ("dpkg-divert --remove --rename '$filename'");
917 }
918
919 sub ve_debconfig_set {
920 my ($self, $dcdata) = @_;
921
922 my $rootdir = $self->{rootfs};
923 my $cfgfile = "/tmp/debconf.txt";
924 write_file ($dcdata, "$rootdir/$cfgfile");
925 $self->ve_command ("debconf-set-selections $cfgfile");
926 unlink "$rootdir/$cfgfile";
927 }
928
929 sub ve_dpkg_set_selection {
930 my ($self, $pkg, $status) = @_;
931
932 $self->ve_command ("dpkg --set-selections", "$pkg $status");
933 }
934
935 sub ve_dpkg {
936 my ($self, $cmd, @pkglist) = @_;
937
938 return if !scalar (@pkglist);
939
940 my $pkginfo = $self->pkginfo();
941
942 my $rootdir = $self->{rootfs};
943 my $cachedir = $self->{cachedir};
944
945 my @files;
946
947 foreach my $pkg (@pkglist) {
948 my $filename = $self->getpkgfile ($pkg);
949 $self->run_command ("cp '$cachedir/$filename' '$rootdir/$filename'");
950 push @files, "/$filename";
951 $self->logmsg ("$cmd: $pkg\n");
952 }
953
954 my $fl = join (' ', @files);
955
956 if ($cmd eq 'install') {
957 $self->ve_command ("dpkg --force-depends --force-confold --install $fl");
958 } elsif ($cmd eq 'unpack') {
959 $self->ve_command ("dpkg --force-depends --unpack $fl");
960 } else {
961 die "internal error";
962 }
963
964 foreach my $fn (@files) { unlink "$rootdir$fn"; }
965 }
966
967 sub ve_destroy {
968 my ($self) = @_;
969
970 my $veid = $self->{veid}; # fixme
971 my $conffile = $self->{veconffile};
972
973 my $vestat = $self->ve_status();
974 if ($vestat->{running}) {
975 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
976 }
977
978 rmtree $self->{rootfs};
979 unlink $self->{veconffile};
980 }
981
982 sub ve_init {
983 my ($self) = @_;
984
985 my $veid = $self->{veid};
986 my $conffile = $self->{veconffile};
987
988 $self->logmsg ("initialize VE $veid\n");
989
990 my $vestat = $self->ve_status();
991 if ($vestat->{running}) {
992 $self->run_command ("lxc-stop -n $veid --rcfile $conffile --kill");
993 }
994
995 rmtree $self->{rootfs};
996 mkpath $self->{rootfs};
997 }
998
999 sub __deb_version_cmp {
1000 my ($cur, $op, $new) = @_;
1001
1002 if (system("dpkg", "--compare-versions", $cur, $op, $new) == 0) {
1003 return 1;
1004 }
1005
1006 return 0;
1007 }
1008
1009 sub __parse_packages {
1010 my ($pkginfo, $filename, $src) = @_;
1011
1012 local $/ = '';
1013 open (PKGLST, "<$filename") ||
1014 die "unable to open '$filename'";
1015
1016 while (my $rec = <PKGLST>) {
1017 $rec =~ s/\n\s+/ /g;
1018 chomp $rec;
1019 $rec .= "\n";
1020
1021 my $res = {};
1022
1023 while ($rec =~ s/^([^:]+):\s+(.*)\s*\n//) {
1024 $res->{lc $1} = $2;
1025 }
1026
1027 my $pkg = $res->{'package'};
1028 if ($pkg && $res->{'filename'}) {
1029 my $cur;
1030 if (my $info = $pkginfo->{$pkg}) {
1031 $cur = $info->{version};
1032 }
1033 my $new = $res->{version};
1034 if (!$cur || __deb_version_cmp ($cur, 'lt', $new)) {
1035 if ($src) {
1036 $res->{url} = "$src/$res->{'filename'}";
1037 } else {
1038 die "no url for package '$pkg'" if !$res->{url};
1039 }
1040 $pkginfo->{$pkg} = $res;
1041 }
1042 }
1043 }
1044
1045 close (PKGLST);
1046 }
1047
1048 sub pkginfo {
1049 my ($self) = @_;
1050
1051 return $self->{pkginfo} if $self->{pkginfo};
1052
1053 my $infodir = $self->{infodir};
1054 my $arch = $self->{config}->{architecture};
1055
1056 my $availfn = "$infodir/available";
1057
1058 my $pkginfo = {};
1059 my $pkgcount = 0;
1060
1061 # reading 'available' is faster, because it only contains latest version
1062 # (no need to do slow version compares)
1063 if (-f $availfn) {
1064 __parse_packages ($pkginfo, $availfn);
1065 $self->{pkginfo} = $pkginfo;
1066 return $pkginfo;
1067 }
1068
1069 $self->logmsg ("generating available package list\n");
1070
1071 foreach my $ss (@{$self->{sources}}) {
1072 foreach my $comp (@{$ss->{comp}}) {
1073 my $url = "$ss->{source}/dists/$ss->{suite}/$comp/binary-$arch/Packages";
1074 my $pkgfilelist = "$infodir/" . __url_to_filename ($url);
1075
1076 my $src = $ss->{mirror} || $ss->{source};
1077
1078 __parse_packages ($pkginfo, $pkgfilelist, $src);
1079 }
1080 }
1081
1082 if (my $dep = $self->{config}->{depends}) {
1083 foreach my $d (split (/,/, $dep)) {
1084 if ($d =~ m/^\s*(\S+)\s*(\((\S+)\s+(\S+)\)\s*)?$/) {
1085 my ($pkg, $op, $rver) = ($1, $3, $4);
1086 $self->logmsg ("checking dependencies: $d\n");
1087 my $info = $pkginfo->{$pkg};
1088 die "package '$pkg' not available\n" if !$info;
1089 if ($op) {
1090 my $cver = $info->{version};
1091 if (!__deb_version_cmp ($cver, $op, $rver)) {
1092 die "detected wrong version '$cver'\n";
1093 }
1094 }
1095 } else {
1096 die "syntax error in depends field";
1097 }
1098 }
1099 }
1100
1101 $self->{pkginfo} = $pkginfo;
1102
1103 my $tmpfn = "$availfn.tmp$$";
1104 my $fd = IO::File->new (">$tmpfn");
1105 foreach my $pkg (sort keys %$pkginfo) {
1106 my $info = $pkginfo->{$pkg};
1107 print $fd "package: $pkg\n";
1108 foreach my $k (sort keys %$info) {
1109 next if $k eq 'description';
1110 next if $k eq 'package';
1111 my $v = $info->{$k};
1112 print $fd "$k: $v\n" if $v;
1113 }
1114 print $fd "description: $info->{description}\n" if $info->{description};
1115 print $fd "\n";
1116 }
1117 close ($fd);
1118
1119 rename ($tmpfn, $availfn);
1120
1121 return $pkginfo;
1122 }
1123
1124 sub __record_provides {
1125 my ($pkginfo, $closure, $list, $skipself) = @_;
1126
1127 foreach my $pname (@$list) {
1128 my $info = $pkginfo->{$pname};
1129 # fixme: if someone install packages directly using dpkg, there
1130 # is no entry in 'available', only in 'status'. In that case, we
1131 # should extract info from $instpkgs
1132 if (!$info) {
1133 warn "hint: ignoring provides for '$pname' - package not in 'available' list.\n";
1134 next;
1135 }
1136 if (my $prov = $info->{provides}) {
1137 my @pl = split (',', $prov);
1138 foreach my $p (@pl) {
1139 $p =~ m/\s*(\S+)/;
1140 if (!($skipself && (grep { $1 eq $_ } @$list))) {
1141 $closure->{$1} = 1;
1142 }
1143 }
1144 }
1145 $closure->{$pname} = 1 if !$skipself;
1146 }
1147 }
1148
1149 sub closure {
1150 my ($self, $closure, $list) = @_;
1151
1152 my $pkginfo = $self->pkginfo();
1153
1154 # first, record provided packages
1155 __record_provides ($pkginfo, $closure, $list, 1);
1156
1157 my $pkghash = {};
1158 my $pkglist = [];
1159
1160 # then resolve dependencies
1161 foreach my $pname (@$list) {
1162 __closure_single ($pkginfo, $closure, $pkghash, $pkglist, $pname, $self->{excl});
1163 }
1164
1165 return $pkglist;
1166 }
1167
1168 sub __closure_single {
1169 my ($pkginfo, $closure, $pkghash, $pkglist, $pname, $excl) = @_;
1170
1171 $pname =~ s/^\s+//;
1172 $pname =~ s/\s+$//;
1173 $pname =~ s/:any$//;
1174
1175 return if $closure->{$pname};
1176
1177 my $info = $pkginfo->{$pname} || die "no such package '$pname'";
1178
1179 my $dep = $info->{depends};
1180 my $predep = $info->{'pre-depends'};
1181
1182 my $size = $info->{size};
1183 my $url = $info->{url};
1184
1185 $url || die "$pname: no url for package '$pname'";
1186
1187 if (!$pkghash->{$pname}) {
1188 unshift @$pkglist, $pname;
1189 $pkghash->{$pname} = 1;
1190 }
1191
1192 __record_provides ($pkginfo, $closure, [$pname]) if $info->{provides};
1193
1194 $closure->{$pname} = 1;
1195
1196 #print "$url\n";
1197
1198 my @l;
1199
1200 push @l, split (/,/, $predep) if $predep;
1201 push @l, split (/,/, $dep) if $dep;
1202
1203 DEPEND: foreach my $p (@l) {
1204 my @l1 = split (/\|/, $p);
1205 foreach my $p1 (@l1) {
1206 if ($p1 =~ m/^\s*(\S+).*/) {
1207 #printf (STDERR "$pname: $p --> $1\n");
1208 if ($closure->{$1}) {
1209 next DEPEND; # dependency already met
1210 }
1211 }
1212 }
1213 # search for non-excluded alternative
1214 my $found;
1215 foreach my $p1 (@l1) {
1216 if ($p1 =~ m/^\s*(\S+).*/) {
1217 next if grep { $1 eq $_ } @$excl;
1218 $found = $1;
1219 last;
1220 }
1221 }
1222 die "package '$pname' depends on exclusion '$p'\n" if !$found;
1223
1224 #printf (STDERR "$pname: $p --> $found\n");
1225
1226 __closure_single ($pkginfo, $closure, $pkghash, $pkglist, $found, $excl);
1227 }
1228 }
1229
1230 sub cache_packages {
1231 my ($self, $pkglist) = @_;
1232
1233 foreach my $pkg (@$pkglist) {
1234 $self->getpkgfile ($pkg);
1235 }
1236 }
1237
1238 sub getpkgfile {
1239 my ($self, $pkg) = @_;
1240
1241 my $pkginfo = $self->pkginfo();
1242 my $info = $pkginfo->{$pkg} || die "no such package '$pkg'";
1243 my $cachedir = $self->{cachedir};
1244
1245 my $url = $info->{url};
1246
1247 my $filename;
1248 if ($url =~ m|/([^/]+.deb)$|) {
1249 $filename = $1;
1250 } else {
1251 die "internal error";
1252 }
1253
1254 return $filename if -f "$cachedir/$filename";
1255
1256 mkpath $cachedir;
1257
1258 $self->download ($url, "$cachedir/$filename");
1259
1260 return $filename;
1261 }
1262
1263 sub install_init_script {
1264 my ($self, $script, $runlevel, $prio) = @_;
1265
1266 my $suite = $self->{config}->{suite};
1267 my $rootdir = $self->{rootfs};
1268
1269 my $base = basename ($script);
1270 my $target = "$rootdir/etc/init.d/$base";
1271
1272 $self->run_command ("install -m 0755 '$script' '$target'");
1273 if ($suite eq 'etch' || $suite eq 'lenny') {
1274 $self->ve_command ("update-rc.d $base start $prio $runlevel .");
1275 } elsif ($suite eq 'xenial' || $suite eq 'wily' || $suite eq 'vivid' ||
1276 $suite eq 'yakkety' || $suite eq 'zesty' || $suite eq 'artful' ||
1277 $suite eq 'bionic' || $suite eq 'cosmic' || $suite eq 'disco' ||
1278 $suite eq 'eoan' || $suite eq 'focal') {
1279 die "unable to install init script (system uses systemd)\n";
1280 } elsif ($suite eq 'trusty' || $suite eq 'precise') {
1281 die "unable to install init script (system uses upstart)\n";
1282 } else {
1283 $self->ve_command ("insserv $base");
1284 }
1285
1286 return $target;
1287 }
1288
1289 sub bootstrap {
1290 my ($self, $opts) = @_;
1291
1292 my $pkginfo = $self->pkginfo();
1293 my $veid = $self->{veid};
1294 my $suite = $self->{config}->{suite};
1295
1296 my $important = [ @{$self->{incl}} ];
1297 my $required;
1298 my $standard;
1299
1300 my $mta = $opts->{exim} ? 'exim' : 'postfix';
1301
1302 if ($mta eq 'postfix') {
1303 push @$important, "postfix";
1304 }
1305
1306 foreach my $p (sort keys %$pkginfo) {
1307 next if grep { $p eq $_ } @{$self->{excl}};
1308 my $pri = $pkginfo->{$p}->{priority};
1309 next if !$pri;
1310 next if $mta ne 'exim' && $p =~ m/exim/;
1311 next if $p =~ m/(selinux|semanage|policycoreutils)/;
1312
1313 push @$required, $p if $pri eq 'required';
1314 push @$important, $p if $pri eq 'important';
1315 push @$standard, $p if $pri eq 'standard' && !$opts->{minimal};
1316 }
1317
1318 my $closure = {};
1319 $required = $self->closure ($closure, $required);
1320 $important = $self->closure ($closure, $important);
1321
1322 if (!$opts->{minimal}) {
1323 push @$standard, 'xbase-clients';
1324 $standard = $self->closure ($closure, $standard);
1325 }
1326
1327 # test if we have all 'ubuntu-minimal' and 'ubuntu-standard' packages
1328 # except those explicitly excluded
1329 if ($suite eq 'hardy' || $suite eq 'intrepid' || $suite eq 'jaunty') {
1330 my $mdeps = $pkginfo->{'ubuntu-minimal'}->{depends};
1331 foreach my $d (split (/,/, $mdeps)) {
1332 if ($d =~ m/^\s*(\S+)$/) {
1333 my $pkg = $1;
1334 next if $closure->{$pkg};
1335 next if grep { $pkg eq $_ } @{$self->{excl}};
1336 die "missing ubuntu-minimal package '$pkg'\n";
1337 }
1338 }
1339 if (!$opts->{minimal}) {
1340 $mdeps = $pkginfo->{'ubuntu-standard'}->{depends};
1341 foreach my $d (split (/,/, $mdeps)) {
1342 if ($d =~ m/^\s*(\S+)$/) {
1343 my $pkg = $1;
1344 next if $closure->{$pkg};
1345 next if grep { $pkg eq $_ } @{$self->{excl}};
1346 die "missing ubuntu-standard package '$pkg'\n";
1347 }
1348 }
1349 }
1350 }
1351
1352 # download/cache all files first
1353 $self->cache_packages ($required);
1354 $self->cache_packages ($important);
1355 $self->cache_packages ($standard);
1356
1357 my $rootdir = $self->{rootfs};
1358
1359 # extract required packages first
1360 $self->logmsg ("create basic environment\n");
1361 foreach my $p (@$required) {
1362 my $filename = $self->getpkgfile ($p);
1363 my $content = $self->run_command("ar -t '$self->{cachedir}/$filename'", undef, 1);
1364 if ($content =~ m/^data.tar.xz$/m) {
1365 $self->run_command ("ar -p '$self->{cachedir}/$filename' data.tar.xz | tar -C '$rootdir' -xJf -");
1366 } else {
1367 $self->run_command ("ar -p '$self->{cachedir}/$filename' data.tar.gz | tar -C '$rootdir' -xzf -");
1368 }
1369 }
1370
1371 # fake dpkg status
1372 my $data = "Package: dpkg\n" .
1373 "Version: $pkginfo->{dpkg}->{version}\n" .
1374 "Status: install ok installed\n";
1375
1376 write_file ($data, "$rootdir/var/lib/dpkg/status");
1377 write_file ("", "$rootdir/var/lib/dpkg/info/dpkg.list");
1378 write_file ("", "$rootdir/var/lib/dpkg/available");
1379
1380 $data = '';
1381 foreach my $ss (@{$self->{sources}}) {
1382 my $url = $ss->{source};
1383 my $comp = join (' ', @{$ss->{comp}});
1384 $data .= "deb $url $ss->{suite} $comp\n\n";
1385 }
1386
1387 write_file ($data, "$rootdir/etc/apt/sources.list");
1388
1389 $data = "# UNCONFIGURED FSTAB FOR BASE SYSTEM\n";
1390 write_file ($data, "$rootdir/etc/fstab", 0644);
1391
1392 write_file ("localhost\n", "$rootdir/etc/hostname", 0644);
1393
1394 # avoid warnings about non-existent resolv.conf
1395 write_file ("", "$rootdir/etc/resolv.conf", 0644);
1396
1397 if ($suite eq 'focal' || $suite eq 'eoan' || $suite eq 'disco' || $suite eq 'cosmic' ||
1398 $suite eq 'bionic' || $suite eq 'artful' ||
1399 $suite eq 'zesty' || $suite eq 'yakkety' || $suite eq 'xenial' ||
1400 $suite eq 'wily') {
1401 # no need to configure loopback device
1402 } else {
1403 $data = "auto lo\niface lo inet loopback\n";
1404 mkdir "$rootdir/etc/network";
1405 write_file ($data, "$rootdir/etc/network/interfaces", 0644);
1406 }
1407
1408 # setup devices
1409 $self->run_command ("tar xzf '$devicetar' -C '$rootdir'");
1410
1411 # avoid warnings about missing default locale
1412 write_file ("LANG=\"C\"\n", "$rootdir/etc/default/locale", 0644);
1413
1414 # fake init
1415 rename ("$rootdir/sbin/init", "$rootdir/sbin/init.org");
1416 $self->run_command ("cp '$fake_init' '$rootdir/sbin/init'");
1417
1418 $self->run_command ("cp '$default_env' '$rootdir/sbin/defenv'");
1419
1420 $self->run_command ("lxc-start -n $veid -f $self->{veconffile}");
1421
1422 $self->logmsg ("initialize ld cache\n");
1423 $self->ve_command ("/sbin/ldconfig");
1424 $self->run_command ("ln -sf mawk '$rootdir/usr/bin/awk'");
1425
1426 $self->logmsg ("installing packages\n");
1427
1428 $self->ve_dpkg ('install', 'base-files', 'base-passwd');
1429
1430 $self->ve_dpkg ('install', 'dpkg');
1431
1432 $self->run_command ("ln -sf /usr/share/zoneinfo/UTC '$rootdir/etc/localtime'");
1433
1434 $self->run_command ("ln -sf bash '$rootdir/bin/sh'");
1435
1436 $self->ve_dpkg ('install', 'libc6');
1437 $self->ve_dpkg ('install', 'perl-base');
1438
1439 unlink "$rootdir/usr/bin/awk";
1440
1441 $self->ve_dpkg ('install', 'mawk');
1442 $self->ve_dpkg ('install', 'debconf');
1443
1444 # unpack required packages
1445 foreach my $p (@$required) {
1446 $self->ve_dpkg ('unpack', $p);
1447 }
1448
1449 rename ("$rootdir/sbin/init.org", "$rootdir/sbin/init");
1450 $self->ve_divert_add ("/sbin/init");
1451 $self->run_command ("cp '$fake_init' '$rootdir/sbin/init'");
1452
1453 # disable service activation
1454 $self->ve_divert_add ("/usr/sbin/policy-rc.d");
1455 $data = "#!/bin/sh\nexit 101\n";
1456 write_file ($data, "$rootdir/usr/sbin/policy-rc.d", 755);
1457
1458 # disable start-stop-daemon
1459 $self->ve_divert_add ("/sbin/start-stop-daemon");
1460 $data = <<EOD;
1461 #!/bin/sh
1462 echo
1463 echo \"Warning: Fake start-stop-daemon called, doing nothing\"
1464 EOD
1465 write_file ($data, "$rootdir/sbin/start-stop-daemon", 0755);
1466
1467 # disable udevd
1468 $self->ve_divert_add ("/sbin/udevd");
1469
1470 if ($suite eq 'etch') {
1471 # disable apache2 startup
1472 write_file ("NO_START=1\n", "$rootdir/etc/default/apache2");
1473 }
1474
1475 $self->logmsg ("configure required packages\n");
1476 $self->ve_command ("dpkg --force-confold --skip-same-version --configure -a");
1477
1478 # set postfix defaults
1479 if ($mta eq 'postfix') {
1480 $data = "postfix postfix/main_mailer_type select Local only\n";
1481 $self->ve_debconfig_set ($data);
1482
1483 $data = "postmaster: root\nwebmaster: root\n";
1484 write_file ($data, "$rootdir/etc/aliases");
1485 }
1486
1487 if ($suite eq 'jaunty') {
1488 # jaunty does not create /var/run/network, so network startup fails.
1489 # so we do not use tmpfs for /var/run and /var/lock
1490 $self->run_command ("sed -e 's/RAMRUN=yes/RAMRUN=no/' -e 's/RAMLOCK=yes/RAMLOCK=no/' -i $rootdir/etc/default/rcS");
1491 # and create the directory here
1492 $self->run_command ("mkdir $rootdir/var/run/network");
1493 }
1494
1495 # unpack base packages
1496 foreach my $p (@$important) {
1497 $self->ve_dpkg ('unpack', $p);
1498 }
1499
1500 # start loopback
1501 if (-x "$rootdir/sbin/ifconfig") {
1502 $self->ve_command ("ifconfig lo up");
1503 } else {
1504 $self->ve_command ("ip link set lo up");
1505 }
1506
1507 $self->logmsg ("configure important packages\n");
1508 $self->ve_command ("dpkg --force-confold --skip-same-version --configure -a");
1509
1510 if (-d "$rootdir/etc/event.d") {
1511 unlink <$rootdir/etc/event.d/tty*>;
1512 }
1513
1514 if (-f "$rootdir/etc/inittab") {
1515 $self->run_command ("sed -i -e '/getty\\s38400\\stty[23456]/d' '$rootdir/etc/inittab'");
1516 }
1517
1518 # Link /etc/mtab to /proc/mounts, so df and friends will work:
1519 unlink "$rootdir/etc/mtab";
1520 $self->ve_command ("ln -s /proc/mounts /etc/mtab");
1521
1522 # reset password
1523 $self->ve_command ("usermod -L root");
1524
1525 if ($mta eq 'postfix') {
1526 $data = "postfix postfix/main_mailer_type select No configuration\n";
1527 $self->ve_debconfig_set ($data);
1528
1529 unlink "$rootdir/etc/mailname";
1530 write_file ($postfix_main_cf, "$rootdir/etc/postfix/main.cf");
1531 }
1532
1533 if (!$opts->{minimal}) {
1534 # unpack standard packages
1535 foreach my $p (@$standard) {
1536 $self->ve_dpkg ('unpack', $p);
1537 }
1538
1539 $self->logmsg ("configure standard packages\n");
1540 $self->ve_command ("dpkg --force-confold --skip-same-version --configure -a");
1541 }
1542
1543 # disable HWCLOCK access
1544 $self->run_command ("echo 'HWCLOCKACCESS=no' >> '$rootdir/etc/default/rcS'");
1545
1546 # disable hald
1547 $self->ve_divert_add ("/usr/sbin/hald");
1548
1549 # disable /dev/urandom init
1550 $self->run_command ("install -m 0755 '$script_init_urandom' '$rootdir/etc/init.d/urandom'");
1551
1552 if ($suite eq 'etch' || $suite eq 'hardy' || $suite eq 'intrepid' || $suite eq 'jaunty') {
1553 # avoid klogd start
1554 $self->ve_divert_add ("/sbin/klogd");
1555 }
1556
1557 # remove unnecessays sysctl entries to avoid warnings
1558 my $cmd = 'sed';
1559 $cmd .= ' -e \'s/^\(kernel\.printk.*\)/#\1/\'';
1560 $cmd .= ' -e \'s/^\(kernel\.maps_protect.*\)/#\1/\'';
1561 $cmd .= ' -e \'s/^\(fs\.inotify\.max_user_watches.*\)/#\1/\'';
1562 $cmd .= ' -e \'s/^\(vm\.mmap_min_addr.*\)/#\1/\'';
1563 $cmd .= " -i '$rootdir/etc/sysctl.conf'";
1564 $self->run_command ($cmd);
1565
1566 my $bindv6only = "$rootdir/etc/sysctl.d/bindv6only.conf";
1567 if (-f $bindv6only) {
1568 $cmd = 'sed';
1569 $cmd .= ' -e \'s/^\(net\.ipv6\.bindv6only.*\)/#\1/\'';
1570 $cmd .= " -i '$bindv6only'";
1571 $self->run_command ($cmd);
1572 }
1573
1574 if ($suite eq 'hardy' || $suite eq 'intrepid' || $suite eq 'jaunty') {
1575 # disable tty init (console-setup)
1576 my $cmd = 'sed';
1577 $cmd .= ' -e \'s/^\(ACTIVE_CONSOLES=.*\)/ACTIVE_CONSOLES=/\'';
1578 $cmd .= " -i '$rootdir/etc/default/console-setup'";
1579 $self->run_command ($cmd);
1580 }
1581
1582 if ($suite eq 'intrepid' || $suite eq 'jaunty') {
1583 # remove sysctl setup (avoid warnings at startup)
1584 my $filelist = "$rootdir/etc/sysctl.d/10-console-messages.conf";
1585 $filelist .= " $rootdir/etc/sysctl.d/10-process-security.conf" if $suite eq 'intrepid';
1586 $filelist .= " $rootdir/etc/sysctl.d/10-network-security.conf";
1587 $self->run_command ("rm $filelist");
1588 }
1589
1590 if (-e "$rootdir/lib/systemd/system/sys-kernel-config.mount") {
1591 $self->ve_command ("ln -s /dev/null /etc/systemd/system/sys-kernel-debug.mount");
1592 }
1593 }
1594
1595 sub enter {
1596 my ($self) = @_;
1597
1598 my $veid = $self->{veid};
1599 my $conffile = $self->{veconffile};
1600
1601 my $vestat = $self->ve_status();
1602
1603 if (!$vestat->{exist}) {
1604 $self->logmsg ("Please create the appliance first (bootstrap)");
1605 return;
1606 }
1607
1608 if (!$vestat->{running}) {
1609 $self->run_command ("lxc-start -n $veid -f $conffile");
1610 }
1611
1612 system ("lxc-attach -n $veid --rcfile $conffile --clear-env");
1613 }
1614
1615 sub ve_mysql_command {
1616 my ($self, $sql, $password) = @_;
1617
1618 #my $bootstrap = "/usr/sbin/mysqld --bootstrap --user=mysql --skip-grant-tables " .
1619 #"--skip-bdb --skip-innodb --skip-ndbcluster";
1620
1621 $self->ve_command ("mysql", $sql);
1622 }
1623
1624 sub ve_mysql_bootstrap {
1625 my ($self, $sql, $password) = @_;
1626
1627 my $cmd;
1628
1629 my $suite = $self->{config}->{suite};
1630
1631 if ($suite eq 'jessie') {
1632 my $rootdir = $self->{rootfs};
1633 $self->run_command ("sed -e 's/^key_buffer\\s*=/key_buffer_size =/' -i $rootdir/etc/mysql/my.cnf");
1634 }
1635
1636 if ($suite eq 'squeeze' || $suite eq 'wheezy' || $suite eq 'jessie') {
1637 $cmd = "/usr/sbin/mysqld --bootstrap --user=mysql --skip-grant-tables";
1638
1639 } else {
1640 $cmd = "/usr/sbin/mysqld --bootstrap --user=mysql --skip-grant-tables " .
1641 "--skip-bdb --skip-innodb --skip-ndbcluster";
1642 }
1643
1644 $self->ve_command ($cmd, $sql);
1645 }
1646
1647 sub compute_required {
1648 my ($self, $pkglist) = @_;
1649
1650 my $pkginfo = $self->pkginfo();
1651 my $instpkgs = $self->read_installed ();
1652
1653 my $closure = {};
1654 __record_provides ($pkginfo, $closure, [keys %$instpkgs]);
1655
1656 return $self->closure ($closure, $pkglist);
1657 }
1658
1659 sub task_postgres {
1660 my ($self, $opts) = @_;
1661
1662 my @supp = ('7.4', '8.1');
1663 my $pgversion = '8.1';
1664
1665 my $suite = $self->{config}->{suite};
1666
1667 if ($suite eq 'lenny' || $suite eq 'hardy' || $suite eq 'intrepid' || $suite eq 'jaunty') {
1668 @supp = ('8.3');
1669 $pgversion = '8.3';
1670 } elsif ($suite eq 'squeeze') {
1671 @supp = ('8.4');
1672 $pgversion = '8.4';
1673 } elsif ($suite eq 'wheezy') {
1674 @supp = ('9.1');
1675 $pgversion = '9.1';
1676 } elsif ($suite eq 'jessie') {
1677 @supp = ('9.4');
1678 $pgversion = '9.4';
1679 } elsif ($suite eq 'stretch') {
1680 @supp = ('9.6');
1681 $pgversion = '9.6';
1682 } elsif ($suite eq 'buster') {
1683 @supp = ('11');
1684 $pgversion = '11';
1685 } elsif ($suite eq 'bullseye') {
1686 # FIXME update on freeze!
1687 @supp = ('12');
1688 $pgversion = '12';
1689 }
1690
1691 $pgversion = $opts->{version} if $opts->{version};
1692
1693 die "unsupported postgres version '$pgversion'\n"
1694 if !grep { $pgversion eq $_; } @supp;
1695
1696 my $rootdir = $self->{rootfs};
1697
1698 my $required = $self->compute_required (["postgresql-$pgversion"]);
1699
1700 $self->cache_packages ($required);
1701
1702 $self->ve_dpkg ('install', @$required);
1703
1704 my $iscript = "postgresql-$pgversion";
1705 if ($suite eq 'squeeze' || $suite eq 'wheezy' || $suite eq 'jessie' ||
1706 $suite eq 'stretch') {
1707 $iscript = 'postgresql';
1708 }
1709
1710 $self->ve_command ("/etc/init.d/$iscript start") if $opts->{start};
1711 }
1712
1713 sub task_mysql {
1714 my ($self, $opts) = @_;
1715
1716 my $password = $opts->{password};
1717 my $rootdir = $self->{rootfs};
1718
1719 my $suite = $self->{config}->{suite};
1720
1721 my $ver = '5.0';
1722 if ($suite eq 'squeeze') {
1723 $ver = '5.1';
1724 } elsif ($suite eq 'wheezy' || $suite eq 'jessie') {
1725 $ver = '5.5';
1726 } else {
1727 die "task_mysql: unsupported suite '$suite'";
1728 }
1729
1730 my $required = $self->compute_required (['mysql-common', "mysql-server-$ver"]);
1731
1732 $self->cache_packages ($required);
1733
1734 $self->ve_dpkg ('install', @$required);
1735
1736 # fix security (see /usr/bin/mysql_secure_installation)
1737 my $sql = "DELETE FROM mysql.user WHERE User='';\n" .
1738 "DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';\n" .
1739 "FLUSH PRIVILEGES;\n";
1740 $self->ve_mysql_bootstrap ($sql);
1741
1742 if ($password) {
1743
1744 my $rpw = $password eq 'random' ? 'admin' : $password;
1745
1746 my $sql = "USE mysql;\n" .
1747 "UPDATE user SET password=PASSWORD(\"$rpw\") WHERE user='root';\n" .
1748 "FLUSH PRIVILEGES;\n";
1749 $self->ve_mysql_bootstrap ($sql);
1750
1751 write_file ("[client]\nuser=root\npassword=\"$rpw\"\n", "$rootdir/root/.my.cnf", 0600);
1752 if ($password eq 'random') {
1753 $self->install_init_script ($script_mysql_randompw, 2, 20);
1754 }
1755 }
1756
1757 $self->ve_command ("/etc/init.d/mysql start") if $opts->{start};
1758 }
1759
1760 sub task_php {
1761 my ($self, $opts) = @_;
1762
1763 my $memlimit = $opts->{memlimit};
1764 my $rootdir = $self->{rootfs};
1765
1766 my $required = $self->compute_required ([qw (php5 php5-cli libapache2-mod-php5 php5-gd)]);
1767
1768 $self->cache_packages ($required);
1769
1770 $self->ve_dpkg ('install', @$required);
1771
1772 if ($memlimit) {
1773 $self->run_command ("sed -e 's/^\\s*memory_limit\\s*=.*;/memory_limit = ${memlimit}M;/' -i $rootdir/etc/php5/apache2/php.ini");
1774 }
1775 }
1776
1777 sub install {
1778 my ($self, $pkglist, $unpack) = @_;
1779
1780 my $required = $self->compute_required ($pkglist);
1781
1782 $self->cache_packages ($required);
1783
1784 $self->ve_dpkg ($unpack ? 'unpack' : 'install', @$required);
1785 }
1786
1787 sub cleanup {
1788 my ($self, $distclean) = @_;
1789
1790 unlink $self->{logfile};
1791 unlink "$self->{targetname}.tar";
1792 unlink "$self->{targetname}.tar.gz";
1793
1794 $self->ve_destroy ();
1795 unlink ".veid";
1796
1797 rmtree $self->{cachedir} if $distclean && !$self->{config}->{cachedir};
1798
1799 rmtree $self->{infodir};
1800
1801 }
1802
1803 1;