Refactoring overlay and snapshot scanning code.
[live-boot-grml.git] / scripts / live-helpers
1 # live-boot helper functions, used by live-boot on boot and by live-snapshot
2
3 if [ ! -x "/bin/fstype" ]
4 then
5         # klibc not in path -> not in initramfs
6         export PATH="${PATH}:/usr/lib/klibc/bin"
7 fi
8
9 # handle upgrade path from old udev (using udevinfo) to
10 # recent versions of udev (using udevadm info)
11 if [ -x /sbin/udevadm ]
12 then
13         udevinfo='/sbin/udevadm info'
14 else
15         udevinfo='udevinfo'
16 fi
17
18 sys2dev ()
19 {
20         sysdev=${1#/sys}
21         echo "/dev/$($udevinfo -q name -p ${sysdev} 2>/dev/null|| echo ${sysdev##*/})"
22 }
23
24 subdevices ()
25 {
26         sysblock=${1}
27         r=""
28
29         for dev in "${sysblock}"/* "${sysblock}"
30         do
31                 if [ -e "${dev}/dev" ]
32                 then
33                         r="${r} ${dev}"
34                 fi
35         done
36
37         echo ${r}
38 }
39
40 storage_devices()
41 {
42         black_listed_devices="${1}"
43         white_listed_devices="${2}"
44
45         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "loop|ram|fd")
46         do
47                 fulldevname=$(sys2dev "${sysblock}")
48
49                 if echo "${black_listed_devices}" | grep -qw "${fulldevname}" || \
50                         [ -n "${white_listed_devices}" ] && \
51                         echo "${white_listed_devices}" | grep -vqw "${fulldevname}"
52                 then
53                         # skip this device entirely
54                         continue
55                 fi
56
57                 for dev in $(subdevices "${sysblock}")
58                 do
59                         devname=$(sys2dev "${dev}")
60
61                         if echo "${black_listed_devices}" | grep -qw "${devname}"
62                         then
63                                 # skip this subdevice
64                                 continue
65                         else
66                                 echo "${devname}"
67                         fi
68                 done
69         done
70 }
71
72 is_supported_fs ()
73 {
74         fstype="${1}"
75
76         # Validate input first
77         if [ -z "${fstype}" ]
78         then
79                 return 1
80         fi
81
82         # Try to look if it is already supported by the kernel
83         if grep -q ${fstype} /proc/filesystems
84         then
85                 return 0
86         else
87                 # Then try to add support for it the gentle way using the initramfs capabilities
88                 modprobe ${fstype}
89                 if grep -q ${fstype} /proc/filesystems
90                 then
91                         return 0
92                 # Then try the hard way if /root is already reachable
93                 else
94                         kmodule="/root/lib/modules/`uname -r`/${fstype}/${fstype}.ko"
95                         if [ -e "${kmodule}" ]
96                         then
97                                 insmod "${kmodule}"
98                                 if grep -q ${fstype} /proc/filesystems
99                                 then
100                                         return 0
101                                 fi
102                         fi
103                 fi
104         fi
105
106         return 1
107 }
108
109 get_fstype ()
110 {
111         /sbin/blkid -s TYPE -o value $1 2>/dev/null
112 }
113
114 where_is_mounted ()
115 {
116         device=${1}
117
118         if grep -q "^${device} " /proc/mounts
119         then
120                 # return the first found
121                 grep -m1 "^${device} " /proc/mounts | cut -f2 -d ' '
122         fi
123 }
124
125 lastline ()
126 {
127         while read lines
128         do
129                 line=${lines}
130         done
131
132         echo "${line}"
133 }
134
135 base_path ()
136 {
137         testpath="${1}"
138         mounts="$(awk '{print $2}' /proc/mounts)"
139         testpath="$(busybox realpath ${testpath})"
140
141         while true
142         do
143                 if echo "${mounts}" | grep -qs "^${testpath}"
144                 then
145                         set -- $(echo "${mounts}" | grep "^${testpath}" | lastline)
146                         echo ${1}
147                         break
148                 else
149                         testpath=$(dirname $testpath)
150                 fi
151         done
152 }
153
154 fs_size ()
155 {
156         # Returns used/free fs kbytes + 5% more
157         # You could pass a block device as ${1} or the mount point as ${2}
158
159         dev="${1}"
160         mountp="${2}"
161         used="${3}"
162
163         if [ -z "${mountp}" ]
164         then
165                 mountp="$(where_is_mounted ${dev})"
166
167                 if [ -z "${mountp}" ]
168                 then
169                         mountp="/mnt/tmp_fs_size"
170
171                         mkdir -p "${mountp}"
172                         mount -t $(get_fstype "${dev}") -o ro "${dev}" "${mountp}" || log_warning_msg "cannot mount -t $(get_fstype ${dev}) -o ro ${dev} ${mountp}"
173
174                         doumount=1
175                 fi
176         fi
177
178         if [ "${used}" = "used" ]
179         then
180                 size=$(du -ks ${mountp} | cut -f1)
181                 size=$(expr ${size} + ${size} / 20 ) # FIXME: 5% more to be sure
182         else
183                 # free space
184                 size="$(df -k | grep -s ${mountp} | awk '{print $4}')"
185         fi
186
187         if [ -n "${doumount}" ]
188         then
189                 umount "${mountp}" || log_warning_msg "cannot umount ${mountp}"
190                 rmdir "${mountp}"
191         fi
192
193         echo "${size}"
194 }
195
196 load_keymap ()
197 {
198         # Load custom keymap
199         if [ -x /bin/loadkeys -a -r /etc/boottime.kmap.gz ]
200         then
201                 loadkeys /etc/boottime.kmap.gz
202         fi
203 }
204
205 setup_loop ()
206 {
207         local fspath=${1}
208         local module=${2}
209         local pattern=${3}
210         local offset=${4}
211         local encryption=${5}
212         local readonly=${6}
213
214         # the output of setup_loop is evaluated in other functions,
215         # modprobe leaks kernel options like "libata.dma=0"
216         # as "options libata dma=0" on stdout, causing serious
217         # problems therefor, so instead always avoid output to stdout
218         modprobe -q -b "${module}" 1>/dev/null
219
220         udevadm settle
221
222         for loopdev in ${pattern}
223         do
224                 if [ "$(cat ${loopdev}/size)" -eq 0 ]
225                 then
226                         dev=$(sys2dev "${loopdev}")
227                         options=''
228
229                         if [ -n "${readonly}" ]
230                         then
231                                 if losetup --help 2>&1 | grep -q -- "-r\b"
232                                 then
233                                         options="${options} -r"
234                                 fi
235                         fi
236
237                         if [ 0 -lt "${offset}" ]
238                         then
239                                 options="${options} -o ${offset}"
240                         fi
241
242                         if [ -z "${encryption}" ]
243                         then
244                                 losetup ${options} "${dev}" "${fspath}"
245                         else
246                                 # Loop AES encryption
247                                 while true
248                                 do
249                                         load_keymap
250
251                                         echo -n "Enter passphrase for root filesystem: " >&6
252                                         read -s passphrase
253                                         echo "${passphrase}" > /tmp/passphrase
254                                         unset passphrase
255                                         exec 9</tmp/passphrase
256                                         /sbin/losetup ${options} -e "${encryption}" -p 9 "${dev}" "${fspath}"
257                                         error=${?}
258                                         exec 9<&-
259                                         rm -f /tmp/passphrase
260
261                                         if [ 0 -eq ${error} ]
262                                         then
263                                                 unset error
264                                                 break
265                                         fi
266
267                                         echo
268                                         echo -n "There was an error decrypting the root filesystem ... Retry? [Y/n] " >&6
269                                         read answer
270
271                                         if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
272                                         then
273                                                 unset answer
274                                                 break
275                                         fi
276                                 done
277                         fi
278
279                         echo "${dev}"
280                         return 0
281                 fi
282         done
283
284         panic "No loop devices available"
285 }
286
287 try_mount ()
288 {
289         dev="${1}"
290         mountp="${2}"
291         opts="${3}"
292         fstype="${4}"
293
294         old_mountp="$(where_is_mounted ${dev})"
295
296         if [ -n "${old_mountp}" ]
297         then
298                 if [ "${opts}" != "ro" ]
299                 then
300                         mount -o remount,"${opts}" "${dev}" "${old_mountp}" || panic "Remounting ${dev} ${opts} on ${old_mountp} failed"
301                 fi
302
303                 mount -o bind "${old_mountp}" "${mountp}" || panic "Cannot bind-mount ${old_mountp} on ${mountp}"
304         else
305                 if [ -z "${fstype}" ]
306                 then
307                         fstype=$(get_fstype "${dev}")
308                 fi
309                 mount -t "${fstype}" -o "${opts}" "${dev}" "${mountp}" || \
310                 ( echo "SKIPPING: Cannot mount ${dev} on ${mountp}, fstype=${fstype}, options=${opts}" > live-boot.log && return 0 )
311         fi
312 }
313
314 find_persistent_media ()
315 {
316         # Scans devices for overlays and snapshots, and returns a whitespace
317         # separated list of how to use them. Only overlays with a partition
318         # label or file name in ${overlays} are returned, and ditto for
319         # snapshots with labels in ${snapshots}.
320         #
321         # When scanning a LUKS device, the user will be asked to enter the
322         # passphrase; on failure to enter it, or if no persistent partitions
323         # or files were found, the LUKS device is closed.
324         #
325         # For a snapshot file the return value is ${label}=${snapdata}", where
326         # ${snapdata} is the parameter used for try_snap().
327         #
328         # For all other cases (overlay/snapshot partition and overlay file) the
329         # return value is "${label}=${device}", where ${device} a device that
330         # can mount the content. In the case of an overlay file, the device
331         # containing the file will remain mounted as a side-effect.
332         #
333         # No devices in ${black_listed_devices} will be scanned, and if
334         # ${white_list_devices} is non-empty, only devices in it will be
335         # scanned.
336
337         overlays="${1}"
338         snapshots="${2}"
339         black_listed_devices="${3}"
340         white_listed_devices="${4}"
341
342         for dev in $(storage_devices "${black_listed_devices}" "${white_listed_devices}")
343         do
344                 luks_device=""
345
346                 # Checking for a luks device
347                 if [ "${PERSISTENT_ENCRYPTION}" = "luks" ] && [ -e /sbin/cryptsetup ]
348                 then
349                         if ! modprobe dm-crypt
350                         then
351                                 log_warning_msg "Unable to load module dm-crypt"
352                                 continue
353                         fi
354
355                         if [ ! -x /lib/cryptsetup/askpass ] || [ ! -x /sbin/cryptsetup ]
356                         then
357                                 log_warning_msg "cryptsetup in unavailable"
358                                 continue
359                         fi
360
361                         if ! /sbin/cryptsetup isLuks ${dev}
362                         then
363                                 # skip device since we strictly want luks devices
364                                 continue
365                         fi
366
367                         load_keymap
368
369                         while true
370                         do
371                                 /lib/cryptsetup/askpass "Enter passphrase for ${dev}: " | /sbin/cryptsetup -T 1 luksOpen ${dev} $(basename ${dev}) --key-file=-
372
373                                 if [ 0 -eq ${?} ]
374                                 then
375                                         luks_device="/dev/mapper/$(basename ${dev})"
376                                         dev="${luks_device}"
377                                         break
378                                 fi
379
380                                 echo >&6
381                                 echo -n "There was an error decrypting ${dev} ... Retry? [Y/n] " >&6
382                                 read answer
383
384                                 if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
385                                 then
386                                         break
387                                 fi
388                         done
389                 fi
390
391                 if echo ${PERSISTENT_STORAGE} | grep -qw filesystem
392                 then
393                         for label in ${overlays} ${snapshots}
394                         do
395                                 if [ "$(/sbin/blkid -s LABEL -o value $dev 2>/dev/null)" = "${label}" ]
396                                 then
397                                         overlays=$(echo ${overlays} | sed -e "s|\<${label}\>||")
398                                         snapshots=$(echo ${snapshots} | sed -e "s|\<${label}\>||")
399                                         echo "${label}=${dev}"
400                                         # skip to the next device
401                                         continue 2
402                                 fi
403                         done
404                 fi
405
406                 if echo ${PERSISTENT_STORAGE} | grep -qw file
407                 then
408                         devfstype="$(get_fstype ${dev})"
409                         overlay_on_dev=""
410                         snapshot_on_dev=""
411                         backing="/$(basename ${dev})-backing"
412                         mkdir -p "${backing}"
413                         if is_supported_fs ${devfstype} && try_mount "${dev}" "${backing}" "rw" "${devfstype}"
414                         then
415                                 for label in ${overlays}
416                                 do
417                                         path=${backing}/${PERSISTENT_PATH}${label}
418                                         if [ -f "${path}" ]
419                                         then
420                                                 overlays=$(echo ${overlays} | sed -e "s|\<${label}\>||")
421                                                 overlay_on_dev="yes"
422                                                 echo "${label}=$(setup_loop "${path}" "loop" "/sys/block/loop*")"
423                                         fi
424                                 done
425
426                                 for label in ${snapshots}
427                                 do
428                                         for ext in squashfs cpio.gz ext2 ext3 ext4 jffs2
429                                         do
430                                                 path="${PERSISTENT_PATH}${label}.${ext}"
431                                                 if [ -f "${backing}/${path}" ]
432                                                 then
433                                                         snapshots=$(echo ${snapshots} | sed -e "s|\<${label}\>||")
434                                                         snapshot_on_dev="yes"
435                                                         echo "${label}=${dev}:${backing}:${path}"
436                                                 fi
437                                         done
438                                 done
439                         fi
440                         if [ -z "${overlay_on_dev}" ]
441                         then
442                                 umount ${backing} > /dev/null 2>&1 || true
443                                 if [ -z "${snapshot_on_dev}" ] && [ -n "${luks_device}" ] && /sbin/cryptsetup status "${luks_device}" 1> /dev/null
444                                 then
445                                         /sbin/cryptsetup luksClose "${luks_device}"
446                                 fi
447                         fi
448                 fi
449         done
450 }
451
452 get_mac ()
453 {
454         mac=""
455
456         for adaptor in /sys/class/net/*
457         do
458                 status="$(cat ${adaptor}/iflink)"
459
460                 if [ "${status}" -eq 2 ]
461                 then
462                         mac="$(cat ${adaptor}/address)"
463                         mac="$(echo ${mac} | sed 's/:/-/g' | tr '[a-z]' '[A-Z]')"
464                 fi
465         done
466
467         echo ${mac}
468 }
469
470 is_luks()
471 {
472     devname="${1}"
473     if [ -x /sbin/cryptsetup ]
474     then
475         /sbin/cryptsetup isLuks "${devname}" 2>/dev/null || ret=${?}
476         return ${ret}
477     else
478         return 1
479     fi
480
481 }
482
483 removable_dev ()
484 {
485         output_format="${1}"
486         want_usb="${2}"
487         ret=
488
489         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
490         do
491                 dev_ok=
492                 if [ "$(cat ${sysblock}/removable)" = "1" ]
493                 then
494                         if [ -z "${want_usb}" ]
495                         then
496                                 dev_ok="yes"
497                         else
498                                 if readlink ${sysblock} | grep -q usb
499                                 then
500                                         dev_ok="yes"
501                                 fi
502                         fi
503                 fi
504
505                 if [ "${dev_ok}" = "yes" ]
506                 then
507                         case "${output_format}" in
508                                 sys)
509                                         ret="${ret} ${sysblock}"
510                                         ;;
511                                 *)
512                                         devname=$(sys2dev "${sysblock}")
513                                         ret="${ret} ${devname}"
514                                         ;;
515                         esac
516                 fi
517         done
518
519         echo "${ret}"
520 }
521
522 removable_usb_dev ()
523 {
524         output_format="${1}"
525
526         removable_dev "${output_format}" "want_usb"
527 }
528
529 non_removable_dev ()
530 {
531         output_format="${1}"
532         ret=
533
534         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
535         do
536                 if [ "$(cat ${sysblock}/removable)" = "0" ]
537                 then
538                         case "${output_format}" in
539                                 sys)
540                                         ret="${ret} ${sysblock}"
541                                         ;;
542                                 *)
543                                         devname=$(sys2dev "${sysblock}")
544                                         ret="${ret} ${devname}"
545                                         ;;
546                         esac
547                 fi
548         done
549
550         echo "${ret}"
551 }