deleted files to not track
[stack/code/debianlive.git] / xfce-desktop / config / includes.chroot / lib / live / 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 -kP | 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 -q /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="/live/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 /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 unionro
1201         unionmountpoint="${1}"  # directory where the union is mounted
1202         shift
1203         unionrw="${1}"          # branch where the union changes are stored
1204         shift
1205         unionro="${*}"          # space separated list of read-only branches (optional)
1206
1207         case "${UNIONTYPE}" in
1208                 aufs)
1209                         rw_opt="rw"
1210                         ro_opt="rr+wh"
1211                         noxino_opt="noxino"
1212                         ;;
1213
1214                 unionfs-fuse)
1215                         rw_opt="RW"
1216                         ro_opt="RO"
1217                         ;;
1218
1219                 *)
1220                         rw_opt="rw"
1221                         ro_opt="ro"
1222                         ;;
1223         esac
1224
1225         case "${UNIONTYPE}" in
1226                 unionfs-fuse)
1227                         unionmountopts="-o cow -o noinitgroups -o default_permissions -o allow_other -o use_ino -o suid"
1228                         unionmountopts="${unionmountopts} ${unionrw}=${rw_opt}"
1229                         if [ -n "${unionro}" ]
1230                         then
1231                                 for rofs in ${unionro}
1232                                 do
1233                                         unionmountopts="${unionmountopts}:${rofs}=${ro_opt}"
1234                                 done
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 multiple unionro be used? (overlayfs only handles two dirs, but perhaps they can be chained?)
1244                         # XXX: and can unionro be optional? i.e. can overlayfs skip lowerdir?
1245                         if echo ${unionro} | grep -q " "
1246                         then
1247                                 panic "Multiple lower filesystems are currently not supported with overlayfs (unionro = ${unionro})."
1248                         elif [ -z "${unionro}"  ]
1249                         then
1250                                 panic "Overlayfs needs at least one lower filesystem (read-only branch)."
1251                         fi
1252                         unionmountopts="-o noatime,lowerdir=${unionro},upperdir=${unionrw}"
1253                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
1254                         ;;
1255
1256                 *)
1257                         unionmountopts="-o noatime,${noxino_opt},dirs=${unionrw}=${rw_opt}"
1258                         if [ -n "${unionro}" ]
1259                         then
1260                                 for rofs in ${unionro}
1261                                 do
1262                                         unionmountopts="${unionmountopts}:${rofs}=${ro_opt}"
1263                                 done
1264                         fi
1265                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
1266                         ;;
1267         esac
1268 }
1269
1270 get_custom_mounts ()
1271 {
1272         # Side-effect: leaves $devices with persistence.conf mounted in /live/persistence
1273         # Side-effect: prints info to file $custom_mounts
1274
1275         local custom_mounts devices bindings links
1276         custom_mounts=${1}
1277         shift
1278         devices=${@}
1279
1280         bindings="/tmp/bindings.list"
1281         links="/tmp/links.list"
1282         rm -rf ${bindings} ${links} 2> /dev/null
1283
1284         for device in ${devices}
1285         do
1286                 if [ ! -b "${device}" ]
1287                 then
1288                         continue
1289                 fi
1290
1291                 local device_name backing include_list
1292                 device_name="$(basename ${device})"
1293                 backing=$(mount_persistence_media ${device})
1294                 if [ -z "${backing}" ]
1295                 then
1296                         continue
1297                 fi
1298
1299                 if [ -r "${backing}/${persistence_list}" ]
1300                 then
1301                         include_list="${backing}/${persistence_list}"
1302                 elif [ -r "${backing}/${old_persistence_list}" ]
1303                 then
1304                         include_list="${backing}/${old_persistence_list}"
1305                 else
1306                         continue
1307                 fi
1308
1309                 if [ -n "${DEBUG}" ] && [ -e "${include_list}" ]
1310                 then
1311                         cp ${include_list} /live/persistence/${persistence_list}.${device_name}
1312                 fi
1313
1314                 while read dir options # < ${include_list}
1315                 do
1316                         if echo ${dir} | grep -qe "^[[:space:]]*\(#.*\)\?$"
1317                         then
1318                                 # skipping empty or commented lines
1319                                 continue
1320                         fi
1321
1322                         if trim_path ${dir} | grep -q -e "^[^/]" -e "^/lib" -e "^/lib/live\(/.*\)\?$" -e "^/\(.*/\)\?\.\.\?\(/.*\)\?$"
1323                         then
1324                                 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."
1325                                 continue
1326                         fi
1327
1328                         local opt_source opt_link source full_source full_dest
1329                         opt_source=""
1330                         opt_link=""
1331                         for opt in $(echo ${options} | tr ',' ' ');
1332                         do
1333                                 case "${opt}" in
1334                                         source=*)
1335                                                 opt_source=${opt#source=}
1336                                                 ;;
1337                                         link)
1338                                                 opt_link="true"
1339                                                 ;;
1340                                         union|bind)
1341                                                 ;;
1342                                         *)
1343                                                 log_warning_msg "Skipping custom mount with unkown option: ${opt}"
1344                                                 continue 2
1345                                                 ;;
1346                                 esac
1347                         done
1348
1349                         source="${dir}"
1350                         if [ -n "${opt_source}" ]
1351                         then
1352                                 if echo ${opt_source} | grep -q -e "^/" -e "^\(.*/\)\?\.\.\?\(/.*\)\?$" && [ "${opt_source}" != "." ]
1353                                 then
1354                                         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"
1355                                         continue
1356                                 else
1357                                         source="${opt_source}"
1358                                 fi
1359                         fi
1360
1361                         full_source="$(trim_path ${backing}/${source})"
1362                         full_dest="$(trim_path ${rootmnt}/${dir})"
1363                         if [ -n "${opt_link}" ]
1364                         then
1365                                 echo "${device} ${full_source} ${full_dest} ${options}" >> ${links}
1366                         else
1367                                 echo "${device} ${full_source} ${full_dest} ${options}" >> ${bindings}
1368                         fi
1369                 done < ${include_list}
1370         done
1371
1372         # We sort the list according to destination so we're sure that
1373         # we won't hide a previous mount. We also ignore duplicate
1374         # destinations in a more or less arbitrary way.
1375         [ -e "${bindings}" ] && sort -k3 -sbu ${bindings} >> ${custom_mounts} && rm ${bindings}
1376
1377         # After all mounts are considered we add symlinks so they
1378         # won't be hidden by some mount.
1379         [ -e "${links}" ] && cat ${links} >> ${custom_mounts} && rm ${links}
1380
1381         # We need to make sure that no two custom mounts have the same sources
1382         # or are nested; if that is the case, too much weird stuff can happen.
1383         local prev_source prev_dest
1384         prev_source="impossible source" # first iteration must not match
1385         prev_dest=""
1386         # This sort will ensure that a source /a comes right before a source
1387         # /a/b so we only need to look at the previous source
1388         sort -k2 -b ${custom_mounts} |
1389         while read device source dest options
1390         do
1391                 if echo ${source} | grep -qe "^${prev_source}\(/.*\)\?$"
1392                 then
1393                         panic "Two persistence mounts have the same or nested sources: ${source} on ${dest}, and ${prev_source} on ${prev_dest}"
1394                 fi
1395                 prev_source=${source}
1396                 prev_dest=${dest}
1397         done
1398 }
1399
1400 activate_custom_mounts ()
1401 {
1402         local custom_mounts used_devices
1403         custom_mounts="${1}" # the ouput from get_custom_mounts()
1404         used_devices=""
1405
1406         while read device source dest options # < ${custom_mounts}
1407         do
1408                 local opt_bind opt_link opt_union
1409                 opt_bind="true"
1410                 opt_link=""
1411                 opt_union=""
1412                 for opt in $(echo ${options} | tr ',' ' ');
1413                 do
1414                         case "${opt}" in
1415                                 bind)
1416                                         opt_bind="true"
1417                                         unset opt_link opt_union
1418                                         ;;
1419                                 link)
1420                                         opt_link="true"
1421                                         unset opt_bind opt_union
1422                                         ;;
1423                                 union)
1424                                         opt_union="true"
1425                                         unset opt_bind opt_link
1426                                         ;;
1427                         esac
1428                 done
1429
1430                 if [ -n "$(what_is_mounted_on "${dest}")" ]
1431                 then
1432                         if [ "${dest}" = "${rootmnt}" ]
1433                         then
1434                                 umount "${dest}"
1435                         else
1436                                 log_warning_msg "Skipping custom mount ${dest}: $(what_is_mounted_on "${dest}") is already mounted there"
1437                                 continue
1438                         fi
1439                 fi
1440
1441                 if [ ! -d "${dest}" ]
1442                 then
1443                         # create the destination and delete existing files in
1444                         # its path that are in the way
1445                         path="/"
1446                         for dir in $(echo ${dest} | sed -e 's|/\+| |g')
1447                         do
1448                                 path=$(trim_path ${path}/${dir})
1449                                 if [ -f ${path} ]
1450                                 then
1451                                         rm -f ${path}
1452                                 fi
1453                                 if [ ! -e ${path} ]
1454                                 then
1455                                         mkdir -p ${path}
1456                                         if echo ${path} | grep -qe "^${rootmnt}/*home/[^/]\+"
1457                                         then
1458                                                 # if ${dest} is in /home try fixing proper ownership by assuming that the intended user is the first, which is usually the case
1459                                                 # FIXME: this should really be handled by live-config since we don't know for sure which uid a certain user has until then
1460                                                 chown 1000:1000 ${path}
1461                                         fi
1462                                 fi
1463                         done
1464                 fi
1465
1466                 # if ${source} doesn't exist on our persistence media
1467                 # we bootstrap it with $dest from the live filesystem.
1468                 # this both makes sense and is critical if we're
1469                 # dealing with /etc or other system dir.
1470                 if [ ! -d "${source}" ]
1471                 then
1472                         if [ -n "${PERSISTENCE_READONLY}" ]
1473                         then
1474                                 continue
1475                         elif [ -n "${opt_union}" ] || [ -n "${opt_link}" ]
1476                         then
1477                                 # unions and don't need to be bootstrapped
1478                                 # link dirs can't be bootstrapped in a sensible way
1479                                 mkdir -p "${source}"
1480                                 chown_ref "${dest}" "${source}"
1481                                 chmod_ref "${dest}" "${source}"
1482                         elif [ -n "${opt_bind}" ]
1483                         then
1484                                 # ensure that $dest is not copied *into* $source
1485                                 mkdir -p "$(dirname ${source})"
1486                                 cp -a "${dest}" "${source}"
1487                         fi
1488                 fi
1489
1490                 # XXX: If CONFIG_AUFS_ROBR is added to the Debian kernel we can
1491                 # ignore the loop below and set rootfs_dest_backing=$dest
1492                 local rootfs_dest_backing
1493                 rootfs_dest_backing=""
1494                 if [ -n "${opt_link}"]
1495                 then
1496                         for d in /live/rootfs/*
1497                         do
1498                                 if [ -n "${rootmnt}" ]
1499                                 then
1500                                         fs="${d}/$(echo ${dest} | sed -e "s|${rootmnt}||")"
1501                                 else
1502                                         fs="${d}/${dest}"
1503                                 fi
1504                                 if [ -d "${fs}" ]
1505                                 then
1506                                         rootfs_dest_backing="${rootfs_dest_backing} ${fs}"
1507                                 fi
1508                         done
1509                 fi
1510
1511                 local cow_dir links_source
1512                 if [ -n "${opt_link}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1513                 then
1514                         link_files ${source} ${dest} ${rootmnt}
1515                 elif [ -n "${opt_link}" ] && [ -n "${PERSISTENCE_READONLY}" ]
1516                 then
1517                         mkdir -p ${rootmnt}/lib/live/mount/persistence
1518                         links_source=$(mktemp -d ${rootmnt}/lib/live/mount/persistence/links-source-XXXXXX)
1519                         chown_ref ${source} ${links_source}
1520                         chmod_ref ${source} ${links_source}
1521                         # We put the cow dir in the below strange place to
1522                         # make it absolutely certain that the link source
1523                         # has its own directory and isn't nested with some
1524                         # other custom mount (if so that mount's files would
1525                         # be linked, causing breakage.
1526                         cow_dir="/live/overlay/lib/live/mount/persistence/$(basename ${links_source})"
1527                         mkdir -p ${cow_dir}
1528                         chown_ref "${source}" "${cow_dir}"
1529                         chmod_ref "${source}" "${cow_dir}"
1530                         do_union ${links_source} ${cow_dir} ${source} ${rootfs_dest_backing}
1531                         link_files ${links_source} ${dest} ${rootmnt}
1532                 elif [ -n "${opt_union}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1533                 then
1534                         do_union ${dest} ${source} ${rootfs_dest_backing}
1535                 elif [ -n "${opt_bind}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1536                 then
1537                         mount --bind "${source}" "${dest}"
1538                 elif [ -n "${opt_bind}" -o -n "${opt_union}" ] && [ -n "${PERSISTENCE_READONLY}" ]
1539                 then
1540                         # bind-mount and union mount are handled the same
1541                         # in read-only mode, but note that rootfs_dest_backing
1542                         # is non-empty (and necessary) only for unions
1543                         cow_dir="/live/overlay/${dest}"
1544                         if [ -e "${cow_dir}" ] && [ -z "${opt_link}" ]
1545                         then
1546                                 # If an earlier custom mount has files here
1547                                 # it will "block" the current mount's files
1548                                 # which is undesirable
1549                                 rm -rf "${cow_dir}"
1550                         fi
1551                         mkdir -p ${cow_dir}
1552                         chown_ref "${source}" "${cow_dir}"
1553                         chmod_ref "${source}" "${cow_dir}"
1554                         do_union ${dest} ${cow_dir} ${source} ${rootfs_dest_backing}
1555                 fi
1556
1557                 PERSISTENCE_IS_ON="1"
1558                 export PERSISTENCE_IS_ON
1559
1560                 if echo ${used_devices} | grep -qve "^\(.* \)\?${device}\( .*\)\?$"
1561                 then
1562                         used_devices="${used_devices} ${device}"
1563                 fi
1564         done < ${custom_mounts}
1565
1566         echo ${used_devices}
1567 }
1568
1569 fix_backwards_compatibility ()
1570 {
1571         local device dir opt backing include_list
1572         device=${1}
1573         dir=${2}
1574         opt=${3}
1575
1576         if [ -n "${PERSISTENCE_READONLY}" ]
1577         then
1578                 return
1579         fi
1580
1581         backing="$(mount_persistence_media ${device})"
1582         if [ -z "${backing}" ]
1583         then
1584                 return
1585         fi
1586
1587         include_list="${backing}/${persistence_list}"
1588         if [ ! -r "${include_list}" ] && [ ! -r "${backing}/${old_persistence_list}" ]
1589         then
1590                 echo "# persistence backwards compatibility:
1591 ${dir} ${opt},source=." > "${include_list}"
1592         fi
1593 }
1594
1595 is_mountpoint ()
1596 {
1597         directory="$1"
1598
1599         [ $(stat -fc%d:%D "${directory}") != $(stat -fc%d:%D "${directory}/..") ]
1600 }