Debian Codegraph @

convert-usrmerge

raw
1 #!/usr/bin/perl
2 # vim: shiftwidth=4 tabstop=4
3 #
4 # Copyright 2014-2022 by Marco d'Itri <[email protected]>
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 use warnings;
12 use strict;
13 use autodie;
14 use v5.16;
15
16 use File::Find::Rule;
17 use Cwd qw(abs_path);
18 use Errno;
19
20 my $Debug = 0;
21 my $Program_RC = 0;
22 my $Is_Hurd = is_hurd();
23
24 # If a file exists both in / and /usr then ignore (delete) the one in /
25 # Justification for these entries:
26 # /lib/udev/hwdb.bin -> systemd-hwdb --usr update [LP: #1930573, Ubuntu-specific]
27 my %Ignore_In_Root = map { $_ => 1 } qw(
28 /lib/udev/hwdb.bin
29 );
30
31 $ENV{LC_ALL} = 'C';
32
33 check_free_space();
34
35 check_overlayfs();
36
37 check_uml();
38
39 go_faster();
40
41 # print the long error message if something fails due to autodie
42 $SIG{__DIE__} = sub { fatal($_[0]); };
43
44 {
45 foreach my $name (early_conversion_files()) {
46 next if $name =~ m#^/usr/#; # already converted
47 convert_file($name);
48 }
49
50 my @dirs = directories_to_merge();
51
52 # create any directory which is in / but not in /usr
53 umask(0022);
54 foreach my $dir (@dirs) {
55 next if -e "/usr$dir";
56 next if not -d $dir; # but only if it actually exists in /
57 mkdir("/usr$dir");
58 restore_context("/usr$dir");
59 }
60
61 my @later;
62 my $rule = File::Find::Rule->mindepth(1)->maxdepth(1)->start(@dirs);
63 while (defined (my $name = $rule->match)) {
64 convert_file($name, \@later);
65 }
66
67 # symlinks must be converted after the rest to avoid races, because
68 # they may point to binaries which have not been converted yet
69 if ($Is_Hurd) {
70 while (@later) {
71 my @newlater;
72 convert_file($_, \@newlater) foreach @later;
73 @later = @newlater;
74 }
75 } else {
76 convert_file($_) foreach @later;
77 }
78
79 verify_links_only($_) foreach @dirs;
80
81 convert_directory($_) foreach @dirs;
82
83 exit($Program_RC) if $Program_RC;
84 print "The system has been successfully converted.\n";
85 exit;
86 }
87
88 ##############################################################################
89 sub convert_file {
90 my ($n, $later) = @_;
91 print "==== $n ====\n" if $Debug;
92
93 # the source is a broken link
94 if (-l $n and not -e $n and -e "/usr$n") {
95 warn "WARNING: $n is a broken symlink and has been renamed!\n";
96 rename($n, "$n.usrmerge-broken");
97 return;
98 }
99
100 # the destination is a broken link
101 if (-l "/usr$n" and not -e "/usr$n") {
102 warn "WARNING: /usr$n is a broken symlink and has been renamed!\n";
103 rename("/usr$n", "/usr$n.usrmerge-broken");
104 # continue and move the source as usual
105 }
106
107 # is a directory and the destination does not exist
108 if (-d $n and not -e "/usr$n") {
109 mv($n, "/usr$n"); # XXX race
110 symlink("/usr$n", $n);
111 return;
112 }
113
114 # is a link and the destination does not exist, but defer the conversion
115 if (-l $n and not -e "/usr$n" and $later and not $Is_Hurd) {
116 push(@$later, $n);
117 return;
118 }
119
120 # the same, but only tested on Hurd systems (see #1020463 for details)
121 if (-l $n and not -e "/usr$n" and $later and $Is_Hurd) {
122 my $l = readlink($n);
123 my ($basedir) = $n =~ m#^(.+)/[^/]+$#;
124 if ($l !~ m#^/# and not -e "/usr$basedir/$l") {
125 fatal("Converted link /usr$n would point to non-existing"
126 . " /usr$basedir/$l but we are not deferring conversion")
127 if not $later;
128 push(@$later, $n);
129 return;
130 }
131 }
132
133 # is a file or link and the destination does not exist
134 if (not -e "/usr$n") {
135 cp($n, "/usr$n");
136 symlink("/usr$n", "$n~~tmp~usrmerge~~");
137 rename("$n~~tmp~usrmerge~~", $n);
138 # XXX alternative implementation:
139 #mv($n, "/usr$n"); # XXX race
140 #symlink("/usr$n", $n);
141 return;
142 }
143
144 # The other cases are more complex and there are some corner cases that
145 # we do not try to resolve automatically.
146
147 # both source and dest are links
148 if (-l $n and -l "/usr$n") {
149 my $l1 = readlink($n);
150 my $l2 = readlink("/usr$n");
151 my ($basedir) = $n =~ m#^(.+)/[^/]+$#;
152 return if $l1 eq $l2; # and they point to the same file
153 return if "$basedir/$l1" eq $l2; # same (the / link is relative)
154 return if $l1 eq "/usr$basedir/$l2";# same (the /usr link is relative)
155 return if $l1 eq "/usr$n"; # and the / link points to the /usr link
156 if ($l2 eq $n) { # and the /usr link points to the / link
157 # the target of the new link will be an absolute path, so it
158 # may be different from the original one even if both point to
159 # the same file
160 symlink(abs_path($n), "/usr$n~~tmp~usrmerge~~");
161 rename("/usr$n~~tmp~usrmerge~~", "/usr$n");
162 # convert the /bin link too to make the program idempotent
163 symlink(abs_path($n), "$n~~tmp~usrmerge~~");
164 rename("$n~~tmp~usrmerge~~", "$n");
165 return;
166 }
167 fatal("Both $n and /usr$n exist");
168 }
169
170 # the source is a link
171 if (-l $n) {
172 my $l = readlink($n);
173 return if $l eq "/usr$n"; # and it points to dest
174 fatal("Both $n and /usr$n exist");
175 }
176
177 # the destination is a link
178 if (-l "/usr$n") {
179 my $l = readlink("/usr$n");
180 if ($l eq $n) { # and it points to source
181 cp($n, "/usr$n~~tmp~usrmerge~~");
182 rename("/usr$n~~tmp~usrmerge~~", "/usr$n");
183 symlink("/usr$n", "$n~~tmp~usrmerge~~");
184 rename("$n~~tmp~usrmerge~~", $n);
185 # XXX alternative implementation:
186 #mv($n, "/usr$n"); # XXX race
187 #symlink("/usr$n", $n);
188 return;
189 }
190 fatal("Both $n and /usr$n exist");
191 }
192
193 # both source and dest are directories
194 # this is the second most common case
195 if (-d $n and -d "/usr$n") {
196 # so they have to be merged recursively
197 my $rule = File::Find::Rule->mindepth(1)->maxdepth(1)->start($n);
198 while (defined (my $name = $rule->match)) {
199 convert_file($name, $later);
200 }
201 return;
202 }
203
204 fatal("$n is a directory and /usr$n is not")
205 if -d $n and -e "/usr$n";
206 fatal("/usr$n is a directory and $n is not")
207 if -d "/usr$n";
208 if (-e "/usr$n" and exists $Ignore_In_Root{$n}) {
209 rm($n);
210 return;
211 }
212 fatal("Both $n and /usr$n exist")
213 if -e "/usr$n";
214
215 fatal("The status of $n and /usr$n is really unexpected");
216 }
217
218 ##############################################################################
219 # To prevent a failure later, the regular files of the libraries used by
220 # cp and mv must be converted before of the symlinks that point to them.
221 sub early_conversion_files {
222 no autodie qw(close);
223
224 my $bin_cp = '/bin/cp';
225 $bin_cp = '/usr/bin/cp' unless -x $bin_cp;
226 open(my $fh, '-|', "ldd $bin_cp");
227 my @ldd = <$fh>;
228 close $fh or fatal("Failed to execute 'ldd $bin_cp'");
229
230 # the libraries
231 my @list = grep { $_ } map { /^\s+\S+ => (\/\S+) / and $1 } @ldd;
232 # the dynamic linker
233 push(@list, grep { $_ } map { /^\s+(\/\S+) \(/ and $1 } @ldd);
234
235 # this is the equivalent of readlink --canonicalize
236 my @newlist;
237 foreach my $name (@list) {
238 my $newname = -l $name ? readlink($name) : $name;
239 if ($newname !~ m#^/#) {
240 my $dir = $name;
241 $dir =~ s#[^/]+$##;
242 $newname = $dir . $newname;
243 }
244 my $topdir = $newname;
245 $topdir =~ s#^(/[^/]+).*#$1#;
246 # this is needed to be idempotent after a complete conversion
247 next if -l $topdir;
248 push(@newlist, $newname);
249 }
250
251 return @newlist;
252 }
253
254 ##############################################################################
255 # Safety check: verify that there are no regular files in the directories
256 # that will be deleted by the final pass.
257 sub verify_links_only {
258 my ($dir) = @_;
259
260 my $link_or_dir = File::Find::Rule->or(
261 File::Find::Rule->symlink,
262 File::Find::Rule->directory,
263 );
264
265 my $rule = File::Find::Rule->mindepth(1)->not($link_or_dir)->start($dir);
266 while (defined (my $name = $rule->match)) {
267 print STDERR "$name is not a symlink!\n";
268 print STDERR "\nSafety check: the conversion has failed!\n";
269 exit 1;
270 }
271 }
272
273 sub convert_directory {
274 my ($dir) = @_;
275
276 return if -l $dir;
277
278 if (not -d $dir) {
279 # do not create a broken symlink to /usr$dir if it does not exist
280 return if not -e "usr$dir";
281 symlink("usr$dir", $dir);
282 restore_context($dir);
283 return;
284 }
285
286 no autodie;
287 if (not rename($dir, "$dir~~delete~usrmerge~~")) { # XXX race
288 if ($!{EBUSY}) {
289 handle_ebusy($dir);
290 return;
291 }
292 die "Can't rename $dir: $!";
293 }
294 use autodie;
295 symlink("usr$dir", $dir);
296 restore_context($dir);
297
298 rm('-rf', "$dir~~delete~usrmerge~~");
299 }
300
301 sub restore_context {
302 my ($file) = @_;
303
304 return if not (-x '/sbin/restorecon' or -x '/usr/sbin/restorecon');
305
306 safe_system('restorecon', $file);
307 }
308
309 sub handle_ebusy {
310 my ($dir) = @_;
311
312 print STDERR <<END;
313
314 WARNING: renaming $dir/ (for the purpose of replacing it with a symlink
315 to /usr$dir/) has failed with the EBUSY error.
316 This is probably caused by a systemd service started with the
317 ProtectSystem option. Before running again this program you will need to
318 stop the relevant daemon(s) or reboot the system.
319 Do not install or update other Debian packages until the program
320 has been run successfully. (Removing packages is not harmful.)
321 END
322
323 # continue, but have the program eventually return an error
324 $Program_RC = 1;
325
326 # if systemd is running...
327 return if -d '/run/systemd/system';
328
329 # list the services with ProtectSystem enabled
330 my $cmd = q{
331 for service in $(systemctl --no-legend --full list-units \
332 --state=active --type=service | cut -d ' ' -f 1); do
333 if systemctl show $service | egrep -q "^ProtectSystem=(yes|full)"; then
334 echo $service
335 fi
336 done
337 };
338
339 my $cmd_output = qx{$cmd} || return;
340 print STDERR <<END;
341
342 The following services are using the ProtectSystem feature:
343 $cmd_output
344 END
345 }
346
347 ##############################################################################
348 sub check_free_space {
349 no autodie qw(close);
350
351 my $fh;
352 open($fh, '-|', 'stat --dereference --file-system --format="%i" /');
353 my $root_id = <$fh>;
354 die "stat / failed" if not defined $root_id;
355 chomp $root_id;
356
357 # beware: df(1) reports the value of %a, not of %f
358 open($fh, '-|',
359 'stat --dereference --file-system --format="%f %S %i" /usr/');
360 my $stat_output = <$fh>;
361 die "stat /usr failed" if not defined $stat_output;
362 chomp $stat_output;
363 my ($free_blocks, $bs, $usr_id) = split(/ /, $stat_output);
364
365 return if $root_id eq $usr_id;
366
367 my $free = $free_blocks * ($bs / 1024);
368 my @dirs = grep { -e $_ } directories_to_merge();
369
370 my $cmd = "du --summarize --no-dereference --total --block-size=1K @dirs";
371 open($fh, '-|', $cmd);
372 my $needed;
373 while (<$fh>) {
374 ($needed) = /^(\d+)\s+total$/;
375 }
376 close $fh or fatal("Failed to execute $cmd");
377 die "$cmd failed" if not defined $needed;
378
379 say "Free space in /usr: $free KB." if $Debug;
380 say "The origin directories (@dirs) require $needed KB." if $Debug;
381
382 die "$free KB in /usr but $needed KB are required!\n" if $needed > $free;
383 }
384
385 # check if we are running under overlayfs, and if so, try and see if directories
386 # are movable - we might be running in a container, thus running under overlayfs
387 # but still able to do the conversion because the chroot is not overlayed.
388 sub check_overlayfs {
389 no autodie qw(close);
390
391 my $fh;
392 open($fh, '-|', "stat --file-system --format=%T /");
393 my $fs_type = <$fh>;
394 close $fh or fatal("Failed to execute stat --file-system --format=%T /");
395 die "stat / failed" if not defined $fs_type;
396 chomp $fs_type;
397 return if $fs_type ne "overlayfs";
398
399 # We have detected overlayfs on /. Let's see if we can move the directories
400 # with a (hopefully) quick back-and-forth. This is not risk-free, but it's
401 # the best we can do.
402 my @dirs = directories_to_merge();
403 foreach my $dir (@dirs) {
404 next if not -e "$dir";
405
406 no autodie qw(rename);
407 if ((not rename("$dir", "$dir~usrmerge~")) && $!{EXDEV}) {
408 die("Warning: overlayfs detected, /usr/lib/usrmerge/convert-usrmerge will not
409 be run automatically. See #1008202 for details.
410
411 If this is a container then it can be converted by unpacking the image,
412 entering it with chroot(8), installing usrmerge and then repacking the
413 image again.");
414 }
415 use autodie qw(rename);
416
417 rename("$dir~usrmerge~", "$dir");
418 }
419 }
420
421 sub is_hurd {
422 my $architecture = qx{dpkg --print-architecture};
423 return 1 if $architecture =~ /^hurd-/;
424 return 0;
425 }
426
427 sub is_mount_point {
428 my ($path) = @_;
429
430 my @cmd = ('mountpoint', '-q', $path);
431 my $rc = system(@cmd);
432 die "Failed to execute @cmd: $!\n" if $rc == -1;
433 return 0 if $rc;
434 return 1;
435 }
436
437 # Check if something is mounted on /lib/modules/ in User Mode Linux systems.
438 # See #1021180 for details.
439 sub check_uml {
440 return if not is_mount_point('/lib/modules/');
441
442 print STDERR <<END;
443
444 FATAL ERROR:
445
446 /lib/modules/ is a mount point.
447 Probably this system is using User Mode Linux or some variant of Xen.
448
449 To continue the conversion please unmount /lib/modules/ (try the command
450 'umount -l /lib/modules/') and then try again.
451 Do not forget to reboot after the conversion is complete to have it
452 mounted again.
453
454 END
455 exit(1);
456 }
457
458 ##############################################################################
459 # Try to avoid the inherent races by being as fast as possible.
460 sub go_faster {
461 system('/usr/bin/ionice', '--class=realtime', "--pid=$$")
462 if -x '/usr/bin/ionice';
463 system('/usr/bin/chrt', '--rr', '-p', '99', '--pid', $$)
464 if -x '/usr/bin/chrt';
465 }
466
467 # We use cp from coreutils because it preserves extended attributes and
468 # handles sparse files.
469 sub cp {
470 my ($source, $dest) = @_;
471
472 safe_system('cp', '--no-dereference', '--preserve=all',
473 '--reflink=auto', '--sparse=always', $source, $dest);
474 }
475
476 # We use mv from coreutils because it supports moving directories across
477 # filesystems, which would be inconvenient to implement here.
478 sub mv {
479 my ($source, $dest) = @_;
480
481 safe_system('mv', '--no-clobber', $source, $dest);
482 }
483
484 # We use rm from coreutils because I cannot be bothered to implement -r.
485 sub rm {
486 safe_system('rm', @_);
487 }
488
489 sub safe_system {
490 my (@cmd) = @_;
491
492 my $rc = system(@cmd);
493 die "Failed to execute @cmd: $!\n" if $rc == -1;
494 die "@cmd: rc=" . ($? >> 8) . "\n" if $rc;
495 }
496
497 sub fatal {
498 my ($msg) = @_;
499
500 $msg .= ".\n" if $msg !~ /\n$/;
501
502 print STDERR <<END;
503
504 FATAL ERROR:
505 $msg
506 You can try correcting the errors reported and running again
507 $0 until it will complete without errors.
508 Do not install or update other Debian packages until the program
509 has been run successfully.
510
511 END
512 exit(1);
513 }
514
515 # Find out where the runtime dynamic linker and the shared libraries
516 # can be installed on each architecture: native and multilib.
517 sub directories_to_merge {
518 return qw(/bin /sbin /lib /lib32 /lib64 /libo32 /libx32);
519 }
520
521 # check if the argument is one of the architectures enabled on the system
522 sub running_arch {
523 my ($wanted) = @_;
524
525 state @system_arch;
526 if (not @system_arch) {
527 push(@system_arch, `dpkg --print-architecture`);
528 push(@system_arch, `dpkg --print-foreign-architectures`);
529 chomp @system_arch;
530 }
531
532 return 1 if grep { $_ eq $wanted } @system_arch;
533 return 0;
534 }
535
536 ##############################################################################
537 __END__
538
539 =head1 NAME
540
541 convert-usrmerge - converts the system to everything-in-usr
542
543 =head1 SYNOPSIS
544
545 convert-usrmerge
546
547 =head1 DESCRIPTION
548
549 This program will automatically convert the system to the
550 everything-in-usr directory scheme.
551
552 There is no automatic method to restore the precedent configuration, so
553 there is no going back once the program has been run.
554
555 The program is idempotent, unless the system crashes at a really bad time.
556
557 The conflicts of all files in the Debian archive can be solved
558 automatically, but some corner cases of custom setups may require
559 manual changes.
560
561 =head1 CONFLICTS RESOLUTION MATRIX
562
563 s/d F D L B
564 F X X S Rd
565 D X D S Rd
566 L K K K? Rd
567 B Rs Rs Rs Rs
568
569 I<Source> is / and I<destination> is /usr.
570
571 Types of files:
572
573 =over 4
574
575 =item F: file
576
577 =item D: directory
578
579 =item L: symbolic link
580
581 =item B: broken symbolic link
582
583 =back
584
585 Actions:
586
587 =over 4
588
589 =item X: unresolvable conflict
590
591 =item D: recurse and compare the content of the directories
592
593 =item K: keep the source (if the link matches the destination)
594
595 =item S: swap source and destination (if the link matches the destination)
596
597 =item R: rename (source or destination)
598
599 =back
600
601 =head1 BUGS
602
603 Replacing a directory with a symlink is racy unless we do a complex dance
604 of bind mounts. We should decide if this is really needed.
605
606 Conflicting relative symbolic links are not handled automatically.
607
608 The libc6-i386 and libc6-x32 packages require to convert the /lib32 and
609 /libx32 directories as well, otherwise they would only contain the
610 symlink to the dynamic linker specified by the architecture ABI.
611
612 =head1 AUTHOR
613
614 The program and this man page have been written by Marco d'Itri
615 and are licensed under the terms of the GNU General Public License,
616 version 2 or higher.
617