Merge remote-tracking branch 'grml'
[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         # get_fstype might report "unknown" or "swap", ignore it as no such kernel module exists
424         if [ "${fstype}" = "unknown" ] || [ "${fstype}" = "swap" ]
425         then
426                 return 1
427         fi
428
429         # Try to look if it is already supported by the kernel
430         if grep -q ${fstype} /proc/filesystems
431         then
432                 return 0
433         else
434                 # Then try to add support for it the gentle way using the initramfs capabilities
435                 modprobe -q -b ${fstype}
436                 if grep -q ${fstype} /proc/filesystems
437                 then
438                         return 0
439                 # Then try the hard way if /root is already reachable
440                 else
441                         kmodule="/root/lib/modules/`uname -r`/${fstype}/${fstype}.ko"
442                         if [ -e "${kmodule}" ]
443                         then
444                                 insmod "${kmodule}"
445                                 if grep -q ${fstype} /proc/filesystems
446                                 then
447                                         return 0
448                                 fi
449                         fi
450                 fi
451         fi
452
453         return 1
454 }
455
456 get_fstype ()
457 {
458         /sbin/blkid -s TYPE -o value $1 2>/dev/null
459 }
460
461 where_is_mounted ()
462 {
463         device=${1}
464         # return first found
465         grep -m1 "^${device} " /proc/mounts | cut -f2 -d ' '
466 }
467
468 trim_path ()
469 {
470         # remove all unnecessary /:s in the path, including last one (except
471         # if path is just "/")
472         echo ${1} | sed 's|//\+|/|g' | sed 's|^\(.*[^/]\)/$|\1|'
473 }
474
475 what_is_mounted_on ()
476 {
477         local dir
478         dir="$(trim_path ${1})"
479         grep -m1 "^[^ ]\+ ${dir} " /proc/mounts | cut -d' ' -f1
480 }
481
482 chown_ref ()
483 {
484         local reference targets owner
485         reference="${1}"
486         shift
487         targets=${@}
488         owner=$(stat -c %u:%g "${reference}")
489         chown -h ${owner} ${targets}
490 }
491
492 chmod_ref ()
493 {
494         local reference targets rights
495         reference="${1}"
496         shift
497         targets=${@}
498         rights=$(stat -c %a "${reference}")
499         chmod ${rights} ${targets}
500 }
501
502 lastline ()
503 {
504         while read lines
505         do
506                 line=${lines}
507         done
508
509         echo "${line}"
510 }
511
512 base_path ()
513 {
514         testpath="${1}"
515         mounts="$(awk '{print $2}' /proc/mounts)"
516         testpath="$(busybox realpath ${testpath})"
517
518         while true
519         do
520                 if echo "${mounts}" | grep -qs "^${testpath}"
521                 then
522                         set -- $(echo "${mounts}" | grep "^${testpath}" | lastline)
523                         echo ${1}
524                         break
525                 else
526                         testpath=$(dirname $testpath)
527                 fi
528         done
529 }
530
531 fs_size ()
532 {
533         # Returns used/free fs kbytes + 5% more
534         # You could pass a block device as ${1} or the mount point as ${2}
535
536         dev="${1}"
537         mountp="${2}"
538         used="${3}"
539
540         if [ -z "${mountp}" ]
541         then
542                 mountp="$(where_is_mounted ${dev})"
543
544                 if [ -z "${mountp}" ]
545                 then
546                         mountp="/mnt/tmp_fs_size"
547
548                         mkdir -p "${mountp}"
549                         mount -t $(get_fstype "${dev}") -o ro "${dev}" "${mountp}" || log_warning_msg "cannot mount -t $(get_fstype ${dev}) -o ro ${dev} ${mountp}"
550
551                         doumount=1
552                 fi
553         fi
554
555         if [ "${used}" = "used" ]
556         then
557                 size=$(du -ks ${mountp} | cut -f1)
558                 size=$(expr ${size} + ${size} / 20 ) # FIXME: 5% more to be sure
559         else
560                 # free space
561                 size="$(df -kP | grep -s ${mountp} | awk '{print $4}')"
562         fi
563
564         if [ -n "${doumount}" ]
565         then
566                 umount "${mountp}" || log_warning_msg "cannot umount ${mountp}"
567                 rmdir "${mountp}"
568         fi
569
570         echo "${size}"
571 }
572
573 load_keymap ()
574 {
575         # Load custom keymap
576         if [ -x /bin/loadkeys -a -r /etc/boottime.kmap.gz ]
577         then
578                 loadkeys --quiet /etc/boottime.kmap.gz
579         fi
580 }
581
582 setup_loop ()
583 {
584         local fspath module pattern offset encryption readonly
585         fspath=${1}
586         module=${2}
587         pattern=${3}
588         offset=${4}
589         encryption=${5}
590         readonly=${6}
591
592         # the output of setup_loop is evaluated in other functions,
593         # modprobe leaks kernel options like "libata.dma=0"
594         # as "options libata dma=0" on stdout, causing serious
595         # problems therefor, so instead always avoid output to stdout
596         modprobe -q -b "${module}" 1>/dev/null
597
598         udevadm settle
599
600         for loopdev in ${pattern}
601         do
602                 if [ "$(cat ${loopdev}/size)" -eq 0 ]
603                 then
604                         dev=$(sys2dev "${loopdev}")
605                         options=''
606
607                         if [ -n "${readonly}" ]
608                         then
609                                 if losetup --help 2>&1 | grep -q -- "-r\b"
610                                 then
611                                         options="${options} -r"
612                                 fi
613                         fi
614
615                         if [ -n "${offset}" ] && [ 0 -lt "${offset}" ]
616                         then
617                                 options="${options} -o ${offset}"
618                         fi
619
620                         if [ -z "${encryption}" ]
621                         then
622                                 losetup ${options} "${dev}" "${fspath}"
623                         else
624                                 # Loop AES encryption
625                                 while true
626                                 do
627                                         load_keymap
628
629                                         echo -n "Enter passphrase for root filesystem: " >&6
630                                         read -s passphrase
631                                         echo "${passphrase}" > /tmp/passphrase
632                                         unset passphrase
633                                         exec 9</tmp/passphrase
634                                         /sbin/losetup ${options} -e "${encryption}" -p 9 "${dev}" "${fspath}"
635                                         error=${?}
636                                         exec 9<&-
637                                         rm -f /tmp/passphrase
638
639                                         if [ 0 -eq ${error} ]
640                                         then
641                                                 unset error
642                                                 break
643                                         fi
644
645                                         echo
646                                         echo -n "There was an error decrypting the root filesystem ... Retry? [Y/n] " >&6
647                                         read answer
648
649                                         if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
650                                         then
651                                                 unset answer
652                                                 break
653                                         fi
654                                 done
655                         fi
656
657                         echo "${dev}"
658                         return 0
659                 fi
660         done
661
662         panic "No loop devices available"
663 }
664
665 try_mount ()
666 {
667         dev="${1}"
668         mountp="${2}"
669         opts="${3}"
670         fstype="${4}"
671
672         old_mountp="$(where_is_mounted ${dev})"
673
674         if [ -n "${old_mountp}" ]
675         then
676                 if [ "${opts}" != "ro" ]
677                 then
678                         mount -o remount,"${opts}" "${dev}" "${old_mountp}" || panic "Remounting ${dev} ${opts} on ${old_mountp} failed"
679                 fi
680
681                 mount -o bind "${old_mountp}" "${mountp}" || panic "Cannot bind-mount ${old_mountp} on ${mountp}"
682         else
683                 if [ -z "${fstype}" ]
684                 then
685                         fstype=$(get_fstype "${dev}")
686                 fi
687                 mount -t "${fstype}" -o "${opts}" "${dev}" "${mountp}" || \
688                 ( echo "SKIPPING: Cannot mount ${dev} on ${mountp}, fstype=${fstype}, options=${opts}" > boot.log && return 0 )
689         fi
690 }
691
692 # Try to mount $device to the place expected by live-boot. If $device
693 # is already mounted somewhere, move it to the expected place. If $device
694 # ends with a "/" this is a directory path.
695 # If we're only probing $device (to check if it has custom persistence)
696 # $probe should be set, which suppresses warnings upon failure. On
697 # success, print the mount point for $device.
698 mount_persistence_media ()
699 {
700         local device probe backing old_backing fstype mount_opts
701         device=${1}
702         probe=${2}
703
704         # get_custom_mounts() might call this with a directory path instead
705         # of a block device path. This means we have found sub-directory path
706         # underneath /lib/live/mounts/persistence, so we're done
707         if [ -d "${device}" ]
708         then
709                 echo "${device}"
710                 return 0
711         fi
712
713         if [ ! -b "${device}" ]
714         then
715                 return 1
716         fi
717
718         backing="/live/persistence/$(basename ${device})"
719
720         mkdir -p "${backing}"
721         old_backing="$(where_is_mounted ${device})"
722         if [ -z "${old_backing}" ]
723         then
724                 fstype="$(get_fstype ${device})"
725                 mount_opts="rw,noatime"
726                 if [ -n "${PERSISTENCE_READONLY}" ]
727                 then
728                         mount_opts="ro,noatime"
729                 fi
730                 if mount -t "${fstype}" -o "${mount_opts}" "${device}" "${backing}" >/dev/null
731                 then
732                         echo ${backing}
733                         return 0
734                 else
735                         [ -z "${probe}" ] && log_warning_msg "Failed to mount persistence media ${device}"
736                         rmdir "${backing}"
737                         return 1
738                 fi
739         elif [ "${backing}" != "${old_backing}" ]
740         then
741                 if ! mount --move ${old_backing} ${backing} >/dev/null
742                 then
743                         [ -z "${probe}" ] && log_warning_msg "Failed to move persistence media ${device}"
744                         rmdir "${backing}"
745                         return 1
746                 fi
747                 mount_opts="rw,noatime"
748                 if [ -n "${PERSISTENCE_READONLY}" ]
749                 then
750                         mount_opts="ro,noatime"
751                 fi
752                 if ! mount -o "remount,${mount_opts}" "${backing}" >/dev/null
753                 then
754                         log_warning_msg "Failed to remount persistence media ${device} writable"
755                         # Don't unmount or rmdir the new mountpoint in this case
756                 fi
757                 echo ${backing}
758                 return 0
759         else
760                 # This means that $device has already been mounted on
761                 # the place expected by live-boot, so we're done.
762                 echo ${backing}
763                 return 0
764         fi
765 }
766
767 close_persistence_media ()
768 {
769         local device backing
770         device=${1}
771         backing="$(where_is_mounted ${device})"
772
773         if [ -d "${backing}" ]
774         then
775                 umount "${backing}" >/dev/null 2>&1
776                 rmdir "${backing}" >/dev/null 2>&1
777         fi
778
779         if is_active_luks_mapping ${device}
780         then
781                 /sbin/cryptsetup luksClose ${device}
782         fi
783 }
784
785 open_luks_device ()
786 {
787         dev="${1}"
788         name="$(basename ${dev})"
789         opts="--key-file=-"
790         if [ -n "${PERSISTENCE_READONLY}" ]
791         then
792                 opts="${opts} --readonly"
793         fi
794
795         if /sbin/cryptsetup status "${name}" >/dev/null 2>&1
796         then
797                 re="^[[:space:]]*device:[[:space:]]*\([^[:space:]]*\)$"
798                 opened_dev=$(cryptsetup status ${name} 2>/dev/null | grep "${re}" | sed "s|${re}|\1|")
799                 if [ "${opened_dev}" = "${dev}" ]
800                 then
801                         luks_device="/dev/mapper/${name}"
802                         echo ${luks_device}
803                         return 0
804                 else
805                         log_warning_msg "Cannot open luks device ${dev} since ${opened_dev} already is opened with its name"
806                         return 1
807                 fi
808         fi
809
810         load_keymap
811
812         # check for plymouth
813         if [ -x /bin/plymouth ]
814         then
815                 _PLYMOUTH="true"
816         fi
817
818         case "${_PLYMOUTH}" in
819                 true)
820                         plymouth --ping
821
822                         cryptkeyscript="plymouth ask-for-password --prompt"
823                         # Plymouth will add a : if it is a non-graphical prompt
824                         cryptkeyprompt="Please unlock disk ${dev}"
825                         ;;
826
827                 *)
828                         cryptkeyscript="/lib/cryptsetup/askpass"
829                         cryptkeyprompt="Please unlock disk ${dev}: "
830                         ;;
831         esac
832
833         while true
834         do
835                 $cryptkeyscript "$cryptkeyprompt" | \
836                         /sbin/cryptsetup -T 1 luksOpen ${dev} ${name} ${opts}
837
838                 if [ 0 -eq ${?} ]
839                 then
840                         luks_device="/dev/mapper/${name}"
841                         echo ${luks_device}
842                         return 0
843                 fi
844
845                 echo >&6
846                 retryprompt="There was an error decrypting ${dev} ... Retry? [Y/n]"
847
848                 case "${_PLYMOUTH}" in
849                         true)
850                                 plymouth display-message --text "${retryprompt}"
851                                 answer=$(plymouth watch-keystroke --keys="YNyn")
852                                 ;;
853
854                         *)
855                                 echo -n "${retryprompt} " >&6
856                                 read answer
857                                 ;;
858                 esac
859
860                 if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
861                 then
862                         case "${_PLYMOUTH}" in
863                                 true)
864                                         plymouth display-message --text ""
865                                         ;;
866                         esac
867
868                         return 2
869                 fi
870         done
871 }
872
873 get_gpt_name ()
874 {
875     local dev
876     dev="${1}"
877     /sbin/blkid -s PART_ENTRY_NAME -p -o value ${dev} 2>/dev/null
878 }
879
880 is_gpt_device ()
881 {
882     local dev
883     dev="${1}"
884     [ "$(/sbin/blkid -s PART_ENTRY_SCHEME -p -o value ${dev} 2>/dev/null)" = "gpt" ]
885 }
886
887 probe_for_gpt_name ()
888 {
889         local overlays dev gpt_dev gpt_name
890         overlays="${1}"
891         dev="${2}"
892
893         gpt_dev="${dev}"
894         if is_active_luks_mapping ${dev}
895         then
896                 # if $dev is an opened luks device, we need to check
897                 # GPT stuff on the backing device
898                 gpt_dev=$(get_luks_backing_device "${dev}")
899         fi
900
901         if ! is_gpt_device ${gpt_dev}
902         then
903                 return
904         fi
905
906         gpt_name=$(get_gpt_name ${gpt_dev})
907         for label in ${overlays}
908         do
909                 if [ "${gpt_name}" = "${label}" ]
910                 then
911                         echo "${label}=${dev}"
912                 fi
913         done
914 }
915
916 probe_for_fs_label ()
917 {
918         local overlays dev
919         overlays="${1}"
920         dev="${2}"
921
922         for label in ${overlays}
923         do
924                 if [ "$(/sbin/blkid -s LABEL -o value $dev 2>/dev/null)" = "${label}" ]
925                 then
926                         echo "${label}=${dev}"
927                 fi
928         done
929 }
930
931 probe_for_file_name ()
932 {
933         local overlays dev ret backing
934         overlays="${1}"
935         dev="${2}"
936
937         ret=""
938         backing="$(mount_persistence_media ${dev} probe)"
939         if [ -z "${backing}" ]
940         then
941             return
942         fi
943
944         for label in ${overlays}
945         do
946                 path=${backing}/${PERSISTENCE_PATH}/${label}
947                 if [ -f "${path}" ]
948                 then
949                         local loopdev
950                         loopdev=$(setup_loop "${path}" "loop" "/sys/block/loop*")
951                         ret="${ret} ${label}=${loopdev}"
952                 fi
953         done
954
955         if [ -n "${ret}" ]
956         then
957                 echo ${ret}
958         else
959                 # unmount and remove mountpoint
960                 umount ${backing} > /dev/null 2>&1 || true
961                 rmdir ${backing} > /dev/null 2>&1 || true
962         fi
963 }
964
965 probe_for_directory_name ()
966 {
967         local overlays dev ret backing
968         overlays="${1}"
969         dev="${2}"
970
971         ret=""
972         backing="$(mount_persistence_media ${dev} probe)"
973         if [ -z "${backing}" ]
974         then
975             return
976         fi
977
978         for label in ${overlays}
979         do
980                 path=${backing}/${PERSISTENCE_PATH}/${label}
981                 if [ -d "${path}" ]
982                 then
983                         # in this case the "device" ends with a "/"
984                         ret="${ret} ${label}=${backing}/${PERSISTENCE_PATH}/${label%%/}/"
985                 fi
986         done
987
988         if [ -n "${ret}" ]
989         then
990                 echo ${ret}
991         else
992                 # unmount and remove mountpoint
993                 umount ${backing} > /dev/null 2>&1 || true
994                 rmdir ${backing} > /dev/null 2>&1 || true
995         fi
996 }
997
998 find_persistence_media ()
999 {
1000         # Scans devices for overlays, and returns a whitespace
1001         # separated list of how to use them. Only overlays with a partition
1002         # label or file name in ${overlays} are returned.
1003         #
1004         # When scanning a LUKS device, the user will be asked to enter the
1005         # passphrase; on failure to enter it, or if no persistence partitions
1006         # or files were found, the LUKS device is closed.
1007         #
1008         # For all other cases (overlay partition and overlay file) the
1009         # return value is "${label}=${device}", where ${device} a device that
1010         # can mount the content. In the case of an overlay file, the device
1011         # containing the file will remain mounted as a side-effect.
1012         #
1013         # No devices in ${black_listed_devices} will be scanned, and if
1014         # ${white_list_devices} is non-empty, only devices in it will be
1015         # scanned.
1016
1017         local overlays white_listed_devices ret black_listed_devices
1018         overlays="${1}"
1019         white_listed_devices="${2}"
1020         ret=""
1021
1022         #
1023         # The devices that are hosting the actual live rootfs should not be
1024         # used for persistence storage since otherwise you might mount a
1025         # parent directory on top of a sub-directory of the same filesystem
1026         # in one union together.
1027         #
1028         black_listed_devices=""
1029         for d in /live/rootfs/* /live/findiso /live/fromiso
1030         do
1031                 black_listed_devices="${black_listed_devices} $(what_is_mounted_on d)"
1032         done
1033
1034         for dev in $(storage_devices "${black_listed_devices}" "${white_listed_devices}")
1035         do
1036                 local result luks_device
1037                 result=""
1038
1039                 luks_device=""
1040                 # Check if it's a luks device; we'll have to open the device
1041                 # in order to probe any filesystem it contains, like we do
1042                 # below. activate_custom_mounts() also depends on that any luks
1043                 # device already has been opened.
1044                 if is_in_comma_sep_list luks ${PERSISTENCE_ENCRYPTION} && is_luks_partition ${dev}
1045                 then
1046                         if luks_device=$(open_luks_device "${dev}")
1047                         then
1048                                 dev="${luks_device}"
1049                         else
1050                                 # skip $dev since we failed/chose not to open it
1051                                 continue
1052                         fi
1053                 elif ! is_in_comma_sep_list none ${PERSISTENCE_ENCRYPTION}
1054                 then
1055                         # skip $dev since we don't allow unencrypted storage
1056                         continue
1057                 fi
1058
1059                 # Probe for matching GPT partition names or filesystem labels
1060                 if is_in_comma_sep_list filesystem ${PERSISTENCE_STORAGE}
1061                 then
1062                         result=$(probe_for_gpt_name "${overlays}" ${dev})
1063                         if [ -n "${result}" ]
1064                         then
1065                                 ret="${ret} ${result}"
1066                                 continue
1067                         fi
1068
1069                         result=$(probe_for_fs_label "${overlays}" ${dev})
1070                         if [ -n "${result}" ]
1071                         then
1072                                 ret="${ret} ${result}"
1073                                 continue
1074                         fi
1075                 fi
1076
1077                 # Probe for files with matching name on mounted partition
1078                 if is_in_comma_sep_list file ${PERSISTENCE_STORAGE}
1079                 then
1080                         result=$(probe_for_file_name "${overlays}" ${dev})
1081                         if [ -n "${result}" ]
1082                         then
1083                                 local loopdevice
1084                                 loopdevice=${result##*=}
1085                                 if is_in_comma_sep_list luks ${PERSISTENCE_ENCRYPTION} && is_luks_partition ${loopdevice}
1086                                 then
1087                                         local luksfile
1088                                         luksfile=""
1089                                         if luksfile=$(open_luks_device "${loopdevice}")
1090                                         then
1091                                                 result=${result%%=*}
1092                                                 result="${result}=${luksfile}"
1093                                         else
1094                                                 losetup -d $loopdevice
1095                                                 result=""
1096                                         fi
1097                                 fi
1098                                 ret="${ret} ${result}"
1099                                 continue
1100                         fi
1101                 fi
1102
1103                 # Probe for directory with matching name on mounted partition
1104                 if is_in_comma_sep_list directory ${PERSISTENCE_STORAGE}
1105                 then
1106                         result=$(probe_for_directory_name "${overlays}" ${dev})
1107                         if [ -n "${result}" ]
1108                         then
1109                                 ret="${ret} ${result}"
1110                                 continue
1111                         fi
1112                 fi
1113
1114                 # Close luks device if it isn't used
1115                 if [ -z "${result}" ] && [ -n "${luks_device}" ] && is_active_luks_mapping "${luks_device}"
1116                 then
1117                         /sbin/cryptsetup luksClose "${luks_device}"
1118                 fi
1119         done
1120
1121         if [ -n "${ret}" ]
1122         then
1123                 echo ${ret}
1124         fi
1125 }
1126
1127 get_mac ()
1128 {
1129         mac=""
1130
1131         for adaptor in /sys/class/net/*
1132         do
1133                 status="$(cat ${adaptor}/iflink)"
1134
1135                 if [ "${status}" -eq 2 ]
1136                 then
1137                         mac="$(cat ${adaptor}/address)"
1138                         mac="$(echo ${mac} | sed 's/:/-/g' | tr '[a-z]' '[A-Z]')"
1139                 fi
1140         done
1141
1142         echo ${mac}
1143 }
1144
1145 is_luks_partition ()
1146 {
1147         device="${1}"
1148         /sbin/cryptsetup isLuks "${device}" 1>/dev/null 2>&1
1149 }
1150
1151 is_active_luks_mapping ()
1152 {
1153         device="${1}"
1154         /sbin/cryptsetup status "${device}" 1>/dev/null 2>&1
1155 }
1156
1157 get_luks_backing_device ()
1158 {
1159         device=${1}
1160         cryptsetup status ${device} 2> /dev/null | \
1161                 awk '{if ($1 == "device:") print $2}'
1162 }
1163
1164 removable_dev ()
1165 {
1166         output_format="${1}"
1167         want_usb="${2}"
1168         ret=
1169
1170         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
1171         do
1172                 dev_ok=
1173                 if [ "$(cat ${sysblock}/removable)" = "1" ]
1174                 then
1175                         if [ -z "${want_usb}" ]
1176                         then
1177                                 dev_ok="true"
1178                         else
1179                                 if readlink ${sysblock} | grep -q usb
1180                                 then
1181                                         dev_ok="true"
1182                                 fi
1183                         fi
1184                 fi
1185
1186                 if [ "${dev_ok}" = "true" ]
1187                 then
1188                         case "${output_format}" in
1189                                 sys)
1190                                         ret="${ret} ${sysblock}"
1191                                         ;;
1192                                 *)
1193                                         devname=$(sys2dev "${sysblock}")
1194                                         ret="${ret} ${devname}"
1195                                         ;;
1196                         esac
1197                 fi
1198         done
1199
1200         echo "${ret}"
1201 }
1202
1203 removable_usb_dev ()
1204 {
1205         output_format="${1}"
1206
1207         removable_dev "${output_format}" "want_usb"
1208 }
1209
1210 non_removable_dev ()
1211 {
1212         output_format="${1}"
1213         ret=
1214
1215         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
1216         do
1217                 if [ "$(cat ${sysblock}/removable)" = "0" ]
1218                 then
1219                         case "${output_format}" in
1220                                 sys)
1221                                         ret="${ret} ${sysblock}"
1222                                         ;;
1223                                 *)
1224                                         devname=$(sys2dev "${sysblock}")
1225                                         ret="${ret} ${devname}"
1226                                         ;;
1227                         esac
1228                 fi
1229         done
1230
1231         echo "${ret}"
1232 }
1233
1234 link_files ()
1235 {
1236         # create source's directory structure in dest, and recursively
1237         # create symlinks in dest to to all files in source. if mask
1238         # is non-empty, remove mask from all source paths when
1239         # creating links (will be necessary if we change root, which
1240         # live-boot normally does (into $rootmnt)).
1241         local src_dir dest_dir src_transform
1242
1243         # remove multiple /:s and ensure ending on /
1244         src_dir="$(trim_path ${1})/"
1245         dest_dir="$(trim_path ${2})/"
1246         src_transform="${3}"
1247
1248         # This check can only trigger on the inital, non-recursive call since
1249         # we create the destination before recursive calls
1250         if [ ! -d "${dest_dir}" ]
1251         then
1252                 log_warning_msg "Must link_files into a directory"
1253                 return
1254         fi
1255
1256         find "${src_dir}" -mindepth 1 -maxdepth 1 | \
1257         while read src
1258         do
1259                 local dest final_src
1260                 dest="${dest_dir}$(basename "${src}")"
1261                 if [ -d "${src}" ]
1262                 then
1263                         if [ -z "$(ls -A "${src}")" ]
1264                         then
1265                                 continue
1266                         fi
1267                         if [ ! -d "${dest}" ]
1268                         then
1269                                 mkdir -p "${dest}"
1270                                 chown_ref "${src}" "${dest}"
1271                                 chmod_ref "${src}" "${dest}"
1272                         fi
1273                         link_files "${src}" "${dest}" "${src_transform}"
1274                 else
1275                         final_src=${src}
1276                         if [ -n "${src_transform}" ]
1277                         then
1278                                 final_src="$(echo ${final_src} | sed "${src_transform}")"
1279                         fi
1280                         rm -rf "${dest}" 2> /dev/null
1281                         ln -s "${final_src}" "${dest}"
1282                         chown_ref "${src}" "${dest}"
1283                 fi
1284         done
1285 }
1286
1287 do_union ()
1288 {
1289         local unionmountpoint unionrw unionro
1290         unionmountpoint="${1}"  # directory where the union is mounted
1291         shift
1292         unionrw="${1}"          # branch where the union changes are stored
1293         shift
1294         unionro="${*}"          # space separated list of read-only branches (optional)
1295
1296         case "${UNIONTYPE}" in
1297                 aufs)
1298                         rw_opt="rw"
1299                         ro_opt="rr+wh"
1300                         noxino_opt="noxino"
1301
1302                         unionmountopts="-o noatime,${noxino_opt},dirs=${unionrw}=${rw_opt}"
1303                         if [ -n "${unionro}" ]
1304                         then
1305                                 for rofs in ${unionro}
1306                                 do
1307                                         unionmountopts="${unionmountopts}:${rofs}=${ro_opt}"
1308                                 done
1309                         fi
1310                         ;;
1311
1312                 overlay)
1313                         # XXX: can unionro be optional? i.e. can overlay skip lowerdir?
1314                         if [ -z "${unionro}" ]
1315                         then
1316                                 panic "overlay needs at least one lower filesystem (read-only branch)."
1317                         fi
1318                         # Multiple lower layers can now be given using the the colon (":") as a
1319                         # separator character between the directory names.
1320                         unionro="$(echo ${unionro} | sed -e 's| |:|g')"
1321                         # overlayfs requires:
1322                         # + a workdir to become mounted
1323                         # + workdir and upperdir to reside under the same mount
1324                         # + workdir and upperdir to be in separate directories
1325                         mkdir "${unionrw}/rw"
1326                         mkdir "${unionrw}/work"
1327                         unionmountopts="-o noatime,lowerdir=${unionro},upperdir=${unionrw}/rw,workdir=${unionrw}/work"
1328                         ;;
1329         esac
1330
1331         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
1332 }
1333
1334 get_custom_mounts ()
1335 {
1336         # Side-effect: leaves $devices with persistence.conf mounted in /live/persistence
1337         # Side-effect: prints info to file $custom_mounts
1338
1339         local custom_mounts devices bindings links
1340         custom_mounts=${1}
1341         shift
1342         devices=${@}
1343
1344         bindings="/tmp/bindings.list"
1345         links="/tmp/links.list"
1346         rm -rf ${bindings} ${links} 2> /dev/null
1347
1348         for device in ${devices}
1349         do
1350                 local device_name backing include_list
1351                 device_name="$(basename ${device})"
1352                 backing=$(mount_persistence_media ${device})
1353                 if [ -z "${backing}" ]
1354                 then
1355                         continue
1356                 fi
1357
1358                 if [ -r "${backing}/${persistence_list}" ]
1359                 then
1360                         include_list="${backing}/${persistence_list}"
1361                 else
1362                         continue
1363                 fi
1364
1365                 if [ -n "${LIVE_BOOT_DEBUG}" ] && [ -e "${include_list}" ]
1366                 then
1367                         cp ${include_list} /live/persistence/${persistence_list}.${device_name}
1368                 fi
1369
1370                 while read dir options # < ${include_list}
1371                 do
1372                         if echo ${dir} | grep -qe "^[[:space:]]*\(#.*\)\?$"
1373                         then
1374                                 # skipping empty or commented lines
1375                                 continue
1376                         fi
1377
1378                         if trim_path ${dir} | grep -q -e "^[^/]" -e "^/lib" -e "^/lib/live\(/.*\)\?$" -e "^/\(.*/\)\?\.\.\?\(/.*\)\?$"
1379                         then
1380                                 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."
1381                                 continue
1382                         fi
1383
1384                         local opt_source opt_link source full_source full_dest
1385                         opt_source=""
1386                         opt_link=""
1387                         for opt in $(echo ${options} | tr ',' ' ');
1388                         do
1389                                 case "${opt}" in
1390                                         source=*)
1391                                                 opt_source=${opt#source=}
1392                                                 ;;
1393                                         link)
1394                                                 opt_link="true"
1395                                                 ;;
1396                                         union|bind)
1397                                                 ;;
1398                                         *)
1399                                                 log_warning_msg "Skipping custom mount with unknown option: ${opt}"
1400                                                 continue 2
1401                                                 ;;
1402                                 esac
1403                         done
1404
1405                         source="${dir}"
1406                         if [ -n "${opt_source}" ]
1407                         then
1408                                 if echo ${opt_source} | grep -q -e "^/" -e "^\(.*/\)\?\.\.\?\(/.*\)\?$" && [ "${opt_source}" != "." ]
1409                                 then
1410                                         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"
1411                                         continue
1412                                 else
1413                                         source="${opt_source}"
1414                                 fi
1415                         fi
1416
1417                         full_source="$(trim_path ${backing}/${source})"
1418                         full_dest="$(trim_path ${rootmnt}/${dir})"
1419                         if [ -n "${opt_link}" ]
1420                         then
1421                                 echo "${device} ${full_source} ${full_dest} ${options}" >> ${links}
1422                         else
1423                                 echo "${device} ${full_source} ${full_dest} ${options}" >> ${bindings}
1424                         fi
1425                 done < ${include_list}
1426         done
1427
1428         # We sort the list according to destination so we're sure that
1429         # we won't hide a previous mount. We also ignore duplicate
1430         # destinations in a more or less arbitrary way.
1431         [ -e "${bindings}" ] && sort -k3 -sbu ${bindings} >> ${custom_mounts} && rm ${bindings}
1432
1433         # After all mounts are considered we add symlinks so they
1434         # won't be hidden by some mount.
1435         [ -e "${links}" ] && cat ${links} >> ${custom_mounts} && rm ${links}
1436
1437         # We need to make sure that no two custom mounts have the same sources
1438         # or are nested; if that is the case, too much weird stuff can happen.
1439         local prev_source prev_dest
1440         prev_source="impossible source" # first iteration must not match
1441         prev_dest=""
1442         # This sort will ensure that a source /a comes right before a source
1443         # /a/b so we only need to look at the previous source
1444         [ -e ${custom_mounts} ] && sort -k2 -b ${custom_mounts} |
1445         while read device source dest options
1446         do
1447                 if echo ${source} | grep -qe "^${prev_source}\(/.*\)\?$"
1448                 then
1449                         panic "Two persistence mounts have the same or nested sources: ${source} on ${dest}, and ${prev_source} on ${prev_dest}"
1450                 fi
1451                 prev_source=${source}
1452                 prev_dest=${dest}
1453         done
1454 }
1455
1456 activate_custom_mounts ()
1457 {
1458         local custom_mounts used_devices
1459         custom_mounts="${1}" # the ouput from get_custom_mounts()
1460         used_devices=""
1461
1462         while read device source dest options # < ${custom_mounts}
1463         do
1464                 local opt_bind opt_link opt_union
1465                 opt_bind="true"
1466                 opt_link=""
1467                 opt_union=""
1468                 for opt in $(echo ${options} | tr ',' ' ');
1469                 do
1470                         case "${opt}" in
1471                                 bind)
1472                                         opt_bind="true"
1473                                         unset opt_link opt_union
1474                                         ;;
1475                                 link)
1476                                         opt_link="true"
1477                                         unset opt_bind opt_union
1478                                         ;;
1479                                 union)
1480                                         opt_union="true"
1481                                         unset opt_bind opt_link
1482                                         ;;
1483                         esac
1484                 done
1485
1486                 if [ -n "$(what_is_mounted_on "${dest}")" ]
1487                 then
1488                         if [ "${dest}" = "${rootmnt}" ]
1489                         then
1490                                 umount "${dest}"
1491                         else
1492                                 log_warning_msg "Skipping custom mount ${dest}: $(what_is_mounted_on "${dest}") is already mounted there"
1493                                 continue
1494                         fi
1495                 fi
1496
1497                 if [ ! -d "${dest}" ]
1498                 then
1499                         # create the destination and delete existing files in
1500                         # its path that are in the way
1501                         path="/"
1502                         for dir in $(echo ${dest} | sed -e 's|/\+| |g')
1503                         do
1504                                 path=$(trim_path ${path}/${dir})
1505                                 if [ -f ${path} ]
1506                                 then
1507                                         rm -f ${path}
1508                                 fi
1509                                 if [ ! -e ${path} ]
1510                                 then
1511                                         mkdir -p ${path}
1512                                         if echo ${path} | grep -qe "^${rootmnt}/*home/[^/]\+"
1513                                         then
1514                                                 # if ${dest} is in /home try fixing proper ownership by assuming that the intended user is the first, which is usually the case
1515                                                 # FIXME: this should really be handled by live-config since we don't know for sure which uid a certain user has until then
1516                                                 chown 1000:1000 ${path}
1517                                         fi
1518                                 fi
1519                         done
1520                 fi
1521
1522                 # if ${source} doesn't exist on our persistence media
1523                 # we bootstrap it with $dest from the live filesystem.
1524                 # this both makes sense and is critical if we're
1525                 # dealing with /etc or other system dir.
1526                 if [ ! -d "${source}" ]
1527                 then
1528                         if [ -n "${PERSISTENCE_READONLY}" ]
1529                         then
1530                                 continue
1531                         elif [ -n "${opt_union}" ] || [ -n "${opt_link}" ]
1532                         then
1533                                 # unions and don't need to be bootstrapped
1534                                 # link dirs can't be bootstrapped in a sensible way
1535                                 mkdir -p "${source}"
1536                                 chown_ref "${dest}" "${source}"
1537                                 chmod_ref "${dest}" "${source}"
1538                         elif [ -n "${opt_bind}" ]
1539                         then
1540                                 # ensure that $dest is not copied *into* $source
1541                                 mkdir -p "$(dirname ${source})"
1542                                 cp -a "${dest}" "${source}"
1543                         fi
1544                 fi
1545
1546                 # XXX: If CONFIG_AUFS_ROBR is added to the Debian kernel we can
1547                 # ignore the loop below and set rootfs_dest_backing=$dest
1548                 local rootfs_dest_backing
1549                 rootfs_dest_backing=""
1550                 if [ -n "${opt_link}" ] || [ -n "${opt_union}" ]
1551                 then
1552                         for d in /live/rootfs/*
1553                         do
1554                                 if [ -n "${rootmnt}" ]
1555                                 then
1556                                         fs="${d}/$(echo ${dest} | sed -e "s|${rootmnt}||")"
1557                                 else
1558                                         fs="${d}/${dest}"
1559                                 fi
1560                                 if [ -d "${fs}" ]
1561                                 then
1562                                         rootfs_dest_backing="${rootfs_dest_backing} ${fs}"
1563                                 fi
1564                         done
1565                 fi
1566
1567                 local cow_dir links_source
1568                 if [ -n "${opt_link}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1569                 then
1570                         link_files ${source} ${dest} "s|^/live/|/lib/live/mount/|"
1571                 elif [ -n "${opt_link}" ] && [ -n "${PERSISTENCE_READONLY}" ]
1572                 then
1573                         mkdir -p ${rootmnt}/lib/live/mount/persistence
1574                         links_source=$(mktemp -d ${rootmnt}/lib/live/mount/persistence/links-source-XXXXXX)
1575                         chown_ref ${source} ${links_source}
1576                         chmod_ref ${source} ${links_source}
1577                         # We put the cow dir in the below strange place to
1578                         # make it absolutely certain that the link source
1579                         # has its own directory and isn't nested with some
1580                         # other custom mount (if so that mount's files would
1581                         # be linked, causing breakage.
1582                         cow_dir="/live/overlay/lib/live/mount/persistence/$(basename ${links_source})"
1583                         mkdir -p ${cow_dir}
1584                         chown_ref "${source}" "${cow_dir}"
1585                         chmod_ref "${source}" "${cow_dir}"
1586                         do_union ${links_source} ${cow_dir} ${source} ${rootfs_dest_backing}
1587                         link_files ${links_source} ${dest} "s|^${rootmnt}||"
1588                 elif [ -n "${opt_union}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1589                 then
1590                         do_union ${dest} ${source} ${rootfs_dest_backing}
1591                 elif [ -n "${opt_bind}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1592                 then
1593                         mount --bind "${source}" "${dest}"
1594                 elif [ -n "${opt_bind}" -o -n "${opt_union}" ] && [ -n "${PERSISTENCE_READONLY}" ]
1595                 then
1596                         # bind-mount and union mount are handled the same
1597                         # in read-only mode, but note that rootfs_dest_backing
1598                         # is non-empty (and necessary) only for unions
1599                         cow_dir="/live/overlay/${dest}"
1600                         if [ -e "${cow_dir}" ] && [ -z "${opt_link}" ]
1601                         then
1602                                 # If an earlier custom mount has files here
1603                                 # it will "block" the current mount's files
1604                                 # which is undesirable
1605                                 rm -rf "${cow_dir}"
1606                         fi
1607                         mkdir -p ${cow_dir}
1608                         chown_ref "${source}" "${cow_dir}"
1609                         chmod_ref "${source}" "${cow_dir}"
1610                         do_union ${dest} ${cow_dir} ${source} ${rootfs_dest_backing}
1611                 fi
1612
1613                 PERSISTENCE_IS_ON="1"
1614                 export PERSISTENCE_IS_ON
1615
1616                 if echo ${used_devices} | grep -qve "^\(.* \)\?${device}\( .*\)\?$"
1617                 then
1618                         used_devices="${used_devices} ${device}"
1619                 fi
1620         done < ${custom_mounts}
1621
1622         echo ${used_devices}
1623 }
1624
1625 is_mountpoint ()
1626 {
1627         directory="$1"
1628
1629         [ $(stat -fc%d:%D "${directory}") != $(stat -fc%d:%D "${directory}/..") ]
1630 }