Supress warnings when probing media for persistence.
[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 probe=${2}
747
748         local backing="/live/persistence/$(basename ${device})"
749
750         mkdir -p "${backing}"
751         local old_backing="$(where_is_mounted ${device})"
752         if [ -z "${old_backing}" ]
753         then
754                 local fstype="$(get_fstype ${device})"
755                 local mount_opts="rw,noatime"
756                 if [ -n "${PERSISTENCE_READONLY}" ]
757                 then
758                         mount_opts="ro,noatime"
759                 fi
760                 if mount -t "${fstype}" -o "${mount_opts}" "${device}" "${backing}" >/dev/null
761                 then
762                         echo ${backing}
763                         return 0
764                 else
765                         [ -z "${probe}" ] && log_warning_msg "Failed to mount persistence media ${device}"
766                         rmdir "${backing}"
767                         return 1
768                 fi
769         elif [ "${backing}" != "${old_backing}" ]
770         then
771                 if mount --move ${old_backing} ${backing} >/dev/null
772                 then
773                         echo ${backing}
774                         return 0
775                 else
776                         [ -z "${probe}" ] && log_warning_msg "Failed to move persistence media ${device}"
777                         rmdir "${backing}"
778                         return 1
779                 fi
780         fi
781         return 0
782 }
783
784 close_persistence_media () {
785         local device=${1}
786         local backing="$(where_is_mounted ${device})"
787
788         if [ -d "${backing}" ]
789         then
790                 umount "${backing}" >/dev/null 2>&1
791                 rmdir "${backing}" >/dev/null 2>&1
792         fi
793
794         if is_active_luks_mapping ${device}
795         then
796                 /sbin/cryptsetup luksClose ${device}
797         fi
798 }
799
800 open_luks_device ()
801 {
802         dev="${1}"
803         name="$(basename ${dev})"
804         opts="--key-file=-"
805         if [ -n "${PERSISTENCE_READONLY}" ]
806         then
807                 opts="${opts} --readonly"
808         fi
809
810         if /sbin/cryptsetup status "${name}" >/dev/null 2>&1
811         then
812                 re="^[[:space:]]*device:[[:space:]]*\([^[:space:]]*\)$"
813                 opened_dev=$(cryptsetup status ${name} 2>/dev/null | grep "${re}" | sed "s|${re}|\1|")
814                 if [ "${opened_dev}" = "${dev}" ]
815                 then
816                         luks_device="/dev/mapper/${name}"
817                         echo ${luks_device}
818                         return 0
819                 else
820                         log_warning_msg "Cannot open luks device ${dev} since ${opened_dev} already is opened with its name"
821                         return 1
822                 fi
823         fi
824
825         load_keymap
826
827         while true
828         do
829                 /lib/cryptsetup/askpass "Enter passphrase for ${dev}: " | \
830                         /sbin/cryptsetup -T 1 luksOpen ${dev} ${name} ${opts}
831
832                 if [ 0 -eq ${?} ]
833                 then
834                         luks_device="/dev/mapper/${name}"
835                         echo ${luks_device}
836                         return 0
837                 fi
838
839                 echo >&6
840                 echo -n "There was an error decrypting ${dev} ... Retry? [Y/n] " >&6
841                 read answer
842
843                 if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
844                 then
845                         return 2
846                 fi
847         done
848 }
849
850 get_gpt_name ()
851 {
852     local dev="${1}"
853     /sbin/blkid -s PART_ENTRY_NAME -p -o value ${dev} 2>/dev/null
854 }
855
856 is_gpt_device ()
857 {
858     local dev="${1}"
859     [ "$(/sbin/blkid -s PART_ENTRY_SCHEME -p -o value ${dev} 2>/dev/null)" = "gpt" ]
860 }
861
862 probe_for_gpt_name ()
863 {
864         local overlays="${1}"
865         local snapshots="${2}"
866         local dev="${3}"
867
868         local gpt_dev="${dev}"
869         if is_active_luks_mapping ${dev}
870         then
871                 # if $dev is an opened luks device, we need to check
872                 # GPT stuff on the backing device
873                 gpt_dev=$(get_luks_backing_device "${dev}")
874         fi
875
876         if ! is_gpt_device ${gpt_dev}
877         then
878                 return
879         fi
880
881         local gpt_name=$(get_gpt_name ${gpt_dev})
882         for label in ${overlays} ${snapshots}
883         do
884                 if [ "${gpt_name}" = "${label}" ]
885                 then
886                         echo "${label}=${dev}"
887                 fi
888         done
889 }
890
891 probe_for_fs_label ()
892 {
893         local overlays="${1}"
894         local snapshots="${2}"
895         local dev="${3}"
896
897         for label in ${overlays} ${snapshots}
898         do
899                 if [ "$(/sbin/blkid -s LABEL -o value $dev 2>/dev/null)" = "${label}" ]
900                 then
901                         echo "${label}=${dev}"
902                 fi
903         done
904 }
905
906 probe_for_file_name ()
907 {
908         local overlays="${1}"
909         local snapshots="${2}"
910         local dev="${3}"
911
912         local ret=""
913         local backing="$(mount_persistence_media ${dev} probe)"
914         if [ -z "${backing}" ]
915         then
916             return
917         fi
918
919         for label in ${overlays}
920         do
921                 path=${backing}/${PERSISTENCE_PATH}${label}
922                 if [ -f "${path}" ]
923                 then
924                         local loopdev=$(setup_loop "${path}" "loop" "/sys/block/loop*")
925                         ret="${ret} ${label}=${loopdev}"
926                 fi
927         done
928         for label in ${snapshots}
929         do
930                 for ext in squashfs cpio.gz ext2 ext3 ext4 jffs2
931                 do
932                         path="${PERSISTENCE_PATH}${label}.${ext}"
933                         if [ -f "${backing}/${path}" ]
934                         then
935                                 ret="${ret} ${label}=${dev}:${backing}:${path}"
936                         fi
937                 done
938         done
939
940         if [ -n "${ret}" ]
941         then
942                 echo ${ret}
943         else
944                 umount ${backing} > /dev/null 2>&1 || true
945         fi
946 }
947
948 find_persistence_media ()
949 {
950         # Scans devices for overlays and snapshots, and returns a whitespace
951         # separated list of how to use them. Only overlays with a partition
952         # label or file name in ${overlays} are returned, and ditto for
953         # snapshots with labels in ${snapshots}.
954         #
955         # When scanning a LUKS device, the user will be asked to enter the
956         # passphrase; on failure to enter it, or if no persistence partitions
957         # or files were found, the LUKS device is closed.
958         #
959         # For a snapshot file the return value is ${label}=${snapdata}", where
960         # ${snapdata} is the parameter used for try_snap().
961         #
962         # For all other cases (overlay/snapshot partition and overlay file) the
963         # return value is "${label}=${device}", where ${device} a device that
964         # can mount the content. In the case of an overlay file, the device
965         # containing the file will remain mounted as a side-effect.
966         #
967         # No devices in ${black_listed_devices} will be scanned, and if
968         # ${white_list_devices} is non-empty, only devices in it will be
969         # scanned.
970
971         local overlays="${1}"
972         local snapshots="${2}"
973         local white_listed_devices="${3}"
974         local ret=""
975
976         for dev in $(storage_devices "" "${white_listed_devices}")
977         do
978                 local result=""
979
980                 local luks_device=""
981                 # Check if it's a luks device; we'll have to open the device
982                 # in order to probe any filesystem it contains, like we do
983                 # below. activate_custom_mounts() also depends on that any luks
984                 # device already has been opened.
985                 if echo ${PERSISTENCE_ENCRYPTION} | grep -qe "\<luks\>" && \
986                    is_luks_partition ${dev}
987                 then
988                         if luks_device=$(open_luks_device "${dev}")
989                         then
990                                 dev="${luks_device}"
991                         else
992                                 # skip $dev since we failed/chose not to open it
993                                 continue
994                         fi
995                 elif echo ${PERSISTENCE_ENCRYPTION} | grep -qve "\<none\>"
996                 then
997                         # skip $dev since we don't allow unencrypted storage
998                         continue
999                 fi
1000
1001                 # Probe for matching GPT partition names or filesystem labels
1002                 if echo ${PERSISTENCE_STORAGE} | grep -qe "\<filesystem\>"
1003                 then
1004                         result=$(probe_for_gpt_name "${overlays}" "${snapshots}" ${dev})
1005                         if [ -n "${result}" ]
1006                         then
1007                                 ret="${ret} ${result}"
1008                                 continue
1009                         fi
1010
1011                         result=$(probe_for_fs_label "${overlays}" "${snapshots}" ${dev})
1012                         if [ -n "${result}" ]
1013                         then
1014                                 ret="${ret} ${result}"
1015                                 continue
1016                         fi
1017                 fi
1018
1019                 # Probe for files with matching name on mounted partition
1020                 if echo ${PERSISTENCE_STORAGE} | grep -qe "\<file\>"
1021                 then
1022                         result=$(probe_for_file_name "${overlays}" "${snapshots}" ${dev})
1023                         if [ -n "${result}" ]
1024                         then
1025                                 ret="${ret} ${result}"
1026                                 continue
1027                         fi
1028                 fi
1029
1030                 # Close luks device if it isn't used
1031                 if [ -z "${result}" ] && [ -n "${luks_device}" ] && \
1032                    is_active_luks_mapping "${luks_device}"
1033                 then
1034                         /sbin/cryptsetup luksClose "${luks_device}"
1035                 fi
1036         done
1037
1038         if [ -n "${ret}" ]
1039         then
1040                 echo ${ret}
1041         fi
1042 }
1043
1044 get_mac ()
1045 {
1046         mac=""
1047
1048         for adaptor in /sys/class/net/*
1049         do
1050                 status="$(cat ${adaptor}/iflink)"
1051
1052                 if [ "${status}" -eq 2 ]
1053                 then
1054                         mac="$(cat ${adaptor}/address)"
1055                         mac="$(echo ${mac} | sed 's/:/-/g' | tr '[a-z]' '[A-Z]')"
1056                 fi
1057         done
1058
1059         echo ${mac}
1060 }
1061
1062 is_luks_partition ()
1063 {
1064         device="${1}"
1065         /sbin/cryptsetup isLuks "${device}" 1>/dev/null 2>&1
1066 }
1067
1068 is_active_luks_mapping ()
1069 {
1070         device="${1}"
1071         /sbin/cryptsetup status "${device}" 1>/dev/null 2>&1
1072 }
1073
1074 get_luks_backing_device () {
1075         device=${1}
1076         cryptsetup status ${device} 2> /dev/null | \
1077                 awk '{if ($1 == "device:") print $2}'
1078 }
1079
1080 removable_dev ()
1081 {
1082         output_format="${1}"
1083         want_usb="${2}"
1084         ret=
1085
1086         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
1087         do
1088                 dev_ok=
1089                 if [ "$(cat ${sysblock}/removable)" = "1" ]
1090                 then
1091                         if [ -z "${want_usb}" ]
1092                         then
1093                                 dev_ok="yes"
1094                         else
1095                                 if readlink ${sysblock} | grep -q usb
1096                                 then
1097                                         dev_ok="yes"
1098                                 fi
1099                         fi
1100                 fi
1101
1102                 if [ "${dev_ok}" = "yes" ]
1103                 then
1104                         case "${output_format}" in
1105                                 sys)
1106                                         ret="${ret} ${sysblock}"
1107                                         ;;
1108                                 *)
1109                                         devname=$(sys2dev "${sysblock}")
1110                                         ret="${ret} ${devname}"
1111                                         ;;
1112                         esac
1113                 fi
1114         done
1115
1116         echo "${ret}"
1117 }
1118
1119 removable_usb_dev ()
1120 {
1121         output_format="${1}"
1122
1123         removable_dev "${output_format}" "want_usb"
1124 }
1125
1126 non_removable_dev ()
1127 {
1128         output_format="${1}"
1129         ret=
1130
1131         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
1132         do
1133                 if [ "$(cat ${sysblock}/removable)" = "0" ]
1134                 then
1135                         case "${output_format}" in
1136                                 sys)
1137                                         ret="${ret} ${sysblock}"
1138                                         ;;
1139                                 *)
1140                                         devname=$(sys2dev "${sysblock}")
1141                                         ret="${ret} ${devname}"
1142                                         ;;
1143                         esac
1144                 fi
1145         done
1146
1147         echo "${ret}"
1148 }
1149
1150 link_files ()
1151 {
1152         # create source's directory structure in dest, and recursively
1153         # create symlinks in dest to to all files in source. if mask
1154         # is non-empty, remove mask from all source paths when
1155         # creating links (will be necessary if we change root, which
1156         # live-boot normally does (into $rootmnt)).
1157
1158         # remove multiple /:s and ensure ending on /
1159         local src_dir="$(trim_path ${1})/"
1160         local dest_dir="$(trim_path ${2})/"
1161         local src_mask="${3}"
1162
1163         # This check can only trigger on the inital, non-recursive call since
1164         # we create the destination before recursive calls
1165         if [ ! -d "${dest_dir}" ]
1166         then
1167                 log_warning_msg "Must link_files into a directory"
1168                 return
1169         fi
1170
1171         find "${src_dir}" -mindepth 1 -maxdepth 1 | while read src; do
1172                 local dest="${dest_dir}$(basename "${src}")"
1173                 if [ -d "${src}" ]
1174                 then
1175                         if [ -z "$(ls -A "${src}")" ]
1176                         then
1177                                 continue
1178                         fi
1179                         if [ ! -d "${dest}" ]
1180                         then
1181                                 mkdir -p "${dest}"
1182                                 chown_ref "${src}" "${dest}"
1183                                 chmod_ref "${src}" "${dest}"
1184                         fi
1185                         link_files "${src}" "${dest}" "${src_mask}"
1186                 else
1187                         local final_src=${src}
1188                         if [ -n "${src_mask}" ]
1189                         then
1190                                 final_src="$(echo ${final_src} | sed "s|^${src_mask}||")"
1191                         fi
1192                         rm -rf "${dest}" 2> /dev/null
1193                         ln -s "${final_src}" "${dest}"
1194                         chown_ref "${src}" "${dest}"
1195                 fi
1196         done
1197 }
1198
1199 do_union ()
1200 {
1201         local unionmountpoint="${1}"    # directory where the union is mounted
1202         local unionrw="${2}"            # branch where the union changes are stored
1203         local unionro1="${3}"           # first underlying read-only branch (optional)
1204         local unionro2="${4}"           # second underlying read-only branch (optional)
1205
1206         if [ "${UNIONTYPE}" = "aufs" ]
1207         then
1208                 rw_opt="rw"
1209                 ro_opt="rr+wh"
1210                 noxino_opt="noxino"
1211         elif [ "${UNIONTYPE}" = "unionfs-fuse" ]
1212         then
1213                 rw_opt="RW"
1214                 ro_opt="RO"
1215         else
1216                 rw_opt="rw"
1217                 ro_opt="ro"
1218         fi
1219
1220         case "${UNIONTYPE}" in
1221                 unionfs-fuse)
1222                         unionmountopts="-o cow -o noinitgroups -o default_permissions -o allow_other -o use_ino -o suid"
1223                         unionmountopts="${unionmountopts} ${unionrw}=${rw_opt}"
1224                         if [ -n "${unionro1}" ]
1225                         then
1226                                 unionmountopts="${unionmountopts}:${unionro1}=${ro_opt}"
1227                         fi
1228                         if [ -n "${unionro2}" ]
1229                         then
1230                                 unionmountopts="${unionmountopts}:${unionro2}=${ro_opt}"
1231                         fi
1232                         ( sysctl -w fs.file-max=391524 ; ulimit -HSn 16384
1233                         unionfs-fuse ${unionmountopts} "${unionmountpoint}" ) && \
1234                         ( mkdir -p /run/sendsigs.omit.d
1235                         pidof unionfs-fuse >> /run/sendsigs.omit.d/unionfs-fuse || true )
1236                         ;;
1237
1238                 overlayfs)
1239                         # XXX: can unionro2 be used? (overlayfs only handles two dirs, but perhaps they can be chained?)
1240                         # XXX: and can unionro1 be optional? i.e. can overlayfs skip lowerdir?
1241                         unionmountopts="-o noatime,lowerdir=${unionro1},upperdir=${unionrw}"
1242                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
1243                         ;;
1244
1245                 *)
1246                         unionmountopts="-o noatime,${noxino_opt},dirs=${unionrw}=${rw_opt}"
1247                         if [ -n "${unionro1}" ]
1248                         then
1249                                 unionmountopts="${unionmountopts}:${unionro1}=${ro_opt}"
1250                         fi
1251                         if [ -n "${unionro2}" ]
1252                         then
1253                                 unionmountopts="${unionmountopts}:${unionro2}=${ro_opt}"
1254                         fi
1255                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
1256                         ;;
1257         esac
1258 }
1259
1260 get_custom_mounts ()
1261 {
1262         # Side-effect: leaves $devices with live-persistence.conf mounted in /live/persistence
1263         # Side-effect: prints info to file $custom_mounts
1264
1265         local custom_mounts=${1}
1266         shift
1267         local devices=${@}
1268
1269         local bindings="/tmp/bindings.list"
1270         local links="/tmp/links.list"
1271         rm -rf ${bindings} ${links} 2> /dev/null
1272
1273         for device in ${devices}
1274         do
1275                 if [ ! -b "${device}" ]
1276                 then
1277                         continue
1278                 fi
1279
1280                 local device_name="$(basename ${device})"
1281                 local backing=$(mount_persistence_media ${device})
1282                 if [ -z "${backing}" ]
1283                 then
1284                         continue
1285                 fi
1286
1287                 local include_list="${backing}/${persistence_list}"
1288                 if [ ! -r "${include_list}" ]
1289                 then
1290                         continue
1291                 fi
1292
1293                 if [ -n "${DEBUG}" ] && [ -e "${include_list}" ]
1294                 then
1295                         cp ${include_list} /live/persistence/${persistence_list}.${device_name}
1296                 fi
1297
1298                 while read dir options # < ${include_list}
1299                 do
1300                         if echo ${dir} | grep -qe "^[[:space:]]*\(#.*\)\?$"
1301                         then
1302                                 # skipping empty or commented lines
1303                                 continue
1304                         fi
1305
1306                         if trim_path ${dir} | grep -q -e "^[^/]" -e "^/live\(/.*\)\?$" -e "^/\(.*/\)\?\.\.\?\(/.*\)\?$"
1307                         then
1308                                 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."
1309                                 continue
1310                         fi
1311
1312                         local opt_source=""
1313                         local opt_link=""
1314                         for opt in $(echo ${options} | tr ',' ' ');
1315                         do
1316                                 case "${opt}" in
1317                                         source=*)
1318                                                 opt_source=${opt#source=}
1319                                                 ;;
1320                                         link)
1321                                                 opt_link="yes"
1322                                                 ;;
1323                                         union|bind)
1324                                                 ;;
1325                                         *)
1326                                                 log_warning_msg "Skipping custom mount with unkown option: ${opt}"
1327                                                 continue 2
1328                                                 ;;
1329                                 esac
1330                         done
1331
1332                         local source="${dir}"
1333                         if [ -n "${opt_source}" ]
1334                         then
1335                                 if echo ${opt_source} | grep -q -e "^/" -e "^\(.*/\)\?\.\.\?\(/.*\)\?$" && [ "${source}" != "." ]
1336                                 then
1337                                         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"
1338                                         continue
1339                                 else
1340                                         source="${opt_source}"
1341                                 fi
1342                         fi
1343
1344                         local full_source="$(trim_path ${backing}/${source})"
1345                         local full_dest="$(trim_path ${rootmnt}/${dir})"
1346                         if [ -n "${opt_link}" ]
1347                         then
1348                                 echo "${device} ${full_source} ${full_dest} ${options}" >> ${links}
1349                         else
1350                                 echo "${device} ${full_source} ${full_dest} ${options}" >> ${bindings}
1351                         fi
1352                 done < ${include_list}
1353         done
1354
1355         # We sort the list according to destination so we're sure that
1356         # we won't hide a previous mount. We also ignore duplicate
1357         # destinations in a more or less arbitrary way.
1358         [ -e "${bindings}" ] && sort -k3 -sbu ${bindings} >> ${custom_mounts} && rm ${bindings}
1359
1360         # After all mounts are considered we add symlinks so they
1361         # won't be hidden by some mount.
1362         [ -e "${links}" ] && cat ${links} >> ${custom_mounts} && rm ${links}
1363
1364         # We need to make sure that no two custom mounts have the same sources
1365         # or are nested; if that is the case, too much weird stuff can happen.
1366         local prev_source="impossible source" # first iteration must not match
1367         local prev_dest=""
1368         # This sort will ensure that a source /a comes right before a source
1369         # /a/b so we only need to look at the previous source
1370         sort -k2 -b ${custom_mounts} |
1371         while read device source dest options
1372         do
1373                 if echo ${source} | grep -qe "^${prev_source}\(/.*\)\?$"
1374                 then
1375                         panic "Two persistence mounts have the same or nested sources: ${source} on ${dest}, and ${prev_source} on ${prev_dest}"
1376                 fi
1377                 prev_source=${source}
1378                 prev_dest=${dest}
1379         done
1380 }
1381
1382 activate_custom_mounts ()
1383 {
1384         local custom_mounts="${1}" # the ouput from get_custom_mounts()
1385         local used_devices=""
1386
1387         while read device source dest options # < ${custom_mounts}
1388         do
1389                 local opt_bind="yes"
1390                 local opt_link=""
1391                 local opt_union=""
1392                 for opt in $(echo ${options} | tr ',' ' ');
1393                 do
1394                         case "${opt}" in
1395                                 bind)
1396                                         opt_bind="yes"
1397                                         unset opt_link opt_union
1398                                         ;;
1399                                 link)
1400                                         opt_link="yes"
1401                                         unset opt_bind opt_union
1402                                         ;;
1403                                 union)
1404                                         opt_union="yes"
1405                                         unset opt_bind opt_link
1406                                         ;;
1407                         esac
1408                 done
1409
1410                 if [ -n "$(what_is_mounted_on "${dest}")" ]
1411                 then
1412                         if [ "${dest}" = "${rootmnt}" ]
1413                         then
1414                                 umount "${dest}"
1415                         else
1416                                 log_warning_msg "Skipping custom mount ${dest}: $(what_is_mounted_on "${dest}") is already mounted there"
1417                                 continue
1418                         fi
1419                 fi
1420
1421                 if [ ! -d "${dest}" ]
1422                 then
1423                         # create the destination and delete existing files in
1424                         # its path that are in the way
1425                         path="/"
1426                         for dir in $(echo ${dest} | sed -e 's|/\+| |g')
1427                         do
1428                                 path=$(trim_path ${path}/${dir})
1429                                 if [ -f ${path} ]
1430                                 then
1431                                         rm -f ${path}
1432                                 fi
1433                                 if [ ! -e ${path} ]
1434                                 then
1435                                         mkdir -p ${path}
1436                                         if echo ${path} | grep -qe "^${rootmnt}/*home/[^/]\+"
1437                                         then
1438                                                 # if ${dest} is in /home try fixing proper ownership by assuming that the intended user is the first, which is usually the case
1439                                                 # FIXME: this should really be handled by live-config since we don't know for sure which uid a certain user has until then
1440                                                 chown 1000:1000 ${path}
1441                                         fi
1442                                 fi
1443                         done
1444                 fi
1445
1446                 # if ${source} doesn't exist on our persistence media
1447                 # we bootstrap it with $dest from the live filesystem.
1448                 # this both makes sense and is critical if we're
1449                 # dealing with /etc or other system dir.
1450                 if [ ! -d "${source}" ]
1451                 then
1452                         if [ -n "${PERSISTENCE_READONLY}" ]
1453                         then
1454                                 continue
1455                         elif [ -n "${opt_union}" ] || [ -n "${opt_link}" ]
1456                         then
1457                                 # unions and don't need to be bootstrapped
1458                                 # link dirs can't be bootstrapped in a sensible way
1459                                 mkdir -p "${source}"
1460                                 chown_ref "${dest}" "${source}"
1461                                 chmod_ref "${dest}" "${source}"
1462                         elif [ -n "${opt_bind}" ]
1463                         then
1464                                 # ensure that $dest is not copied *into* $source
1465                                 mkdir -p "$(dirname ${source})"
1466                                 cp -a "${dest}" "${source}"
1467                         fi
1468                 fi
1469
1470                 # XXX: If CONFIG_AUFS_ROBR is added to the Debian kernel we can
1471                 # ignore the loop below and set rofs_dest_backing=$dest
1472                 local rofs_dest_backing=""
1473                 if [ -n "${opt_link}"]
1474                 then
1475                         for d in /live/rofs/*
1476                         do
1477                                 if [ -n "${rootmnt}" ]
1478                                 then
1479                                         rofs_dest_backing="${d}/$(echo ${dest} | sed -e "s|${rootmnt}||")"
1480                                 else
1481                                         rofs_dest_backing="${d}/${dest}"
1482                                 fi
1483                                 if [ -d "${rofs_dest_backing}" ]
1484                                 then
1485                                         break
1486                                 else
1487                                         rofs_dest_backing=""
1488                                 fi
1489                         done
1490                 fi
1491
1492                 if [ -n "${opt_link}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1493                 then
1494                         link_files ${source} ${dest} ${rootmnt}
1495                 elif [ -n "${opt_link}" ] && [ -n "${PERSISTENCE_READONLY}" ]
1496                 then
1497                         mkdir -p /live/persistence
1498                         local links_source=$(mktemp -d /live/persistence/links-source-XXXXXX)
1499                         chown_ref ${source} ${links_source}
1500                         chmod_ref ${source} ${links_source}
1501                         # We put the cow dir in the below strange place to
1502                         # make it absolutely certain that the link source
1503                         # has its own directory and isn't nested with some
1504                         # other custom mount (if so that mount's files would
1505                         # be linked, causing breakage.
1506                         local cow_dir="/live/overlay/live/persistence/$(basename ${links_source})"
1507                         mkdir -p ${cow_dir}
1508                         chown_ref "${source}" "${cow_dir}"
1509                         chmod_ref "${source}" "${cow_dir}"
1510                         do_union ${links_source} ${cow_dir} ${source} ${rofs_dest_backing}
1511                         link_files ${links_source} ${dest} ${rootmnt}
1512                 elif [ -n "${opt_union}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1513                 then
1514                         do_union ${dest} ${source} ${rofs_dest_backing}
1515                 elif [ -n "${opt_bind}" ] && [ -z "${PERSISTENCE_READONLY}" ]
1516                 then
1517                         mount --bind "${source}" "${dest}"
1518                 elif [ -n "${opt_bind}" -o -n "${opt_union}" ] && [ -n "${PERSISTENCE_READONLY}" ]
1519                 then
1520                         # bind-mount and union mount are handled the same
1521                         # in read-only mode, but note that rofs_dest_backing
1522                         # is non-empty (and necessary) only for unions
1523                         if [ -n "${rootmnt}" ]
1524                         then
1525                                 local cow_dir="$(echo ${dest} | sed -e "s|^${rootmnt}|/live/overlay/|")"
1526                         else
1527                                 # This is happens if persistence is activated
1528                                 # post boot
1529                                 local cow_dir="/live/overlay/${dest}"
1530                         fi
1531                         if [ -e "${cow_dir}" ] && [ -z "${opt_link}" ]
1532                         then
1533                                 # If an earlier custom mount has files here
1534                                 # it will "block" the current mount's files
1535                                 # which is undesirable
1536                                 rm -rf "${cow_dir}"
1537                         fi
1538                         mkdir -p ${cow_dir}
1539                         chown_ref "${source}" "${cow_dir}"
1540                         chmod_ref "${source}" "${cow_dir}"
1541                         do_union ${dest} ${cow_dir} ${source} ${rofs_dest_backing}
1542                 fi
1543
1544                 PERSISTENCE_IS_ON="1"
1545                 export PERSISTENCE_IS_ON
1546
1547                 if echo ${used_devices} | grep -qve "^\(.* \)\?${device}\( .*\)\?$"
1548                 then
1549                         used_devices="${used_devices} ${device}"
1550                 fi
1551         done < ${custom_mounts}
1552
1553         echo ${used_devices}
1554 }
1555
1556 fix_backwards_compatibility ()
1557 {
1558         local device=${1}
1559         local dir=${2}
1560         local opt=${3}
1561
1562         if [ -n "${PERSISTENCE_READONLY}" ]
1563         then
1564                 return
1565         fi
1566
1567         local backing="$(mount_persistence_media ${device})"
1568         if [ -z "${backing}" ]
1569         then
1570                 return
1571         fi
1572
1573         local include_list="${backing}/${persistence_list}"
1574         if [ ! -r "${include_list}" ]
1575         then
1576                 echo "# persistence backwards compatibility:
1577 ${dir} ${opt},source=." > "${include_list}"
1578         fi
1579 }
1580
1581 is_mountpoint ()
1582 {
1583         directory="$1"
1584
1585         [ $(stat -fc%d:%D "${directory}") != $(stat -fc%d:%D "${directory}/..") ]
1586 }