Close unused LUKS devices in all cases.
[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 sys2dev ()
19 {
20         sysdev=${1#/sys}
21         echo "/dev/$($udevinfo -q name -p ${sysdev} 2>/dev/null|| echo ${sysdev##*/})"
22 }
23
24 subdevices ()
25 {
26         sysblock=${1}
27         r=""
28
29         for dev in "${sysblock}"/* "${sysblock}"
30         do
31                 if [ -e "${dev}/dev" ]
32                 then
33                         r="${r} ${dev}"
34                 fi
35         done
36
37         echo ${r}
38 }
39
40 storage_devices()
41 {
42         black_listed_devices="${1}"
43         white_listed_devices="${2}"
44
45         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "loop|ram|fd")
46         do
47                 fulldevname=$(sys2dev "${sysblock}")
48
49                 if echo "${black_listed_devices}" | grep -qe "\<${fulldevname}\>" || \
50                         [ -n "${white_listed_devices}" ] && \
51                         echo "${white_listed_devices}" | grep -qve "\<${fulldevname}\>"
52                 then
53                         # skip this device entirely
54                         continue
55                 fi
56
57                 for dev in $(subdevices "${sysblock}")
58                 do
59                         devname=$(sys2dev "${dev}")
60
61                         if echo "${black_listed_devices}" | grep -qe "\<${devname}\>"
62                         then
63                                 # skip this subdevice
64                                 continue
65                         else
66                                 echo "${devname}"
67                         fi
68                 done
69         done
70 }
71
72 is_supported_fs ()
73 {
74         fstype="${1}"
75
76         # Validate input first
77         if [ -z "${fstype}" ]
78         then
79                 return 1
80         fi
81
82         # Try to look if it is already supported by the kernel
83         if grep -q ${fstype} /proc/filesystems
84         then
85                 return 0
86         else
87                 # Then try to add support for it the gentle way using the initramfs capabilities
88                 modprobe ${fstype}
89                 if grep -q ${fstype} /proc/filesystems
90                 then
91                         return 0
92                 # Then try the hard way if /root is already reachable
93                 else
94                         kmodule="/root/lib/modules/`uname -r`/${fstype}/${fstype}.ko"
95                         if [ -e "${kmodule}" ]
96                         then
97                                 insmod "${kmodule}"
98                                 if grep -q ${fstype} /proc/filesystems
99                                 then
100                                         return 0
101                                 fi
102                         fi
103                 fi
104         fi
105
106         return 1
107 }
108
109 get_fstype ()
110 {
111         /sbin/blkid -s TYPE -o value $1 2>/dev/null
112 }
113
114 where_is_mounted ()
115 {
116         device=${1}
117
118         if grep -q "^${device} " /proc/mounts
119         then
120                 # return the first found
121                 grep -m1 "^${device} " /proc/mounts | cut -f2 -d ' '
122         fi
123 }
124
125 lastline ()
126 {
127         while read lines
128         do
129                 line=${lines}
130         done
131
132         echo "${line}"
133 }
134
135 base_path ()
136 {
137         testpath="${1}"
138         mounts="$(awk '{print $2}' /proc/mounts)"
139         testpath="$(busybox realpath ${testpath})"
140
141         while true
142         do
143                 if echo "${mounts}" | grep -qs "^${testpath}"
144                 then
145                         set -- $(echo "${mounts}" | grep "^${testpath}" | lastline)
146                         echo ${1}
147                         break
148                 else
149                         testpath=$(dirname $testpath)
150                 fi
151         done
152 }
153
154 fs_size ()
155 {
156         # Returns used/free fs kbytes + 5% more
157         # You could pass a block device as ${1} or the mount point as ${2}
158
159         dev="${1}"
160         mountp="${2}"
161         used="${3}"
162
163         if [ -z "${mountp}" ]
164         then
165                 mountp="$(where_is_mounted ${dev})"
166
167                 if [ -z "${mountp}" ]
168                 then
169                         mountp="/mnt/tmp_fs_size"
170
171                         mkdir -p "${mountp}"
172                         mount -t $(get_fstype "${dev}") -o ro "${dev}" "${mountp}" || log_warning_msg "cannot mount -t $(get_fstype ${dev}) -o ro ${dev} ${mountp}"
173
174                         doumount=1
175                 fi
176         fi
177
178         if [ "${used}" = "used" ]
179         then
180                 size=$(du -ks ${mountp} | cut -f1)
181                 size=$(expr ${size} + ${size} / 20 ) # FIXME: 5% more to be sure
182         else
183                 # free space
184                 size="$(df -k | grep -s ${mountp} | awk '{print $4}')"
185         fi
186
187         if [ -n "${doumount}" ]
188         then
189                 umount "${mountp}" || log_warning_msg "cannot umount ${mountp}"
190                 rmdir "${mountp}"
191         fi
192
193         echo "${size}"
194 }
195
196 load_keymap ()
197 {
198         # Load custom keymap
199         if [ -x /bin/loadkeys -a -r /etc/boottime.kmap.gz ]
200         then
201                 loadkeys /etc/boottime.kmap.gz
202         fi
203 }
204
205 setup_loop ()
206 {
207         local fspath=${1}
208         local module=${2}
209         local pattern=${3}
210         local offset=${4}
211         local encryption=${5}
212         local readonly=${6}
213
214         # the output of setup_loop is evaluated in other functions,
215         # modprobe leaks kernel options like "libata.dma=0"
216         # as "options libata dma=0" on stdout, causing serious
217         # problems therefor, so instead always avoid output to stdout
218         modprobe -q -b "${module}" 1>/dev/null
219
220         udevadm settle
221
222         for loopdev in ${pattern}
223         do
224                 if [ "$(cat ${loopdev}/size)" -eq 0 ]
225                 then
226                         dev=$(sys2dev "${loopdev}")
227                         options=''
228
229                         if [ -n "${readonly}" ]
230                         then
231                                 if losetup --help 2>&1 | grep -q -- "-r\b"
232                                 then
233                                         options="${options} -r"
234                                 fi
235                         fi
236
237                         if [ -n "${offset}" ] && [ 0 -lt "${offset}" ]
238                         then
239                                 options="${options} -o ${offset}"
240                         fi
241
242                         if [ -z "${encryption}" ]
243                         then
244                                 losetup ${options} "${dev}" "${fspath}"
245                         else
246                                 # Loop AES encryption
247                                 while true
248                                 do
249                                         load_keymap
250
251                                         echo -n "Enter passphrase for root filesystem: " >&6
252                                         read -s passphrase
253                                         echo "${passphrase}" > /tmp/passphrase
254                                         unset passphrase
255                                         exec 9</tmp/passphrase
256                                         /sbin/losetup ${options} -e "${encryption}" -p 9 "${dev}" "${fspath}"
257                                         error=${?}
258                                         exec 9<&-
259                                         rm -f /tmp/passphrase
260
261                                         if [ 0 -eq ${error} ]
262                                         then
263                                                 unset error
264                                                 break
265                                         fi
266
267                                         echo
268                                         echo -n "There was an error decrypting the root filesystem ... Retry? [Y/n] " >&6
269                                         read answer
270
271                                         if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
272                                         then
273                                                 unset answer
274                                                 break
275                                         fi
276                                 done
277                         fi
278
279                         echo "${dev}"
280                         return 0
281                 fi
282         done
283
284         panic "No loop devices available"
285 }
286
287 try_mount ()
288 {
289         dev="${1}"
290         mountp="${2}"
291         opts="${3}"
292         fstype="${4}"
293
294         old_mountp="$(where_is_mounted ${dev})"
295
296         if [ -n "${old_mountp}" ]
297         then
298                 if [ "${opts}" != "ro" ]
299                 then
300                         mount -o remount,"${opts}" "${dev}" "${old_mountp}" || panic "Remounting ${dev} ${opts} on ${old_mountp} failed"
301                 fi
302
303                 mount -o bind "${old_mountp}" "${mountp}" || panic "Cannot bind-mount ${old_mountp} on ${mountp}"
304         else
305                 if [ -z "${fstype}" ]
306                 then
307                         fstype=$(get_fstype "${dev}")
308                 fi
309                 mount -t "${fstype}" -o "${opts}" "${dev}" "${mountp}" || \
310                 ( echo "SKIPPING: Cannot mount ${dev} on ${mountp}, fstype=${fstype}, options=${opts}" > live-boot.log && return 0 )
311         fi
312 }
313
314 open_luks_device ()
315 {
316         dev="${1}"
317         name="$(basename ${dev})"
318         opts="--key-file=-"
319         if [ -n "${PERSISTENT_READONLY}" ]
320         then
321                 opts="${opts} --readonly"
322         fi
323
324         load_keymap
325
326         while true
327         do
328                 /lib/cryptsetup/askpass "Enter passphrase for ${dev}: " | \
329                         /sbin/cryptsetup -T 1 luksOpen ${dev} ${name} ${opts}
330
331                 if [ 0 -eq ${?} ]
332                 then
333                         luks_device="/dev/mapper/${name}"
334                         echo ${luks_device}
335                         return 0
336                 fi
337
338                 echo >&6
339                 echo -n "There was an error decrypting ${dev} ... Retry? [Y/n] " >&6
340                 read answer
341
342                 if [ "$(echo "${answer}" | cut -b1 | tr A-Z a-z)" = "n" ]
343                 then
344                         return 2
345                 fi
346         done
347 }
348
349 find_persistent_media ()
350 {
351         # Scans devices for overlays and snapshots, and returns a whitespace
352         # separated list of how to use them. Only overlays with a partition
353         # label or file name in ${overlays} are returned, and ditto for
354         # snapshots with labels in ${snapshots}.
355         #
356         # When scanning a LUKS device, the user will be asked to enter the
357         # passphrase; on failure to enter it, or if no persistent partitions
358         # or files were found, the LUKS device is closed.
359         #
360         # For a snapshot file the return value is ${label}=${snapdata}", where
361         # ${snapdata} is the parameter used for try_snap().
362         #
363         # For all other cases (overlay/snapshot partition and overlay file) the
364         # return value is "${label}=${device}", where ${device} a device that
365         # can mount the content. In the case of an overlay file, the device
366         # containing the file will remain mounted as a side-effect.
367         #
368         # No devices in ${black_listed_devices} will be scanned, and if
369         # ${white_list_devices} is non-empty, only devices in it will be
370         # scanned.
371
372         overlays="${1}"
373         snapshots="${2}"
374         black_listed_devices="${3}"
375         white_listed_devices="${4}"
376         persistent_backing="${rootmnt}/live/persistent"
377
378         for dev in $(storage_devices "${black_listed_devices}" "${white_listed_devices}")
379         do
380                 luks_device=""
381
382                 # Checking for a luks device
383                 if echo ${PERSISTENT_ENCRYPTION} | grep -qe "\<luks\>" && \
384                    /sbin/cryptsetup isLuks ${dev}
385                 then
386                         if luks_device=$(open_luks_device "${dev}")
387                         then
388                                 dev="${luks_device}"
389                         else
390                                 # skip $dev since we failed/chose not to open it
391                                 continue
392                         fi
393                 elif echo ${PERSISTENT_ENCRYPTION} | grep -qve "\<none\>"
394                 then
395                         # skip $dev since we don't allow unencrypted storage
396                         continue
397                 fi
398
399                 if echo ${PERSISTENT_STORAGE} | grep -qe "\<filesystem\>"
400                 then
401                         for label in ${overlays} ${snapshots}
402                         do
403                                 if [ "$(/sbin/blkid -s LABEL -o value $dev 2>/dev/null)" = "${label}" ]
404                                 then
405                                         echo "${label}=${dev}"
406                                         # skip to the next device
407                                         continue 2
408                                 fi
409                         done
410                 fi
411
412                 overlay_on_dev=""
413                 snapshot_on_dev=""
414                 if echo ${PERSISTENT_STORAGE} | grep -qe "\<file\>"
415                 then
416                         devfstype="$(get_fstype ${dev})"
417                         backing="${persistent_backing}/$(basename ${dev})"
418                         mkdir -p "${backing}"
419                         if is_supported_fs ${devfstype} && try_mount "${dev}" "${backing}" "rw" "${devfstype}"
420                         then
421                                 for label in ${overlays}
422                                 do
423                                         path=${backing}/${PERSISTENT_PATH}${label}
424                                         if [ -f "${path}" ]
425                                         then
426                                                 overlay_on_dev="yes"
427                                                 echo "${label}=$(setup_loop "${path}" "loop" "/sys/block/loop*")"
428                                         fi
429                                 done
430
431                                 for label in ${snapshots}
432                                 do
433                                         for ext in squashfs cpio.gz ext2 ext3 ext4 jffs2
434                                         do
435                                                 path="${PERSISTENT_PATH}${label}.${ext}"
436                                                 if [ -f "${backing}/${path}" ]
437                                                 then
438                                                         snapshot_on_dev="yes"
439                                                         echo "${label}=${dev}:${backing}:${path}"
440                                                 fi
441                                         done
442                                 done
443                         fi
444                         if [ -z "${overlay_on_dev}" ] && [ -z "${snapshot_on_dev}" ]
445                         then
446                                 umount ${backing} > /dev/null 2>&1 || true
447                         fi
448                 fi
449                 if [ -z "${overlay_on_dev}" ] && [ -z "${snapshot_on_dev}" ] && \
450                    [ -n "${luks_device}" ] && \
451                    /sbin/cryptsetup status "${luks_device}" 1> /dev/null 2>&1
452                 then
453                         /sbin/cryptsetup luksClose "${luks_device}"
454                 fi
455         done
456 }
457
458 get_mac ()
459 {
460         mac=""
461
462         for adaptor in /sys/class/net/*
463         do
464                 status="$(cat ${adaptor}/iflink)"
465
466                 if [ "${status}" -eq 2 ]
467                 then
468                         mac="$(cat ${adaptor}/address)"
469                         mac="$(echo ${mac} | sed 's/:/-/g' | tr '[a-z]' '[A-Z]')"
470                 fi
471         done
472
473         echo ${mac}
474 }
475
476 is_luks()
477 {
478     devname="${1}"
479     if [ -x /sbin/cryptsetup ]
480     then
481         /sbin/cryptsetup isLuks "${devname}" 2>/dev/null || ret=${?}
482         return ${ret}
483     else
484         return 1
485     fi
486
487 }
488
489 removable_dev ()
490 {
491         output_format="${1}"
492         want_usb="${2}"
493         ret=
494
495         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
496         do
497                 dev_ok=
498                 if [ "$(cat ${sysblock}/removable)" = "1" ]
499                 then
500                         if [ -z "${want_usb}" ]
501                         then
502                                 dev_ok="yes"
503                         else
504                                 if readlink ${sysblock} | grep -q usb
505                                 then
506                                         dev_ok="yes"
507                                 fi
508                         fi
509                 fi
510
511                 if [ "${dev_ok}" = "yes" ]
512                 then
513                         case "${output_format}" in
514                                 sys)
515                                         ret="${ret} ${sysblock}"
516                                         ;;
517                                 *)
518                                         devname=$(sys2dev "${sysblock}")
519                                         ret="${ret} ${devname}"
520                                         ;;
521                         esac
522                 fi
523         done
524
525         echo "${ret}"
526 }
527
528 removable_usb_dev ()
529 {
530         output_format="${1}"
531
532         removable_dev "${output_format}" "want_usb"
533 }
534
535 non_removable_dev ()
536 {
537         output_format="${1}"
538         ret=
539
540         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
541         do
542                 if [ "$(cat ${sysblock}/removable)" = "0" ]
543                 then
544                         case "${output_format}" in
545                                 sys)
546                                         ret="${ret} ${sysblock}"
547                                         ;;
548                                 *)
549                                         devname=$(sys2dev "${sysblock}")
550                                         ret="${ret} ${devname}"
551                                         ;;
552                         esac
553                 fi
554         done
555
556         echo "${ret}"
557 }
558
559 link_files ()
560 {
561         # create source's directory structure in dest, and recursively
562         # create symlinks in dest to to all files in source. if mask
563         # is non-empty, remove mask from all source paths when
564         # creating links (will be necessary if we change root, which
565         # live-boot normally does (into $rootmnt)).
566
567         # remove multiple /:s and ensure ending on /
568         local src_dir="$(echo "${1}"/ | sed -e 's|/\+|/|g')"
569         local dest_dir="$(echo "${2}"/ | sed -e 's|/\+|/|g')"
570         local src_mask="${3}"
571
572         # This check can only trigger on the inital, non-recursive call since
573         # we create the destination before recursive calls
574         if [ ! -d "${dest_dir}" ];
575         then
576                 log_warning_msg "Must link_files into a directory"
577                 return
578         fi
579
580         find "${src_dir}" -mindepth 1 -maxdepth 1 | while read x; do
581                 local src="${x}"
582                 local dest="${dest_dir}$(basename "${x}")"
583                 if [ -d "${src}" ];
584                 then
585                         if [ -z "$(ls -A "${src}")" ];
586                         then
587                                 continue
588                         fi
589                         if [ ! -d "${dest}" ];
590                         then
591                                 mkdir -p "${dest}"
592                                 prev="$(dirname "${dest}")"
593                                 chown $(stat -c %u:%g "${prev}") "${dest}"
594                                 chmod $(stat -c %a "${prev}") "${dest}"
595                         fi
596                         link_files "${src}" "${dest}" "${src_mask}"
597                 else
598                         if [ -n "${src_mask}" ]
599                         then
600                                 src="$(echo ${src} | sed "s|^${src_mask}||")"
601                         fi
602                         rm -rf "${dest}" 2> /dev/null
603                         ln -s "${src}" "${dest}"
604                 fi
605         done
606 }
607
608 do_union () {
609         local unionmountpoint="${1}"    # directory where the union is mounted
610         local unionrw="${2}"            # branch where the union changes are stored
611         local unionro1="${3}"           # first underlying read-only branch (optional)
612         local unionro2="${4}"           # second underlying read-only branch (optional)
613
614         if [ "${UNIONTYPE}" = "aufs" ]
615         then
616                 rw_opt="rw"
617                 ro_opt="rr+wh"
618                 noxino_opt="noxino"
619         elif [ "${UNIONTYPE}" = "unionfs-fuse" ]
620         then
621                 rw_opt="RW"
622                 ro_opt="RO"
623         else
624                 rw_opt="rw"
625                 ro_opt="ro"
626         fi
627
628         case "${UNIONTYPE}" in
629                 unionfs-fuse)
630                         unionmountopts="-o cow -o noinitgroups -o default_permissions -o allow_other -o use_ino -o suid"
631                         unionmountopts="${unionmountopts} ${unionrw}=${rw_opt}"
632                         if [ -n "${unionro1}" ]
633                         then
634                                 unionmountopts="${unionmountopts}:${unionro1}=${ro_opt}"
635                         fi
636                         if [ -n "${unionro2}" ]
637                         then
638                                 unionmountopts="${unionmountopts}:${unionro2}=${ro_opt}"
639                         fi
640                         ( sysctl -w fs.file-max=391524 ; ulimit -HSn 16384
641                         unionfs-fuse ${unionmountopts} "${unionmountpoint}" ) && \
642                         ( mkdir -p /run/sendsigs.omit.d
643                         pidof unionfs-fuse >> /run/sendsigs.omit.d/unionfs-fuse || true )
644                         ;;
645
646                 overlayfs)
647                         # XXX: can unionro2 be used? (overlayfs only handles two dirs, but perhaps they can be chained?)
648                         # XXX: and can unionro1 be optional? i.e. can overlayfs skip lowerdir?
649                         unionmountopts="-o noatime,lowerdir=${unionro1},upperdir=${unionrw}"
650                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
651                         ;;
652
653                 *)
654                         unionmountopts="-o noatime,${noxino_opt},dirs=${unionrw}=${rw_opt}"
655                         if [ -n "${unionro1}" ]
656                         then
657                                 unionmountopts="${unionmountopts}:${unionro1}=${ro_opt}"
658                         fi
659                         if [ -n "${unionro2}" ]
660                         then
661                                 unionmountopts="${unionmountopts}:${unionro2}=${ro_opt}"
662                         fi
663                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
664                         ;;
665         esac
666 }
667
668 get_custom_mounts () {
669         # Side-effect: leaves $devices with live.persist mounted in ${rootmnt}/live/persistent
670         # Side-effect: prints info to file $custom_mounts
671
672         local devices="${1}"
673         local custom_mounts="${2}" # print result to this file
674         local rootmnt="${3}"       # should be set empty post-live-boot
675
676         local bindings="/bindings.list"
677         local links="/links.list"
678         rm -rf ${bindings} ${links} 2> /dev/null
679         local persistent_backing="${rootmnt}/live/persistent"
680
681         for device in ${devices}
682         do
683                 if [ ! -b "${device}" ]
684                 then
685                         continue
686                 fi
687                 local device_name="$(basename ${device})"
688                 local backing="${persistent_backing}/${device_name}"
689                 mkdir -p "${backing}"
690                 local device_fstype="$(get_fstype ${device})"
691                 if [ -z "${PERSISTENT_READONLY}" ]
692                 then
693                         device_mount_opts="rw,noatime"
694                 else
695                         device_mount_opts="ro,noatime"
696                 fi
697                 local device_used=""
698                 mount -t "${device_fstype}" -o "${device_mount_opts}" "${device}" "${backing}"
699                 local include_list="${backing}/${persistence_list}"
700                 if [ ! -r "${include_list}" ]
701                 then
702                         umount "${backing}"
703                         rmdir "${backing}"
704                         continue
705                 fi
706
707                 [ "${DEBUG}" = "Yes" ] && cp ${include_list} ${persistent_backing}/${persistence_list}.${device_name}
708                 while read source dest options # < ${include_list}
709                 do
710                         if echo ${source} | grep -qe "^[[:space:]]*\(#.*\)\?$"
711                         then
712                                 # skipping empty or commented lines
713                                 continue
714                         fi
715
716                         if echo ${dest} | grep -qe "^[^/]"
717                         then
718                                 options="${dest}"
719                                 dest="${source}"
720                         elif [ -z "${dest}" ]
721                         then
722                                 dest="${source}"
723                         fi
724
725                         if echo ${dest} | grep -qe "^/\+$\|^/\+live\(/.*\)\?$"
726                         then
727                                 # mounting on / or /live could cause trouble
728                                 log_warning_msg "Skipping unsafe custom mount on ${dest}"
729                                 continue
730                         fi
731
732                         for opt in $(echo ${options} | tr ',' ' ');
733                         do
734                                 case "${opt}" in
735                                         linkfiles|union)
736                                                 ;;
737                                         *)
738                                                 log_warning_msg "Skipping custom mount with unkown option: ${opt}"
739                                                 continue 2
740                                                 ;;
741                                 esac
742                         done
743
744                         # FIXME: handle case: we already have /a/b in
745                         # $bindings added from current $device, but
746                         # now we find /a -- /a should replace /a/b in
747                         # $bindings.
748
749                         # FIXME: handle case: we have /a in $bindings
750                         # from current $device, now we find /a/b, so
751                         # we skip /a/b
752
753                         # ensure that no multiple-/ occur in paths
754                         local full_source="$(echo ${backing}/${source}/ | sed -e 's|/\+|/|g')"
755                         local full_dest="$(echo ${rootmnt}/${dest}/ | sed -e 's|/\+|/|g')"
756                         device_used="yes"
757                         if echo ${options} | grep -qe "\<linkfiles\>";
758                         then
759                                 echo "${full_source} ${full_dest} ${options}" >> ${links}
760                         else
761                                 echo "${full_source} ${full_dest} ${options}" >> ${bindings}
762                         fi
763                 done < ${include_list}
764
765                 if [ -z "${device_used}" ]
766                 then
767                         # this device was not used for / earlier, or
768                         # custom mount point now, so it's useless
769                         umount "${backing}"
770                         rmdir "${backing}"
771                 fi
772         done
773
774         # We sort the list according to destination so we're sure that
775         # we won't hide a previous mount. We also ignore duplicate
776         # destinations in a more or less arbitrary way.
777         [ -e "${bindings}" ] && sort -k2 -sbu ${bindings} >> ${custom_mounts}
778         rm ${bindings}
779
780         # After all mounts are considered we add symlinks so they
781         # won't be hidden by some mount.
782         [ -e "${links}" ] && sort -k2 -sbu ${links} >> ${custom_mounts}
783         rm ${links}
784
785         rm -f ${bindings} ${links} 2> /dev/null
786         echo ${custom_mounts}
787 }
788
789 do_custom_mounts () {
790         local custom_mounts="${1}" # the ouput from get_custom_mounts()
791         local rootmnt="${2}"       # should be set empty post-live-boot
792
793         while read source dest options # < ${custom_mounts}
794         do
795                 local opt_linkfiles=""
796                 local opt_union=""
797                 for opt in $(echo ${options} | tr ',' ' ');
798                 do
799                          case "${opt}" in
800                                 linkfiles)
801                                         opt_linkfiles="yes"
802                                         ;;
803                                 union)
804                                         opt_union="yes"
805                                         ;;
806                         esac
807                 done
808
809                 if mountpoint -q "${dest}";
810                 then
811                         log_warning_msg "Skipping custom mount ${source} on ${dest}: destination is already a mount point"
812                         continue
813                 fi
814
815                 # FIXME: we don't handle already existing
816                 # non-directory files in the paths of both $source and
817                 # $dest.
818
819                 if [ ! -d "${dest}" ]
820                 then
821                         # if ${dest} is in /home/$user, try fixing
822                         # proper ownership
823                         # FIXME: this should really be handled by
824                         # live-config since we don't know for sure
825                         # which uid a certain user has until then
826                         if echo ${dest} | grep -qe "^${rootmnt}/*home/\+[^/]\+"
827                         then
828                                 path="/"
829                                 for dir in $(echo ${dest} | sed -e 's|/\+| |g')
830                                 do
831                                         path=${path}/${dir}
832                                         if [ ! -e ${path} ]
833                                         then
834                                                 mkdir -p ${path}
835                                                 # assume that the intended user is the first, which is usually the case
836                                                 chown 1000:1000 ${path}
837                                         fi
838                                 done
839                         else
840                                 mkdir -p ${dest}
841                         fi
842                 fi
843
844                 # if ${source} doesn't exist on our persistent media
845                 # we bootstrap it with $dest from the live filesystem.
846                 # this both makes sense and is critical if we're
847                 # dealing with /etc or other system dir.
848                 if [ ! -d "${source}" ]
849                 then
850                         if [ -n "${PERSISTENT_READONLY}" ] || [ -n "${opt_linkfiles}" ]
851                         then
852                                 continue
853                         elif [ -n "${opt_union}" ]
854                         then
855                                 # union's don't need to be bootstrapped
856                                 mkdir "${source}"
857                         else
858                                 # ensure that $dest is not copied *into* $source
859                                 mkdir -p "$(dirname ${source})"
860                                 cp -a "${dest}" "${source}"
861                         fi
862                 fi
863
864                 rofs_dest_backing=""
865                 for d in ${rootmnt}/live/rofs/*
866                 do
867                         if [ -n "${rootmnt}" ]
868                         then
869                                 rofs_dest_backing="${d}/$(echo ${dest} | sed -e "s|${rootmnt}||")"
870                         else
871                                 rofs_dest_backing="${d}/${dest}"
872
873                         fi
874                         if [ -d "${rofs_dest_backing}" ]
875                         then
876                                 break
877                         else
878                                 rofs_dest_backing=""
879                         fi
880                 done
881
882                 if [ -z "${PERSISTENT_READONLY}" ]
883                 then
884                         if [ -n "${opt_linkfiles}" ]
885                         then
886                                 links_source="${source}"
887                                 links_dest="${dest}"
888                         elif [ -n "${opt_union}" ]
889                         then
890                                 do_union ${dest} ${source} ${rofs_dest_backing}
891                         else
892                                 mount --bind "${source}" "${dest}"
893                         fi
894                 else
895                         if [ -n "${opt_linkfiles}" ]
896                         then
897                                 links_dest="${dest}"
898                                 dest="$(mktemp -d ${persistent_backing}/links_source-XXXXXX)"
899                                 links_source="${dest}"
900                         fi
901                         if [ -n "${rootmnt}" ]
902                         then
903                                 cow_dir="$(echo ${dest} | sed -e "s|${rootmnt}|/cow/|")"
904                         else
905                                 cow_dir="/live/cow/${dest}"
906                         fi
907                         mkdir -p ${cow_dir}
908                         do_union ${dest} ${cow_dir} ${source} ${rofs_dest_backing}
909                 fi
910
911                 if [ -n "${opt_linkfiles}" ]
912                 then
913                         link_files "${links_source}" "${links_dest}" "${rootmnt}"
914                 fi
915
916                 PERSISTENCE_IS_ON="1"
917                 export PERSISTENCE_IS_ON
918         done < ${custom_mounts}
919 }