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