crypt: remove emergency source of dracut-lib.sh
[dracut.git] / dracut-functions
blob5e486bf70b76378392dbc43a0c26e2e03a66efb0
1 #!/bin/bash
3 # functions used by dracut and other tools.
5 # Copyright 2005-2009 Red Hat, Inc. All rights reserved.
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 IF_RTLD=""
22 IF_dynamic=""
24 # Generic substring function. If $2 is in $1, return 0.
25 strstr() { [[ $1 =~ $2 ]]; }
27 # Create all subdirectories for given path without creating the last element.
28 # $1 = path
29 mksubdirs() { mkdir -p ${1%/*}; }
31 # Version comparision function. Assumes Linux style version scheme.
32 # $1 = version a
33 # $2 = comparision op (gt, ge, eq, le, lt, ne)
34 # $3 = version b
35 vercmp() {
36 local n1=(${1//./ }) op=$2 n2=(${3//./ }) i res
38 for ((i=0; ; i++))
40 if [[ ! ${n1[i]}${n2[i]} ]]; then res=0
41 elif ((${n1[i]:-0} > ${n2[i]:-0})); then res=1
42 elif ((${n1[i]:-0} < ${n2[i]:-0})); then res=2
43 else continue
45 break
46 done
48 case $op in
49 gt) ((res == 1));;
50 ge) ((res != 2));;
51 eq) ((res == 0));;
52 le) ((res != 1));;
53 lt) ((res == 2));;
54 ne) ((res != 0));;
55 esac
58 # Log initrd creation.
59 if ! [[ $dracutlogfile ]]; then
60 [[ $dracutbasedir = /usr/share/dracut ]] && \
61 dracutlogfile=/var/log/dracut.log || \
62 dracutlogfile=/tmp/dracut.log
63 # [[ -w $dracutlogfile ]] || dracutlogfile=/tmp/dracut.log
64 if [[ -w $dracutlogfile ]]; then
65 >"$dracutlogfile"
69 dwarning() {
70 echo "W: $@" >&2
71 [[ -w $dracutlogfile ]] && echo "W: $@" >>"$dracutlogfile"
74 dinfo() {
75 [[ $beverbose ]] && echo "I: $@" >&2
76 [[ -w $dracutlogfile ]] && echo "I: $@" >>"$dracutlogfile"
79 derror() {
80 echo "E: $@" >&2
81 [[ -w $dracutlogfile ]] && echo "E: $@" >>"$dracutlogfile"
84 # Function prints global variables in format name=value line by line.
85 # $@ = list of global variables' name
86 print_vars() {
87 local var value
89 for var in $@
91 value=$(eval echo \$$var)
92 [[ ${value} ]] && echo "${var}=\"${value}\""
93 done
96 get_fs_env() {
97 eval $(udevadm info --query=env --name=$1|egrep 'ID_FS_(TYPE|UUID)=')
98 [[ $ID_FS_TYPE ]] && return
100 if [[ -x /lib/udev/vol_id ]]; then
101 eval $(/lib/udev/vol_id --export $1)
102 elif find_binary blkid >/dev/null; then
103 eval $(blkid -o udev $1)
104 else
105 return 1
109 get_fs_type() (
110 get_fs_env $1 || return
111 echo $ID_FS_TYPE
114 get_fs_uuid() (
115 get_fs_env $1 || return
116 echo $ID_FS_UUID
119 # finds the major:minor of the block device backing the root filesystem.
120 find_block_device() {
121 local rootdev blkdev fs type opts misc
122 while read blkdev fs type opts misc; do
123 [[ $blkdev = rootfs ]] && continue # skip rootfs entry
124 [[ $fs = $1 ]] && { rootdev=$blkdev; break; } # we have a winner!
125 done < /proc/mounts
126 [[ -b $rootdev ]] || return 1 # oops, not a block device.
127 # get major/minor for the device
128 ls -nLl "$rootdev" | \
129 (read x x x x maj min x; maj=${maj//,/}; echo $maj:$min)
132 find_root_block_device() { find_block_device /; }
134 # Walk all the slave relationships for a given block device.
135 # Stop when our helper function returns success
136 # $1 = function to call on every found block device
137 # $2 = block device in major:minor format
138 check_block_and_slaves() {
139 local x
140 [[ -b /dev/block/$2 ]] || return 1 # Not a block device? So sorry.
141 "$1" $2 && return
142 check_vol_slaves "$@" && return 0
143 if [[ -f "/sys/dev/block/$2/../dev" ]]; then
144 check_block_and_slaves $1 $(cat "/sys/dev/block/$2/../dev") && return 0
146 [[ -d /sys/dev/block/$2/slaves ]] || return 1
147 for x in /sys/dev/block/$2/slaves/*/dev; do
148 [[ -f $x ]] || continue
149 check_block_and_slaves $1 $(cat "$x") && return 0
150 done
151 return 1
154 get_numeric_dev() {
155 ls -lH "$1" | { read a b c d maj min rest; printf "%d:%d" ${maj%%,} $min;}
158 # ugly workaround for the lvm design
159 # There is no volume group device,
160 # so, there are no slave devices for volume groups.
161 # Logical volumes only have the slave devices they really live on,
162 # but you cannot create the logical volume without the volume group.
163 # And the volume group might be bigger than the devices the LV needs.
164 check_vol_slaves() {
165 for i in /dev/mapper/*; do
166 lv=$(get_numeric_dev $i)
167 if [[ $lv = $2 ]]; then
168 vg=$(lvm lvs --noheadings -o vg_name $i 2>/dev/null)
169 # strip space
170 vg=$(echo $vg)
171 if [[ $vg ]]; then
172 for pv in $(lvm vgs --noheadings -o pv_name "$vg" 2>/dev/null); \
174 check_block_and_slaves $1 $(get_numeric_dev $pv) \
175 && return 0
176 done
179 done
180 return 1
183 # Install a directory, keeping symlinks as on the original system.
184 # Example: if /lib64 points to /lib on the host, "inst_dir /lib/file"
185 # will create ${initdir}/lib64, ${initdir}/lib64/file,
186 # and a symlink ${initdir}/lib -> lib64.
187 inst_dir() {
188 local dir="$1"
189 [[ -e "${initdir}$dir" ]] && return 0
191 # iterate over parent directories
192 local file=""
193 local IFS="/"
194 for part in $dir; do
195 [ -z "$part" ] && continue
196 file="$file/$part"
197 [[ -e "${initdir}$file" ]] && continue
199 if [ -L "$file" ]; then
200 # create link as the original
201 local target=$(readlink "$file")
202 ln -sfn "$target" "${initdir}$file" || return 1
203 # resolve relative path and recursively install destionation
204 [[ "$target" = "${target##*/}" ]] && target="${file%/*}/$target"
205 inst_dir "$target"
206 else
207 # create directory
208 mkdir -p "${initdir}$file" || return 1
210 done
213 # $1 = file to copy to ramdisk
214 # $2 (optional) Name for the file on the ramdisk
215 # Location of the image dir is assumed to be $initdir
216 # We never overwrite the target if it exists.
217 inst_simple() {
218 local src target
219 [[ -f $1 ]] || return 1
220 src=$1 target="${2:-$1}"
221 if ! [[ -d ${initdir}$target ]]; then
222 [[ -e ${initdir}$target ]] && return 0
223 inst_dir "${target%/*}"
225 dinfo "Installing $src"
226 cp -pfL "$src" "${initdir}$target"
229 # find symlinks linked to given library file
230 # $1 = library file
231 # Function searches for symlinks by stripping version numbers appended to
232 # library filename, checks if it points to the same target and finally
233 # prints the list of symlinks to stdout.
235 # Example:
236 # rev_lib_symlinks libfoo.so.8.1
237 # output: libfoo.so.8 libfoo.so
238 # (Only if libfoo.so.8 and libfoo.so exists on host system.)
239 rev_lib_symlinks() {
240 [[ ! $1 ]] && return 0
242 local fn="$1" orig="$(readlink -f "$1")" links=''
244 [[ ${fn} =~ .*\.so\..* ]] || return 1
246 until [[ ${fn##*.} == so ]]; do
247 fn="${fn%.*}"
248 [[ -L ${fn} && $(readlink -f "${fn}") == ${orig} ]] && links+=" ${fn}"
249 done
251 echo ${links}
254 # Same as above, but specialized to handle dynamic libraries.
255 # It handles making symlinks according to how the original library
256 # is referenced.
257 inst_library() {
258 local src=$1 dest=${2:-$1} lib reallib symlink
259 [[ -e $initdir$dest ]] && return 0
260 if [[ -L $src ]]; then
261 reallib=$(readlink -f "$src")
262 lib=${src##*/}
263 inst_simple "$reallib" "$reallib"
264 inst_dir "${dest%/*}"
265 (cd "${initdir}${dest%/*}" && ln -s "$reallib" "$lib")
266 else
267 inst_simple "$src" "$dest"
270 # Create additional symlinks. See rev_symlinks description.
271 for symlink in $(rev_lib_symlinks $src) $(rev_lib_symlinks $reallib); do
272 [[ ! -e $initdir$symlink ]] && {
273 dinfo "Creating extra symlink: $symlink"
274 inst_symlink $symlink
276 done
279 # find a binary. If we were not passed the full path directly,
280 # search in the usual places to find the binary.
281 find_binary() {
282 local binpath="/bin /sbin /usr/bin /usr/sbin" p
283 [[ -z ${1##/*} && -x $1 ]] && { echo $1; return 0; }
284 for p in $binpath; do
285 [[ -x $p/$1 ]] && { echo "$p/$1"; return 0; }
286 done
287 return 1
290 # Same as above, but specialized to install binary executables.
291 # Install binary executable, and all shared library dependencies, if any.
292 inst_binary() {
293 local bin target
294 bin=$(find_binary "$1") || return 1
295 target=${2:-$bin}
296 inst_symlink $bin $target && return 0
297 local LDSO NAME IO FILE ADDR I1 n f TLIBDIR
298 [[ -e $initdir$target ]] && return 0
299 # I love bash!
300 LC_ALL=C ldd $bin 2>/dev/null | while read line; do
301 [[ $line = 'not a dynamic executable' ]] && return 1
302 if [[ $line =~ not\ found ]]; then
303 derror "Missing a shared library required by $bin."
304 derror "Run \"ldd $bin\" to find out what it is."
305 derror "dracut cannot create an initrd."
306 exit 1
308 so_regex='([^ ]*/lib[^/]*/[^ ]*\.so[^ ]*)'
309 [[ $line =~ $so_regex ]] || continue
310 FILE=${BASH_REMATCH[1]}
311 [[ -e ${initdir}$FILE ]] && continue
312 # see if we are loading an optimized version of a shared lib.
313 lib_regex='^(/lib[^/]*).*'
314 if [[ $FILE =~ $lib_regex ]]; then
315 TLIBDIR=${BASH_REMATCH[1]}
316 BASE=${FILE##*/}
317 # prefer nosegneg libs, then unoptimized ones.
318 for f in "$TLIBDIR/i686/nosegneg" "$TLIBDIR"; do
319 [[ -e $f/$BASE ]] || continue
320 FILE=$f/$BASE
321 break
322 done
323 inst_library "$FILE" "$TLIBDIR/$BASE"
324 IF_dynamic=yes
325 continue
327 inst_library "$FILE"
328 done
329 inst_simple "$bin" "$target"
332 # same as above, except for shell scripts.
333 # If your shell script does not start with shebang, it is not a shell script.
334 inst_script() {
335 [[ -f $1 ]] || return 1
336 local line
337 read -r -n 80 line <"$1"
338 # If debug is set, clean unprintable chars to prevent messing up the term
339 [[ $debug ]] && line=$(echo -n "$line" | tr -c -d '[:print:][:space:]')
340 shebang_regex='(#! *)(/[^ ]+).*'
341 [[ $line =~ $shebang_regex ]] || return 1
342 inst "${BASH_REMATCH[2]}" && inst_simple "$@"
345 # same as above, but specialized for symlinks
346 inst_symlink() {
347 local src=$1 target=$initdir${2:-$1} realsrc
348 [[ -L $1 ]] || return 1
349 [[ -L $target ]] && return 0
350 realsrc=$(readlink -f "$src")
351 [[ $realsrc = ${realsrc##*/} ]] && realsrc=${src%/*}/$realsrc
352 inst "$realsrc" && ln -s "$realsrc" "$target"
355 # find a udev rule in the usual places.
356 find_rule() {
357 [[ -f $1 ]] && { echo "$1"; return 0; }
358 for r in . /lib/udev/rules.d /etc/udev/rules.d $dracutbasedir/rules.d; do
359 [[ -f $r/$1 ]] && { echo "$r/$1"; return 0; }
360 done
361 return 1
364 # udev rules always get installed in the same place, so
365 # create a function to install them to make life simpler.
366 inst_rules() {
367 local target=/etc/udev/rules.d rule found
369 inst_dir "/lib/udev/rules.d"
370 inst_dir "$target"
371 for rule in "$@"; do
372 found=$(find_rule "$rule") && \
373 inst_simple "$found" "$target/${found##*/}" \
374 || dinfo "Skipping udev rule: $rule"
375 done
378 # general purpose installation function
379 # Same args as above.
380 inst() {
381 case $# in
382 1) ;;
384 [[ -z $initdir ]] && [[ -d $2 ]] && export initdir=$2
385 [[ $initdir = $2 ]] && set $1
388 [[ -z $initdir ]] && export initdir=$2
389 set $1 $3
392 derror "inst only takes 1 or 2 or 3 arguments"
393 exit 1
395 esac
396 for x in inst_symlink inst_script inst_binary inst_simple; do
397 $x "$@" && return 0
398 done
399 return 1
402 # install function specialized for hooks
403 # $1 = type of hook, $2 = hook priority (lower runs first), $3 = hook
404 # All hooks should be POSIX/SuS compliant, they will be sourced by init.
405 inst_hook() {
406 if ! [[ -f $3 ]]; then
407 derror "Cannot install a hook ($3) that does not exist."
408 derror "Aborting initrd creation."
409 exit 1
410 elif ! strstr "$hookdirs" "$1"; then
411 derror "No such hook type $1. Aborting initrd creation."
412 exit 1
414 inst_simple "$3" "/${1}/${2}${3##*/}"
417 dracut_install() {
418 if [[ $1 = '-o' ]]; then
419 local optional=yes
420 shift
422 while (($# > 0)); do
423 if ! inst "$1" ; then
424 if [[ $optional = yes ]]; then
425 dwarning "Skipping program $1 as it cannot be found and is flagged to be optional"
426 else
427 derror "Failed to install $1"
428 exit 1
431 shift
432 done
435 # install function decompressing the target and handling symlinks
436 # $@ = list of compressed (gz or bz2) files or symlinks pointing to such files
438 # Function install targets in the same paths inside overlay but decompressed
439 # and without extensions (.gz, .bz2).
440 inst_decompress() {
441 local src dst realsrc realdst cmd
443 for src in $@
445 case ${src} in
446 *.gz) cmd='gzip -d' ;;
447 *.bz2) cmd='bzip2 -d' ;;
448 *) return 1 ;;
449 esac
451 if [[ -L ${src} ]]
452 then
453 realsrc="$(readlink -f ${src})" # symlink target with extension
454 dst="${src%.*}" # symlink without extension
455 realdst="${realsrc%.*}" # symlink target without extension
456 mksubdirs "${initdir}/${src}"
457 # Create symlink without extension to target without extension.
458 ln -s "${realdst}" "${initdir}/${dst}"
461 # If the source is symlink we operate on its target.
462 [[ ${realsrc} ]] && src=${realsrc}
463 inst ${src}
464 # Decompress with chosen tool. We assume that tool changes name e.g.
465 # from 'name.gz' to 'name'.
466 ${cmd} "${initdir}${src}"
467 done
470 # It's similar to above, but if file is not compressed, performs standard
471 # install.
472 # $@ = list of files
473 inst_opt_decompress() {
474 local src
476 for src in $@
478 inst_decompress "${src}" || inst "${src}"
479 done
482 check_module_deps() {
483 local moddir dep ret
484 # if we are already set to be loaded, we do not have to be checked again.
485 strstr "$mods_to_load" " $1 " && return
486 # turn a module name into a directory, if we can.
487 moddir=$(echo ${dracutbasedir}/modules.d/??${1})
488 [[ -d $moddir && -x $moddir/install ]] || return 1
489 # if we do not have a check script, we are unconditionally included
490 if [[ -x $moddir/check ]]; then
491 "$moddir/check"
492 ret=$?
493 # a return value of 255 = load module only as a dependency.
494 ((ret==0||ret==255)) || return 1
495 for dep in $("$moddir/check" -d); do
496 check_module_deps "$dep" && continue
497 dwarning "Dependency $mod failed."
498 return 1
499 done
501 mods_to_load+=" $1 "
504 should_source_module() {
505 local dep
506 if [[ $kernel_only = yes ]]; then
507 [[ -x $1/installkernel ]] && return 0
508 return 1
510 [[ -x $1/install ]] || [[ -x $1/installkernel ]] || return 1
511 [[ -x $1/check ]] || return 0
512 "$1/check" $hostonly || return 1
513 for dep in $("$1/check" -d); do
514 check_module_deps "$dep" && continue
515 dwarning "Cannot load dracut module \"$mod\", dependencies failed."
516 return 1
517 done
520 check_modules() {
521 local modcheck;
522 local mod;
523 for moddir in "$dracutbasedir/modules.d"/[0-9][0-9]*; do
524 local mod=${moddir##*/}; mod=${mod#[0-9][0-9]}
525 # If we are already scheduled to be loaded, no need to check again.
526 strstr "$mods_to_load" " $mod " && continue
527 # This should never happen, but...
528 [[ -d $moddir ]] || continue
529 [[ $dracutmodules != all ]] && ! strstr "$dracutmodules" "$mod" && \
530 continue
531 strstr "$omit_dracutmodules" "$mod" && continue
532 if ! strstr "$add_dracutmodules" "$mod"; then
533 should_source_module "$moddir" || continue
535 mods_to_load+=" $mod "
536 done
538 modcheck=$add_dracutmodules
539 [[ $dracutmodules != all ]] && modcheck="$m $dracutmodules"
540 for mod in $modcheck; do
541 strstr "$mods_to_load" "$mod" && continue
542 strstr "$omit_dracutmodules" "$mod" && continue
543 dwarning "Dracut module \"$mod\" cannot be found."
544 done
547 # Install a single kernel module along with any firmware it may require.
548 # $1 = full path to kernel module to install
549 install_kmod_with_fw() {
550 local modname=${1##*/} fwdir found
551 modname=${modname%.ko*}
552 inst_simple "$1" "/lib/modules/$kernel/${1##*/lib/modules/$kernel/}" || \
553 return 0 # no need to go further if the module is already installed
554 for fw in $(modinfo -k $kernel -F firmware $1 2>/dev/null); do
555 found=''
556 for fwdir in $fw_dir; do
557 if [[ -d $fwdir && -f $fwdir/$fw ]]; then
558 inst_simple "$fwdir/$fw" "/lib/firmware/$fw"
559 found=yes
561 done
562 if [[ $found != yes ]]; then
563 dinfo "Possible missing firmware \"${fw}\" for kernel module \"${mod}.ko\""
565 done
568 # Do something with all the dependencies of a kernel module.
569 # Note that kernel modules depend on themselves using the technique we use
570 # $1 = function to call for each dependency we find
571 # It will be passed the full path to the found kernel module
572 # $2 = module to get dependencies for
573 # rest of args = arguments to modprobe
574 for_each_kmod_dep() {
575 local func=$1 kmod=$2 cmd modpapth options
576 shift 2
577 modprobe "$@" --ignore-install --show-depends $kmod 2>/dev/null | \
578 while read cmd modpath options; do
579 [[ $cmd = insmod ]] || continue
580 $func $modpath
581 done
584 # filter kernel modules to install certain modules that meet specific
585 # requirements.
586 # $1 = function to call with module name to filter.
587 # This function will be passed the full path to the module to test.
588 # The behaviour of this function can vary depending on whether $hostonly is set.
589 # If it is, we will only look at modules that are already in memory.
590 # If it is not, we will look at all kernel modules
591 # This function returns the full filenames of modules that match $1
592 filter_kernel_modules () (
593 if ! [[ $hostonly ]]; then
594 filtercmd='find "$srcmods/kernel/drivers" -name "*.ko" -o -name "*.ko.gz"'
595 else
596 filtercmd='cut -d " " -f 1 </proc/modules|xargs modinfo -F filename -k $kernel'
598 for modname in $(eval $filtercmd); do
599 case $modname in
600 *.ko)
601 "$1" "$modname" && echo "$modname"
603 *.ko.gz)
604 gzip -dc "$modname" > $initdir/$$.ko
605 $1 $initdir/$$.ko && echo "$modname"
606 rm -f $initdir/$$.ko
608 esac
609 done
612 # install kernel modules along with all their dependencies.
613 instmods() {
614 [[ $no_kernel = yes ]] && return
615 local mod mpargs modpath modname cmd moddirname
616 while (($# > 0)); do
617 mod=${1%.ko*}
618 case $mod in
619 =*) # This introduces 2 incompatible meanings for =* arguments
620 # to instmods. We need to decide which one to keep.
621 if [[ $mod = =ata && -f $srcmods/modules.block ]] ; then
622 instmods $mpargs $(egrep 'ata|ahci' "${srcmods}/modules.block")
623 elif [ -f $srcmods/modules.${mod#=} ]; then
624 instmods $mpargs $(cat ${srcmods}/modules.${mod#=} )
625 else
626 instmods $mpargs $(find "$srcmods" -path "*/${mod#=}/*")
629 --*)
630 mod=${mod##*/}
631 mpargs+=" $mod";;
632 i2o_scsi)
633 # Must never run this diagnostic-only module
634 shift; continue;
637 mod=${mod##*/}
638 # if we are already installed, skip this module and go on
639 # to the next one.
640 [[ -f $initdir/$1 ]] && { shift; continue; }
641 # If we are building a host-specific initramfs and this
642 # module is not already loaded, move on to the next one.
643 [[ $hostonly ]] && ! grep -q "${mod//-/_}" /proc/modules && \
644 ! echo $add_drivers | grep -qe "\<${mod}\>" && {
645 shift; continue;
648 # We use '-d' option in modprobe only if modules prefix path
649 # differs from default '/'. This allows us to use Dracut with
650 # old version of modprobe which doesn't have '-d' option.
651 moddirname=${srcmods%%/lib/modules/*}
652 [[ -n ${moddirname} ]] && moddirname="-d ${moddirname}/"
654 # ok, load the module, all its dependencies, and any firmware
655 # it may require
656 for_each_kmod_dep install_kmod_with_fw $mod \
657 --set-version $kernel ${moddirname}
659 esac
660 shift
661 done
664 # vim:ts=8:sw=4:sts=4:et