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