-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon-code
More file actions
1905 lines (1749 loc) · 57.5 KB
/
Copy pathcommon-code
File metadata and controls
1905 lines (1749 loc) · 57.5 KB
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
#!/bedrock/libexec/busybox sh
#
# Shared Bedrock Linux shell functions
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
#
# Copyright (c) 2016-2020 Daniel Thau <danthau@bedrocklinux.org>
# Print the Bedrock Linux ASCII logo.
#
# ${1} can be provided to indicate a tag line. This should typically be the
# contents of /bedrock/etc/bedrock-release such that this function should be
# called with:
# print_logo "$(cat /bedrock/etc/bedrock-release)"
# This path is not hard-coded so that this function can be called in a
# non-Bedrock environment, such as with the installer.
print_logo() {
printf "${color_logo}"
# Shellcheck indicates an escaped backslash - `\\` - is preferred over
# the implicit situation below. Typically this is agreeable as it
# minimizes confusion over whether a given backslash is a literal or
# escaping something. However, in this situation it ruins the pretty
# ASCII alignment.
#
# shellcheck disable=SC1117
cat <<EOF
__ __ __
\ \_________\ \____________\ \___
\ _ \ _\ _ \ _\ __ \ __\ /
\___/\__/\__/ \_\ \___/\__/\_\_\
EOF
if [ -n "${1:-}" ]; then
printf "%35s\\n" "${1}"
fi
printf "${color_norm}\\n"
}
# Compare Bedrock Linux versions. Returns success if the first argument is
# newer than the second. Returns failure if the two parameters are equal or if
# the second is newer than the first.
#
# To compare for equality or inequality, simply do a string comparison.
#
# For example
# ver_cmp_first_newer() "0.7.0beta5" "0.7.0beta4"
# returns success while
# ver_cmp_first_newer() "0.7.0beta5" "0.7.0"
# returns failure.
ver_cmp_first_newer() {
# 0.7.0beta1
# ^ ^ ^^ ^^
# | | || |\ tag_ver
# | | |\--+- tag
# | | \----- patch
# | \------- minor
# \--------- major
left_major="$(echo "${1}" | awk -F'[^0-9][^0-9]*' '{print$1}')"
left_minor="$(echo "${1}" | awk -F'[^0-9][^0-9]*' '{print$2}')"
left_patch="$(echo "${1}" | awk -F'[^0-9][^0-9]*' '{print$3}')"
left_tag="$(echo "${1}" | awk -F'[0-9][0-9]*' '{print$4}')"
left_tag_ver="$(echo "${1}" | awk -F'[^0-9][^0-9]*' '{print$4}')"
right_major="$(echo "${2}" | awk -F'[^0-9][^0-9]*' '{print$1}')"
right_minor="$(echo "${2}" | awk -F'[^0-9][^0-9]*' '{print$2}')"
right_patch="$(echo "${2}" | awk -F'[^0-9][^0-9]*' '{print$3}')"
right_tag="$(echo "${2}" | awk -F'[0-9][0-9]*' '{print$4}')"
right_tag_ver="$(echo "${2}" | awk -F'[^0-9][^0-9]*' '{print$4}')"
[ "${left_major}" -gt "${right_major}" ] && return 0
[ "${left_major}" -lt "${right_major}" ] && return 1
[ "${left_minor}" -gt "${right_minor}" ] && return 0
[ "${left_minor}" -lt "${right_minor}" ] && return 1
[ "${left_patch}" -gt "${right_patch}" ] && return 0
[ "${left_patch}" -lt "${right_patch}" ] && return 1
[ -z "${left_tag}" ] && [ -n "${right_tag}" ] && return 0
[ -n "${left_tag}" ] && [ -z "${right_tag}" ] && return 1
[ -z "${left_tag}" ] && [ -z "${right_tag}" ] && return 1
[ "${left_tag}" \> "${right_tag}" ] && return 0
[ "${left_tag}" \< "${right_tag}" ] && return 1
[ "${left_tag_ver}" -gt "${right_tag_ver}" ] && return 0
[ "${left_tag_ver}" -lt "${right_tag_ver}" ] && return 1
return 1
}
# Call to return successfully.
exit_success() {
trap '' EXIT
exit 0
}
# Abort the given program. Prints parameters as an error message.
#
# This should be called whenever a situation arises which cannot be handled.
#
# This file sets various shell settings to exit on unexpected errors and traps
# EXIT to call abort. To exit without an error, call `exit_success`.
abort() {
trap '' EXIT
printf "${color_alert}ERROR: %s\\n${color_norm}" "${@}" >&2
exit 1
}
# Clean up "${target_dir}" and prints an error message.
#
# `brl fetch`'s various back-ends trap EXIT with this to clean up on an
# unexpected error.
fetch_abort() {
set +x # if someone turned `set -x` on in a per-distro fetch script, it's probably no longer needed at this point
trap '' EXIT
printf "${color_alert}ERROR: %s\\n${color_norm}" "${@}" >&2
printf "${color_alert}This is commonly due to distro mirror layout changes breaking \`brl fetch\`. Possible solutions:\\n${color_norm}" >&2
printf "${color_alert}- If you did not, consider manually providing a mirror with --mirror\\n${color_norm}" >&2
printf "${color_alert}- Check for a Bedrock Linux update with \`brl update\`\\n${color_norm}" >&2
printf "${color_alert}- Check for a Bedrock Linux beta which may contain a fix\\n${color_norm}" >&2
printf "${color_alert}- Try \`brl import\` which does not rely on mirror layout\\n${color_norm}" >&2
printf "${color_alert}\\n${color_norm}" >&2
if cfg_values "miscellaneous" "debug" | grep -q "brl-fetch"; then
printf "${color_alert}Skipping cleaning up ${target_dir:-} due to bedrock.conf debug setting.${color_norm}\n"
elif [ -n "${target_dir:-}" ] && [ -d "${target_dir:-}" ]; then
if ! less_lethal_rm_rf "${target_dir:-}"; then
printf "${color_alert}ERROR cleaning up ${target_dir:-}
You will have to clean up yourself.
!!! BE CAREFUL !!!
\`rm\` around mount points may result in accidentally deleting something you wish to keep.
Consider rebooting to remove mount points and kill errant processes first.${color_norm}
"
fi
fi
exit 1
}
# Define print_help() then call with:
# handle_help "${@:-}"
# at the beginning of brl subcommands to get help handling out of the way
# early.
handle_help() {
if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
print_help
exit_success
fi
}
# Print a message indicating some step without a corresponding step count was
# completed.
notice() {
printf "${color_misc}* ${color_norm}${*}\\n"
}
# Initialize step counter.
#
# This is used when performing some action with multiple steps to give the user
# a sense of progress. Call this before any calls to step(), setting the total
# expected step count. For example:
# step_init 3
# step "Completed step 1"
# step "Completed step 2"
# step "Completed step 3"
step_init() {
step_current=0
step_total="${1}"
}
# Indicate a given step has been completed.
#
# See `step_init()` above.
step() {
step_current=$((step_current + 1))
step_count=$(printf "%d" "${step_total}" | wc -c)
percent=$((step_current * 100 / step_total))
printf "${color_misc}[%${step_count}d/%d (%3d%%)]${color_norm} ${*:-}${color_norm}\\n" \
"${step_current}" \
"${step_total}" \
"${percent}"
}
get_width() {
width=$( (stty size 2>/dev/null || echo "x 40") | cut -d' ' -f2)
if [ "${width}" -gt 80 ]; then
width=80
fi
}
progress_bar() {
get_width
awk -v"total=${1}" -v"width=${width}" '
BEGIN {
width -= 8
bar = ""
for (i = 0; i < width; i++) {
bar = bar " "
}
printf "\r[%s] %3d%%", bar, NR * 100 / total
}
{
bar = ""
for (i = 0; i < width; i++) {
if ((NR / total) >= (i / width)) {
bar = bar "\\"
} else {
bar = bar " "
}
}
printf "\r[%s] %3d%%", bar, NR * 100 / total
}
END {
bar = ""
for (i = 0; i < width; i++) {
bar = bar "\\"
}
printf "\r[%s] 100%%\n", bar
}
' -
}
progress_unknown() {
get_width
awk -v"width=${width}" '
BEGIN {
width -= 8
s[0] = "-"; s[1] = "\\"; s[2] = "|"; s[3] = "/"
printf "\r["
for (i = 0; i < width; i++) {
bar = bar " "
}
printf "\r[%s] ??%%", bar
}
{
bar = ""
for (i = 0; i < width; i++) {
if (!(i % 3)) {
bar = bar "" s[(NR + i) % 4]
} else {
bar = bar " "
}
}
printf "\r[%s] ??%%", bar
}
END {
bar = ""
for (i = 0; i < width; i++) {
bar = bar "\\"
}
printf "\r[%s] 100%%\n", bar
}
' -
}
# Abort if parameter is not a legal stratum name.
ensure_legal_stratum_name() {
name="${1}"
if echo "${name}" | grep -q '[[:space:]/\\:=$"'"'"']'; then
abort "\"${name}\" contains disallowed character: whitespace, forward slash, back slash, colon, equals sign, dollar sign, single quote, and/or double quote."
elif echo "x${name}" | grep "^x-"; then
abort "\"${name}\" starts with a \"-\" which is disallowed."
elif [ "${name}" = "bedrock" ] || [ "${name}" = "init" ]; then
abort "\"${name}\" is one of the reserved strata names: bedrock, init."
fi
}
strip_illegal_stratum_name_characters() {
cat | sed -e 's![[:space:]/\\:=$"'"'"']!!g' -e "s!^-!!"
}
# Call with:
# min_args "${#}" "<minimum-expected-arg-count>"
# at the beginning of brl subcommands to error early if insufficient parameters
# are provided.
min_args() {
arg_cnt="${1}"
tgt_cnt="${2}"
if [ "${arg_cnt}" -lt "${tgt_cnt}" ]; then
abort "Insufficient arguments, see \`--help\`."
fi
}
# Aborts if not running as root.
require_root() {
if ! [ "$(id -u)" -eq "0" ]; then
abort "Operation requires root."
fi
}
# Bedrock lock subsystem management.
#
# Locks specified directory. If no directory is specified, defaults to
# /bedrock/var/.
#
# This is used to avoid race conditions between various Bedrock subsystems.
# For example, it would be unwise to allow multiple simultaneous attempts to
# enable the same stratum.
#
# By default will this will block until the lock is acquired. Do not use this
# on long-running commands. If --nonblock is provided, will return non-zero if
# the lock is already in use rather than block.
#
# The lock is automatically dropped when the shell script (and any child
# processes) ends, and thus an explicit unlock is typically not needed. See
# drop_lock() for cases where an explicit unlock is needed.
#
# Only one lock may be held at a time.
lock() {
require_root
if [ "${1:-}" = "--nonblock" ]; then
nonblock="${1}"
shift
fi
dir="${1:-/bedrock/var/}"
# The list of directories which can be locked is white-listed to help
# catch typos/bugs. Abort if not in the list.
if echo "${dir}" | grep -q "^\\/bedrock\\/var\\/\\?$"; then
# system lock
true
elif echo "${dir}" | grep -q "^\\/bedrock\\/var\\/cache\\/[^/]*/\\?$"; then
# cache lock
true
else
abort "Attempted to lock non-white-listed item \"${1}\""
fi
# Update timestamps on lock to delay removal by cache cleaning logic.
mkdir -p "${dir}"
touch "${dir}"
touch "${dir}/lock"
exec 9>"${dir}/lock"
# Purposefully not quoting so an empty string is ignored rather than
# treated as a parameter.
# shellcheck disable=SC2086
flock ${nonblock:-} -x 9
}
# Drop lock on Bedrock subsystem management.
#
# This can be used in two ways:
#
# 1. If a shell script needs to unlock before it finishes. This is primarily
# intended for long-running shell scripts to strategically lock only required
# sections rather than lock for an unacceptably large period of time. Call
# with:
# drop_lock
#
# 2. If the shell script launches a process which will outlive it (and
# consequently the intended lock period), as child processes inherit locks. To
# drop the lock for just the child process and not the parent script, call with:
# ( drop_lock ; cmd )
drop_lock() {
exec 9>&-
}
# Various Bedrock subsystems - most notably brl-fetch - create files which are
# cached for use in the future. Clean up any that have not been utilized in a
# configured amount of time.
clear_old_cache() {
require_root
life="$(cfg_value "miscellaneous" "cache-life")"
life="${life:-90}"
one_day="$((24 * 60 * 60))"
age_in_sec="$((life * one_day))"
current_time="$(date +%s)"
if [ "${life}" -ge 0 ]; then
export del_time="$((current_time - age_in_sec))"
else
# negative value indicates cache never times out. Set deletion
# time to some far future time which will not be hit while the
# logic below is running.
export del_time="$((current_time + one_day))"
fi
# If there are no cache items, abort early
if ! echo /bedrock/var/cache/* >/dev/null 2>&1; then
return
fi
for dir in /bedrock/var/cache/*; do
# Lock directory so nothing uses it mid-removal. Skip it if it
# is currently in use.
if ! lock --nonblock "${dir}"; then
continue
fi
# Busybox ignores -xdev when combine with -delete and/or -depth.
# http://lists.busybox.net/pipermail/busybox-cvs/2012-December/033720.html
# Rather than take performance hit with alternative solutions,
# disallow mounting into cache directories and drop -xdev.
#
# /bedrock/var/cache/ should be on the same filesystem as
# /bedrock/libexec/busybox. Save some disk writes and
# hardlink.
#
# busybox also lacks find -ctime, so implement it ourselves
# with a bit of overhead.
if ! [ -x "${dir}/busybox" ]; then
ln /bedrock/libexec/busybox "${dir}/busybox"
else
touch "${dir}/busybox"
fi
chroot "${dir}" /busybox find / -mindepth 1 ! -type d -exec /busybox sh -c "[ \"\$(stat -c \"%Z\" \"{}\")\" -lt \"${del_time}\" ] && rm -- \"{}\"" \;
# Remove all empty directories irrelevant of timestamp. Only cache files.
chroot "${dir}" /busybox find / -depth -mindepth 1 -type d -exec /busybox rmdir -- "{}" \; >/dev/null 2>&1 || true
# If the cache directory only contains the above-created lock
# and busybox, it's no longer caching anything meaningful.
# Remove it.
if [ "$(echo "${dir}/"* | wc -w)" -le 2 ]; then
rm -f "${dir}/lock"
rm -f "${dir}/busybox"
rmdir "${dir}"
fi
drop_lock "${dir}"
done
}
#
# pmm locking functions
#
# Bedrock lock management code is very shell oriented. This makes it awkward
# to use in the awk oriented pmm code. Place it in the shared shell code for
# pmm to shell out to.
#
pmm_cache_package_manager_list() {
lock /bedrock/var/cache/pmm
# pmm will export these variables
echo "${strata}" >/bedrock/var/cache/pmm/strata
# variable is inherited from function caller
# shellcheck disable=SC2154
echo "${bedrock_conf_sha1sum}" >/bedrock/var/cache/pmm/bedrock_conf_sha1sum
# pmm provides pair list via pipe
cat >/bedrock/var/cache/pmm/package_manager_list
exit_success
}
pmm_cache_package_manager_db() {
# pmm will export ${stratum} and ${package_manager}
# shellcheck disable=SC2154
lock "/bedrock/var/cache/pmm-${stratum}:${package_manager}"
db="/bedrock/var/cache/pmm-${stratum}:${package_manager}/package-db/"
ready="/bedrock/var/cache/pmm-${stratum}:${package_manager}/package-db-ready"
rm -rf "${db}" "${ready}"
mkdir -p "${db}"
cd "${db}"
# pmm provides db information via pipe
awk '
function brldbpath(name) {
if (substr(name,1,3) == "lib") {
return substr(name, 4, 2)
} else {
return substr(name, 1, 2)
}
}
{
print >> brldbpath($0)
}'
echo 1 >"${ready}"
exit_success
}
# List all strata irrelevant of their state.
list_strata() {
find /bedrock/strata/ -maxdepth 1 -mindepth 1 -type d -exec basename {} \;
}
# List all aliases irrelevant of their state.
list_aliases() {
find /bedrock/strata/ -maxdepth 1 -mindepth 1 -type l -exec basename {} \;
}
# Dereference a stratum alias. If called on a non-alias stratum, that stratum
# is returned.
deref() {
alias="${1}"
if ! filepath="$(realpath "/bedrock/strata/${alias}" 2>/dev/null)"; then
return 1
elif ! name="$(basename "${filepath}")"; then
return 1
else
echo "${name}"
fi
}
# Checks if a given file has a given bedrock extended filesystem attribute.
has_attr() {
file="${1}"
attr="${2}"
/bedrock/libexec/getfattr --only-values --absolute-names -n "user.bedrock.${attr}" "${file}" >/dev/null 2>&1
}
# Prints a given file's given bedrock extended filesystem attribute.
get_attr() {
file="${1}"
attr="${2}"
printf "%s\\n" "$(/bedrock/libexec/getfattr --only-values --absolute-names -n "user.bedrock.${attr}" "${file}")"
}
# Sets a given file's given bedrock extended filesystem attribute.
set_attr() {
file="${1}"
attr="${2}"
value="${3}"
/bedrock/libexec/setfattr -n "user.bedrock.${attr}" -v "${value}" "${file}"
}
# Removes a given file's given bedrock extended filesystem attribute.
rm_attr() {
file="${1}"
attr="${2}"
if has_attr "${file}" "${attr}"; then
/bedrock/libexec/setfattr -x "user.bedrock.${attr}" "${file}"
fi
}
# Checks if argument is an existing stratum
is_stratum() {
[ -d "/bedrock/strata/${1}" ] && ! [ -h "/bedrock/strata/${1}" ]
}
# Checks if argument is an existing alias
is_alias() {
[ -h "/bedrock/strata/${1}" ]
}
# Checks if argument is an existing stratum or alias
is_stratum_or_alias() {
[ -d "/bedrock/strata/${1}" ] || [ -h "/bedrock/strata/${1}" ]
}
# Checks if argument is an enabled stratum or alias
is_enabled() {
[ -e "/bedrock/run/enabled_strata/$(deref "${1}")" ]
}
# Checks if argument is the init-providing stratum
is_init() {
[ "$(deref init)" = "$(deref "${1}")" ]
}
# Checks if argument is the bedrock stratum
is_bedrock() {
[ "bedrock" = "$(deref "${1}")" ]
}
# Prints the root of the given stratum from the point of view of the init
# stratum.
#
# Sometimes this function's output is used directly, and sometimes it is
# prepended to another path. Use `--empty` in the latter situation to indicate
# the init-providing stratum's root should be treated as an empty string to
# avoid doubled up `/` characters.
stratum_root() {
if [ "${1}" = "--empty" ]; then
init_root=""
shift
else
init_root="/"
fi
stratum="${1}"
if is_init "${stratum}"; then
echo "${init_root}"
else
echo "/bedrock/strata/$(deref "${stratum}")"
fi
}
# Applies /bedrock/etc/bedrock.conf symlink requirements to the specified stratum.
#
# Use `--force` to indicate that, should a scenario occur which cannot be
# handled cleanly, remove problematic files. Otherwise generate a warning.
enforce_symlinks() {
force=false
if [ "${1}" = "--force" ]; then
force=true
shift
fi
stratum="${1}"
root="$(stratum_root --empty "${stratum}")"
for link in $(cfg_keys "symlinks"); do
proc_link="/proc/1/root${root}${link}"
tgt="$(cfg_values "symlinks" "${link}")"
proc_tgt="/proc/1/root${root}${tgt}"
cur_tgt="$(readlink "${proc_link}")" || true
if [ "${cur_tgt}" = "${tgt}" ]; then
# This is the desired situation. Everything is already
# setup.
continue
elif [ -h "${proc_link}" ]; then
# The symlink exists but is pointing to the wrong
# location. Fix it.
rm -f "${proc_link}"
ln -s "${tgt}" "${proc_link}"
elif ! [ -e "${proc_link}" ]; then
# Nothing exists at the symlink location. Create it.
mkdir -p "$(dirname "${proc_link}")"
ln -s "${tgt}" "${proc_link}"
elif [ -e "${proc_link}" ] && [ -h "${proc_tgt}" ]; then
# Non-symlink file exists at symlink location and a
# symlink exists at the target location. Swap them and
# ensure the symlink points where we want it to.
rm -f "${proc_tgt}"
mv "${proc_link}" "${proc_tgt}"
ln -s "${tgt}" "${proc_link}"
elif [ -e "${proc_link}" ] && ! [ -e "${proc_tgt}" ]; then
# Non-symlink file exists at symlink location, but
# nothing exists at tgt location. Move file to
# tgt then create symlink.
mkdir -p "$(dirname "${proc_tgt}")"
mv "${proc_link}" "${proc_tgt}"
ln -s "${tgt}" "${proc_link}"
elif "${force}" && ! mounts_in_dir "${root}" | grep '.'; then
# A file exists both at the desired location and at the
# target location. We do not know which of the two the
# user wishes to retain. Since --force was indicated
# and we found no mount points to indicate otherwise,
# assume this is a newly fetched stratum and we are
# free to manipulate its files aggressively.
rm -rf "${proc_link}"
ln -s "${tgt}" "${proc_link}"
elif [ "${link}" = "/var/lib/dbus/machine-id" ]; then
# Both /var/lib/dbus/machine-id and the symlink target
# /etc/machine-id exist. This occurs relatively often,
# such as when hand creating a stratum. Rather than
# nag end-users, pick which to use ourselves.
rm -f "${proc_link}"
ln -s "${tgt}" "${proc_link}"
else
# A file exists both at the desired location and at the
# target location. We do not know which of the two the
# user wishes to retain. Play it safe and just
# generate a warning.
printf "${color_warn}WARNING: File or directory exists at both \`${proc_link}\` and \`${proc_tgt}\`. Bedrock Linux expects only one to exist. Inspect both and determine which you wish to keep, then remove the other, and finally run \`brl repair ${stratum}\` to remedy the situation.${color_norm}\\n"
fi
done
}
enforce_shells() {
for stratum in $(/bedrock/bin/brl list); do
root="$(stratum_root --empty "${stratum}")"
shells="/proc/1/root${root}/etc/shells"
if [ -r "${shells}" ]; then
cat "/proc/1/root/${root}/etc/shells"
fi
done | awk -F/ '/^\// {print "/bedrock/cross/bin/"$NF}' |
sort | uniq >/bedrock/run/shells
for stratum in $(/bedrock/bin/brl list); do
root="$(stratum_root --empty "${stratum}")"
shells="/proc/1/root${root}/etc/shells"
if ! [ -r "${shells}" ] || [ "$(awk '/^\/bedrock\/cross\/bin\//' "${shells}")" != "$(cat /bedrock/run/shells)" ]; then
(
if [ -r "${shells}" ]; then
cat "${shells}"
fi
cat /bedrock/run/shells
) | sort | uniq >"${shells}-"
mv "${shells}-" "${shells}"
fi
done
rm -f /bedrock/run/shells
}
ensure_line() {
file="${1}"
good_regex="${2}"
bad_regex="${3}"
value="${4}"
if grep -q "${good_regex}" "${file}"; then
true
elif grep -q "${bad_regex}" "${file}"; then
sed "s!${bad_regex}!${value}!" "${file}" >"${file}-new"
mv "${file}-new" "${file}"
else
(
cat "${file}"
echo "${value}"
) >"${file}-new"
mv "${file}-new" "${file}"
fi
}
enforce_id_ranges() {
for stratum in $(/bedrock/bin/brl list); do
# /etc/login.defs is global such that in theory we only need to
# update one file. However, the logic to potentially update
# multiple is retained in case it is ever made local.
cfg="/bedrock/strata/${stratum}/etc/login.defs"
if [ -e "${cfg}" ]; then
ensure_line "${cfg}" "^[ \t]*UID_MIN[ \t][ \t]*1000$" "^[ \t]*UID_MIN\>.*$" "UID_MIN 1000"
ensure_line "${cfg}" "^[ \t]*UID_MAX[ \t][ \t]*65534$" "^[ \t]*UID_MAX\>.*$" "UID_MAX 65534"
ensure_line "${cfg}" "^[ \t]*SYS_UID_MIN[ \t][ \t]*1$" "^[ \t]*SYS_UID_MIN\>.*$" "SYS_UID_MIN 1"
ensure_line "${cfg}" "^[ \t]*SYS_UID_MAX[ \t][ \t]*999$" "^[ \t]*SYS_UID_MAX\>.*$" "SYS_UID_MAX 999"
ensure_line "${cfg}" "^[ \t]*GID_MIN[ \t][ \t]*1000$" "^[ \t]*GID_MIN\>.*$" "GID_MIN 1000"
ensure_line "${cfg}" "^[ \t]*GID_MAX[ \t][ \t]*65534$" "^[ \t]*GID_MAX\>.*$" "GID_MAX 65534"
ensure_line "${cfg}" "^[ \t]*SYS_GID_MIN[ \t][ \t]*1$" "^[ \t]*SYS_GID_MIN\>.*$" "SYS_GID_MIN 1"
ensure_line "${cfg}" "^[ \t]*SYS_GID_MAX[ \t][ \t]*999$" "^[ \t]*SYS_GID_MAX\>.*$" "SYS_GID_MAX 999"
fi
cfg="/bedrock/strata/${stratum}/etc/adduser.conf"
if [ -e "${cfg}" ]; then
ensure_line "${cfg}" "^FIRST_UID=1000$" "^FIRST_UID=.*$" "FIRST_UID=1000"
ensure_line "${cfg}" "^LAST_UID=65534$" "^LAST_UID=.*$" "LAST_UID=65534"
ensure_line "${cfg}" "^FIRST_SYSTEM_UID=1$" "^FIRST_SYSTEM_UID=.*$" "FIRST_SYSTEM_UID=1"
ensure_line "${cfg}" "^LAST_SYSTEM_UID=999$" "^LAST_SYSTEM_UID=.*$" "LAST_SYSTEM_UID=999"
ensure_line "${cfg}" "^FIRST_GID=1000$" "^FIRST_GID=.*$" "FIRST_GID=1000"
ensure_line "${cfg}" "^LAST_GID=65534$" "^LAST_GID=.*$" "LAST_GID=65534"
ensure_line "${cfg}" "^FIRST_SYSTEM_GID=1$" "^FIRST_SYSTEM_GID=.*$" "FIRST_SYSTEM_GID=1"
ensure_line "${cfg}" "^LAST_SYSTEM_GID=999$" "^LAST_SYSTEM_GID=.*$" "LAST_SYSTEM_GID=999"
fi
done
}
# List of architectures Bedrock Linux supports.
brl_archs() {
cat <<EOF
aarch64
armv7hl
armv7l
mips
mipsel
mips64el
ppc
ppc64
ppc64le
s390x
i386
i486
i586
i686
x86_64
EOF
}
#
# Many distros have different phrasing for the same exact CPU architecture.
# Standardize witnessed variations against Bedrock's convention.
#
standardize_architecture() {
case "${1}" in
aarch64 | arm64) echo "aarch64" ;;
armhf | armhfp | armv7h | armv7hl | armv7a) echo "armv7hl" ;;
arm | armel | armle | arm7 | armv7 | armv7l | armv7a_hardfp) echo "armv7l" ;;
i386) echo "i386" ;;
i486) echo "i486" ;;
i586) echo "i586" ;;
x86 | i686) echo "i686" ;;
mips | mipsbe | mipseb) echo "mips" ;;
mipsel | mipsle) echo "mipsel" ;;
mips64el | mips64le) echo "mips64el" ;;
ppc | ppc32 | powerpc | powerpc32) echo "ppc" ;;
ppc64 | powerpc64) echo "ppc64" ;;
ppc64el | ppc64le | powerpc64el | powerpc64le) echo "ppc64le" ;;
s390x) echo "s390x" ;;
amd64 | x86_64) echo "x86_64" ;;
esac
}
get_system_arch() {
if ! system_arch="$(standardize_architecture "$(get_attr "/bedrock/strata/bedrock/" "arch")")" || [ -z "${system_arch}" ]; then
system_arch="$(standardize_architecture "$(uname -m)")"
fi
if [ -z "${system_arch}" ]; then
abort "Unable to determine system CPU architecture"
fi
echo "${system_arch}"
}
check_arch_supported_natively() {
arch="${1}"
system_arch="$(get_system_arch)"
if [ "${system_arch}" = "${arch}" ]; then
return
fi
case "${system_arch}:${arch}" in
aarch64:armv7hl) return ;;
aarch64:armv7l) return ;;
armv7hl:armv7l) return ;;
# Not technically true, but binfmt does not differentiate
armv7l:armv7hl) return ;;
ppc64:ppc) return ;;
ppc64le:ppc) return ;;
x86_64:i386) return ;;
x86_64:i486) return ;;
x86_64:i586) return ;;
x86_64:i686) return ;;
esac
false
}
qemu_binary_for_arch() {
case "${1}" in
aarch64) echo "qemu-aarch64-static" ;;
i386) echo "qemu-i386-static" ;;
i486) echo "qemu-i386-static" ;;
i586) echo "qemu-i386-static" ;;
i686) echo "qemu-i386-static" ;;
armv7hl) echo "qemu-arm-static" ;;
armv7l) echo "qemu-arm-static" ;;
mips) echo "qemu-mips-static" ;;
mipsel) echo "qemu-mipsel-static" ;;
mips64el) echo "qemu-mips64el-static" ;;
ppc) echo "qemu-ppc-static" ;;
ppc64) echo "qemu-ppc64-static" ;;
ppc64le) echo "qemu-ppc64le-static" ;;
s390x) echo "qemu-s390x-static" ;;
x86_64) echo "qemu-x86_64-static" ;;
esac
}
setup_binfmt_misc() {
stratum="${1}"
mount="/proc/sys/fs/binfmt_misc"
arch="$(get_attr "/bedrock/strata/${stratum}" "arch" 2>/dev/null)" || true
# If stratum is native, skip setting up binfmt_misc
if [ -z "${arch}" ] || check_arch_supported_natively "${arch}"; then
return
fi
# ensure module is loaded
if ! [ -d "${mount}" ]; then
modprobe binfmt_misc
fi
if ! [ -d "${mount}" ]; then
abort "Unable to mount binfmt_misc to register handler for ${stratum}"
fi
# mount binfmt_misc if it is not already mounted
if ! [ -r "${mount}/register" ]; then
mount binfmt_misc -t binfmt_misc "${mount}"
fi
if ! [ -r "${mount}/register" ]; then
abort "Unable to mount binfmt_misc to register handler for ${stratum}"
fi
# Gather information needed to register with binfmt
unset name
unset sum
unset reg
case "${arch}" in
aarch64)
name="qemu-aarch64"
sum="707cf2bfbdb58152fc97ed4c1643ecd16b064465"
reg=':qemu-aarch64:M:0:\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-aarch64-static:OC'
;;
armv7l | armv7hl)
name="qemu-arm"
sum="bbada633c3eda72c9be979357b51c0ac8edb9eba"
reg=':qemu-arm:M:0:\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x28\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-arm-static:OC'
;;
mips)
name="qemu-mips"
sum="5751a5cf2bbc2cb081d314f4b340ca862c11b90c"
reg=':qemu-mips:M:0:\x7fELF\x01\x02\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x08:\xff\xff\xff\xff\xff\xff\xff\x00\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff:/usr/bin/qemu-mips-static:OC'
;;
mipsel)
name="qemu-mipsel"
sum="2bccf248508ffd8e460b211f5f4159906754a498"
reg=':qemu-mipsel:M:0:\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x08\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xfe\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-mipsel-static:OC'
;;
mips64el)
name="qemu-mips64el"
sum="ed9513fa110eed9085cf21a789a55e047f660237"
reg=':qemu-mips64el:M:0:\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x08\x00:\xff\xff\xff\xff\xff\xff\xff\x00\xfe\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-mips64el-static:OC'
;;
ppc)
name="qemu-ppc"
sum="da30ac101e6b9b5abeb975542c4420ad4e1a38a9"
reg=':qemu-ppc:M:0:\x7fELF\x01\x02\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x14:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff:/usr/bin/qemu-ppc-static:OC'
;;
ppc64)
name="qemu-ppc64"
sum="92eedc92be15ada7ee3d5703253f4e7744021a73"
reg=':qemu-ppc64:M:0:\x7fELF\x02\x02\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x15:\xff\xff\xff\xff\xff\xff\xff\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff:/usr/bin/qemu-ppc64-static:OC'
;;
ppc64le)
name="qemu-ppc64le"
sum="b42c326e62f05cae1d412d3b5549a06228aeb409"
reg=':qemu-ppc64le:M:0:\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x15\x00:\xff\xff\xff\xff\xff\xff\xff\xfc\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\x00:/usr/bin/qemu-ppc64le-static:OC'
;;
s390x)
name="qemu-s390x"
sum="9aed062ea40b5388fd4dea5e5da837c157854021"
reg=':qemu-s390x:M:0:\x7fELF\x02\x02\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x16:\xff\xff\xff\xff\xff\xff\xff\xfc\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff:/usr/bin/qemu-s390x-static:OC'
;;
i386 | i486 | i586 | i686)
name="qemu-i386"
sum="59723d1b5d3983ff606ff2befc151d0a26543707"
reg=':qemu-i386:M:0:\x7fELF\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x03\x00:\xff\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfe\xff\xff\xff:/usr/bin/qemu-i386-static:OC'
;;
x86_64)
name="qemu-x86_64"
sum="823c58bdb19743335c68d036fdc795e3be57e243"
reg=':qemu-x86_64:M:0:\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x3e\x00:\xff\xff\xff\xff\xff\xfe\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff:/usr/bin/qemu-x86_64-static:OC'
;;
*)
abort "Stratum \"${stratum}\" has unrecognized arch ${arch}"
;;
esac
# Remove registration with differing values.
if [ -r "${mount}/${name}" ] && [ "$(sha1sum "${mount}/${name}" | awk '{print$1}')" != "${sum}" ]; then
notice "Removing conflicting ${arch} binfmt registration"
echo '-1' >"${mount}/${name}"
fi
# Register if not already registered
if ! [ -r "${mount}/${name}" ]; then
echo "${reg}" >"${mount}/register"
fi
# Enable
printf "1" >"${mount}/${name}"
printf "1" >"${mount}/status"
}
# Run executable in /bedrock/libexec with init stratum.
#
# Requires the init stratum to be enabled, which is typically true in a
# healthy, running Bedrock system.
stinit() {
cmd="${1}"
shift
/bedrock/bin/strat init "/bedrock/libexec/${cmd}" "${@:-}"
}
# Kill all processes chrooted into the specified directory or a subdirectory
# thereof.
#
# Use `--init` to indicate this should be run from the init stratum's point of
# view.
kill_chroot_procs() {
if [ "${1:-}" = "--init" ]; then
x_readlink="stinit busybox readlink"
x_realpath="stinit busybox realpath"
shift
else
x_readlink="readlink"
x_realpath="realpath"
fi
dir="$(${x_realpath} "${1}")"
require_root
sent_sigterm=false
# Try SIGTERM. Since this is not atomic - a process could spawn
# between recognition of its parent and killing its parent - try
# multiple times to minimize the chance we miss one.
for _ in $(seq 1 5); do
for pid in $(ps -A -o pid); do
root="$(${x_readlink} "/proc/${pid}/root")" || continue
case "${root}" in
"${dir}" | "${dir}/"*)
kill "${pid}" 2>/dev/null || true
sent_sigterm=true
;;
esac
done
done
# If we sent SIGTERM to any process, give it time to finish then
# ensure it is dead with SIGKILL. Again, try multiple times just in
# case new processes spawn.
if "${sent_sigterm}"; then
# sleep for a quarter second
usleep 250000
for _ in $(seq 1 5); do
for pid in $(ps -A -o pid); do
root="$(${x_readlink} "/proc/${pid}/root")" || continue
case "${root}" in
"${dir}" | "${dir}/"*)
kill -9 "${pid}" 2>/dev/null || true
;;
esac
done
done
fi
# Unless we were extremely unlucky with kill/spawn race conditions or