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