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