Debian Codegraph @

scripts/functions

raw
1 # -*- shell-script -*-
2 # shellcheck shell=sh
3
4 _log_msg()
5 {
6 if [ "${quiet?}" = "y" ]; then return; fi
7 # shellcheck disable=SC2059
8 printf "$@"
9 return 0 # Prevents error carry over in case of unavailable console
10 }
11
12 log_success_msg()
13 {
14 _log_msg "Success: %s\\n" "$*"
15 }
16
17 log_failure_msg()
18 {
19 _log_msg "Failure: %s\\n" "$*"
20 }
21
22 log_warning_msg()
23 {
24 _log_msg "Warning: %s\\n" "$*"
25 }
26
27 log_begin_msg()
28 {
29 _log_msg "Begin: %s ... " "$*"
30 }
31
32 log_end_msg()
33 {
34 _log_msg "done.\\n"
35 }
36
37 panic()
38 {
39 local console rest IFS
40
41 if command -v chvt >/dev/null 2>&1; then
42 chvt 1
43 fi
44
45 echo "$@"
46
47 # The panic= parameter implies we should disallow console access
48 if [ -n "${panic?}" ]; then
49 delay=
50 case "${panic?}" in
51 -*[![:digit:].]*) # invalid: wait forever
52 ;;
53 -*) # timeout < 0: reboot immediately
54 delay=0
55 ;;
56 0 | *[![:digit:].]*) # timeout = 0 or invalid: wait forever
57 ;;
58 *) # timeout > 0: seconds before rebooting
59 delay="${panic}"
60 ;;
61 esac
62 if [ -n "${delay}" ]; then
63 echo "Rebooting automatically due to panic= boot argument"
64 sleep "${delay}"
65 reboot -f
66 else
67 echo "Halting automatically due to panic= boot argument"
68 halt -f
69 fi
70 exit # in case reboot fails, force kernel panic
71 fi
72
73 run_scripts /scripts/panic
74
75 # Try to use setsid, which will enable job control in the shell
76 # and paging in more
77 if command -v setsid >/dev/null 2>&1; then
78 unset IFS
79 read -r console rest </proc/consoles
80 if [ "${console}" = "tty0" ]; then
81 # Need to choose a specific VT
82 console="tty1"
83 fi
84 # We don't have 'setsid -c' so we need to setsid, open
85 # the tty, and finally exec an interactive shell
86 REASON="$*" PS1='(initramfs) ' setsid sh -c "exec sh -i <>/dev/${console} 1>&0 2>&1"
87 else
88 REASON="$*" PS1='(initramfs) ' sh -i </dev/console >/dev/console 2>&1
89 fi
90 }
91
92 maybe_break()
93 {
94 case ",${break?}," in
95 *,$1,*)
96 if [ "$1" = "top" ]; then
97 # udev is not yet running, so load keyboard drivers
98 if [ "${quiet}" = "y" ]; then
99 opts="-q"
100 else
101 opts="-v"
102 fi
103 /sbin/modprobe ${opts} -a i8042 atkbd ehci-pci ehci-orion \
104 ehci-hcd ohci-hcd ohci-pci uhci-hcd usbhid xhci \
105 xhci-pci xhci-hcd
106 /sbin/modprobe ${opts} -a simpledrm simplefb framebuffer_coreboot
107 sleep 2
108 for modalias in /sys/bus/hid/devices/*/modalias; do
109 if [ -f "${modalias}" ]; then
110 /sbin/modprobe ${opts} -b "$(cat "${modalias}")"
111 fi
112 done
113 fi
114 panic "Spawning shell within the initramfs"
115 ;;
116 esac
117 }
118
119 # For boot time only; this is overridden at build time in hook-functions
120 run_scripts()
121 {
122 initdir=${1}
123 [ ! -d "${initdir}" ] && return
124
125 shift
126 . "${initdir}/ORDER"
127 }
128
129 # Load custom modules first
130 load_modules()
131 {
132 if [ -e /conf/modules ]; then
133 while read -r m; do
134 # Skip empty lines
135 if [ -z "$m" ]; then
136 continue
137 fi
138 # Skip comments - d?ash removes whitespace prefix
139 com=$(printf "%.1s" "${m}")
140 if [ "$com" = "#" ]; then
141 continue
142 fi
143 # shellcheck disable=SC2086
144 /sbin/modprobe $m
145 done < /conf/modules
146 fi
147 }
148
149 _uptime() {
150 local uptime
151 uptime="$(cat /proc/uptime)"
152 uptime="${uptime%%[. ]*}"
153 echo "$uptime"
154 }
155
156 time_elapsed() {
157 if [ -z "${starttime-}" ]; then
158 log_failure_msg "time_elapsed() called before \$starttime initialized"
159 echo 0
160 fi
161 local delta
162 delta="$(_uptime)"
163 delta=$((delta - starttime))
164 echo "$delta"
165 }
166
167 # lilo compatibility
168 parse_numeric() {
169 case $1 in
170 *:*)
171 # Does it match /[0-9]*:[0-9]*/?
172 minor=${1#*:}
173 major=${1%:*}
174 case $major$minor in
175 *[!0-9]*)
176 # No.
177 return
178 ;;
179 esac
180 ;;
181 "" | *[!A-Fa-f0-9]*)
182 # "", "/*", etc.
183 return
184 ;;
185 *)
186 # [A-Fa-f0-9]*
187 value=$(( 0x${1} ))
188 minor=$(( (value & 0xff) | (value >> 12) & 0xfff00 ))
189 major=$(( (value >> 8) & 0xfff ))
190 ;;
191 esac
192
193 # shellcheck disable=SC2034
194 ROOT="/dev/block/${major}:${minor}"
195 }
196
197 # Parameter: device node to check
198 # Echos fstype to stdout
199 # Return value: indicates if an fs could be recognized
200 get_fstype ()
201 {
202 local FS FSTYPE
203 FS="${1}"
204
205 # blkid has a more complete list of file systems,
206 # but fstype is more robust
207 FSTYPE="unknown"
208 eval "$(fstype "${FS}" 2> /dev/null)"
209 if [ "$FSTYPE" = "unknown" ]; then
210 FSTYPE=$(blkid -o value -s TYPE "${FS}") || return
211 fi
212 echo "${FSTYPE}"
213 return 0
214 }
215
216 _set_netdev_from_ip_param()
217 {
218 # If the ip= parameter is present and specifies a device, use
219 # that in preference to any device name we already have
220 local IFS=:
221 set -f
222 # shellcheck disable=SC2086
223 set -- ${IP-}
224 set +f
225 if [ -n "${6-}" ]; then
226 DEVICE="$6"
227 return 0
228 fi
229 return 1
230 }
231
232 _set_netdev_from_hw_address()
233 {
234 local want_address="$1"
235 local device
236 for device in /sys/class/net/*; do
237 if [ -f "$device/address" ] &&
238 [ "$(cat "$device/address")" = "$want_address" ]; then
239 DEVICE="${device##*/}"
240 return 0
241 fi
242 done
243 return 1
244 }
245
246 _usable_netdev_exists()
247 {
248 # Look for a device with IFF_LOOPBACK clear and (IFF_BROADCAST
249 # or IFF_POINTTOPOINT) set. This is the same test the kernel
250 # and ipconfig apply to find a device.
251 local device
252 local flags
253 for device in /sys/class/net/*; do
254 if [ -f "${device}/flags" ]; then
255 flags="$(cat "${device}/flags")"
256 if [ "$((flags & 8))" -eq 0 ] &&
257 [ "$((flags & 0x12))" -ne 0 ]; then
258 return 0
259 fi
260 fi
261 done
262 return 1
263 }
264
265 _update_ip_param()
266 {
267 # If the ip= parameter is present, and is a colon-separated list,
268 # but does not specify a device, substitute in the device name
269 # we have
270 local IFS=:
271 set -f
272 # shellcheck disable=SC2086
273 set -- ${IP}
274 set +f
275 if [ -z "${6-}" ] && [ $# -ge 2 ] && [ -n "${DEVICE-}" ]; then
276 IP="$1:$2:$3:$4:$5:${DEVICE}"
277 shift 6 || shift $#
278 IP="${IP}:$*"
279 fi
280 }
281
282 configure_networking()
283 {
284 local netdev_desc
285
286 # The order of precedence here is:
287 # 1. Device specified by ip= kernel parameter
288 # 2. Device matching MAC specified by BOOTIF= kernel parameter
289 # 3. Build-time DEVICE variable
290 # In case 2 we only discover the device name while waiting
291 # for a device.
292 if _set_netdev_from_ip_param; then
293 netdev_desc="${DEVICE}"
294 elif [ -n "${BOOTIF-}" ]; then
295 # pxelinux sets BOOTIF to a value based on the mac address of the
296 # network card used to PXE boot
297 # pxelinux sets BOOTIF to 01-$mac_address
298
299 # strip off the leading "01-", which isn't part of the mac
300 # address
301 temp_mac=${BOOTIF#*-}
302
303 # convert to typical mac address format by replacing "-" with ":"
304 bootif_mac=""
305 IFS='-'
306 for x in $temp_mac ; do
307 if [ -z "$bootif_mac" ]; then
308 bootif_mac="$x"
309 else
310 bootif_mac="$bootif_mac:$x"
311 fi
312 done
313 unset IFS
314
315 _set_netdev_from_hw_address "${bootif_mac}"
316 netdev_desc="device with address ${bootif_mac}"
317 elif [ -n "${DEVICE-}" ]; then
318 netdev_desc="${DEVICE}"
319 else
320 netdev_desc="any network device"
321 fi
322
323 # networking already configured thus bail out
324 [ -n "${DEVICE-}" ] && [ -e /run/net-"${DEVICE}".conf ] && return 0
325
326 local netdevwait=180
327 log_begin_msg "Waiting up to ${netdevwait} secs for ${netdev_desc} to become available"
328 while true; do
329 if [ "$(time_elapsed)" -ge "$netdevwait" ]; then
330 log_failure_msg "Network device did not appear in time"
331 break
332 fi
333 if [ -n "${DEVICE-}" ]; then
334 [ -e "/sys/class/net/${DEVICE}" ] && break
335 elif [ -n "${bootif_mac-}" ]; then
336 _set_netdev_from_hw_address "${bootif_mac}" && break
337 else
338 _usable_netdev_exists && break
339 fi
340 sleep 1
341 done
342 log_end_msg
343
344 _update_ip_param
345
346 wait_for_udev 10
347
348 # support ip options see linux sources
349 # Documentation/filesystems/nfs/nfsroot.txt
350 # Documentation/frv/booting.txt
351
352 for ROUNDTTT in 2 3 4 6 9 16 25 36 64 100; do
353
354 # The NIC is to be configured if this file does not exist.
355 # Ip-Config tries to create this file and when it succeds
356 # creating the file, ipconfig is not run again.
357 for x in /run/net-"${DEVICE-}".conf /run/net-*.conf ; do
358 [ -e "$x" ] && break 2
359 done
360
361 case "${IP-}" in
362 none|off)
363 # Do nothing
364 ;;
365 ""|on|any)
366 # Bring up device
367 ipconfig -t ${ROUNDTTT} "${DEVICE}"
368 ;;
369 dhcp|bootp|rarp|both)
370 ipconfig -t ${ROUNDTTT} -c "${IP}" -d "${DEVICE}"
371 ;;
372 *)
373 ipconfig -t ${ROUNDTTT} -d "$IP"
374 ;;
375 esac
376 done
377
378 # source ipconfig output (first try specific bootdevice, then any
379 # interface...). ipconfig should have quit after first response
380 local file
381 for file in "/run/net-${DEVICE-}.conf" /run/net-*.conf; do
382 if [ -e "$file" ]; then
383 . "$file"
384 break
385 fi
386 done
387
388 netinfo_to_resolv_conf /etc/resolv.conf "/run/net-${DEVICE-}.conf" /run/net-*.conf
389
390 if test -n "${HOSTNAME-}"; then
391 persist_hostname "${HOSTNAME}" "${DNSDOMAIN-}"
392 fi
393 }
394
395 # Write resolv.conf from /run/net-<device> style files.
396 # $1=resolv.conf path (print to stdout if "-" is specified)
397 # remaining parameters: /run/net-<device> style files
398 netinfo_to_resolv_conf()
399 {
400 local domain="" n="" nameservers="" net_file="" resolv_conf="" search="" output="$1" CR="
401 "
402 shift
403
404 for net_file in "$@"; do
405 # Define sourced variables as local to avoid causing side effects.
406 # shellcheck disable=SC2034
407 local DEVICE="" PROTO="" IPV4ADDR="" IPV4BROADCAST="" IPV4NETMASK="" IPV4ROUTE0SUBNET="" \
408 IPV4ROUTE0GATEWAY="" IPV4ROUTE1SUBNET="" IPV4ROUTE1GATEWAY="" IPV4GATEWAY="" \
409 IPV4DNS0="" IPV4DNS1="" HOSTNAME="" DNSDOMAIN="" NISDOMAIN="" ROOTSERVER="" ROOTPATH="" \
410 filename="" UPTIME="" DHCPLEASETIME="" DOMAINSEARCH=""
411 [ -e "$net_file" ] || continue
412 . "$net_file" || { echo "Error: Failed to source $net_file" >&2; return 1; }
413 if test -n "${DNSDOMAIN}"; then
414 domain="${DNSDOMAIN}"
415 fi
416 for n in "${IPV4DNS0}" "${IPV4DNS1}"; do
417 if test -z "$n" -o "$n" = 0.0.0.0; then
418 continue
419 fi
420 # Remove duplicates
421 case " ${nameservers} " in
422 *\ $n\ *)
423 continue ;;
424 esac
425 nameservers="${nameservers} ${n}"
426 done
427 for n in ${DOMAINSEARCH}; do
428 [ -n "$n" ] || continue
429 # Remove duplicates
430 case " ${search} " in
431 *\ $n\ *)
432 continue ;;
433 esac
434 search="${search} ${n}"
435 done
436 done
437
438 # Construct content for resolv.conf
439 if test -n "${domain}"; then
440 resolv_conf="${resolv_conf}domain ${domain}${CR}"
441 fi
442 for n in ${nameservers}; do
443 resolv_conf="${resolv_conf}nameserver $n${CR}"
444 done
445 if test -n "${search}"; then
446 resolv_conf="${resolv_conf}search ${search# }${CR}"
447 fi
448
449 if test -z "$resolv_conf"; then
450 echo "no search or nameservers found in $*" 1>&2
451 return
452 fi
453 if test "$output" = "-"; then
454 printf "%s" "$resolv_conf"
455 else
456 printf "%s" "$resolv_conf" > "$output"
457 fi
458 }
459
460 _generate_hosts_content()
461 {
462 local hostname="$1"
463 local domain="$2"
464 local fqdn
465
466 if test -n "${domain}"; then
467 fqdn="${hostname}.${domain} "
468 else
469 fqdn=""
470 fi
471 cat <<EOF
472 127.0.0.1 localhost
473 127.0.1.1 ${fqdn}${hostname}
474
475 # The following lines are desirable for IPv6 capable hosts
476 ::1 localhost ip6-localhost ip6-loopback
477 ff02::1 ip6-allnodes
478 ff02::2 ip6-allrouters
479 EOF
480 }
481
482 # Write hostname into /etc/hostname and /etc/hosts
483 # $1=hostname
484 # $2=domain (optional)
485 persist_hostname()
486 {
487 local hostname="$1"
488 local domain="${2-}"
489
490 echo "$hostname" > /etc/hostname
491 echo "$hostname" > /proc/sys/kernel/hostname
492 _generate_hosts_content "$hostname" "$domain" > /etc/hosts
493 }
494
495 # Wait for queued kernel/udev events
496 wait_for_udev()
497 {
498 command -v udevadm >/dev/null 2>&1 || return 0
499 udevadm settle ${1:+--timeout=$1}
500 }
501
502 # Find a specific fstab entry
503 # $1=mountpoint
504 # $2=fstype (optional)
505 # returns 0 on success, 1 on failure (not found or no fstab)
506 read_fstab_entry() {
507 # Not found by default.
508 found=1
509
510 for file in ${rootmnt?}/etc/fstab; do
511 if [ -f "$file" ]; then
512 # shellcheck disable=SC2034
513 while read -r MNT_FSNAME MNT_DIR MNT_TYPE MNT_OPTS MNT_FREQ MNT_PASS MNT_JUNK; do
514 case "$MNT_FSNAME" in
515 ""|\#*)
516 continue;
517 ;;
518 esac
519 if [ "$MNT_DIR" = "$1" ]; then
520 if [ -n "${2-}" ]; then
521 [ "$MNT_TYPE" = "$2" ] || continue;
522 fi
523 found=0
524 break 2
525 fi
526 done < "$file"
527 fi
528 done
529
530 return $found
531 }
532
533 # Resolve device node from a name. This expands any LABEL or UUID.
534 # $1=name
535 # Resolved name is echoed.
536 resolve_device() {
537 DEV="$1"
538
539 case "$DEV" in
540 LABEL=* | UUID=* | PARTLABEL=* | PARTUUID=*)
541 DEV="$(blkid -l -t "$DEV" -o device)" || return 1
542 ;;
543 esac
544 [ -e "$DEV" ] && echo "$DEV"
545 }
546
547 # Check a file system.
548 # $1=device
549 # $2=mountpoint (for diagnostics only)
550 # $3=type (may be "auto")
551 _checkfs_once()
552 {
553 DEV="$1"
554 NAME="$2"
555 TYPE="$3"
556 if [ "$NAME" = "/" ] ; then
557 NAME="root"
558 fi
559 FSCK_LOGFILE=/run/initramfs/fsck.log
560 FSCK_STAMPFILE=/run/initramfs/fsck-${NAME#/}
561
562 if [ "${TYPE}" = "auto" ]; then
563 TYPE="$(get_fstype "${DEV}")"
564 fi
565
566 FSCKCODE=0
567 if [ -z "${TYPE}" ]; then
568 log_warning_msg "Type of $NAME file system is unknown, so skipping check."
569 return
570 fi
571 if ! command -v fsck >/dev/null 2>&1; then
572 log_warning_msg "fsck not present, so skipping $NAME file system"
573 return
574 fi
575 if [ "${fastboot?}" = "y" ] ; then
576 log_warning_msg "Fast boot enabled, so skipping $NAME file system check."
577 return
578 fi
579
580 if [ "${forcefsck?}" = "y" ]
581 then
582 force="-f"
583 else
584 force=""
585 fi
586
587 if [ "${fsckfix?}" = "y" ]
588 then
589 fix="-y"
590 elif [ "${fsckfix?}" = "n" ]
591 then
592 fix="-n"
593 else
594 fix="-a"
595 fi
596
597 spinner=""
598 if [ -z "${debug?}" ]; then
599 spinner="-C"
600 fi
601
602 if [ "${quiet}" = n ]
603 then
604 log_begin_msg "Will now check $NAME file system"
605 logsave -a -s $FSCK_LOGFILE fsck $spinner $force $fix -V -t "$TYPE" "$DEV"
606 FSCKCODE=$?
607 log_end_msg
608 else
609 log_begin_msg "Checking $NAME file system"
610 logsave -a -s $FSCK_LOGFILE fsck $spinner $force $fix -T -t "$TYPE" "$DEV"
611 FSCKCODE=$?
612 log_end_msg
613 fi
614
615 # NOTE: "failure" is defined as exiting with a return code of
616 # 4, possibly or-ed with other flags. A return code of 1
617 # indicates that file system errors were corrected but that
618 # the boot may proceed.
619 #
620 if [ "$FSCKCODE" -eq 32 ]
621 then
622 log_warning_msg "File system check was interrupted by user"
623 elif [ $((FSCKCODE & 4)) -eq 4 ]
624 then
625 log_failure_msg "File system check of the $NAME filesystem failed"
626 return 1
627 elif [ "$FSCKCODE" -gt 1 ]
628 then
629 log_warning_msg "File system check failed but did not detect errors"
630 sleep 5
631 else
632 true >"$FSCK_STAMPFILE"
633 fi
634 return 0
635 }
636
637 checkfs()
638 {
639 while ! _checkfs_once "$@"; do
640 panic "The $2 filesystem on $1 requires a manual fsck"
641 done
642 }
643
644 # Mount a file system. We parse the information from the fstab. This
645 # should be overridden by any boot script which can mount arbitrary
646 # filesystems such as /usr. This default implementation delegates to
647 # local or nfs based upon the filesystem type.
648 # $1=mountpoint mount location
649 mountfs()
650 {
651 type=local
652 read_fstab_entry "$1"
653 if [ "${MNT_TYPE}" = "nfs" ] || [ "${MNT_TYPE}" = "nfs4" ]; then
654 type=nfs
655 fi
656
657 ${type}_mount_fs "$1"
658 }
659
660 # Filter matching items out of a comma-separated list.
661 # $1=list
662 # $2=pattern to match (may include shell wildcards)
663 list_filter_out()
664 {
665 local pattern="$2"
666 local item result
667 local IFS=,
668 set -f
669 # shellcheck disable=SC2086
670 set -- $1
671 set +f
672 for item in "$@"; do
673 # shellcheck disable=SC2254
674 case "$item" in
675 $pattern)
676 ;;
677 *)
678 result="${result:+$result,}${item}"
679 ;;
680 esac
681 done
682 echo "$result"
683 }
684
685 # Mount the root file system. It should be overridden by all
686 # boot scripts.
687 mountroot()
688 {
689 :
690 }
691
692 # Run /scripts/${boot}-top. This should be overridden by all boot
693 # scripts.
694 mount_top()
695 {
696 :
697 }
698
699 # Run /scripts/${boot}-premount. This should be overridden by all boot
700 # scripts.
701 mount_premount()
702 {
703 :
704 }
705
706 # Run /scripts/${boot}-bottom. This should be overridden by all boot
707 # scripts.
708 mount_bottom()
709 {
710 :
711 }