Simplifying code a bit after removal of no longer supported overlay alternatives.
[live-boot-grml.git] / components / 9990-misc-helpers.sh
1 #!/bin/sh
2
3 #set -e
4
5 is_live_path()
6 {
7         DIRECTORY="${1}/${LIVE_MEDIA_PATH}"
8         for FILESYSTEM in squashfs ext2 ext3 ext4 xfs dir jffs
9         do
10                 if ls "${DIRECTORY}/"*.${FILESYSTEM} > /dev/null 2>&1
11                 then
12                         return 0
13                 fi
14         done
15         return 1
16 }
17
18 matches_uuid ()
19 {
20         if [ "${IGNORE_UUID}" ] || [ ! -e /conf/uuid.conf ]
21         then
22                 return 0
23         fi
24
25         path="${1}"
26         uuid="$(cat /conf/uuid.conf)"
27
28         for try_uuid_file in "${path}/.disk/live-uuid"*
29         do
30                 [ -e "${try_uuid_file}" ] || continue
31
32                 try_uuid="$(cat "${try_uuid_file}")"
33
34                 if [ "${uuid}" = "${try_uuid}" ]
35                 then
36                         return 0
37                 fi
38         done
39
40         return 1
41 }
42
43 get_backing_device ()
44 {
45         case "${1}" in
46                 *.squashfs|*.ext2|*.ext3|*.ext4|*.jffs2)
47                         echo $(setup_loop "${1}" "loop" "/sys/block/loop*" '0' "${LIVE_MEDIA_ENCRYPTION}" "${2}")
48                         ;;
49
50                 *.dir)
51                         echo "directory"
52                         ;;
53
54                 *)
55                         panic "Unrecognized live filesystem: ${1}"
56                         ;;
57         esac
58 }
59
60 mount_images_in_directory ()
61 {
62         directory="${1}"
63         rootmnt="${2}"
64         mac="${3}"
65
66         if is_live_path "${directory}"
67         then
68                 [ -n "${mac}" ] && adddirectory="${directory}/${LIVE_MEDIA_PATH}/${mac}"
69                 setup_unionfs "${directory}/${LIVE_MEDIA_PATH}" "${rootmnt}" "${adddirectory}"
70         else
71                 panic "No supported filesystem images found at /${LIVE_MEDIA_PATH}."
72         fi
73 }
74
75 is_nice_device ()
76 {
77         sysfs_path="${1#/sys}"
78
79         if udevadm info --query=all --path="${sysfs_path}" | egrep -q "DEVTYPE=disk"
80         then
81                 return 0
82         elif echo "${sysfs_path}" | grep -q '^/block/vd[a-z]$'
83         then
84                 return 0
85         elif echo ${sysfs_path} | grep -q "^/block/dm-"
86         then
87                 return 0
88         elif echo ${sysfs_path} | grep -q "^/block/mtdblock"
89         then
90                 return 0
91         fi
92
93         return 1
94 }
95
96 check_dev ()
97 {
98         sysdev="${1}"
99         devname="${2}"
100         skip_uuid_check="${3}"
101
102         # support for fromiso=.../isofrom=....
103         if [ -n "$FROMISO" ]
104         then
105                 ISO_DEVICE=$(dirname $FROMISO)
106                 if ! [ -b $ISO_DEVICE ]
107                 then
108                         # to support unusual device names like /dev/cciss/c0d0p1
109                         # as well we have to identify the block device name, let's
110                         # do that for up to 15 levels
111                         i=15
112                         while [ -n "$ISO_DEVICE" ] && [ "$i" -gt 0 ]
113                         do
114                                 ISO_DEVICE=$(dirname ${ISO_DEVICE})
115                                 [ -b "$ISO_DEVICE" ] && break
116                                 i=$(($i -1))
117                         done
118                 fi
119
120                 if [ "$ISO_DEVICE" = "/" ]
121                 then
122                         echo "Warning: device for bootoption fromiso= ($FROMISO) not found.">>/boot.log
123                 else
124                         fs_type=$(get_fstype "${ISO_DEVICE}")
125                         if is_supported_fs ${fs_type}
126                         then
127                                 mkdir /live/fromiso
128                                 mount -t $fs_type "$ISO_DEVICE" /live/fromiso
129                                 ISO_NAME="$(echo $FROMISO | sed "s|$ISO_DEVICE||")"
130                                 loopdevname=$(setup_loop "/live/fromiso/${ISO_NAME}" "loop" "/sys/block/loop*" "" '')
131                                 devname="${loopdevname}"
132                         else
133                                 echo "Warning: unable to mount $ISO_DEVICE." >>/boot.log
134                         fi
135                 fi
136         fi
137
138         if [ -z "${devname}" ]
139         then
140                 devname=$(sys2dev "${sysdev}")
141         fi
142
143         if [ -d "${devname}" ]
144         then
145                 mount -o bind "${devname}" $mountpoint || continue
146
147                 if is_live_path $mountpoint
148                 then
149                         echo $mountpoint
150                         return 0
151                 else
152                         umount $mountpoint
153                 fi
154         fi
155
156         IFS=","
157         for device in ${devname}
158         do
159                 case "$device" in
160                         *mapper*)
161                                 # Adding lvm support
162                                 if [ -x /scripts/local-top/lvm2 ]
163                                 then
164                                         ROOT="$device" resume="" /scripts/local-top/lvm2 >>/boot.log
165                                 fi
166                                 ;;
167
168                         /dev/md*)
169                                 # Adding raid support
170                                 if [ -x /scripts/local-top/mdadm ]
171                                 then
172                                         [ -r /conf/conf.d/md ] && cp /conf/conf.d/md /conf/conf.d/md.orig
173                                         echo "MD_DEVS=$device " >> /conf/conf.d/md
174                                         /scripts/local-top/mdadm >>/boot.log
175                                         [ -r /conf/conf.d/md.orig ] && mv /conf/conf.d/md.orig /conf/conf.d/md
176                                 fi
177                                 ;;
178                 esac
179         done
180         unset IFS
181
182         [ -n "$device" ] && devname="$device"
183
184         [ -e "$devname" ] || continue
185
186         if [ -n "${LIVE_MEDIA_OFFSET}" ]
187         then
188                 loopdevname=$(setup_loop "${devname}" "loop" "/sys/block/loop*" "${LIVE_MEDIA_OFFSET}" '')
189                 devname="${loopdevname}"
190         fi
191
192         fstype=$(get_fstype "${devname}")
193
194         if is_supported_fs ${fstype}
195         then
196                 devuid=$(blkid -o value -s UUID "$devname")
197                 [ -n "$devuid" ] && grep -qs "\<$devuid\>" /var/lib/live/boot/devices-already-tried-to-mount && continue
198                 mount -t ${fstype} -o ro,noatime "${devname}" ${mountpoint} || continue
199                 [ -n "$devuid" ] && echo "$devuid" >> /var/lib/live/boot/devices-already-tried-to-mount
200
201                 if [ -n "${FINDISO}" ]
202                 then
203                         if [ -f ${mountpoint}/${FINDISO} ]
204                         then
205                                 umount ${mountpoint}
206                                 mkdir -p /live/findiso
207                                 mount -t ${fstype} -o ro,noatime "${devname}" /live/findiso
208                                 loopdevname=$(setup_loop "/live/findiso/${FINDISO}" "loop" "/sys/block/loop*" 0 "")
209                                 devname="${loopdevname}"
210                                 mount -t iso9660 -o ro,noatime "${devname}" ${mountpoint}
211                         else
212                                 umount ${mountpoint}
213                         fi
214                 fi
215
216                 if is_live_path ${mountpoint} && \
217                         ([ "${skip_uuid_check}" ] || matches_uuid ${mountpoint})
218                 then
219                         echo ${mountpoint}
220                         return 0
221                 else
222                         umount ${mountpoint} 2>/dev/null
223                 fi
224         fi
225
226         if [ -n "${LIVE_MEDIA_OFFSET}" ]
227         then
228                 losetup -d "${loopdevname}"
229         fi
230
231         return 1
232 }
233
234 find_livefs ()
235 {
236         timeout="${1}"
237
238         # don't start autodetection before timeout has expired
239         if [ -n "${LIVE_MEDIA_TIMEOUT}" ]
240         then
241                 if [ "${timeout}" -lt "${LIVE_MEDIA_TIMEOUT}" ]
242                 then
243                         return 1
244                 fi
245         fi
246
247         # first look at the one specified in the command line
248         case "${LIVE_MEDIA}" in
249                 removable-usb)
250                         for sysblock in $(removable_usb_dev "sys")
251                         do
252                                 for dev in $(subdevices "${sysblock}")
253                                 do
254                                         if check_dev "${dev}"
255                                         then
256                                                 return 0
257                                         fi
258                                 done
259                         done
260                         return 1
261                         ;;
262
263                 removable)
264                         for sysblock in $(removable_dev "sys")
265                         do
266                                 for dev in $(subdevices "${sysblock}")
267                                 do
268                                         if check_dev "${dev}"
269                                         then
270                                                 return 0
271                                         fi
272                                 done
273                         done
274                         return 1
275                         ;;
276
277                 *)
278                         if [ ! -z "${LIVE_MEDIA}" ]
279                         then
280                                 if check_dev "null" "${LIVE_MEDIA}" "skip_uuid_check"
281                                 then
282                                         return 0
283                                 fi
284                         fi
285                         ;;
286         esac
287
288         # or do the scan of block devices
289         # prefer removable devices over non-removable devices, so scan them first
290         devices_to_scan="$(removable_dev 'sys') $(non_removable_dev 'sys')"
291
292         for sysblock in $devices_to_scan
293         do
294                 devname=$(sys2dev "${sysblock}")
295                 [ -e "$devname" ] || continue
296                 fstype=$(get_fstype "${devname}")
297
298                 if /lib/udev/cdrom_id ${devname} > /dev/null
299                 then
300                         if check_dev "null" "${devname}"
301                         then
302                                 return 0
303                         fi
304                 elif is_nice_device "${sysblock}"
305                 then
306                         for dev in $(subdevices "${sysblock}")
307                         do
308                                 if check_dev "${dev}"
309                                 then
310                                         return 0
311                                 fi
312                         done
313                 elif [ "${fstype}" = "squashfs" -o \
314                         "${fstype}" = "btrfs" -o \
315                         "${fstype}" = "ext2" -o \
316                         "${fstype}" = "ext3" -o \
317                         "${fstype}" = "ext4" -o \
318                         "${fstype}" = "jffs2" ]
319                 then
320                         # This is an ugly hack situation, the block device has
321                         # an image directly on it.  It's hopefully
322                         # live-boot, so take it and run with it.
323                         ln -s "${devname}" "${devname}.${fstype}"
324                         echo "${devname}.${fstype}"
325                         return 0
326                 fi
327         done
328
329         return 1
330 }
331
332 is_in_list_separator_helper ()
333 {
334         local sep element list
335         sep=${1}
336         shift
337         element=${1}
338         shift
339         list=${*}
340         echo ${list} | grep -qe "^\(.*${sep}\)\?${element}\(${sep}.*\)\?$"
341 }
342
343 is_in_space_sep_list ()
344 {
345         local element
346         element=${1}
347         shift
348         is_in_list_separator_helper "[[:space:]]" "${element}" "${*}"
349 }
350
351 is_in_comma_sep_list ()
352 {
353         local element
354         element=${1}
355         shift
356         is_in_list_separator_helper "," "${element}" "${*}"
357 }
358
359 sys2dev ()
360 {
361         sysdev=${1#/sys}
362         echo "/dev/$(udevadm info -q name -p ${sysdev} 2>/dev/null|| echo ${sysdev##*/})"
363 }
364
365 subdevices ()
366 {
367         sysblock=${1}
368         r=""
369
370         for dev in "${sysblock}"/* "${sysblock}"
371         do
372                 if [ -e "${dev}/dev" ]
373                 then
374                         r="${r} ${dev}"
375                 fi
376         done
377
378         echo ${r}
379 }
380
381 storage_devices()
382 {
383         black_listed_devices="${1}"
384         white_listed_devices="${2}"
385
386         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "loop|ram|fd")
387         do
388                 fulldevname=$(sys2dev "${sysblock}")
389
390                 if is_in_space_sep_list ${fulldevname} ${black_listed_devices} || \
391                         [ -n "${white_listed_devices}" ] && \
392                         ! is_in_space_sep_list ${fulldevname} ${white_listed_devices}
393                 then
394                         # skip this device entirely
395                         continue
396                 fi
397
398                 for dev in $(subdevices "${sysblock}")
399                 do
400                         devname=$(sys2dev "${dev}")
401
402                         if is_in_space_sep_list ${devname} ${black_listed_devices}
403                         then
404                                 # skip this subdevice
405                                 continue
406                         else
407                                 echo "${devname}"
408                         fi
409                 done
410         done
411 }
412
413 is_supported_fs ()
414 {
415         fstype="${1}"
416
417         # Validate input first
418         if [ -z "${fstype}" ]
419         then
420                 return 1
421         fi
422
423         # Try to look if it is already supported by the kernel
424         if grep -q ${fstype} /proc/filesystems
425         then
426                 return 0
427         else
428                 # Then try to add support for it the gentle way using the initramfs capabilities
429                 modprobe -q -b ${fstype}
430                 if grep -q ${fstype} /proc/filesystems
431                 then
432                         return 0
433                 # Then try the hard way if /root is already reachable
434                 else
435                         kmodule="/root/lib/modules/`uname -r`/${fstype}/${fstype}.ko"
436                         if [ -e "${kmodule}" ]
437                         then
438                                 insmod "${kmodule}"
439                                 if grep -q ${fstype} /proc/filesystems
440                                 then
441                                         return 0
442                                 fi
443                         fi
444                 fi
445         fi
446
447         return 1
448 }
449
450 get_fstype ()
451 {
452         /sbin/blkid -s TYPE -o value $1 2>/dev/null
453 }
454
455 where_is_mounted ()
456 {
457         device=${1}
458         # return first found
459         grep -m1 "^${device} " /proc/mounts | cut -f2 -d ' '
460 }
461
462 trim_path ()
463 {
464         # remove all unnecessary /:s in the path, including last one (except
465         # if path is just "/")
466         echo ${1} | sed 's|//\+|/|g' | sed 's|^\(.*[^/]\)/$|\1|'
467 }
468
469 what_is_mounted_on ()
470 {
471         local dir
472         dir="$(trim_path ${1})"
473         grep -m1 "^[^ ]\+ ${dir} " /proc/mounts | cut -d' ' -f1
474 }
475
476 chown_ref ()
477 {
478         local reference targets owner
479         reference="${1}"
480         shift
481         targets=${@}
482         owner=$(stat -c %u:%g "${reference}")
483         chown -h ${owner} ${targets}
484 }
485
486 chmod_ref ()
487 {
488         local reference targets rights
489         reference="${1}"
490         shift
491         targets=${@}
492         rights=$(stat -c %a "${reference}")
493         chmod ${rights} ${targets}
494 }
495
496 lastline ()
497 {
498         while read lines
499         do
500                 line=${lines}
501         done
502
503         echo "${line}"
504 }
505
506 base_path ()
507 {
508         testpath="${1}"
509         mounts="$(awk '{print $2}' /proc/mounts)"
510         testpath="$(busybox realpath ${testpath})"
511
512         while true
513         do
514                 if echo "${mounts}" | grep -qs "^${testpath}"
515                 then
516                         set -- $(echo "${mounts}" | grep "^${testpath}" | lastline)
517                         echo ${1}
518                         break
519                 else
520                         testpath=$(dirname $testpath)
521                 fi
522         done
523 }
524
525 fs_size ()
526 {
527         # Returns used/free fs kbytes + 5% more
528         # You could pass a block device as ${1} or the mount point as ${2}
529
530         dev="${1}"
531         mountp="${2}"
532         used="${3}"
533
534         if [ -z "${mountp}" ]
535         then
536                 mountp="$(where_is_mounted ${dev})"
537
538                 if [ -z "${mountp}" ]
539                 then
540                         mountp="/mnt/tmp_fs_size"
541
542                         mkdir -p "${mountp}"
543                         mount -t $(get_fstype "${dev}") -o ro "${dev}" "${mountp}" || log_warning_msg "cannot mount -t $(get_fstype ${dev}) -o ro ${dev} ${mountp}"
544
545                         doumount=1
546                 fi
547         fi
548
549         if [ "${used}" = "used" ]
550         then
551                 size=$(du -ks ${mountp} | cut -f1)
552                 size=$(expr ${size} + ${size} / 20 ) # FIXME: 5% more to be sure
553         else
554                 # free space
555                 size="$(df -kP | grep -s ${mountp} | awk '{print $4}')"
556         fi
557
558         if [ -n "${doumount}" ]
559         then
560                 umount "${mountp}" || log_warning_msg "cannot umount ${mountp}"
561                 rmdir "${mountp}"
562         fi
563
564         echo "${size}"
565 }
566
567 load_keymap ()
568 {
569         # Load custom keymap
570         if [ -x /bin/loadkeys -a -r /etc/boottime.kmap.gz ]
571         then
572                 loadkeys --quiet /etc/boottime.kmap.gz
573         fi
574 }
575
576 setup_loop ()
577 {
578         local fspath module pattern offset encryption readonly
579         fspath=${1}
580         module=${2}
581         pattern=${3}
582         offset=${4}
583         encryption=${5}
584         readonly=${6}
585
586         # the output of setup_loop is evaluated in other functions,
587         # modprobe leaks kernel options like "libata.dma=0"
588         # as "options libata dma=0" on stdout, causing serious
589         # problems therefor, so instead always avoid output to stdout
590         modprobe -q -b "${module}" 1>/dev/null
591
592         udevadm settle
593
594         for loopdev in ${pattern}
595         do
596                 if [ "$(cat ${loopdev}/size)" -eq 0 ]
597                 then
598                         dev=$(sys2dev "${loopdev}")
599                         options=''
600
601                         if [ -n "${readonly}" ]
602                         then
603                                 if losetup --help 2>&1 | grep -q -- "-r\b"
604                                 then
605                                         options="${options} -r"
606                                 fi
607                         fi
608
609                         if [ -n "${offset}" ] && [ 0 -lt "${offset}" ]
610                         then
611                                 options="${options} -o ${offset}"
612                         fi
613
614                         if [ -z "${encryption}" ]
615                         then
616                                 losetup ${options} "${dev}" "${fspath}"
617                         else
618                                 # Loop AES encryption
619                                 while true
620                                 do
621                                         load_keymap
622
623                                         echo -n "Enter passphrase for root filesystem: " >&6
624                                         read -s passphrase
625                                         echo "${passphrase}" > /tmp/passphrase
626                                         unset passphrase
627                                         exec 9</tmp/passphrase
628                                         /sbin/losetup ${options} -e "${encryption}" -p 9 "${dev}" "${fspath}"
629                                         error=${?}
630                                         exec 9<&-
631                                         rm -f /tmp/passphrase
632
633                                         if [ 0 -eq ${error} ]
634                                         then
635                                                 unset error
636                                                 break
637                                         fi
638
639                                         echo
640                                         echo -n "There was an error decrypting the root filesystem ... Retry? [Y/n] " >&6
641                                         read answer
642
643                                         if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
644                                         then
645                                                 unset answer
646                                                 break
647                                         fi
648                                 done
649                         fi
650
651                         echo "${dev}"
652                         return 0
653                 fi
654         done
655
656         panic "No loop devices available"
657 }
658
659 try_mount ()
660 {
661         dev="${1}"
662         mountp="${2}"
663         opts="${3}"
664         fstype="${4}"
665
666         old_mountp="$(where_is_mounted ${dev})"
667
668         if [ -n "${old_mountp}" ]
669         then
670                 if [ "${opts}" != "ro" ]
671                 then
672                         mount -o remount,"${opts}" "${dev}" "${old_mountp}" || panic "Remounting ${dev} ${opts} on ${old_mountp} failed"
673                 fi
674
675                 mount -o bind "${old_mountp}" "${mountp}" || panic "Cannot bind-mount ${old_mountp} on ${mountp}"
676         else
677                 if [ -z "${fstype}" ]
678                 then
679                         fstype=$(get_fstype "${dev}")
680                 fi
681                 mount -t "${fstype}" -o "${opts}" "${dev}" "${mountp}" || \
682                 ( echo "SKIPPING: Cannot mount ${dev} on ${mountp}, fstype=${fstype}, options=${opts}" > boot.log && return 0 )
683         fi
684 }
685
686 # Try to mount $device to the place expected by live-boot. If $device
687 # is already mounted somewhere, move it to the expected place. If $device
688 # ends with a "/" this is a directory path.
689 # If we're only probing $device (to check if it has custom persistence)
690 # $probe should be set, which suppresses warnings upon failure. On
691 # success, print the mount point for $device.
692 mount_persistence_media ()
693 {
694         local device probe backing old_backing fstype mount_opts
695         device=${1}
696         probe=${2}
697
698         # get_custom_mounts() might call this with a directory path instead
699         # of a block device path. This means we have found sub-directory path
700         # underneath /lib/live/mounts/persistence, so we're done
701         if [ -d "${device}" ]
702         then
703                 echo "${device}"
704                 return 0
705         fi
706
707         if [ ! -b "${device}" ]
708         then
709                 return 1
710         fi
711
712         backing="/live/persistence/$(basename ${device})"
713
714         mkdir -p "${backing}"
715         old_backing="$(where_is_mounted ${device})"
716         if [ -z "${old_backing}" ]
717         then
718                 fstype="$(get_fstype ${device})"
719                 mount_opts="rw,noatime"
720                 if [ -n "${PERSISTENCE_READONLY}" ]
721                 then
722                         mount_opts="ro,noatime"
723                 fi
724                 if mount -t "${fstype}" -o "${mount_opts}" "${device}" "${backing}" >/dev/null
725                 then
726                         echo ${backing}
727                         return 0
728                 else
729                         [ -z "${probe}" ] && log_warning_msg "Failed to mount persistence media ${device}"
730                         rmdir "${backing}"
731                         return 1
732                 fi
733         elif [ "${backing}" != "${old_backing}" ]
734         then
735                 if ! mount --move ${old_backing} ${backing} >/dev/null
736                 then
737                         [ -z "${probe}" ] && log_warning_msg "Failed to move persistence media ${device}"
738                         rmdir "${backing}"
739                         return 1
740                 fi
741                 mount_opts="rw,noatime"
742                 if [ -n "${PERSISTENCE_READONLY}" ]
743                 then
744                         mount_opts="ro,noatime"
745                 fi
746                 if ! mount -o "remount,${mount_opts}" "${backing}" >/dev/null
747                 then
748                         log_warning_msg "Failed to remount persistence media ${device} writable"
749                         # Don't unmount or rmdir the new mountpoint in this case
750                 fi
751                 echo ${backing}
752                 return 0
753         else
754                 # This means that $device has already been mounted on
755                 # the place expected by live-boot, so we're done.
756                 echo ${backing}
757                 return 0
758         fi
759 }
760
761 close_persistence_media ()
762 {
763         local device backing
764         device=${1}
765         backing="$(where_is_mounted ${device})"
766
767         if [ -d "${backing}" ]
768         then
769                 umount "${backing}" >/dev/null 2>&1
770                 rmdir "${backing}" >/dev/null 2>&1
771         fi
772
773         if is_active_luks_mapping ${device}
774         then
775                 /sbin/cryptsetup luksClose ${device}
776         fi
777 }
778
779 open_luks_device ()
780 {
781         dev="${1}"
782         name="$(basename ${dev})"
783         opts="--key-file=-"
784         if [ -n "${PERSISTENCE_READONLY}" ]
785         then
786                 opts="${opts} --readonly"
787         fi
788
789         if /sbin/cryptsetup status "${name}" >/dev/null 2>&1
790         then
791                 re="^[[:space:]]*device:[[:space:]]*\([^[:space:]]*\)$"
792                 opened_dev=$(cryptsetup status ${name} 2>/dev/null | grep "${re}" | sed "s|${re}|\1|")
793                 if [ "${opened_dev}" = "${dev}" ]
794                 then
795                         luks_device="/dev/mapper/${name}"
796                         echo ${luks_device}
797                         return 0
798                 else
799                         log_warning_msg "Cannot open luks device ${dev} since ${opened_dev} already is opened with its name"
800                         return 1
801                 fi
802         fi
803
804         load_keymap
805
806         # check for plymouth
807         if [ -x /bin/plymouth ]
808         then
809                 _PLYMOUTH="true"
810         fi
811
812         case "${_PLYMOUTH}" in
813                 true)
814                         plymouth --ping
815
816                         cryptkeyscript="plymouth ask-for-password --prompt"
817                         # Plymouth will add a : if it is a non-graphical prompt
818                         cryptkeyprompt="Please unlock disk ${dev}"
819                         ;;
820
821                 *)
822                         cryptkeyscript="/lib/cryptsetup/askpass"
823                         cryptkeyprompt="Please unlock disk ${dev}: "
824                         ;;
825         esac
826
827         while true
828         do
829                 $cryptkeyscript "$cryptkeyprompt" | \
830                         /sbin/cryptsetup -T 1 luksOpen ${dev} ${name} ${opts}
831
832                 if [ 0 -eq ${?} ]
833                 then
834                         luks_device="/dev/mapper/${name}"
835                         echo ${luks_device}
836                         return 0
837                 fi
838
839                 echo >&6
840                 retryprompt="There was an error decrypting ${dev} ... Retry? [Y/n]"
841
842                 case "${_PLYMOUTH}" in
843                         true)
844                                 plymouth display-message --text "${retryprompt}"
845                                 answer=$(plymouth watch-keystroke --keys="YNyn")
846                                 ;;
847
848                         *)
849                                 echo -n "${retryprompt} " >&6
850                                 read answer
851                                 ;;
852                 esac
853
854                 if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
855                 then
856                         case "${_PLYMOUTH}" in
857                                 true)
858                                         plymouth display-message --text ""
859                                         ;;
860                         esac
861
862                         return 2
863                 fi
864         done
865 }
866
867 get_gpt_name ()
868 {
869     local dev
870     dev="${1}"
871     /sbin/blkid -s PART_ENTRY_NAME -p -o value ${dev} 2>/dev/null
872 }
873
874 is_gpt_device ()
875 {
876     local dev
877     dev="${1}"
878     [ "$(/sbin/blkid -s PART_ENTRY_SCHEME -p -o value ${dev} 2>/dev/null)" = "gpt" ]
879 }
880
881 probe_for_gpt_name ()
882 {
883         local overlays dev gpt_dev gpt_name
884         overlays="${1}"
885         dev="${2}"
886
887         gpt_dev="${dev}"
888         if is_active_luks_mapping ${dev}
889         then
890                 # if $dev is an opened luks device, we need to check
891                 # GPT stuff on the backing device
892                 gpt_dev=$(get_luks_backing_device "${dev}")
893         fi
894
895         if ! is_gpt_device ${gpt_dev}
896         then
897                 return
898         fi
899
900         gpt_name=$(get_gpt_name ${gpt_dev})
901         for label in ${overlays}
902         do
903                 if [ "${gpt_name}" = "${label}" ]
904                 then
905                         echo "${label}=${dev}"
906                 fi
907         done
908 }
909
910 probe_for_fs_label ()
911 {
912         local overlays dev
913         overlays="${1}"
914         dev="${2}"
915
916         for label in ${overlays}
917         do
918                 if [ "$(/sbin/blkid -s LABEL -o value $dev 2>/dev/null)" = "${label}" ]
919                 then
920                         echo "${label}=${dev}"
921                 fi
922         done
923 }
924
925 probe_for_file_name ()
926 {
927         local overlays dev ret backing
928         overlays="${1}"
929         dev="${2}"
930
931         ret=""
932         backing="$(mount_persistence_media ${dev} probe)"
933         if [ -z "${backing}" ]
934         then
935             return
936         fi
937
938         for label in ${overlays}
939         do
940                 path=${backing}/${PERSISTENCE_PATH}/${label}
941                 if [ -f "${path}" ]
942                 then
943                         local loopdev
944                         loopdev=$(setup_loop "${path}" "loop" "/sys/block/loop*")
945                         ret="${ret} ${label}=${loopdev}"
946                 fi
947         done
948
949         if [ -n "${ret}" ]
950         then
951                 echo ${ret}
952         else
953                 # unmount and remove mountpoint
954                 umount ${backing} > /dev/null 2>&1 || true
955                 rmdir ${backing} > /dev/null 2>&1 || true
956         fi
957 }
958
959 probe_for_directory_name ()
960 {
961         local overlays dev ret backing
962         overlays="${1}"
963         dev="${2}"
964
965         ret=""
966         backing="$(mount_persistence_media ${dev} probe)"
967         if [ -z "${backing}" ]
968         then
969             return
970         fi
971
972         for label in ${overlays}
973         do
974                 path=${backing}/${PERSISTENCE_PATH}/${label}
975                 if [ -d "${path}" ]
976                 then
977                         # in this case the "device" ends with a "/"
978                         ret="${ret} ${label}=${backing}/${PERSISTENCE_PATH}/${label%%/}/"
979                 fi
980         done
981
982         if [ -n "${ret}" ]
983         then
984                 echo ${ret}
985         else
986                 # unmount and remove mountpoint
987                 umount ${backing} > /dev/null 2>&1 || true
988                 rmdir ${backing} > /dev/null 2>&1 || true
989         fi
990 }
991
992 find_persistence_media ()
993 {
994         # Scans devices for overlays, and returns a whitespace
995         # separated list of how to use them. Only overlays with a partition
996         # label or file name in ${overlays} are returned.
997         #
998         # When scanning a LUKS device, the user will be asked to enter the
999         # passphrase; on failure to enter it, or if no persistence partitions
1000         # or files were found, the LUKS device is closed.
1001         #
1002         # For all other cases (overlay partition and overlay file) the
1003         # return value is "${label}=${device}", where ${device} a device that
1004         # can mount the content. In the case of an overlay file, the device
1005         # containing the file will remain mounted as a side-effect.
1006         #
1007         # No devices in ${black_listed_devices} will be scanned, and if
1008         # ${white_list_devices} is non-empty, only devices in it will be
1009         # scanned.
1010
1011         local overlays white_listed_devices ret black_listed_devices
1012         overlays="${1}"
1013         white_listed_devices="${2}"
1014         ret=""
1015
1016         #
1017         # The devices that are hosting the actual live rootfs should not be
1018         # used for persistence storage since otherwise you might mount a
1019         # parent directory on top of a sub-directory of the same filesystem
1020         # in one union together.
1021         #
1022         black_listed_devices=""
1023         for d in /live/rootfs/* /live/findiso /live/fromiso
1024         do
1025                 black_listed_devices="${black_listed_devices} $(what_is_mounted_on d)"
1026         done
1027
1028         for dev in $(storage_devices "${black_listed_devices}" "${white_listed_devices}")
1029         do
1030                 local result luks_device
1031                 result=""
1032
1033                 luks_device=""
1034                 # Check if it's a luks device; we'll have to open the device
1035                 # in order to probe any filesystem it contains, like we do
1036                 # below. activate_custom_mounts() also depends on that any luks
1037                 # device already has been opened.
1038                 if is_in_comma_sep_list luks ${PERSISTENCE_ENCRYPTION} && is_luks_partition ${dev}
1039                 then
1040                         if luks_device=$(open_luks_device "${dev}")
1041                         then
1042                                 dev="${luks_device}"
1043                         else
1044                                 # skip $dev since we failed/chose not to open it
1045                                 continue
1046                         fi
1047                 elif ! is_in_comma_sep_list none ${PERSISTENCE_ENCRYPTION}
1048                 then
1049                         # skip $dev since we don't allow unencrypted storage
1050                         continue
1051                 fi
1052
1053                 # Probe for matching GPT partition names or filesystem labels
1054                 if is_in_comma_sep_list filesystem ${PERSISTENCE_STORAGE}
1055                 then
1056                         result=$(probe_for_gpt_name "${overlays}" ${dev})
1057                         if [ -n "${result}" ]
1058                         then
1059                                 ret="${ret} ${result}"
1060                                 continue
1061                         fi
1062
1063                         result=$(probe_for_fs_label "${overlays}" ${dev})
1064                         if [ -n "${result}" ]
1065                         then
1066                                 ret="${ret} ${result}"
1067                                 continue
1068                         fi
1069                 fi
1070
1071                 # Probe for files with matching name on mounted partition
1072                 if is_in_comma_sep_list file ${PERSISTENCE_STORAGE}
1073                 then
1074                         result=$(probe_for_file_name "${overlays}" ${dev})
1075                         if [ -n "${result}" ]
1076                         then
1077                                 local loopdevice
1078                                 loopdevice=${result##*=}
1079                                 if is_in_comma_sep_list luks ${PERSISTENCE_ENCRYPTION} && is_luks_partition ${loopdevice}
1080                                 then
1081                                         local luksfile
1082                                         luksfile=""
1083                                         if luksfile=$(open_luks_device "${loopdevice}")
1084                                         then
1085                                                 result=${result%%=*}
1086                                                 result="${result}=${luksfile}"
1087                                         else
1088                                                 losetup -d $loopdevice
1089                                                 result=""
1090                                         fi
1091                                 fi
1092                                 ret="${ret} ${result}"
1093                                 continue
1094                         fi
1095                 fi
1096
1097                 # Probe for directory with matching name on mounted partition
1098                 if is_in_comma_sep_list directory ${PERSISTENCE_STORAGE}
1099                 then
1100                         result=$(probe_for_directory_name "${overlays}" ${dev})
1101                         if [ -n "${result}" ]
1102                         then
1103                                 ret="${ret} ${result}"
1104                                 continue
1105                         fi
1106                 fi
1107
1108                 # Close luks device if it isn't used
1109                 if [ -z "${result}" ] && [ -n "${luks_device}" ] && is_active_luks_mapping "${luks_device}"
1110                 then
1111                         /sbin/cryptsetup luksClose "${luks_device}"
1112                 fi
1113         done
1114
1115         if [ -n "${ret}" ]
1116         then
1117                 echo ${ret}
1118         fi
1119 }
1120
1121 get_mac ()
1122 {
1123         mac=""
1124
1125         for adaptor in /sys/class/net/*
1126         do
1127                 status="$(cat ${adaptor}/iflink)"
1128
1129                 if [ "${status}" -eq 2 ]
1130                 then
1131                         mac="$(cat ${adaptor}/address)"
1132                         mac="$(echo ${mac} | sed 's/:/-/g' | tr '[a-z]' '[A-Z]')"
1133                 fi
1134         done
1135
1136         echo ${mac}
1137 }
1138
1139 is_luks_partition ()
1140 {
1141         device="${1}"
1142         /sbin/cryptsetup isLuks "${device}" 1>/dev/null 2>&1
1143 }
1144
1145 is_active_luks_mapping ()
1146 {
1147         device="${1}"
1148         /sbin/cryptsetup status "${device}" 1>/dev/null 2>&1
1149 }
1150
1151 get_luks_backing_device ()
1152 {
1153         device=${1}
1154         cryptsetup status ${device} 2> /dev/null | \
1155                 awk '{if ($1 == "device:") print $2}'
1156 }
1157
1158 removable_dev ()
1159 {
1160         output_format="${1}"
1161         want_usb="${2}"
1162         ret=
1163
1164         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
1165         do
1166                 dev_ok=
1167                 if [ "$(cat ${sysblock}/removable)" = "1" ]
1168                 then
1169                         if [ -z "${want_usb}" ]
1170                         then
1171                                 dev_ok="true"
1172                         else
1173                                 if readlink ${sysblock} | grep -q usb
1174                                 then
1175                                         dev_ok="true"
1176                                 fi
1177                         fi
1178                 fi
1179
1180                 if [ "${dev_ok}" = "true" ]
1181                 then
1182                         case "${output_format}" in
1183                                 sys)
1184                                         ret="${ret} ${sysblock}"
1185                                         ;;
1186                                 *)
1187                                         devname=$(sys2dev "${sysblock}")
1188                                         ret="${ret} ${devname}"
1189                                         ;;
1190                         esac
1191                 fi
1192         done
1193
1194         echo "${ret}"
1195 }
1196
1197 removable_usb_dev ()
1198 {
1199         output_format="${1}"
1200
1201         removable_dev "${output_format}" "want_usb"
1202 }
1203
1204 non_removable_dev ()
1205 {
1206         output_format="${1}"
1207         ret=
1208
1209         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
1210         do
1211                 if [ "$(cat ${sysblock}/removable)" = "0" ]
1212                 then
1213                         case "${output_format}" in
1214                                 sys)
1215                                         ret="${ret} ${sysblock}"
1216                                         ;;
1217                                 *)
1218                                         devname=$(sys2dev "${sysblock}")
1219                                         ret="${ret} ${devname}"
1220                                         ;;
1221                         esac
1222                 fi
1223         done
1224
1225         echo "${ret}"
1226 }
1227
1228 link_files ()
1229 {
1230         # create source's directory structure in dest, and recursively
1231         # create symlinks in dest to to all files in source. if mask
1232         # is non-empty, remove mask from all source paths when
1233         # creating links (will be necessary if we change root, which
1234         # live-boot normally does (into $rootmnt)).
1235         local src_dir dest_dir src_transform
1236
1237         # remove multiple /:s and ensure ending on /
1238         src_dir="$(trim_path ${1})/"
1239         dest_dir="$(trim_path ${2})/"
1240         src_transform="${3}"
1241
1242         # This check can only trigger on the inital, non-recursive call since
1243         # we create the destination before recursive calls
1244         if [ ! -d "${dest_dir}" ]
1245         then
1246                 log_warning_msg "Must link_files into a directory"
1247                 return
1248         fi
1249
1250         find "${src_dir}" -mindepth 1 -maxdepth 1 | \
1251         while read src
1252         do
1253                 local dest final_src
1254                 dest="${dest_dir}$(basename "${src}")"
1255                 if [ -d "${src}" ]
1256                 then
1257                         if [ -z "$(ls -A "${src}")" ]
1258                         then
1259                                 continue
1260                         fi
1261                         if [ ! -d "${dest}" ]
1262                         then
1263                                 mkdir -p "${dest}"
1264                                 chown_ref "${src}" "${dest}"
1265                                 chmod_ref "${src}" "${dest}"
1266                         fi
1267                         link_files "${src}" "${dest}" "${src_transform}"
1268                 else
1269                         final_src=${src}
1270                         if [ -n "${src_transform}" ]
1271                         then
1272                                 final_src="$(echo ${final_src} | sed "${src_transform}")"
1273                         fi
1274                         rm -rf "${dest}" 2> /dev/null
1275                         ln -s "${final_src}" "${dest}"
1276                         chown_ref "${src}" "${dest}"
1277                 fi
1278         done
1279 }
1280
1281 do_union ()
1282 {
1283         local unionmountpoint unionrw unionro
1284         unionmountpoint="${1}"  # directory where the union is mounted
1285         shift
1286         unionrw="${1}"          # branch where the union changes are stored
1287         shift
1288         unionro="${*}"          # space separated list of read-only branches (optional)
1289
1290         case "${UNIONTYPE}" in
1291                 aufs)
1292                         rw_opt="rw"
1293                         ro_opt="rr+wh"
1294                         noxino_opt="noxino"
1295
1296                         unionmountopts="-o noatime,${noxino_opt},dirs=${unionrw}=${rw_opt}"
1297                         if [ -n "${unionro}" ]
1298                         then
1299                                 for rofs in ${unionro}
1300                                 do
1301                                         unionmountopts="${unionmountopts}:${rofs}=${ro_opt}"
1302                                 done
1303                         fi
1304                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
1305                         ;;
1306
1307                 overlay)
1308                         rw_opt="rw"
1309                         ro_opt="ro"
1310
1311                         # XXX: can multiple unionro be used? (overlay only handles two dirs, but perhaps they can be chained?)
1312                         # XXX: and can unionro be optional? i.e. can overlay skip lowerdir?
1313                         if echo ${unionro} | grep -q " "
1314                         then
1315                                 panic "Multiple lower filesystems are currently not supported with overlay (unionro = ${unionro})."
1316                         elif [ -z "${unionro}"  ]
1317                         then
1318                                 panic "overlay needs at least one lower filesystem (read-only branch)."
1319                         fi
1320                         unionmountopts="-o noatime,lowerdir=${unionro},upperdir=${unionrw}"
1321                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
1322                         ;;
1323         esac
1324 }
1325
1326 get_custom_mounts ()
1327 {
1328         # Side-effect: leaves $devices with persistence.conf mounted in /live/persistence
1329         # Side-effect: prints info to file $custom_mounts
1330
1331         local custom_mounts devices bindings links
1332         custom_mounts=${1}
1333         shift
1334         devices=${@}
1335
1336         bindings="/tmp/bindings.list"
1337         links="/tmp/links.list"
1338         rm -rf ${bindings} ${links} 2> /dev/null
1339
1340         for device in ${devices}
1341         do
1342                 local device_name backing include_list
1343                 device_name="$(basename ${device})"
1344                 backing=$(mount_persistence_media ${device})
1345                 if [ -z "${backing}" ]
1346                 then
1347                         continue
1348                 fi
1349
1350                 if [ -r "${backing}/${persistence_list}" ]
1351                 then
1352                         include_list="${backing}/${persistence_list}"
1353                 else
1354                         continue
1355                 fi
1356
1357                 if [ -n "${LIVE_BOOT_DEBUG}" ] && [ -e "${include_list}" ]
1358                 then
1359                         cp ${include_list} /live/persistence/${persistence_list}.${device_name}
1360                 fi
1361
1362                 while read dir options # < ${include_list}
1363                 do
1364                         if echo ${dir} | grep -qe "^[[:space:]]*\(#.*\)\?$"
1365                         then
1366                                 # skipping empty or commented lines
1367                                 continue
1368                         fi
1369
1370                         if trim_path ${dir} | grep -q -e "^[^/]" -e "^/lib" -e "^/lib/live\(/.*\)\?$" -e "^/\(.*/\)\?\.\.\?\(/.*\)\?$"
1371                         then
1372                                 log_warning_msg "Skipping unsafe custom mount ${dir}: must be an absolute path containing neither the \".\" nor \"..\" special dirs, and cannot be \"/lib\", or \"/lib/live\" or any of its sub-directories."
1373                                 continue
1374                         fi
1375
1376                         local opt_source opt_link source full_source full_dest
1377                         opt_source=""
1378                         opt_link=""
1379                         for opt in $(echo ${options} | tr ',' ' ');
1380                         do
1381                                 case "${opt}" in
1382                                         source=*)
1383                                                 opt_source=${opt#source=}
1384                                                 ;;
1385                                         link)
1386                                                 opt_link="true"
1387                                                 ;;
1388                                         union|bind)
1389                                                 ;;
1390                                         *)
1391                                                 log_warning_msg "Skipping custom mount with unknown option: ${opt}"
1392                                                 continue 2
1393                                                 ;;
1394                                 esac
1395                         done
1396
1397                         source="${dir}"
1398                         if [ -n "${opt_source}" ]
1399                         then
1400                                 if echo ${opt_source} | grep -q -e "^/" -e "^\(.*/\)\?\.\.\?\(/.*\)\?$" && [ "${opt_source}" != "." ]
1401                                 then
1402                                         log_warning_msg "Skipping unsafe custom mount with option source=${opt_source}: must be either \".\" (the media root) or a relative path w.r.t. the media root that contains neither comas, nor the special \".\" and \"..\" path components"
1403                                         continue
1404                                 else
1405                                         source="${opt_source}"
1406                                 fi
1407                         fi
1408
1409                         full_source="$(trim_path ${backing}/${source})"
1410                         full_dest="$(trim_path ${rootmnt}/${dir})"
1411                         if [ -n "${opt_link}" ]
1412                         then
1413                                 echo "${device} ${full_source} ${full_dest} ${options}" >> ${links}
1414                         else
1415                                 echo "${device} ${full_source} ${full_dest} ${options}" >> ${bindings}
1416                         fi
1417                 done < ${include_list}
1418         done
1419
1420         # We sort the list according to destination so we're sure that
1421         # we won't hide a previous mount. We also ignore duplicate
1422         # destinations in a more or less arbitrary way.
1423         [ -e "${bindings}" ] && sort -k3 -sbu ${bindings} >> ${custom_mounts} && rm ${bindings}
1424
1425         # After all mounts are considered we add symlinks so they
1426         # won't be hidden by some mount.
1427         [ -e "${links}" ] && cat ${links} >> ${custom_mounts} && rm ${links}
1428
1429         # We need to make sure that no two custom mounts have the same sources
1430         # or are nested; if that is the case, too much weird stuff can happen.
1431         local prev_source prev_dest
1432         prev_source="impossible source" # first iteration must not match
1433         prev_dest=""
1434         # This sort will ensure that a source /a comes right before a source
1435         # /a/b so we only need to look at the previous source
1436         [ -e ${custom_mounts} ] && sort -k2 -b ${custom_mounts} |
1437         while read device source dest options
1438         do
1439                 if echo ${source} | grep -qe "^${prev_source}\(/.*\)\?$"
1440                 then
1441                         panic "Two persistence mounts have the same or nested sources: ${source} on ${dest}, and ${prev_source} on ${prev_dest}"
1442                 fi
1443                 prev_source=${source}
1444                 prev_dest=${dest}
1445         done
1446 }
1447
1448 activate_custom_mounts ()
1449 {
1450         local custom_mounts used_devices
1451         custom_mounts="${1}" # the ouput from get_custom_mounts()
1452         used_devices=""
1453
1454         while read device source dest options # < ${custom_mounts}
1455         do
1456                 local opt_bind opt_link opt_union
1457                 opt_bind="true"
1458                 opt_link=""
1459                 opt_union=""
1460                 for opt in $(echo ${options} | tr ',' ' ');
1461                 do
1462                         case "${opt}" in
1463                                 bind)
1464                                         opt_bind="true"
1465                                         unset opt_link opt_union
1466                                         ;;
1467                                 link)
1468                                         opt_link="true"
1469                                         unset opt_bind opt_union
1470                                         ;;
1471                                 union)
1472                                         opt_union="true"
1473                                         unset opt_bind opt_link
1474                                         ;;
1475                         esac
1476                 done
1477
1478                 if [ -n "$(what_is_mounted_on "${dest}")" ]
1479                 then
1480                         if [ "${dest}" = "${rootmnt}" ]
1481                         then
1482                                 umount "${dest}"
1483                         else
1484                                 log_warning_msg "Skipping custom mount ${dest}: $(what_is_mounted_on "${dest}") is already mounted there"
1485                                 continue
1486                         fi
1487                 fi
1488
1489                 if [ ! -d "${dest}" ]
1490                 then
1491                         # create the destination and delete existing files in
1492                         # its path that are in the way
1493                         path="/"
1494                         for dir in $(echo ${dest} | sed -e 's|/\+| |g')
1495                         do
1496                                 path=$(trim_path ${path}/${dir})
1497                                 if [ -f ${path} ]
1498                                 then
1499                                         rm -f ${path}
1500                                 fi
1501                                 if [ ! -e ${path} ]
1502                                 then
1503                                         mkdir -p ${path}
1504                                         if echo ${path} | grep -qe "^${rootmnt}/*home/[^/]\+"
1505                                         then
1506                                                 # if ${dest} is in /home try fixing proper ownership by assuming that the intended user is the first, which is usually the case
1507                                                 # FIXME: this should really be handled by live-config since we don't know for sure which uid a certain user has until then
1508                                                 chown 1000:1000 ${path}
1509                                         fi
1510                                 fi
1511                         done
1512                 fi
1513
1514                 # if ${source} doesn't exist on our persistence media
1515                 # we bootstrap it with $dest from the live filesystem.
1516                 # this both makes sense and is critical if we're
1517                 # dealing with /etc or other system dir.
1518                 if [ ! -d "${source}" ]
1519                 then
1520                         if [ -n "${PERSISTENCE_READONLY}" ]
1521                         then
1522                                 continue
1523                         elif [ -n "${opt_union}" ] || [ -n "${opt_link}" ]
1524                         then
1525                                 # unions and don't need to be bootstrapped
1526                                 # link dirs can't be bootstrapped in a sensible way
1527                                 mkdir -p "${source}"
1528                                 chown_ref "${dest}" "${source}"
1529                                 chmod_ref "${dest}" "${source}"
1530                         elif [ -n "${opt_bind}" ]
1531                         then
1532                                 # ensure that $dest is not copied *into* $source
1533                                 mkdir -p "$(dirname ${source})"
1534                                 cp -a "${dest}" "${source}"
1535                         fi
1536                 fi
1537
1538                 # XXX: If CONFIG_AUFS_ROBR is added to the Debian kernel we can
1539                 # ignore the loop below and set rootfs_dest_backing=$dest
1540                 local rootfs_dest_backing
1541                 rootfs_dest_backing=""
1542                 if [ -n "${opt_link}" ] || [ -n "${opt_union}" ]
1543                 then
1544                         for d in /live/rootfs/*
1545                         do
1546                                 if [ -n "${rootmnt}" ]
1547                                 then
1548                                         fs="${d}/$(echo ${dest} | sed -e "s|${rootmnt}||")"
1549                                 else
1550                                         fs="${d}/${dest}"
1551                                 fi
1552                                 if [ -d "${fs}" ]
1553                                 then
1554                                         rootfs_dest_backing="${rootfs_dest_backing} ${fs}"
1555                                 fi
1556                         done
1557                 fi
1558
1559                 local cow_dir links_source
1560                 if [ -n "${opt_link}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1561                 then
1562                         link_files ${source} ${dest} "s|^/live/|/lib/live/mount/|"
1563                 elif [ -n "${opt_link}" ] && [ -n "${PERSISTENCE_READONLY}" ]
1564                 then
1565                         mkdir -p ${rootmnt}/lib/live/mount/persistence
1566                         links_source=$(mktemp -d ${rootmnt}/lib/live/mount/persistence/links-source-XXXXXX)
1567                         chown_ref ${source} ${links_source}
1568                         chmod_ref ${source} ${links_source}
1569                         # We put the cow dir in the below strange place to
1570                         # make it absolutely certain that the link source
1571                         # has its own directory and isn't nested with some
1572                         # other custom mount (if so that mount's files would
1573                         # be linked, causing breakage.
1574                         cow_dir="/live/overlay/lib/live/mount/persistence/$(basename ${links_source})"
1575                         mkdir -p ${cow_dir}
1576                         chown_ref "${source}" "${cow_dir}"
1577                         chmod_ref "${source}" "${cow_dir}"
1578                         do_union ${links_source} ${cow_dir} ${source} ${rootfs_dest_backing}
1579                         link_files ${links_source} ${dest} "s|^${rootmnt}||"
1580                 elif [ -n "${opt_union}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1581                 then
1582                         do_union ${dest} ${source} ${rootfs_dest_backing}
1583                 elif [ -n "${opt_bind}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1584                 then
1585                         mount --bind "${source}" "${dest}"
1586                 elif [ -n "${opt_bind}" -o -n "${opt_union}" ] && [ -n "${PERSISTENCE_READONLY}" ]
1587                 then
1588                         # bind-mount and union mount are handled the same
1589                         # in read-only mode, but note that rootfs_dest_backing
1590                         # is non-empty (and necessary) only for unions
1591                         cow_dir="/live/overlay/${dest}"
1592                         if [ -e "${cow_dir}" ] && [ -z "${opt_link}" ]
1593                         then
1594                                 # If an earlier custom mount has files here
1595                                 # it will "block" the current mount's files
1596                                 # which is undesirable
1597                                 rm -rf "${cow_dir}"
1598                         fi
1599                         mkdir -p ${cow_dir}
1600                         chown_ref "${source}" "${cow_dir}"
1601                         chmod_ref "${source}" "${cow_dir}"
1602                         do_union ${dest} ${cow_dir} ${source} ${rootfs_dest_backing}
1603                 fi
1604
1605                 PERSISTENCE_IS_ON="1"
1606                 export PERSISTENCE_IS_ON
1607
1608                 if echo ${used_devices} | grep -qve "^\(.* \)\?${device}\( .*\)\?$"
1609                 then
1610                         used_devices="${used_devices} ${device}"
1611                 fi
1612         done < ${custom_mounts}
1613
1614         echo ${used_devices}
1615 }
1616
1617 is_mountpoint ()
1618 {
1619         directory="$1"
1620
1621         [ $(stat -fc%d:%D "${directory}") != $(stat -fc%d:%D "${directory}/..") ]
1622 }