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