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