f57d406cc3f19d86fb778754863fb899e90842e5
[live-boot-grml.git] / scripts / casper
1 #!/bin/sh
2
3 # set -e
4
5 export PATH=/root/usr/bin:/root/usr/sbin:/root/bin:/root/sbin:/usr/bin:/usr/sbin:/bin:/sbin
6
7 mountpoint=/live_media
8
9 root_persistence="casper-rw"
10 home_persistence="home-rw"
11 root_snapshot_label="casper-sn"
12 home_snapshot_label="home-sn"
13
14 USERNAME="casper"
15 USERFULLNAME="Live session user"
16 HOSTNAME="live"
17 BUILD_SYSTEM="Debian"
18
19 mkdir -p $mountpoint
20
21 [ -f /etc/casper.conf ] && . /etc/casper.conf
22 export USERNAME USERFULLNAME HOSTNAME BUILD_SYSTEM
23
24 . /scripts/casper-helpers
25
26 if [ ! -f /casper.vars ]; then
27     touch /casper.vars
28 fi
29
30 parse_cmdline ()
31 {
32     PRESEEDS=
33     # looking for casper specifics options as kernel parameters
34     for x in $(cat /proc/cmdline); do
35         case $x in
36             userfullname=*)
37                 export USERFULLNAME=${x#userfullname=}
38                 export CASPERCONF="changed"
39                 ;;
40             hostname=*)
41                 export HOSTNAME=${x#hostname=}
42                 export CASPERCONF="changed"
43                 ;;
44             username=*)
45                 export USERNAME=${x#username=}
46                 export CASPERCONF="changed"
47                 ;;
48             netboot*)
49                 export NETBOOT=${x#netboot=} ;;
50             access=*)
51                 export ACCESS=${x#access=} ;;
52             xdebconf)
53                 export XDEBCONF="Yes" ;;
54             toram)
55                 export TORAM="Yes" ;;
56             todisk=*)
57                 export TODISK=${x#todisk=} ;;
58             showmounts)
59                 export SHOWMOUNTS="Yes" ;;
60             persistent)
61                 export PERSISTENT="Yes" ;;
62             nopersistent)
63                 export PERSISTENT="" ;;
64             ip*)
65                 STATICIP=${x#ip=}
66                 if [ "${STATICIP}" == "" ]; then
67                     STATICIP="frommedia"
68                 fi
69                 export STATICIP ;;
70             casper-getty)
71                 export CASPERGETTY=1 ;;
72             bootfrom=*|live-media=*)
73                 export LIVEMEDIA=${x#*=} ;;
74             live-media-timeout=*)
75                 export LIVEMEDIA_TIMEOUT=${x#live-media-timeout=} ;;
76             live-media-offset=*)
77                 export LIVEMEDIA_OFFSET=${x#live-media-offset=} ;;
78             locale=*|debian-installer/locale=*)
79                 export LOCALE=${x#*=} ;;
80             keyb=*|kbd-chooser/method=*)
81                 export KBD=${x#*=} ;;
82             klayout=*|console-setup/layoutcode=*)
83                 export KLAYOUT=${x#*=} ;;
84             koptions=*)
85                 export KOPTIONS=${x#koptions=} ;;
86             kvariant=*|console-setup/variantcode=*)
87                 export KVARIANT=${x#*=} ;;
88             kmodel=*|console-setup/modelcode=*)
89                 export KMODEL=${x#*=} ;;
90             preseed/file=*|file=*)
91                 export LOCATION="${x#*=}" ;;
92             */*=*)
93                 question="${x%%=*}"
94                 value="${x#*=}"
95                 PRESEEDS="${PRESEEDS}\"${question}=${value}\" "
96                 ;;
97             console=*)
98                 export DEFCONSOLE="${x#*=}" ;;
99         esac
100     done
101
102     # sort of compatibility with netboot.h from linux docs
103     if [ -z "${NETBOOT}" ]; then
104         if [ "${ROOT}" == "/dev/nfs" ]; then
105             NETBOOT="nfs"
106             export NETBOOT
107         elif [ "${ROOT}" == "/dev/cifs" ]; then
108             NETBOOT="cifs"
109             export NETBOOT
110         fi
111     fi
112 }
113
114 is_casper_path() {
115     path=$1
116     if [ -d "$path/casper" ]; then
117         if [ "$(echo $path/casper/*.squashfs)" != "$path/casper/*.squashfs" ] ||
118             [ "$(echo $path/casper/*.ext2)" != "$path/casper/*.ext2" ] ||
119             [ "$(echo $path/casper/*.dir)" != "$path/casper/*.dir" ]; then
120             return 0
121         fi
122     fi
123     return 1
124 }
125
126 get_backing_device() {
127     case "$1" in
128         *.squashfs|*.ext2)
129             echo $(setup_loop "$1" "loop" "/sys/block/loop*")
130             ;;
131         *.dir)
132             echo "directory"
133             ;;
134         *)
135             panic "Unrecognized casper filesystem: $1"
136             ;;
137     esac
138 }
139
140 match_files_in_dir() {
141     # Does any files match pattern $1 ?
142
143     local pattern="$1"
144     if [ "$(echo $pattern)" != "$pattern" ]; then
145         return 0
146     fi
147     return 1
148 }
149
150 mount_images_in_directory() {
151     directory="$1"
152     rootmnt="$2"
153     if match_files_in_dir "$directory/casper/*.squashfs" ||
154         match_files_in_dir "$directory/casper/*.ext2" ||
155         match_files_in_dir "$directory/casper/*.dir"; then
156         setup_unionfs "$directory/casper" "$rootmnt"
157     else
158         :
159     fi
160 }
161
162 is_nice_device() {
163     sysfs_path="${1#/sys}"
164     if /lib/udev/path_id "${sysfs_path}" | grep -E -q "ID_PATH=(usb|pci-[^-]*-[ide|scsi|usb])"; then
165         return 0
166     fi
167     return 1
168 }
169
170 is_supported_fs ()
171 {
172     # FIXME: do something better like the scan of supported filesystems
173     fstype="${1}"
174     case ${fstype} in
175         vfat|iso9660|udf|ext2|ext3|ntfs)
176             return 0
177             ;;
178     esac
179     return 1
180 }
181
182 copy_live_to() {
183     copyfrom="${1}"
184     copytodev="${2}"
185     copyto="${copyfrom}_swap"
186
187     size=$(fs_size "" ${copyfrom} "used")
188
189     if [ "${copytodev}" = "ram" ]; then
190         # copying to ram:
191         freespace=$( expr $(awk '/MemFree/{print $2}' /proc/meminfo) + $( cat /proc/meminfo | grep Cached | head -n 1 | awk '/Cached/{print $2}' - ) )
192         mount_options="-o size=${size}k"
193         free_string="memory"
194         fstype="tmpfs"
195         dev="/dev/shm"
196     else
197         # it should be a writable block device
198         if [ -b "${copytodev}" ]; then
199             dev="${copytodev}"
200             free_string="space"
201             fstype=$(get_fstype "${dev}")
202             freespace=$(fs_size "${dev}")
203         else
204             [ "$quiet" != "y" ] && log_warning_msg "${copytodev} is not a block device."
205             return 1
206         fi
207     fi
208     if [ "${freespace}" -lt "${size}" ] ; then
209         [ "$quiet" != "y" ] && log_warning_msg "Not enough free ${free_string} (${freespace}k > ${size}k) to copy live media in ${copytodev}."
210         return 1
211     fi
212
213     # begin copying..
214     mkdir "${copyto}"
215     echo "mount -t ${fstype} ${mount_options} ${dev} ${copyto}"
216     mount -t "${fstype}" ${mount_options} "${dev}" "${copyto}"
217     cp -a ${copyfrom}/* ${copyto} # "cp -a" from busybox also copies hidden files
218     umount ${copyfrom}
219     mount -r -o move ${copyto} ${copyfrom}
220     rmdir ${copyto}
221     return 0
222 }
223
224 do_netmount() {
225     rc=1
226
227     modprobe "${MP_QUIET}" af_packet # For DHCP
228
229     ipconfig ${DEVICE} /tmp/net-${DEVICE}.conf | tee /netboot.config
230
231     if [ "${NFSROOT}" = "auto" ]; then
232         NFSROOT=${ROOTSERVER}:${ROOTPATH}
233     fi
234
235     [ "$quiet" != "y" ] && log_begin_msg "Trying netboot from ${NFSROOT}"
236
237     if [ "${NETBOOT}" != "nfs" ] && do_cifsmount ; then
238         rc=0
239     elif do_nfsmount ; then
240         NETBOOT="nfs"
241         export NETBOOT
242         rc=0
243     fi
244
245     [ "$quiet" != "y" ] && log_end_msg
246     return ${rc}
247 }
248
249 do_nfsmount() {
250     rc=1
251     modprobe "${MP_QUIET}" nfs
252     if [ -z "${NFSOPTS}" ]; then
253         NFSOPTS=""
254     fi
255
256     [ "$quiet" != "y" ] && log_begin_msg "Trying nfsmount -o nolock -o ro ${NFSOPTS} ${NFSROOT} ${mountpoint}"
257     # FIXME: This for loop is an ugly HACK round an nfs bug
258     for i in 0 1 2 3 4 5 6 7 8 9 a b c d e f 10 11 12 13; do
259         nfsmount -o nolock -o ro ${NFSOPTS} "${NFSROOT}" "${mountpoint}" && rc=0 && break
260         sleep 1
261     done
262     return ${rc}
263 }
264
265 do_cifsmount() {
266     rc=1
267     if [ -x "/sbin/mount.cifs" ]; then
268         if [ -z "${NFSOPTS}" ]; then
269             CIFSOPTS="-ouser=root,password="
270         else
271             CIFSOPTS="${NFSOPTS}"
272         fi
273
274         [ "$quiet" != "y" ] && log_begin_msg "Trying mount.cifs ${NFSROOT} ${mountpoint} ${CIFSOPTS}"
275         modprobe "${MP_QUIET}" cifs
276
277         if mount.cifs "${NFSROOT}" "${mountpoint}" "${CIFSOPTS}" ; then
278             rc=0
279         fi
280     fi
281     return ${rc}
282 }
283
284 do_snap_copy ()
285 {
286     fromdev="${1}"
287     todir="${2}"
288     snap_type="${3}"
289
290     size=$(fs_size "${fromdev}" "" "used")
291
292     if [ -b "${fromdev}" ]; then
293         # look for free mem
294         if [ -n "${HOMEMOUNTED}" -a "${snap_type}" = "HOME" ]; then
295             todev=$(cat /proc/mounts | grep -s " $(base_path ${todir}) " | awk '{print $1}' )
296             freespace=$(df -k  | grep -s ${todev} | awk '{print $4}')
297         else
298             freespace=$( expr $(awk '/MemFree/{print $2}' /proc/meminfo) + $( cat /proc/meminfo | grep Cached | head -n 1 | awk '/Cached/{print $2}' - ))
299         fi
300
301         tomount="/mnt/tmpsnap"
302         if [ ! -d "${tomount}" ] ; then
303             mkdir -p "${tomount}"
304         fi
305
306         fstype=$(get_fstype "${fromdev}")
307         if [ -n "${fstype}" ]; then
308             # Copying stuff...
309             mount -t "${fstype}" -o ro "${fromdev}" "${tomount}"
310             cp -a "${tomount}"/* ${todir}
311             umount "${tomount}"
312         else
313             log_warning_msg "Unrecognized fstype: ${fstype} on ${fromdev}:${snap_type}"
314         fi
315
316         rmdir "${tomount}"
317         if echo ${fromdev} | grep -qs loop; then
318            losetup -d "${fromdev}"
319         fi
320         return 0
321     else
322         return 1
323         [ "$quiet" != "y" ] && log_warning_msg "Unable to find the snapshot ${snap_type} medium"
324     fi
325 }
326
327 try_snap ()
328 {
329     # Look for $snap_label.* in block devices and copy the contents to $snap_mount
330     #   and remember the device and filename for resync on exit in casper.init
331
332     snap_label="${1}"
333     snap_mount="${2}"
334     snap_type="${3}"
335
336     snapdata=$(find_files "${snap_label}.squashfs ${snap_label}.cpio.gz ${snap_label}.ext2")
337     if [ ! -z "${snapdata}" ]; then
338         snapdev="$(echo ${snapdata} | cut -f1 -d ' ')"
339         snapback="$(echo ${snapdata} | cut -f2 -d ' ')"
340         snapfile="$(echo ${snapdata} | cut -f3 -d ' ')"
341         if echo "${snapfile}" | grep -qs '\(squashfs\|ext2\)'; then
342             # squashfs or ext2 snapshot
343             dev=$(get_backing_device "${snapback}/${snapfile}")
344             if ! do_snap_copy "${dev}" "${snap_mount}" "${snap_type}"; then
345                  log_warning_msg "Impossible to include the ${snapfile} Snapshot"
346                  return 1
347             fi
348         else
349             # cpio.gz snapshot
350             if ! (cd "${snap_mount}" && zcat "${snapback}/${snapfile}" | cpio -i -u -d 2>/dev/null) ; then
351                 log_warning_msg "Impossible to include the ${snapfile} Snapshot"
352                 return 1
353             fi
354         fi
355         umount "${snapback}"
356     else
357         dev=$(find_cow_device "${snap_label}")
358         if [ -b ${dev} ]; then
359             if echo "${dev}" | grep -qs loop; then
360                 # strange things happens, user confused?
361                 snaploop=$( losetup ${dev} | awk '{print $3}' | tr -d '()' )
362                 snapfile=$(basename ${snaploop})
363                 snapdev=$(cat /proc/mounts | awk '{print $2,$1}' | grep -es "^$( dirname ${snaploop} )" | cut -f2 -d ' ')
364             else
365                 snapdev="${dev}"
366             fi
367             if ! do_snap_copy "${dev}" "${snap_mount}" "${snap_type}" ; then
368                 log_warning_msg "Impossible to include the ${snap_label} Snapshot"
369                 return 1
370             else
371                 if [ -n "${snapfile}" ]; then
372                      # it was a loop device, user confused
373                      umount ${snapdev}
374                 fi
375             fi
376         else
377             log_warning_msg "Impossible to include the ${snap_label} Snapshot"
378             return 1
379         fi
380     fi
381     echo "export ${snap_type}SNAP="${snap_mount}":${snapdev}:${snapfile}" >> /etc/casper.conf # for resync on reboot/halt
382     return 0
383 }
384
385 setup_unionfs() {
386     image_directory="$1"
387     rootmnt="$2"
388
389     modprobe "${MP_QUIET}" -b unionfs
390
391     # run-init can't deal with images in a subdir, but we're going to
392     # move all of these away before it runs anyway.  No, we're not,
393     # put them in / since move-mounting them into / breaks mono and
394     # some other apps.
395
396     croot="/"
397
398     # Let's just mount the read-only file systems first
399     rofsstring=""
400     rofslist=""
401     if [ "${NETBOOT}" == "nfs" ] ; then
402         roopt="nfsro" # go aroung a bug in nfs-unionfs locking
403     else
404         roopt="ro"
405     fi
406
407     mkdir -p "${croot}"
408     for image_type in "ext2" "squashfs" "dir" ; do
409         for image in "${image_directory}"/*."${image_type}"; do
410             imagename=$(basename "${image}")
411             if [ -d "${image}" ]; then
412                 # it is a plain directory: do nothing
413                 rofsstring="${image}=${roopt}:${rofsstring}"
414                 rofslist="${image} ${rofslist}"
415             elif [ -f "${image}" ]; then
416                 backdev=$(get_backing_device "$image")
417                 fstype=$(get_fstype "${backdev}")
418                 if [ "${fstype}" = "unknown" ]; then
419                     panic "Unknown file system type on ${backdev} (${image})"
420                 fi
421                 mkdir -p "${croot}/${imagename}"
422                 mount -t "${fstype}" -o ro "${backdev}" "${croot}/${imagename}" || panic "Can not mount $backdev ($image) on ${croot}/${imagename}" && rofsstring="${croot}/${imagename}=${roopt}:${rofsstring}" && rofslist="${croot}/${imagename} ${rofslist}"
423             fi
424         done
425     done
426     rofsstring=${rofsstring%:}
427
428     mkdir -p /cow
429
430     cowdevice="tmpfs"
431     cow_fstype="tmpfs"
432
433     # Looking for "${root_persistence}" device or file
434     if [ -n "${PERSISTENT}" ]; then
435         cowprobe=$(find_cow_device "${root_persistence}")
436         if [ -b "${cowprobe}" ]; then
437             cowdevice=${cowprobe}
438             cow_fstype=$(get_fstype "${cowprobe}")
439         else
440             [ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent medium"
441         fi
442     fi
443
444     mount ${cowdevice} -t ${cow_fstype} -o rw /cow || panic "Can not mount $cowdevice on /cow"
445
446     mount -t unionfs -o dirs=/cow=rw:$rofsstring unionfs "$rootmnt" || panic "Unionfs mount failed"
447
448     # Adding other custom mounts
449     if [ -n "${PERSISTENT}" ]; then
450         # directly mount /home
451         # FIXME: add a custom mounts configurable system
452         homecow=$(find_cow_device "${home_persistence}" )
453         if [ -b "${homecow}" ]; then
454             mount -t $(get_fstype "${homecow}") -o rw "${homecow}" "${rootmnt}/home"
455             export HOMEMOUNTED=1 # used to proper calculate free space in do_snap_copy()
456         else
457             [ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent home medium"
458         fi
459         # Look for other snapshots to copy in
460         try_snap "${root_snapshot_label}" "${rootmnt}" "ROOT"
461         try_snap "${home_snapshot_label}" "${rootmnt}/home" "HOME"
462     fi
463
464     if [ -n "${SHOWMOUNTS}" ]; then
465         for d in ${rofslist}; do
466             mkdir -p "${rootmnt}/casper/${d##*/}"
467             case d in
468                 *.dir) # do nothing # mount -o bind "${d}" "${rootmnt}/casper/${d##*/}"
469                     ;;
470                 *) mount -o move "${d}" "${rootmnt}/casper/${d##*/}"
471                     ;;
472             esac
473         done
474     fi
475
476     # shows cow fs on /cow for use by casper-snapshot
477     mkdir -p "${rootmnt}/cow"
478     mount -o bind /cow "${rootmnt}/cow"
479 }
480
481 check_dev ()
482 {
483     sysdev="${1}"
484     devname="${2}"
485     if [ -z "${devname}" ]; then
486         devname=$(sys2dev "${sysdev}")
487     fi
488
489     if [ -n "${LIVEMEDIA_OFFSET}" ]; then
490         loopdevname=$(setup_loop "${devname}" "loop" "/sys/block/loop*" "${LIVEMEDIA_OFFSET}")
491         devname="${loopdevname}" 
492     fi
493
494     fstype=$(get_fstype "${devname}")
495     if is_supported_fs ${fstype}; then
496         mount -t ${fstype} -o ro "${devname}" $mountpoint || continue
497         if is_casper_path $mountpoint; then
498             echo $mountpoint
499             return 0
500         else
501             umount $mountpoint
502         fi
503     fi
504
505     if [ -n "${LIVEMEDIA_OFFSET}" ]; then
506         losetup -d "${loopdevname}"
507     fi
508     return 1
509 }
510
511 find_livefs() {
512     timeout="${1}"
513     # first look at the one specified in the command line
514     if [ ! -z "${LIVEMEDIA}" ]; then
515         if check_dev "null" "${LIVEMEDIA}"; then
516             return 0
517         fi
518     fi
519     # don't start autodetection before timeout has expired
520     if [ -n "${LIVEMEDIA_TIMEOUT}" ]; then
521         if [ "${timeout}" -lt "${LIVEMEDIA_TIMEOUT}" ]; then
522             return 1
523         fi
524     fi
525     # or do the scan of block devices
526     for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -v loop | grep -v ram); do
527         devname=$(sys2dev "${sysblock}")
528         fstype=$(get_fstype "${devname}")
529         if /lib/udev/cdrom_id ${devname} > /dev/null; then
530             if check_dev "null" "${devname}" ; then
531                 return 0
532             fi
533         elif is_nice_device "${sysblock}" ; then
534             for dev in $(subdevices "${sysblock}"); do
535                 if check_dev "${dev}" ; then
536                     return 0
537                 fi
538             done
539         elif [ "${fstype}" = "squashfs" -o \
540                 "${fstype}" = "ext3" -o \
541                 "${fstype}" = "ext2" ]; then
542             # This is an ugly hack situation, the block device has
543             # an image directly on it.  It's hopefully
544             # casper, so take it and run with it.
545             ln -s "${devname}" "${devname}.${fstype}"
546             echo "${devname}.${fstype}"
547             return 0
548         fi
549     done
550     return 1
551 }
552
553 pulsate() {
554     if [ -x /sbin/usplash_write ]; then
555         /sbin/usplash_write "PULSATE"
556     fi
557 }
558
559 set_usplash_timeout() {
560     if [ -x /sbin/usplash_write ]; then
561         /sbin/usplash_write "TIMEOUT 120"
562     fi
563 }
564
565 mountroot() {
566     exec 6>&1
567     exec 7>&2
568     exec > casper.log
569     exec 2>&1
570
571     parse_cmdline
572
573     set_usplash_timeout
574     [ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-premount"
575     pulsate
576     run_scripts /scripts/casper-premount
577     [ "$quiet" != "y" ] && log_end_msg
578
579     # Needed here too because some things (*cough* udev *cough*)
580     # changes the timeout
581
582     set_usplash_timeout
583
584     if [ ! -z "${NETBOOT}" ]; then
585         if do_netmount ; then
586             livefs_root="${mountpoint}"
587         else
588             panic "Unable to find a the network rootfs live file system"
589         fi
590     else
591         # Scan local devices for the image
592         for i in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19; do
593             livefs_root=$(find_livefs $i)
594             if [ -n "${livefs_root}" ]; then
595                 break
596             fi
597             sleep 1
598         done
599     fi
600
601     if [ -z "${livefs_root}" ]; then
602         panic "Unable to find a medium containing a live file system"
603     fi
604
605     if [ -n "${TORAM}" ]; then
606         live_dest="ram"
607     elif [ -n "${TODISK}" ]; then
608         live_dest="${TODISK}"
609     fi
610     if [ -n "${live_dest}" ]; then
611         [ "$quiet" != "y" ] && log_begin_msg "Copying live_media to ${live_dest}"
612         copy_live_to "${livefs_root}" "${live_dest}"
613         [ "$quiet" != "y" ] && log_end_msg
614     fi
615
616     mount_images_in_directory "${livefs_root}" "${rootmnt}"
617
618     log_end_msg
619
620     maybe_break casper-bottom
621     [ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-bottom"
622
623     pulsate
624     run_scripts /scripts/casper-bottom
625     [ "$quiet" != "y" ] && log_end_msg
626
627     exec 1>&6 6>&-
628     exec 2>&7 7>&-
629     cp casper.log "${rootmnt}/var/log/"
630 }