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