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