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