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