7358f8598c04cd682d224903b6c29a1969598fea
[live-initramfs-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=$(sed -e 's%.*console=%console=%' /proc/cmdline) ;;
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     cowdevice="tmpfs"
430     cow_fstype="tmpfs"
431
432     # Looking for "${root_persistence}" device or file
433     if [ -n "${PERSISTENT}" ]; then
434         cowprobe=$(find_cow_device "${root_persistence}")
435         if [ -b "${cowprobe}" ]; then
436             cowdevice=${cowprobe}
437             cow_fstype=$(get_fstype "${cowprobe}")
438         else
439             [ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent medium"
440         fi
441     fi
442
443     mount ${cowdevice} -t ${cow_fstype} -o rw /cow || panic "Can not mount $cowdevice on /cow"
444
445     mount -t unionfs -o dirs=/cow=rw:$rofsstring unionfs "$rootmnt" || panic "Unionfs mount failed"
446
447     # Adding other custom mounts
448     if [ -n "${PERSISTENT}" ]; then
449         # directly mount /home
450         # FIXME: add a custom mounts configurable system
451         homecow=$(find_cow_device "${home_persistence}" )
452         if [ -b "${homecow}" ]; then
453             mount -t $(get_fstype "${homecow}") -o rw "${homecow}" "${rootmnt}/home"
454             export HOMEMOUNTED=1 # used to proper calculate free space in do_snap_copy()
455         else
456             [ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent home medium"
457         fi
458         # Look for other snapshots to copy in
459         try_snap "${root_snapshot_label}" "${rootmnt}" "ROOT"
460         try_snap "${home_snapshot_label}" "${rootmnt}/home" "HOME"
461     fi
462
463     if [ -n "${SHOWMOUNTS}" ]; then
464         for d in ${rofslist}; do
465             mkdir -p "${rootmnt}/casper/${d##*/}"
466             case d in
467                 *.dir) # do nothing # mount -o bind "${d}" "${rootmnt}/casper/${d##*/}"
468                     ;;
469                 *) mount -o move "${d}" "${rootmnt}/casper/${d##*/}"
470                     ;;
471             esac
472         done
473     fi
474
475     # shows cow fs on /cow for use by casper-snapshot
476     mkdir -p "${rootmnt}/cow"
477     mount -o bind /cow "${rootmnt}/cow"
478 }
479
480 check_dev ()
481 {
482     sysdev="${1}"
483     devname="${2}"
484     if [ -z "${devname}" ]; then
485         devname=$(sys2dev "${sysdev}")
486     fi
487
488     if [ -n "${LIVEMEDIA_OFFSET}" ]; then
489         loopdevname=$(setup_loop "${devname}" "loop" "/sys/block/loop*" "${LIVEMEDIA_OFFSET}")
490         devname="${loopdevname}" 
491     fi
492
493     fstype=$(get_fstype "${devname}")
494     if is_supported_fs ${fstype}; then
495         mount -t ${fstype} -o ro "${devname}" $mountpoint || continue
496         if is_casper_path $mountpoint; then
497             echo $mountpoint
498             return 0
499         else
500             umount $mountpoint
501         fi
502     fi
503
504     if [ -n "${LIVEMEDIA_OFFSET}" ]; then
505         losetup -d "${loopdevname}"
506     fi
507     return 1
508 }
509
510 find_livefs() {
511     timeout="${1}"
512     # first look at the one specified in the command line
513     if [ ! -z "${LIVEMEDIA}" ]; then
514         if check_dev "null" "${LIVEMEDIA}"; then
515             return 0
516         fi
517     fi
518     # don't start autodetection before timeout has expired
519     if [ -n "${LIVEMEDIA_TIMEOUT}" ]; then
520         if [ "${timeout}" -lt "${LIVEMEDIA_TIMEOUT}" ]; then
521             return 1
522         fi
523     fi
524     # or do the scan of block devices
525     for sysblock in $(echo /sys/block/* | tr ' ' '\n' | grep -v loop | grep -v ram); do
526         devname=$(sys2dev "${sysblock}")
527         fstype=$(get_fstype "${devname}")
528         if /lib/udev/cdrom_id ${devname} > /dev/null; then
529             if check_dev "null" "${devname}" ; then
530                 return 0
531             fi
532         elif is_nice_device "${sysblock}" ; then
533             for dev in $(subdevices "${sysblock}"); do
534                 if check_dev "${dev}" ; then
535                     return 0
536                 fi
537             done
538         elif [ "${fstype}" = "squashfs" -o \
539                 "${fstype}" = "ext3" -o \
540                 "${fstype}" = "ext2" ]; then
541             # This is an ugly hack situation, the block device has
542             # an image directly on it.  It's hopefully
543             # casper, so take it and run with it.
544             ln -s "${devname}" "${devname}.${fstype}"
545             echo "${devname}.${fstype}"
546             return 0
547         fi
548     done
549     return 1
550 }
551
552 pulsate() {
553     if [ -x /sbin/usplash_write ]; then
554         /sbin/usplash_write "PULSATE"
555     fi
556 }
557
558 set_usplash_timeout() {
559     if [ -x /sbin/usplash_write ]; then
560         /sbin/usplash_write "TIMEOUT 120"
561     fi
562 }
563
564 mountroot() {
565     exec 6>&1
566     exec 7>&2
567     exec > casper.log
568     exec 2>&1
569
570     parse_cmdline
571
572     set_usplash_timeout
573     [ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-premount"
574     pulsate
575     run_scripts /scripts/casper-premount
576     [ "$quiet" != "y" ] && log_end_msg
577
578     # Needed here too because some things (*cough* udev *cough*)
579     # changes the timeout
580
581     set_usplash_timeout
582
583     if [ ! -z "${NETBOOT}" ]; then
584         if do_netmount ; then
585             livefs_root="${mountpoint}"
586         else
587             panic "Unable to find a the network rootfs live file system"
588         fi
589     else
590         # Scan local devices for the image
591         for i in 0 1 2 3 4 5 6 7 8 9 a b c d e f 10 11 12 13; do
592             livefs_root=$(find_livefs $i)
593             if [ -n "${livefs_root}" ]; then
594                 break
595             fi
596             sleep 1
597         done
598     fi
599
600     if [ -z "${livefs_root}" ]; then
601         panic "Unable to find a medium containing a live file system"
602     fi
603
604     if [ -n "${TORAM}" ]; then
605         live_dest="ram"
606     elif [ -n "${TODISK}" ]; then
607         live_dest="${TODISK}"
608     fi
609     if [ -n "${live_dest}" ]; then
610         [ "$quiet" != "y" ] && log_begin_msg "Copying live_media to ${live_dest}"
611         copy_live_to "${livefs_root}" "${live_dest}"
612         [ "$quiet" != "y" ] && log_end_msg
613     fi
614
615     mount_images_in_directory "${livefs_root}" "${rootmnt}"
616
617     log_end_msg
618
619     maybe_break casper-bottom
620     [ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-bottom"
621
622     pulsate
623     run_scripts /scripts/casper-bottom
624     [ "$quiet" != "y" ] && log_end_msg
625
626     exec 1>&6 6>&-
627     exec 2>&7 7>&-
628     cp casper.log "${rootmnt}/var/log/"
629 }