Refactor persistent custom mounting from live into live-helpers.
[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
377         for dev in $(storage_devices "${black_listed_devices}" "${white_listed_devices}")
378         do
379                 luks_device=""
380
381                 # Checking for a luks device
382                 if echo ${PERSISTENT_ENCRYPTION} | grep -qe "\<luks\>" && \
383                    /sbin/cryptsetup isLuks ${dev}
384                 then
385                         if luks_device=$(open_luks_device "${dev}")
386                         then
387                                 dev="${luks_device}"
388                         else
389                                 # skip $dev since we failed/chose not to open it
390                                 continue
391                         fi
392                 elif echo ${PERSISTENT_ENCRYPTION} | grep -qve "\<none\>"
393                 then
394                         # skip $dev since we don't allow unencrypted storage
395                         continue
396                 fi
397
398                 if echo ${PERSISTENT_STORAGE} | grep -qe "\<filesystem\>"
399                 then
400                         for label in ${overlays} ${snapshots}
401                         do
402                                 if [ "$(/sbin/blkid -s LABEL -o value $dev 2>/dev/null)" = "${label}" ]
403                                 then
404                                         overlays=$(echo ${overlays} | sed -e "s|\<${label}\>||")
405                                         snapshots=$(echo ${snapshots} | sed -e "s|\<${label}\>||")
406                                         echo "${label}=${dev}"
407                                         # skip to the next device
408                                         continue 2
409                                 fi
410                         done
411                 fi
412
413                 if echo ${PERSISTENT_STORAGE} | grep -qe "\<file\>"
414                 then
415                         devfstype="$(get_fstype ${dev})"
416                         overlay_on_dev=""
417                         snapshot_on_dev=""
418                         backing="/$(basename ${dev})-backing"
419                         mkdir -p "${backing}"
420                         if is_supported_fs ${devfstype} && try_mount "${dev}" "${backing}" "rw" "${devfstype}"
421                         then
422                                 for label in ${overlays}
423                                 do
424                                         path=${backing}/${PERSISTENT_PATH}${label}
425                                         if [ -f "${path}" ]
426                                         then
427                                                 overlays=$(echo ${overlays} | sed -e "s|\<${label}\>||")
428                                                 overlay_on_dev="yes"
429                                                 echo "${label}=$(setup_loop "${path}" "loop" "/sys/block/loop*")"
430                                         fi
431                                 done
432
433                                 for label in ${snapshots}
434                                 do
435                                         for ext in squashfs cpio.gz ext2 ext3 ext4 jffs2
436                                         do
437                                                 path="${PERSISTENT_PATH}${label}.${ext}"
438                                                 if [ -f "${backing}/${path}" ]
439                                                 then
440                                                         snapshots=$(echo ${snapshots} | sed -e "s|\<${label}\>||")
441                                                         snapshot_on_dev="yes"
442                                                         echo "${label}=${dev}:${backing}:${path}"
443                                                 fi
444                                         done
445                                 done
446                         fi
447                         if [ -z "${overlay_on_dev}" ]
448                         then
449                                 umount ${backing} > /dev/null 2>&1 || true
450                                 if [ -z "${snapshot_on_dev}" ] && [ -n "${luks_device}" ] && /sbin/cryptsetup status "${luks_device}" 1> /dev/null
451                                 then
452                                         /sbin/cryptsetup luksClose "${luks_device}"
453                                 fi
454                         fi
455                 fi
456         done
457 }
458
459 get_mac ()
460 {
461         mac=""
462
463         for adaptor in /sys/class/net/*
464         do
465                 status="$(cat ${adaptor}/iflink)"
466
467                 if [ "${status}" -eq 2 ]
468                 then
469                         mac="$(cat ${adaptor}/address)"
470                         mac="$(echo ${mac} | sed 's/:/-/g' | tr '[a-z]' '[A-Z]')"
471                 fi
472         done
473
474         echo ${mac}
475 }
476
477 is_luks()
478 {
479     devname="${1}"
480     if [ -x /sbin/cryptsetup ]
481     then
482         /sbin/cryptsetup isLuks "${devname}" 2>/dev/null || ret=${?}
483         return ${ret}
484     else
485         return 1
486     fi
487
488 }
489
490 removable_dev ()
491 {
492         output_format="${1}"
493         want_usb="${2}"
494         ret=
495
496         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
497         do
498                 dev_ok=
499                 if [ "$(cat ${sysblock}/removable)" = "1" ]
500                 then
501                         if [ -z "${want_usb}" ]
502                         then
503                                 dev_ok="yes"
504                         else
505                                 if readlink ${sysblock} | grep -q usb
506                                 then
507                                         dev_ok="yes"
508                                 fi
509                         fi
510                 fi
511
512                 if [ "${dev_ok}" = "yes" ]
513                 then
514                         case "${output_format}" in
515                                 sys)
516                                         ret="${ret} ${sysblock}"
517                                         ;;
518                                 *)
519                                         devname=$(sys2dev "${sysblock}")
520                                         ret="${ret} ${devname}"
521                                         ;;
522                         esac
523                 fi
524         done
525
526         echo "${ret}"
527 }
528
529 removable_usb_dev ()
530 {
531         output_format="${1}"
532
533         removable_dev "${output_format}" "want_usb"
534 }
535
536 non_removable_dev ()
537 {
538         output_format="${1}"
539         ret=
540
541         for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -vE "/(loop|ram|dm-|fd)")
542         do
543                 if [ "$(cat ${sysblock}/removable)" = "0" ]
544                 then
545                         case "${output_format}" in
546                                 sys)
547                                         ret="${ret} ${sysblock}"
548                                         ;;
549                                 *)
550                                         devname=$(sys2dev "${sysblock}")
551                                         ret="${ret} ${devname}"
552                                         ;;
553                         esac
554                 fi
555         done
556
557         echo "${ret}"
558 }
559
560 link_files ()
561 {
562         # create source's directory structure in dest, and recursively
563         # create symlinks in dest to to all files in source. if mask
564         # is non-empty, remove mask from all source paths when
565         # creating links (will be necessary if we change root, which
566         # live-boot normally does (into $rootmnt)).
567
568         # remove multiple /:s and ensure ending on /
569         local src_dir="$(echo "${1}"/ | sed -e 's|/\+|/|g')"
570         local dest_dir="$(echo "${2}"/ | sed -e 's|/\+|/|g')"
571         local src_mask="${3}"
572
573         # This check can only trigger on the inital, non-recursive call since
574         # we create the destination before recursive calls
575         if [ ! -d "${dest_dir}" ];
576         then
577                 log_warning_msg "Must link_files into a directory"
578                 return
579         fi
580
581         find "${src_dir}" -mindepth 1 -maxdepth 1 | while read x; do
582                 local src="${x}"
583                 local dest="${dest_dir}$(basename "${x}")"
584                 if [ -d "${src}" ];
585                 then
586                         if [ -z "$(ls -A "${src}")" ];
587                         then
588                                 continue
589                         fi
590                         if [ ! -d "${dest}" ];
591                         then
592                                 mkdir -p "${dest}"
593                                 prev="$(dirname "${dest}")"
594                                 chown $(stat -c %u:%g "${prev}") "${dest}"
595                                 chmod $(stat -c %a "${prev}") "${dest}"
596                         fi
597                         link_files "${src}" "${dest}" "${src_mask}"
598                 else
599                         if [ -n "${src_mask}" ]
600                         then
601                                 src="$(echo ${src} | sed "s|^${src_mask}||")"
602                         fi
603                         rm -rf "${dest}" 2> /dev/null
604                         ln -s "${src}" "${dest}"
605                 fi
606         done
607 }
608
609 do_union () {
610         local unionmountpoint="${1}"    # directory where the union is mounted
611         local unionrw="${2}"            # branch where the union changes are stored
612         local unionro1="${3}"           # first underlying read-only branch (optional)
613         local unionro2="${4}"           # second underlying read-only branch (optional)
614
615         if [ "${UNIONTYPE}" = "aufs" ]
616         then
617                 rw_opt="rw"
618                 ro_opt="rr+wh"
619                 noxino_opt="noxino"
620         elif [ "${UNIONTYPE}" = "unionfs-fuse" ]
621         then
622                 rw_opt="RW"
623                 ro_opt="RO"
624         else
625                 rw_opt="rw"
626                 ro_opt="ro"
627         fi
628
629         case "${UNIONTYPE}" in
630                 unionfs-fuse)
631                         unionmountopts="-o cow -o noinitgroups -o default_permissions -o allow_other -o use_ino -o suid"
632                         unionmountopts="${unionmountopts} ${unionrw}=${rw_opt}"
633                         if [ -n "${unionro1}" ]
634                         then
635                                 unionmountopts="${unionmountopts}:${unionro1}=${ro_opt}"
636                         fi
637                         if [ -n "${unionro2}" ]
638                         then
639                                 unionmountopts="${unionmountopts}:${unionro2}=${ro_opt}"
640                         fi
641                         ( sysctl -w fs.file-max=391524 ; ulimit -HSn 16384
642                         unionfs-fuse ${unionmountopts} "${unionmountpoint}" ) && \
643                         ( mkdir -p /run/sendsigs.omit.d
644                         pidof unionfs-fuse >> /run/sendsigs.omit.d/unionfs-fuse || true )
645                         ;;
646
647                 overlayfs)
648                         # XXX: can unionro2 be used? (overlayfs only handles two dirs, but perhaps they can be chained?)
649                         # XXX: and can unionro1 be optional? i.e. can overlayfs skip lowerdir?
650                         unionmountopts="-o noatime,lowerdir=${unionro1},upperdir=${unionrw}"
651                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
652                         ;;
653
654                 *)
655                         unionmountopts="-o noatime,${noxino_opt},dirs=${unionrw}=${rw_opt}"
656                         if [ -n "${unionro1}" ]
657                         then
658                                 unionmountopts="${unionmountopts}:${unionro1}=${ro_opt}"
659                         fi
660                         if [ -n "${unionro2}" ]
661                         then
662                                 unionmountopts="${unionmountopts}:${unionro2}=${ro_opt}"
663                         fi
664                         mount -t ${UNIONTYPE} ${unionmountopts} ${UNIONTYPE} "${unionmountpoint}"
665                         ;;
666         esac
667 }
668
669 get_custom_mounts () {
670         # Side-effect: leaves $devices with live.persist mounted in ${rootmnt}/live/persistent
671         # Side-effect: prints info to file $custom_mounts
672
673         local devices="${1}"
674         local custom_mounts="${2}" # print result to this file
675         local rootmnt="${3}"       # should be set empty post-live-boot
676
677         local bindings="/bindings.list"
678         local links="/links.list"
679         rm -rf ${bindings} ${links} 2> /dev/null
680         local persistent_backing="${rootmnt}/live/persistent"
681
682         for device in ${devices}
683         do
684                 if [ ! -b "${device}" ]
685                 then
686                         continue
687                 fi
688                 local device_name="$(basename ${device})"
689                 local backing="${persistent_backing}/${device_name}"
690                 mkdir -p "${backing}"
691                 local device_fstype="$(get_fstype ${device})"
692                 if [ -z "${PERSISTENT_READONLY}" ]
693                 then
694                         device_mount_opts="rw,noatime"
695                 else
696                         device_mount_opts="ro,noatime"
697                 fi
698                 local device_used=""
699                 mount -t "${device_fstype}" -o "${device_mount_opts}" "${device}" "${backing}"
700                 local include_list="${backing}/${persistence_list}"
701                 if [ ! -r "${include_list}" ]
702                 then
703                         umount "${backing}"
704                         rmdir "${backing}"
705                         continue
706                 fi
707
708                 [ "${DEBUG}" = "Yes" ] && cp ${include_list} ${persistent_backing}/${persistence_list}.${device_name}
709                 while read source dest options # < ${include_list}
710                 do
711                         if echo ${source} | grep -qe "^[[:space:]]*\(#.*\)\?$"
712                         then
713                                 # skipping empty or commented lines
714                                 continue
715                         fi
716
717                         if echo ${dest} | grep -qe "^[^/]"
718                         then
719                                 options="${dest}"
720                                 dest="${source}"
721                         elif [ -z "${dest}" ]
722                         then
723                                 dest="${source}"
724                         fi
725
726                         if echo ${dest} | grep -qe "^/\+$\|^/\+live\(/.*\)\?$"
727                         then
728                                 # mounting on / or /live could cause trouble
729                                 log_warning_msg "Skipping unsafe custom mount on ${dest}"
730                                 continue
731                         fi
732
733                         for opt in $(echo ${options} | tr ',' ' ');
734                         do
735                                 case "${opt}" in
736                                         linkfiles|union)
737                                                 ;;
738                                         *)
739                                                 log_warning_msg "Skipping custom mount with unkown option: ${opt}"
740                                                 continue 2
741                                                 ;;
742                                 esac
743                         done
744
745                         # FIXME: handle case: we already have /a/b in
746                         # $bindings added from current $device, but
747                         # now we find /a -- /a should replace /a/b in
748                         # $bindings.
749
750                         # FIXME: handle case: we have /a in $bindings
751                         # from current $device, now we find /a/b, so
752                         # we skip /a/b
753
754                         # ensure that no multiple-/ occur in paths
755                         local full_source="$(echo ${backing}/${source}/ | sed -e 's|/\+|/|g')"
756                         local full_dest="$(echo ${rootmnt}/${dest}/ | sed -e 's|/\+|/|g')"
757                         device_used="yes"
758                         if echo ${options} | grep -qe "\<linkfiles\>";
759                         then
760                                 echo "${full_source} ${full_dest} ${options}" >> ${links}
761                         else
762                                 echo "${full_source} ${full_dest} ${options}" >> ${bindings}
763                         fi
764                 done < ${include_list}
765
766                 if [ -z "${device_used}" ]
767                 then
768                         # this device was not used for / earlier, or
769                         # custom mount point now, so it's useless
770                         umount "${backing}"
771                         rmdir "${backing}"
772                 fi
773         done
774
775         # We sort the list according to destination so we're sure that
776         # we won't hide a previous mount. We also ignore duplicate
777         # destinations in a more or less arbitrary way.
778         [ -e "${bindings}" ] && sort -k2 -sbu ${bindings} >> ${custom_mounts}
779         rm ${bindings}
780
781         # After all mounts are considered we add symlinks so they
782         # won't be hidden by some mount.
783         [ -e "${links}" ] && sort -k2 -sbu ${links} >> ${custom_mounts}
784         rm ${links}
785
786         rm -f ${bindings} ${links} 2> /dev/null
787         echo ${custom_mounts}
788 }
789
790 do_custom_mounts () {
791         local custom_mounts="${1}" # the ouput from get_custom_mounts()
792         local rootmnt="${2}"       # should be set empty post-live-boot
793
794         while read source dest options # < ${custom_mounts}
795         do
796                 local opt_linkfiles=""
797                 local opt_union=""
798                 for opt in $(echo ${options} | tr ',' ' ');
799                 do
800                          case "${opt}" in
801                                 linkfiles)
802                                         opt_linkfiles="yes"
803                                         ;;
804                                 union)
805                                         opt_union="yes"
806                                         ;;
807                         esac
808                 done
809
810                 if mountpoint -q "${dest}";
811                 then
812                         log_warning_msg "Skipping custom mount ${source} on ${dest}: destination is already a mount point"
813                         continue
814                 fi
815
816                 # FIXME: we don't handle already existing
817                 # non-directory files in the paths of both $source and
818                 # $dest.
819
820                 if [ ! -d "${dest}" ]
821                 then
822                         # if ${dest} is in /home/$user, try fixing
823                         # proper ownership
824                         # FIXME: this should really be handled by
825                         # live-config since we don't know for sure
826                         # which uid a certain user has until then
827                         if echo ${dest} | grep -qe "^${rootmnt}/*home/\+[^/]\+"
828                         then
829                                 path="/"
830                                 for dir in $(echo ${dest} | sed -e 's|/\+| |g')
831                                 do
832                                         path=${path}/${dir}
833                                         if [ ! -e ${path} ]
834                                         then
835                                                 mkdir -p ${path}
836                                                 # assume that the intended user is the first, which is usually the case
837                                                 chown 1000:1000 ${path}
838                                         fi
839                                 done
840                         else
841                                 mkdir -p ${dest}
842                         fi
843                 fi
844
845                 # if ${source} doesn't exist on our persistent media
846                 # we bootstrap it with $dest from the live filesystem.
847                 # this both makes sense and is critical if we're
848                 # dealing with /etc or other system dir.
849                 if [ ! -d "${source}" ]
850                 then
851                         if [ -n "${PERSISTENT_READONLY}" ] || [ -n "${opt_linkfiles}" ]
852                         then
853                                 continue
854                         elif [ -n "${opt_union}" ]
855                         then
856                                 # union's don't need to be bootstrapped
857                                 mkdir "${source}"
858                         else
859                                 # ensure that $dest is not copied *into* $source
860                                 mkdir -p "$(dirname ${source})"
861                                 cp -a "${dest}" "${source}"
862                         fi
863                 fi
864
865                 rofs_dest_backing=""
866                 for d in ${rootmnt}/live/rofs/*
867                 do
868                         if [ -n "${rootmnt}" ]
869                         then
870                                 rofs_dest_backing="${d}/$(echo ${dest} | sed -e "s|${rootmnt}||")"
871                         else
872                                 rofs_dest_backing="${d}/${dest}"
873
874                         fi
875                         if [ -d "${rofs_dest_backing}" ]
876                         then
877                                 break
878                         else
879                                 rofs_dest_backing=""
880                         fi
881                 done
882
883                 if [ -z "${PERSISTENT_READONLY}" ]
884                 then
885                         if [ -n "${opt_linkfiles}" ]
886                         then
887                                 links_source="${source}"
888                                 links_dest="${dest}"
889                         elif [ -n "${opt_union}" ]
890                         then
891                                 do_union ${dest} ${source} ${rofs_dest_backing}
892                         else
893                                 mount --bind "${source}" "${dest}"
894                         fi
895                 else
896                         if [ -n "${opt_linkfiles}" ]
897                         then
898                                 links_dest="${dest}"
899                                 dest="$(mktemp -d ${persistent_backing}/links_source-XXXXXX)"
900                                 links_source="${dest}"
901                         fi
902                         if [ -n "${rootmnt}" ]
903                         then
904                                 cow_dir="$(echo ${dest} | sed -e "s|${rootmnt}|/cow/|")"
905                         else
906                                 cow_dir="/live/cow/${dest}"
907                         fi
908                         mkdir -p ${cow_dir}
909                         do_union ${dest} ${cow_dir} ${source} ${rofs_dest_backing}
910                 fi
911
912                 if [ -n "${opt_linkfiles}" ]
913                 then
914                         link_files "${links_source}" "${links_dest}" "${rootmnt}"
915                 fi
916
917                 PERSISTENCE_IS_ON="1"
918                 export PERSISTENCE_IS_ON
919         done < ${custom_mounts}
920 }