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