-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpts_chroot_env_qq.sh
executable file
·1326 lines (1269 loc) · 54.4 KB
/
pts_chroot_env_qq.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /bin/sh
#
# pts_chroot_env_qq.sh: convenient chroot entry point
# by [email protected] at Sat Jul 21 15:02:55 CEST 2018
#
# This shell script works with bash, zsh, dash and busybox sh.
#
# This shell script is affected by the (optional) environment variable
# __QQPERL__ specifying which Perl interpreter to use.
#
# Initialize a chroot directory (e.g. /etc/passwd within) for the current
# user. This is useful so that next time the user can enter the chroot
# environment without sudo (e.g. unshare) on Linux.
__qq_init__() {
(cd "$1" && __qq__ sh -c :)
}
__qq_pts_debootstrap__() {
if test -z "$1" || test "$1" = --help || test $# -lt 2; then
echo "Usage: $0 pts-debootstrap [<flag>...] <debian-distro-name> <target-dir>" >&2
echo "Example: $0 pts-debootstrap feisty feisty_dir"
echo "Example: $0 pts-debootstrap --arch amd64 stretch stretch_dir"
return 1
fi
local ARG DIR=
for ARG in "$@"; do
DIR="$ARG"
done
test "${DIR#/}" = "$DIR" && DIR="./$DIR"
if test -d "$DIR"; then
echo "qq: fatal: target directory already exists, not clobbering: $DIR" >&2
return 100
fi
rm -rf "$DIR.pts-debootstrap"
URL=https://raw.githubusercontent.com/pts/pts-debootstrap/master/pts-debootstrap
if wget -qO "$DIR.pts-debootstrap" "$URL" &&
test -s "$DIR.pts-debootstrap"; then
:
else
echo "qq: fatal: error downloading URL: $URL" >&2
return 103
fi
if ! chmod 755 "$DIR.pts-debootstrap"; then
echo "qq: fatal: error chmodding: $DIR.pts-debootstrap" >&2
return 104
fi
local SUDO=sudo
test "$EUID" = 0 && SUDO=
$SUDO "$DIR.pts-debootstrap" "$@"
local STATUS="$?"
rm -rf "$DIR.pts-debootstrap"
if test "$STATUS" != 0; then
rm -rf "$DIR" 2>/dev/null
test -d "$DIR" && $SUDO rm -rf "$DIR"
return "$STATUS"
fi
__qq_init__ "$DIR"
}
__qq_get_alpine__() {
local ARCH=
if test "$1" = --arch && test $# -gt 1; then
ARCH="$2"
shift; shift
fi
if test -z "$1" || test "$1" = --help || test $# != 2; then
echo "Usage: $0 get-alpine [--arch=<arch>] {<version>|dir} <target-dir>" >&2
echo "Example: $0 get-alpine latest-stable alpine_dir" >&2
echo "Example: $0 get-alpine 3.8 alpine38_dir" >&2
echo "Architectures (<arch>): i386 (x86), amd64 (x86_64), s390x, ppc64le, armhf, aarch64." >&2
return 1
fi
if test -z "$ARCH"; then
ARCH="$(uname -m)"
case "$ARCH" in amd64 | x86_64 | x64) ARCH=i386; esac # 32-bit default.
fi
case "$ARCH" in
i[3456]86 | x86) ARCH=x86 ;;
amd64 | x86_64 | x64) ARCH=x86_64 ;;
ppc64el | ppc64le) ARCH=ppc64le ;;
esac
if test -z "$ARCH"; then
echo "qq: fatal: bad architecture" >&2
return 108
fi
# Works with version 3.5, 3.6, 3.7 and 3.8.
local VERSION="$1"
local DIR="$2"
local SUDO=sudo
test "$EUID" = 0 && SUDO=
if test "$VERSION" = dir; then
if ! (cd "$DIR" 2>/dev/null); then
if ! $SUDO chown "$(id -u)" "$DIR"; then
echo "qq: fatal: chown failed in: $DIR" >&2
return 112
fi
fi
if test -f "$DIR/etc/apk/repositories" && test -x "$DIR/sbin/apk" && test -f "$DIR/etc/issue" && (test -f "$DIR"/sbin/init || test -x "$DIR/sbin/init"); then
:
else
echo "qq: fatal: Alpine Linux not found in directory: $DIR" >&2
return 110
fi
return
fi
test "${DIR#/}" = "$DIR" && DIR="./$DIR"
if test -d "$DIR"; then
echo "qq: fatal: target directory already exists, not clobbering: $DIR" >&2
return 100
fi
rm -rf "$DIR.get" 2>/dev/null
test -d "$DIR.get" && $SUDO rm -rf "$DIR.get"
if ! mkdir -p "$DIR.get/alpine.dir"; then
echo "qq: fatal: mkdir failed" >&2
return 109
fi
if test "${VERSION#*.*.*}" != "$VERSION"; then
VERSION="${VERSION#v}"
local VERSION_SUFFIX="${VERSION#*.*.}"
local VERSION_PREFIX="${VERSION%.$VERSION_SUFFIX}" # 3.8 remains.
local URL="http://dl-cdn.alpinelinux.org/alpine/v$VERSION_PREFIX/releases/$ARCH/alpine-minirootfs-$VERSION-$ARCH.tar.gz"
VERSION="v$VERSION"
else
test "${VERSION#[0-9]}" = "$VERSION" || VERSION="v$VERSION"
local URL="http://dl-cdn.alpinelinux.org/alpine/$VERSION/releases/$ARCH/"
if wget -qO "$DIR.get/alpine.html" "$URL" && test -s "$DIR.get/alpine.html"; then
:
else
echo "qq: fatal: error downloading URL: $URL" >&2
rm -rf "$DIR.get"
return 101
fi
local FILENAME="$(<"$DIR.get"/alpine.html awk -F'"' '$2~/^alpine-minirootfs-.*[.]tar[.]gz$/&&$2!~/[0-9]_rc[0-9]/{print$2}' | sort | tail -1)" #'
if test -z "$FILENAME"; then
echo "qq: fatal: missing alpine-minirootfs-*.tar.gz in: $URL" >&2
rm -rf "$DIR.get"
return 102
fi
local URL="http://dl-cdn.alpinelinux.org/alpine/$VERSION/releases/$ARCH/$FILENAME"
fi
echo "qq: info: downloading: $URL" >&2
if wget -qO "$DIR.get/alpine.tar.gz" "$URL" && test -s "$DIR.get/alpine.tar.gz"; then
:
else
echo "qq: fatal: error downloading URL: $URL" >&2
return 103
fi
# tar in Debian slink (1999-03) supports --numeric-owner, but busybox tar doesn't.
if ! (cd "$DIR.get" &&
(cd alpine.dir && $SUDO tar --numeric-owner -xzf ../alpine.tar.gz) &&
$SUDO chmod 755 alpine.dir &&
$SUDO mv alpine.dir/* ./ &&
$SUDO rmdir alpine.dir &&
rm -f alpine.tar.gz alpine.html); then
echo "qq: fatal: error extracting $DIR.get/alpine.tar.gz" >&2
rm -rf "$DIR.get" 2>/dev/null
test -d "$DIR.get" && $SUDO rm -rf "$DIR.get"
return 104
fi
# TODO(pts): Use staticperl instead, it uses much less disk.
if ! mv "$DIR".get "$DIR"; then
echo "qq: fatal: rename failed from: $DIR.get" >&2
exit 105
fi
echo "qq: info: Alpine Linux $VERSION installed to: $DIR" >&2
__qq_init__ "$DIR"
}
__qq_get_cloud_image__() {
local URL="$1" ARCH="$2" DISTRO="$3" DIR="$4"
if test -z "$ARCH"; then
ARCH="$(uname -m)"
case "$ARCH" in amd64 | x86_64 | x64) ARCH=i386; esac # 32-bit default.
fi
case "$ARCH" in
i[3456]86 | x86) ARCH=i386 ;;
amd64 | x86_64 | x64) ARCH=amd64 ;;
ppc64el | ppc64le) ARCH=ppc64el ;;
esac
if test -z "$ARCH"; then
echo "qq: fatal: bad architecture" >&2
return 108
fi
local SUDO=sudo
test "$EUID" = 0 && SUDO=
test "${DIR#/}" = "$DIR" && DIR="./$DIR"
if test -d "$DIR"; then
echo "qq: fatal: target directory already exists, not clobbering: $DIR" >&2
return 100
fi
rm -rf "$DIR.get" 2>/dev/null
test -d "$DIR.get" && $SUDO rm -rf "$DIR.get"
if ! mkdir -p "$DIR.get/rootfs.dir"; then
echo "qq: fatal: mkdir failed" >&2
return 109
fi
local BASE_URL="${URL%%/streams/v1/*}/"
echo "qq: info: downloading distro list: $URL" >&2
# TODO(pts): Try downloading https:// everywhere first.
if wget -qO "$DIR.get/images.json" "$URL" && test -s "$DIR.get/images.json"; then
:
else
echo "qq: fatal: error downloading URL: $URL" >&2
rm -rf "$DIR.get"
return 101
fi
local TYPE_AND_URL="$(BASE_URL="$BASE_URL" ARCH="$ARCH" DISTRO="$DISTRO" exec "${__QQPERL__:-perl}" -w -e '
BEGIN { $^W = 1 }
use strict;
use integer;
$_=join("", <STDIN>);
my %jsonstr = split(/,/, "b,\b,n,\n,r,\r,t,\t");
# Poor man"s JSON-parser. Safe (resistant to injection attacks) even with eval below.
s` ([{}\[\],\s]+) | (:) | "((?:[^\"\\]+|\\.)*)" | (null) | ([-+.\w]+) | (.) `
if (defined($1)) { $1 }
elsif (defined($2)) { "=>" }
elsif (defined($3)) { my $s = $3; $s =~ s@\\(.)@$1@gs; $s=~s@([\\\x27])@\\$1@g; "\x27$s\x27" } # TODO(pts): Support \uXXXX.
elsif (defined($4)) { "undef" }
elsif (defined($5)) { "\x27$5\x27" } # Includes true and false.
else { die "bad JSON syntax: $7\n" }
`gexs; die $@ if $@;
$_ = eval($_);
die "bad json parse: $@\n" if $@;
#use Data::Dumper; print Dumper($_);
my %all_archs;
my %all_distros;
my $match_distro = $ENV{DISTRO};
my $last_url;
my $last_type;
BEGIN { $^W = 0 } # No warnings about undefined values.
for (values(%{$_->{products}})) {
$all_archs{$_->{arch}} = 1;
my %distros;
$distros{"\L$_->{os}/$_->{release}"} = 1 if $_->{release};
$distros{"$_->{release}"} = 1 if $_->{release};
$distros{"\L$_->{os}/$_->{release_title}"} = 1 if $_->{release_title};
$distros{"$_->{release_title}"} = 1 if $_->{release_title};
for my $alias (split(/[\s,]+/, $_->{aliases})) {
$distros{"\L$_->{os}/$alias"} = 1;
$distros{"\L$alias"} = 1;
}
for my $distro (keys(%distros)) { $all_distros{$distro} = 1 }
next if $_->{arch} ne $ENV{ARCH} or !exists($distros{$match_distro});
# Typical: version: "20181227_04:59", "20171031".
for my $version (sort keys(%{$_->{versions}})) {
my $item_dict = $_->{versions}{$version}{items};
my ($type, $url);
if ($item_dict->{"root.tar.xz"}{path}) { # TODO(pts): Save type.
$url = $item_dict->{"root.tar.xz"}{path}; # TODO(pts): Prefer .tar.xz if available and xz is not $PATH.
$type = "root.tar.xz";
} elsif ($item_dict->{"root.tar.gz"}{path}) { # Do not look at "tar.gz", it contains a filesystem image (.img).
$url = $item_dict->{"root.tar.gz"}{path};
$type = "root.tar.gz";
} elsif ($item_dict->{"root.squashfs"}{path}) {
# Example: qq get-ubuntu zesty zesty_dir
$url = $item_dict->{"root.squashfs"}{path};
$type = "root.squashfs";
} elsif ($item_dict->{"squashfs"}{path}) {
$url = $item_dict->{"squashfs"}{path};
$type = "root.squashfs";
} elsif ($item_dict->{"tar.gz"}{path}) {
# Example: qq get-ubuntu lucid lucid_dir
# http://cloud-images.ubuntu.com/releases/server/releases/lucid/release-20150427/ubuntu-10.04-server-cloudimg-i386.tar.gz
# ubuntu-10.04-server-cloudimg-i386.tar.gz contains:
# -rw-r--r-- 1 root root 3657 Apr 27 2015 README.files
# -rw-r--r-- 1 root root 91708 Apr 27 2015 lucid-server-cloudimg-i386-loader
# -rw-r--r-- 1 root root 4215040 Apr 27 2015 lucid-server-cloudimg-i386-vmlinuz-virtual
# -rw-r--r-- 1 root root 1476395008 Apr 27 2015 lucid-server-cloudimg-i386.img
# The file lucid-server-cloudimg-i386.img is a 1.4 GiB ext3
# filesystem image, we would need so much temporary disk space.
$url = $item_dict->{"tar.gz"}{path};
$type = "img.tar.gz";
}
if (defined($url)) {
$url =~ s@\A/+@@;
# Example $url: server/releases/zesty/release-20171121/ubuntu-17.04-server-cloudimg-armhf.tar.gz -> http://cloud-images.ubuntu.com/releases/server/releases/zesty/release-20171121/ubuntu-17.04-server-cloudimg-armhf.tar.gz
$url = "$ENV{BASE_URL}$url" if $url !~ m@://@;
#die $url;
($last_type, $last_url) = ($type, $url); # Corresponding to the largest $version.
}
}
}
die "qq: fatal: root image of requested <distro>=$match_distro --arch=$ENV{ARCH} not found\n" .
"qq: fatal: available <distro> values: @{[sort keys %all_distros]}\n" .
"qq: fatal: --arch values: @{[sort keys %all_archs]}\n" if !defined($last_url);
print "$last_type:$last_url"
' <"$DIR.get/images.json")"
local TYPE="${TYPE_AND_URL%%:*}"
URL="${TYPE_AND_URL#*:}"
if test -z "$TYPE_AND_URL" || test "$TYPE" = "$TYPE_AND_URL"; then
rm -rf "$DIR.get"
return 102
fi
rm -f "$DIR.get/images.json"
echo "qq: info: downloading root filesystem: $URL" >&2
if test "$TYPE" = root.tar.gz; then
# TODO(pts): Detect partial downloads.
(wget -nv -O- "$URL" && : >"$DIR.get/download.ok") | (cd "$DIR.get/rootfs.dir" && $SUDO tar --numeric-owner -xz && : >"../extract.ok")
elif test "$TYPE" = root.tar.xz; then
(wget -nv -O- "$URL" && : >"$DIR.get/download.ok") | (cd "$DIR.get/rootfs.dir" && $SUDO tar --numeric-owner -xJ && : >"../extract.ok")
elif test "$TYPE" = root.squashfs; then
if wget -nv -O "$DIR.get/rootfs.squashfs" "$URL"; then
# We need to support .squashfs, because .tar.gz and .tar.xz are missing for:
# qq get-ubuntu zesty zesty_dir # http://cloud-images.ubuntu.com/releases/server/releases/zesty/release-20171208/ubuntu-17.04-server-cloudimg-i386.squashfs
echo "qq: info: extractiong root filesystem: $DIR.get/rootfs.squashfs" >&2
if type -p unsquashfs >/dev/null 2>&1; then
if $SUDO unsquashfs -n -f -d "$DIR.get/rootfs.dir" "$DIR.get/rootfs.squashfs"; then
: >"$DIR.get/download.ok"
: >"$DIR.get/extract.ok"
else
echo "qq: fatal: unsquashfs failed" >&2
fi
else
if (cd "$DIR.get" &&
mkdir rootfs.sqm &&
$SUDO mount -t squashfs -o loop,ro,nodev,nosuid,noatime rootfs.squashfs rootfs.sqm &&
# Better preserves hard links than `cp -a'.
(cd rootfs.sqm && $SUDO tar --numeric-owner -c . && : >../download.ok) | (cd rootfs.dir && $SUDO tar --numeric-owner -x && : >../extract.ok) &&
$SUDO umount rootfs.sqm &&
rmdir rootfs.sqm); then
: >"$DIR.get/extract.ok"
else
echo "qq: fatal: by-kernel extraction of squashfs failed" >&2
test -e "$DIR.get/rootfs.sqm" && $SUDO umount "$DIR.get/rootfs.sqm" 2>/dev/null
test -d "$DIR.get/rootfs.sqm" && rmdir rootfs.sqm
fi
fi
fi
elif test "$TYPE" = img.tar.gz; then
# This is a bit tricy because we want to kill wget and tar (with SIGPIPE
# by default) as soon as tar prints a filename ending with .img. Regular
# shell pipelines don't give us this, so we implement it with Perl.
local IMG_FILENAME="$(cd "$DIR.get" && URL="$URL" exec "${__QQPERL__:-perl}" -we '
$SIG{PIPE} = "DEFAULT";
die "qq fatal: open tar.out: $!\n" if !open(TARO, "> tar.out");
close(TARO);
die "qq: fatal: open wget: $!\n" if !open(WGET, "exec wget -qO- \"\$URL\"|");
die "qq: fatal: open tar: $!\n" if !open(TART, "|exec tar --numeric-owner -tz >tar.out 2>/dev/null");
sub maybe_finish() {
if (-s("tar.out")) {
die if !open(TARO, "< tar.out");
for (<TARO>) {
print($_),exit() if m@[.]img$@;
}
close(TARO);
}
}
while (sysread(WGET, $_, 65536) > 0) {
die "qq: fatal: syswrite to tar: $!\n" if syswrite(TART, $_, length($_)) != length($_);
maybe_finish();
}
close(TART);
maybe_finish()')"
rm -f "$DIR.get/tar.out"
if test -z "$IMG_FILENAME"; then
echo "qq: fatal: .img file not found in: ${URL##*/}" >&2
else
echo "qq: info: downloading root filesystem image $IMG_FILENAME from: $URL" >&2
(wget -nv -O- "$URL" && : >"$DIR.get/download.ok") | ($SUDO tar --numeric-owner -xzO "$IMAGE_FILENAME" >"$DIR.get/rootfs.img" && : >"$DIR.get/tar_extract.ok")
if ! (test -f "$DIR.get/download.ok" && test -f "$DIR.get/tar_extract.ok"); then
echo "qq: fatal: root filesystem image extraction failed: $IMG_FILENAME" >&2
else
if (cd "$DIR.get" &&
mkdir rootfs.mounted &&
# Typically an ext3 filesystem.
$SUDO mount -o loop,ro,nodev,nosuid,noatime rootfs.img rootfs.mounted &&
# Better preserves hard links than `cp -a'.
(cd rootfs.mounted && $SUDO tar --numeric-owner -c . && : >../download.ok) | (cd rootfs.dir && $SUDO tar --numeric-owner -x && : >../extract.ok) &&
$SUDO umount rootfs.mounted &&
rmdir rootfs.mounted); then
: >"$DIR.get/extract.ok"
else
echo "qq: fatal: by-kernel extraction of rootfs.img failed" >&2
test -e "$DIR.get/rootfs.mounted" && $SUDO umount "$DIR.get/rootfs.mounted" 2>/dev/null
test -d "$DIR.get/rootfs.mounted" && rmdir rootfs.mounted
fi
fi
fi
else
echo "qq: fatal: unknown type $TYPE for file: ${URL##*/}" >&2
fi
if ! (test -f "$DIR.get/download.ok" && test -f "$DIR.get/extract.ok"); then
echo "qq: fatal: error downloading root filesystem: $URL" >&2
# TODO(pts): Do this cleanup on interrupt exit as well (with trap).
rm -rf "$DIR.get" 2>/dev/null
test -d "$DIR.get" && $SUDO rm -rf "$DIR.get"
return 103
fi
rm -f "$DIR.get/download.ok" "$DIR.get/extract.ok" "$DIR.get/tar_extract.ok" "$DIR.get/rootfs.squashfs" "$DIR.get/rootfs.img"
if ! ( cd "$DIR.get" &&
$SUDO chmod 755 rootfs.dir &&
$SUDO mv rootfs.dir/* ./ &&
$SUDO rm -rf rootfs.dir &&
cd .. &&
mv "$DIR".get "$DIR"); then
echo "qq: fatal: rename failed from: $DIR.get" >&2
rm -rf "$DIR.get" 2>/dev/null
test -d "$DIR.get" && $SUDO rm -rf "$DIR.get"
return 104
fi
echo "qq: info: Linux distro $DISTRO installed to: $DIR" >&2
__qq_init__ "$DIR"
}
# Download from http://images.linuxcontainers.org/
__qq_get_lxc__() {
local ARCH=
if test "$1" = --arch && test $# -gt 1; then
ARCH="$2"
shift; shift
fi
if test -z "$1" || test "$1" = --help || test $# != 2; then
echo "Usage: $0 get-lxc [--arch=<arch>] <distro> <target-dir>" >&2
echo "Example: $0 get-lxc centos/6 centos6_dir" >&2
echo "Architectures (<arch>): i386 (x86), amd64 (x86_64), s390x, ppc64el, armhf, aarch64." >&2
return 1
fi
# Typically redirects to http://uk.images.linuxcontainers.org/...
# http://uk.images.linuxcontainers.org/streams/v1/index.json
__qq_get_cloud_image__ http://images.linuxcontainers.org/streams/v1/images.json "$ARCH" "$@"
}
# Download from http://cloud-images.ubuntu.com/
__qq_get_ubuntu__() {
local ARCH=
if test "$1" = --arch && test $# -gt 1; then
ARCH="$2"
shift; shift
fi
if test -z "$1" || test "$1" = --help || test $# != 2; then
echo "Usage: $0 get-ubuntu [--arch=<arch>] <distro> <target-dir>" >&2
echo "Example: $0 get-ubuntu bionic bionic_dir" >&2
echo "Architectures (<arch>): i386 (x86), amd64 (x86_64), s390x, ppc64el, armhf, aarch64." >&2
return 1
fi
# http://cloud-images.ubuntu.com/releases/streams/v1/index.json
__qq_get_cloud_image__ http://cloud-images.ubuntu.com/releases/streams/v1/com.ubuntu.cloud:released:download.json "$ARCH" "$@"
}
# Download from Docker Hub (https://hub.docker.com/).
__qq_get_docker__() {
if test -z "$1" || test "$1" = --help || test $# != 2; then
echo "Usage: $0 get-docker <image> <target-dir>" >&2
echo "Example: $0 get-docker busybox busybox_dir" >&2
echo "Example: $0 get-docker alpine alpine_dir" >&2
echo "Example: $0 get-docker bitnami/minideb:stretch stretch_dir" >&2
return 1
fi
local IMAGE="$1" DIR="$2"
local SUDO=sudo
test "$EUID" = 0 && SUDO=
test "${DIR#/}" = "$DIR" && DIR="./$DIR"
if test -d "$DIR"; then
echo "qq: fatal: target directory already exists, not clobbering: $DIR" >&2
return 100
fi
rm -rf "$DIR.get" 2>/dev/null
test -d "$DIR.get" && $SUDO rm -rf "$DIR.get"
if ! mkdir -p "$DIR.get"; then
echo "qq: fatal: mkdir failed" >&2
return 109
fi
if ! docker version >/dev/null 2>&1; then
echo "qq: fatal: please install Docker first" >&2
return 101
fi
local CONTAINER="qq_get_docker__$(echo "$IMAGE" | "${__QQPERL__:-perl}" -pe 's@[^-\w\n]+@__@g')"
docker rm -f "$CONTAINER" >/dev/null 2>&1
echo "qq: info: downloading Docker image: $IMAGE" >&2
if ! docker create --name "$CONTAINER" "$IMAGE" >/dev/null; then
echo "qq: fatal: error downloading Docker image: $IMAGE" >&2
docker rm "$CONTAINER" >/dev/null
return 102
fi
echo "qq: info: extracting Docker image: $IMAGE" >&2
if ! (docker export "$CONTAINER" | (cd "$DIR.get" && $SUDO tar --numeric-owner -x && $SUDO sh -c ': >>extract.ok')); then
echo "qq: fatal: error extracting Docker image: $IMAGE" >&2
docker rm "$CONTAINER" >/dev/null
rm -rf "$DIR.get" 2>/dev/null
test -d "$DIR.get" && $SUDO rm -rf "$DIR.get"
return 103
fi
if ! (test -f "$DIR.get/extract.ok" &&
# /etc/qqsystem is needed by $IMAGE busybox, because it doesn't have /sbin/init and /etc/issue.
$SUDO sh -c 'rm -f "$1/extract.ok" && mkdir -p "$1"/etc && : >>"$1/etc/qqsystem"' . "$DIR.get" &&
docker rm "$CONTAINER" >/dev/null &&
mv "$DIR".get "$DIR"); then
echo "qq: fatal: error fixing Docker image: $IMAGE" >&2
docker rm "$CONTAINER" >/dev/null
rm -rf "$DIR.get" 2>/dev/null
test -d "$DIR.get" && $SUDO rm -rf "$DIR.get"
return 103
fi
echo "qq: info: Docker image $IMAGE installed to: $DIR" >&2
__qq_init__ "$DIR"
}
__qq__() {
if test "$1" = pts-debootstrap; then shift; __qq_pts_debootstrap__ "$@"; return "$?"
elif test "$1" = get-alpine; then shift; __qq_get_alpine__ "$@"; return "$?"
elif test "$1" = get-lxc; then shift; __qq_get_lxc__ "$@"; return "$?"
elif test "$1" = get-ubuntu; then shift; __qq_get_ubuntu__ "$@"; return "$?"
elif test "$1" = get-docker; then shift; __qq_get_docker__ "$@"; return "$?"
fi
local __QQD__ __QQPWD__ __QQOLDPWD__ __QQFOUND__
__QQOLDPWD__="$PWD"
test "${__QQOLDPWD__#/}" = "$__QQOLWPWD__" && __QQOLDPWD__="$(pwd)"
if test "${__QQOLDPWD__#/}" = "$__QQOLDPWD__"; then
echo "qq: fatal: cannot find current directory: $__QQOLDPWD__" >&2
return 123
fi
while test "${__QQOLDPWD__#//}" != "$__QQOLDPWD__"; do
__QQOLDPWD__="${__QQOLDPWD__#/}" # Remove duplicate leading slashes.
done
if test "$1" = use-workdir && test $# -gt 1; then
__QQD__="$2"; shift; shift
if ! test -d "$__QQD__"; then
echo "qq: fatal: not a directory: $__QQD__" >&2
return 122
fi
test "${__QQD__#/}" = "$__QQD__" && __QQD__="$(cd "$__QQD__" && pwd)"
if test "${__QQD__#/}" = "$__QQD__"; then
echo "qq: fatal: cannot find work directory: $__QQD__" >&2
return 123
fi
else
__QQD__="$__QQOLDPWD__"
__QQOLDPWD__=
fi
while test "${__QQD__#//}" != "$__QQD__"; do
__QQD__="${__QQD__#/}" # Remove duplicate leading slashes.
done
__QQPWD__="$__QQD__"
while test "$__QQD__"; do
__QQFOUND__=1
test -x "$__QQD__/sbin/init" && test -f "$__QQD__/etc/issue" && break
test -h "$__QQD__/sbin/init" && test -f "$__QQD__/etc/issue" && break
test -f "$__QQD__/etc/qqsystem" && break
__QQFOUND__=
test "${__QQD__%/*}" = "$__QQD__" && break
__QQD__="${__QQD__%/*}"
done
if test -z "$__QQFOUND__"; then
echo "qq: fatal: system-in-chroot not found up from: $__QQPWD__" >&2
return 124
fi
local __QQLIB__='
BEGIN { $^W = 1 }
use integer;
use strict;
my $qqin = "qqin"; # Can be overwritten.
# Linux-specific constants.
sub CLONE_NEWUSER() { 0x10000000 } # New user namespace.
sub CLONE_NEWNS() { 0x20000 } # New mount namespace.
sub CLONE_NEWIPC() { 0x08000000 } # New IPC namespace.
sub MS_RDONLY() { 0x1 }
sub MS_BIND() { 0x1000 }
sub MS_MOVE() { 0x2000 }
sub MS_REC() { 0x4000 }
sub MS_PRIVATE() { 0x40000 }
sub MS_SLAVE() { 0x80000 }
sub O_RDONLY { 0 }
sub O_DIRECTORY() { 00200000 }
sub MNT_DETACH() { 2 }
# Returns (undef, $SYS_mount, $SYS_unshare, $SYS_pivot_root, $SYS_fchdir, $SYS_umount2) or
# ($error, undef, undef, undef, undef).
sub detect_linux_syscalls() {
return ("Linux operating system needed", undef, undef) if $^O ne "linux";
# We figure out the architecture of the current process by opening the Perl
# interpreter binary. Doing require POSIX; die((POSIX::uname())[4])
# would not work, because it would return x86_64 for an i386 process running
# on an amd64 kernel.
my $perl_prog = $^X;
if ($perl_prog !~ m@/@) {
# Perl 5.004 does not have a path to "perl" in $^X, it just has "perl".
# We look it up on $ENV{PATH}.
my $perl_filename = $perl_prog;
$perl_prog = undef;
for my $dir (split(/:+/, $ENV{PATH})) {
next if !length($dir);
$perl_prog = "$dir/$perl_filename";
last if -e $perl_prog;
$perl_prog = undef;
}
return "Perl interpreter not found on \$ENV{PATH}: $perl_filename" if
!defined($perl_prog);
}
local *FH;
return ("open $^X: $!", undef, undef) if !open(FH, "< $perl_prog");
my $got = sysread(FH, $_, 52);
return ("read $^X: $!", undef, undef) if ($got or 0) < 52;
return ("close $^X: $!", undef, undef) if !close(FH);
my $arch = "unknown";
my ($SYS_mount, $SYS_unshare);
# All architectures supported by Debian 9 Stretch are here, plus some more.
# https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header
# System call numbers: https://fedora.juszkiewicz.com.pl/syscalls.html
if (/\A\x7FELF\x02\x01\x01[\x00\x03]........[\x02\x03]\x00\x3E/s) {
$arch = "amd64"; # x86_64, x64.
return (undef, 165, 272, 155, 81, 166);
} elsif (/\A\x7FELF\x02\x01\x01[\x00\x03]........[\x02\x03]\x00\xB7/s) {
$arch = "aarch64"; # arm64.
return (undef, 40, 97, 41, 50, 39);
} elsif (/\A\x7FELF\x01\x01\x01[\x00\x03]........[\x02\x03]\x00\x03/s) {
$arch = "i386"; # i486, i586, i686, x86.
return (undef, 21, 310, 217, 133, 52);
} elsif (/\A\x7FELF\x01\x01\x01[\x00\x03]........[\x02\x03]\x00\x28/s) {
$arch = "arm"; # arm32, armel, armhf.
return (undef, 21, 337, 218, 133, 52);
} elsif (/\A\x7FELF\x02\x02\x01[\x00\x03]........\x00[\x02\x03]\x00/s) {
$arch = "s390x"; # s390. s390x for Debian 9. Last byte is 0 (no architecture).
return (undef, 21, 303, 217, 133, 52);
} elsif (/\A\x7FELF\x01\x02\x01[\x00\x03]........\x00[\x02\x03][\x00\x08]/s) {
$arch = "mips"; # mips for Debian 9. Last byte is 0 (no architecture).
return (undef, 4021, 4303, 4216, 4133, 4052);
} elsif (/\A\x7FELF\x02\x01\x01[\x00\x03]........[\x02\x03]\x00\x08/s) {
$arch = "mips64el";
return (undef, 5160, 5262, 5151, 5079, 5161); # For mips64n32, SYS_unshare is 6266.
} elsif (/\A\x7FELF\x01\x01\x01[\x00\x03]........[\x02\x03]\x00\x08/s) {
$arch = "mipsel"; # Like mips, but LSB-first (little endiel).
return (undef, 4021, 4303, 4216, 4133, 4052);
} elsif (/\A\x7FELF\x02\x01\x01[\x00\x03]........[\x02\x03]\x00\x15/s) {
$arch = "ppc64el"; # ppc64, powerpc64.
return (undef, 21, 282, 203, 133, 52);
} elsif (/\A\x7FELF\x01\x01\x01[\x00\x03]........[\x02\x03]\x00\x15/s) {
$arch = "ppc32el"; # ppc32, powerpc32, powerpc.
return (undef, 21, 282, 203, 133, 52);
} else {
return ("unknown architecture for the Perl process\n", undef, undef);
}
}
# Returns true iff entry was already there.
sub ensure_auth_line($$;$) {
my($filename, $line, $is_check) = @_;
$line =~ s@\n@@g;
$line .= "\n";
die "$qqin: assert: bad auth line: $line" if $line !~ m@\A([^:\n]+:)@;
my $prefix = $1;
local *FH; # my($fh) does not work in Perl 5.004.
my $is_readonly = !open(FH, "+< $filename");
die "$qqin: fatal: open $filename: $!\n" if
$is_readonly and !open(FH, "< $filename");
my $fl;
while (defined($fl = <FH>)) {
if (substr($fl, 0, length($prefix)) eq $prefix) {
close(FH);
return 1;
}
}
if ($is_check) {
close(FH);
return 0;
}
if ($is_readonly) {
die "$qqin: fatal: open-write $filename: $!\n" if !open(FH, "+< $filename");
} else {
die "$qqin: fatal: seek: $!\n" if !sysseek(FH, 0, 2);
}
die "$qqin: fatal: syswrite: $!\n" if
length($line) != (syswrite(FH, $line, length($line)) or 0);
die "$qqin: fatal: close: $!\n" if !close(FH);
0
}
sub get_username() {
my @pwd = getpwuid($>);
@pwd = ($ENV{USER} or $ENV{LOGNAME}) if !@pwd;
die "$qqin: fatal: cannot detect username\n" if !@pwd;
$pwd[0]
}
sub is_owned_and_rwx($$) {
my ($path, $uid) = @_;
my @stat = stat($path);
@stat and $stat[4] == $uid and ($stat[2] & 0700) == 0700;
}
'
__QQPRESUDO__='
# qqpresudo: Entry point for qq before sudo or unshare.
'"$__QQLIB__"'
$qqin = "qqpresudo";
my $qqd = $ENV{__QQD__};
die "$qqin: fatal: empty \$ENV{__QQD__}\n" if !defined($qqd) or !length($qqd);
die "$qqin: fatal: \$ENV{__QQD__} does not start with /: $qqd" if
substr($qqd, 0, 1) ne "/";
# Returns $syscall_error which is undef on no error, otherwise true.
sub try_unshare(;$) {
my $do_ignore_dirs = $_[0];
my ($unshare_error, $SYS_mount, $SYS_unshare) = detect_linux_syscalls();
if (defined($unshare_error) or !defined($SYS_unshare)) {
$unshare_error = "detect_linux_syscalls failed" if !defined($unshare_error);
} elsif ($< != $>) {
$unshare_error = "real and effective UID are different (running as setuid?)";
} elsif ($( + 0 != $) + 0) {
$unshare_error = "real and effective GID are different (running as setgid?)";
} else {
my $pid = fork();
exit(!(!(syscall($SYS_unshare, CLONE_NEWUSER)))) if !$pid; # Child.
my $pid2 = waitpid($pid, 0);
if (!($pid == $pid2 and $? == 0)) {
$unshare_error = "unshare CLONE_NEWUSER failed";
} else { # Check that whatever qqin is doing to set up as root has been done.
my $username = eval { get_username() };
if (!defined($username)) {
$unshare_error = "cannot detect username";
} elsif (!stat("$qqd/proc") or !-d(_)) {
# TODO(pts): Do not follow local symlinks above and elsewhere.
# Maybe use code like this: https://github.com/opencontainers/runc vendor/github.com/cyphar/filepath-securejoin/join.go
$unshare_error = "not a directory: $qqd/proc";
} elsif (!stat("$qqd/dev/pts") or !-d(_)) {
# TODO(pts): Do not follow local symlinks above and elsewhere.
$unshare_error = "not a directory: $qqd/dev/pts";
} elsif (!$do_ignore_dirs and (readlink("$qqd$qqd") or 0) ne "/") {
# TODO(pts): Do not follow local symlinks above and elsewhere.
$unshare_error = "symlink does not point to /: $qqd$qqd";
} elsif (!$do_ignore_dirs and !-d("$qqd/home/$username")) {
# TODO(pts): Do not follow local symlinks above and elsewhere.
$unshare_error = "home directory does not exist: $qqd/home/$username";
} elsif (!$do_ignore_dirs and !is_owned_and_rwx("$qqd/home/$username", $>)) {
# TODO(pts): Do not follow local symlinks above and elsewhere.
$unshare_error = "home directory not owned by $username and rwx: $qqd/home/$username";
} elsif (!$do_ignore_dirs and !ensure_auth_line("$qqd/etc/passwd", "$username:", 1)) {
# TODO(pts): Do not follow local /etc symlinks above and elsewhere.
# TODO(pts): Try to fix it if /etc/passwd, /etc/group and /etc/shadow are writable.
# TODO(pts): Also check that the UID and GID are specified correctly.
$unshare_error = "username $username missing from passwd (to fix, run \`qq root id\x27): $qqd/etc/passwd";
} else {
$unshare_error = undef;
}
}
}
$unshare_error
}
my @sudo = ("sudo", "-E"); # Preserve the environment.
$ENV{__QQUNSHARE__} = 0;
my @run_as_root = (
"root", "su", "sudo", "login", "passwd", "apt-get", "apt", "dpkg", "rpm",
"yum", "apk");
if (@ARGV and grep ({ $_ eq $ARGV[0] } @run_as_root)) {
unshift @ARGV, "root" if $ARGV[0] ne "root";
} elsif (@ARGV and $ARGV[0] eq "use-sudo") { # Override autodetection.
shift @ARGV;
} elsif (@ARGV and ($ARGV[0] eq "use-unshare" or $ARGV[0] eq "use-rootless")) { # Override autodetection.
shift @ARGV;
my $unshare_error = try_unshare(1); # With $do_ignore_dirs=1, we will create those directories later.
die "$qqin: fatal: use-unshare failed: $unshare_error\n" if
$unshare_error;
@sudo = ();
$ENV{__QQUNSHARE__} = 1; # Use unshare (rootless) instead of sudo + chroot.
} elsif (!$>) { # Running as root (EUID 0), no need to run sudo manually.
@sudo = ();
unshift @ARGV, "root"; # Make sure qqin does not look for $ENV{SUDO_USER} etc.
} elsif (-f("$qqd/etc/qqforceroot")) {
} elsif (!try_unshare()) {
@sudo = ();
$ENV{__QQUNSHARE__} = 1; # Use unshare (rootless) instead of sudo + chroot.
}
if ($ENV{__QQUNSHARE__}) {
die "$qqin: fatal: real and effective UID are different (running as setuid?)\n" if $< != $>;
die "$qqin: fatal: real and effective UID are different (running as setgid?)\n" if $( + 0 != $) + 0;
$ENV{USER} = $ENV{LOGNAME} = $ENV{USERNAME} = get_username();
($ENV{SUDO_USER}, $ENV{SUDO_UID}, $ENV{SUDO_GID}) = ($ENV{USER}, $>, $) + 0);
} else {
delete @ENV{"USER", "LOGNAME", "USERNAME", "SUDO_USER", "SUDO_UID", "SUDO_GID"};
}
die "$qqin: fatal: exec failed: $!\n" if
!exec(@sudo, $^X, "-weeval\$ENV{__QQIN__};die\$\@if\$\@", "--", @ARGV);
' __QQIN__='
# qqin: Entry point for qq after sudo.
#
# This Perl script can manage environment variables (and pass them to the
# command in @ARGV) precisely, because it does not invoke a shell, does not
# invoke su(1) or sudo(1).
#
# TODO(pts): Set up /etc/hosts and /etc/resolve.conf automatically.
# TODO(pts): Support qq1, qq2 (i.e. multiple execution environments). How
# can they see the same local directory?
'"$__QQLIB__"'
my $qqd = $ENV{__QQD__};
my $qqpath = $ENV{__QQPATH__};
my $qqpwd = $ENV{__QQPWD__};
my $qqoldpwd = $ENV{__QQOLDPWD__};
$qqoldpwd = undef if defined($qqoldpwd) and !length($qqoldpwd);
my $home = $ENV{__QQHOME__};
die "$qqin: fatal: empty \$ENV{__QQD__}\n" if !defined($qqd) and !length($qqd);
die "$qqin: fatal: empty \$ENV{__QQPATH__}\n" if !$qqpath;
# Too late for a getpwnam or getpwuid after a chroot.
die "$qqin: fatal: empty \$ENV{__QQHOME__}\n" if !$home;
die "$qqin: fatal: bad QQD snytax: $qqd\n" if $qqd !~ m@\A(/[^/]+)+@;
die "$qqin: fatal: bad QQPWD snytax: $qqpwd\n" if $qqpwd !~ m@\A(/[^/]+)+@;
die "$qqin: fatal: bad QQOLDPWD snytax: $qqoldpwd\n" if defined($qqoldpwd) and $qqoldpwd !~ m@\A(/[^/]+)+@;
die "$qqin: fatal: missing \$ENV{__QQUNSHARE__}" if !defined($ENV{__QQUNSHARE__});
my $do_unshare=!(!($ENV{__QQUNSHARE__}));
die "$qqin: fatal: QQD is not a prefix of QQPWD" if
0 == length($qqpwd) or substr("$qqpwd/", 0, length($qqd) + 1) ne "$qqd/";
if ($ENV{__QQLCALL__}) {
$ENV{LC_ALL} = $ENV{__QQLCALL__};
} else {
delete $ENV{LC_ALL};
}
delete @ENV{"__QQD__", "__QQPWD__", "__QQOLDPWD__", "__QQPERL__", "__QQPATH__", "__QQHOME__", "__QQLCALL__", "__QQIN__", "__QQPRESUDO__", "__QQUNSHARE__"};
# We must call this before chroot(...), for the correct $^X value.
my ($syscall_error, $SYS_mount, $SYS_unshare, $SYS_pivot_root, $SYS_fchdir, $SYS_umount2) = detect_linux_syscalls();
umask(0022);
if ($do_unshare) {
# $ENV{SUDO_USER}, $ENV{SUDO_UID} and $ENV{SUDO_GID} is already set up by qqpresudo.
# Do the CLONE_NEWUSER + uid_map magic. Without this CLONE_NEWNS would
# return EPERM.
my $pid = $$;
local (*HR, *PW, *PR, *HW);
die "$qqin: fatal: pipe1: $!\n" if !pipe(HR, PW);
die "$qqin: fatal: pipe2: $!\n" if !pipe(PR, HW);
my $child_pid = fork();
die "$qqin: fatal: fork: $!\n" if !defined($child_pid);
if (!$child_pid) { # Child process.
close(PR); close(PW);
# Wait for parent do CLONE_NEWUSER first.
exit(-1) if !sysread(HR, $_, 1);
local *FH;
die "$qqin: fatal: child: open uid_map: $!\n" if !open(FH, "> /proc/$pid/uid_map");
$_ = "$> $> 1\n"; # Unfortunately we are not able to map just any in-chroot UID to $>.
die "$qqin: fatal: child: write uid_map: $!\n" if (syswrite(FH, $_, length($_)) or 0) != length($_);
die "$qqin: fatal: child: close uid_map: $!\n" if !close(FH);
die "$qqin: fatal: child: open setgroups: $!\n" if !open(FH, "> /proc/$pid/setgroups");
# This disables the groups: groups=65534(nogroup),65534(nogroup),... .
$_ = "deny\n";
die "$qqin: fatal: child: write setgroups: $!\n" if (syswrite(FH, $_, length($_)) or 0) != length($_);
die "$qqin: fatal: child: close setgroups: $!\n" if !close(FH);
die "$qqin: fatal: child: open gid_map: $!\n" if !open(FH, "> /proc/$pid/gid_map");
$_ = ($) + 0)." ".($) + 0)." 1\n";
die "$qqin: fatal: child: write gid_map: $!\n" if (syswrite(FH, $_, length($_)) or 0) != length($_);
die "$qqin: fatal: child: close gid_map: $!\n" if !close(FH);
$_ = "B";
die "$qqin: fatal: child: write helper: $!\n" if !syswrite(HW, $_, 1);
exit(0);
}
close(HR); close(HW);
# CLONE_NEWUSER needs Linux >=3.8 if run as non-root, otherwise EPERM.
die "$qqin: fatal: CLONE_NEWUSER: $!\n" if syscall($SYS_unshare, CLONE_NEWUSER);
$_ = "A";
# Signal the child that it can start writing files in /proc.
die "$qqin: fatal: child: write primary: $!\n" if !syswrite(PW, $_, 1);
# Wait for the child to finish writing to /proc.
die "$qqin: fatal: error in child\n" if !sysread(PR, $_, 1);
close(PR); close(PW);
my $child_pid2 = waitpid($child_pid, 0);
die "$qqin: fatal: bad child_pid2\n" if $child_pid2 != $child_pid;
die "$qqin: fatal: error in child: ".sprintf("0x%x")."$?\n" if $?;
} else {
#die "$qqin: fatal: unexpected \$0: $0\n" if $0 ne "...";
die "$qqin: fatal: must be run as root\n" if $> != 0;
$( = 0;
$) = "0 0"; # Also involves an empty setgroups.
$< = 0; # setuid(0).
}
if ($do_unshare) {
die "$qqin: fatal: SYS_unshare not detected\n" if !defined($SYS_unshare);
die "$qqin: fatal: unshare CLONE_NEWNS: $!\n" if
syscall($SYS_unshare, CLONE_NEWNS);
my @spec = ("none", "/", 0, MS_REC | MS_PRIVATE, 0);
die "$qqin: fatal: mount /: $!\n" if syscall($SYS_mount, @spec);
} else {
# We must call this on our root (/) before chroot to take effect.
if (defined($SYS_unshare) and !syscall($SYS_unshare, CLONE_NEWNS)) {
# Without this call CLONE_NEWS does not take effect when run as root.
my @spec = ("none", "/", 0, MS_REC | MS_PRIVATE, 0);
syscall($SYS_mount, @spec);
}
}
# Follows symlinks. Good.
sub is_same_dir($$) {
my @stata = stat($_[0]);
die "$qqin: fatal: stat $_[0]: $!\n" if !@stata;
return 0 if !-d(_);
my @statb = stat($_[1]);
die "$qqin: fatal: stat $_[1]: $!\n" if !@statb;
($stata[0] == $statb[0]) and ($stata[1] == $statb[1]) # st_dev and st_ino.
}
if (!-d("$qqd/proc")) { # TODO(pts): Disallow symlinks in $qqd/proc.
mkdir("$qqd/proc", 0755);
die "$qqin: fatal: not a directory: $qqd/proc\n" if !-d("$qqd/proc");
}
if (!-d("$qqd/dev/pts")) { # TODO(pts): Disallow symlinks.
mkdir("$qqd/dev", 0755);
mkdir("$qqd/dev/pts", 0755);
die "$qqin: fatal: not a directory: $qqd/dev/pts\n" if !-d("$qqd/dev/pts");
}
if (!-e("$qqd/dev/ptmx")) { # TODO(pts): Disallow symlinks.
symlink("pts/ptmx", "$qqd/dev/ptmx"); # It is OK to fail here.
}
for my $node (qw(null zero full random urandom kmsg tty console)) {
#if (!-c("$qqd/dev/$node")) {...} # TODO(pts): Disallow symlinks.
if (-f("$qqd/dev/$node")) { # Already exists as a regular file. TODO(pts): Disallow symlinks.
if (-c("/dev/$node")) {
#if (!-e("$qqd/dev/$node")) {
# my $qqp = (substr($qqd, 0, 1) eq "/") ? "" : "./";
# close(FH) if open(FH, ">> $qqp$qqd/dev/$node");
#}
my @spec = ("/dev/$node", "$qqd/dev/$node", 0, MS_REC | MS_BIND, 0);
# This bind mount works with use-rootless.
die "$qqin: fatal: mount $qqd/dev/$node: $!\n" if syscall($SYS_mount, @spec);
}
die "$qqin: fatal: not a character device: $qqd/dev/$node\n" if !-c("$qqd/dev/$node");
}
}
# Non-Linux systems will run mount(8) later.
if (defined($SYS_mount) and !is_same_dir($qqd, "/")) {
my @spec = ("/proc", "$qqd/proc", 0, MS_REC | MS_BIND, 0);
die "$qqin: fatal: mount $qqd/proc: $!\n" if syscall($SYS_mount, @spec);
@spec = ("/dev/pts", "$qqd/dev/pts", 0, MS_REC | MS_BIND, 0);
die "$qqin: fatal: mount $qqd/dev/pts: $!\n" if syscall($SYS_mount, @spec);
}
if (defined($qqoldpwd)) { # `qq use-workdir $qqd` was run in directory $qqpwd.
die "$qqin: fatal: missing work directory: $qqpwd\n" if !-d($qqpwd);
die "$qqin: fatal: missing work source directory: $qqoldpwd\n" if !-d($qqoldpwd);
my @spec = ($qqoldpwd, $qqpwd, 0, MS_REC | MS_BIND, 0);
die "$qqin: fatal: mount $qqpwd: $!\n" if syscall($SYS_mount, @spec);
}
my $username;
if (@ARGV and $ARGV[0] eq "root") {
shift @ARGV;
$username = "root";
$ENV{SUDO_UID} = $ENV{SUDO_GID} = "0";
} else {
die "$qqin: fatal: incomplete sudo environment: SUDO_UID, SUDO_GID, SUDO_USER\n" if
!$ENV{SUDO_UID} or !$ENV{SUDO_GID} or !$ENV{SUDO_USER};
die "$qqin: fatal: inconsistent SUDO_USER and SUDO_UID for root\n" if
($ENV{SUDO_USER} eq "root") != ($ENV{SUDO_UID} == 0);
$username = $ENV{SUDO_USER};
}
die "$qqin: fatal: invalid username: $username\n" if
$username !~ m@\A[-+.\w]+\Z(?!\n)@;
$ENV{LOGNAME} = $ENV{USER} = $ENV{USERNAME} = $username;
delete @ENV{qw(SUDO_COMMAND SUDO_USER)};
if (defined($SYS_pivot_root) and $username eq "root") {
# On Linux we use pivot_root(2) (and some other mount(2) and fchdir(2)
# magic, see below) instead of chroot(2) to prevent the chdir("..") escape
# technique (http://www.ouah.org/chroot-break.html), which would work as
# root with chroot(2).
#
# This implementation with pivot_root(2) is based on
# https://github.com/opencontainers/runc/blob/4769cdf607b0d1cbd73e5407d9655da7511fe193/libcontainer/rootfs_linux.go#L693
# with the re-bind-bound below prepended. It also contains msMoveRoot
# (MS_MOVE), but that works only if $qqd is a mount mount, and the
# re-bind-mount rick below doesn not fix it.
#
# There is another implementation at
# https://github.com/vincentbernat/jchroot/blob/3ad09cca4879c27f7eef657b7fa1dd8b4f6aa47b/jchroot.c#L122
# , but that one creates a temporary directory within $qqd.
#
# https://github.com/opencontainers/runc/blob/master/libcontainer/SPEC.md
# claims that pivot_root(2) is not supported in ramfs. It does work within
# tmpfs though on Linux 3.13.
local(*OLDROOT, *NEWROOT);
# Without this bind-mount call, pivot_root would fail if $qqd was not a
# mount point.
# Without the MS_REC below, filesystems mounted within $qqd would not be
# visible.
my @spec = ($qqd, $qqd, 0, MS_REC | MS_BIND, 0);
die "$qqin: fatal: re-bind-mount $qqd: $!\n" if syscall($SYS_mount, @spec);
die "$qqin: fatal: chdir $qqd: $!\n" if !chdir($qqd);
die "$qqin: fatal: open oldroot: $!\n" if
!sysopen(OLDROOT, "/", O_RDONLY | O_DIRECTORY, 0);
die "$qqin: fatal: open newroot: $!\n" if
!sysopen(NEWROOT, $qqd, O_RDONLY | O_DIRECTORY, 0);
# Not using chdir(NEWROOT), because it old versions of Perl (e.g.
# 5.004_04) do not have it.
die "$qqin: fatal: fchdir newroot: $!\n" if
0 != syscall($SYS_fchdir, fileno(NEWROOT));
die "$qqin: fatal: pivot_root . .: $!\n" if