summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/btrfs-functions.sh161
-rw-r--r--src/btrfs-receive-root.sh55
-rw-r--r--src/btrfs-send-root.sh45
-rwxr-xr-xsrc/grub-efi.sh50
-rwxr-xr-xsrc/initrd.sh36
-rw-r--r--src/initrd/common.sh143
-rwxr-xr-xsrc/initrd/grok-block182
-rwxr-xr-xsrc/initrd/halt.montecarlo39
-rwxr-xr-xsrc/initrd/init60
-rw-r--r--src/initrd/init.functions345
-rwxr-xr-xsrc/initrd/init.shutdown30
-rw-r--r--src/initrd/loop-layer.sh15
-rw-r--r--src/initrd/lvm-create.sh299
-rw-r--r--src/initrd/lvm.conf773
-rw-r--r--src/initrd/mdadm-dup.sh217
-rwxr-xr-xsrc/initrd/menu-select123
-rwxr-xr-xsrc/initrd/samizdat-cdrom-copy75
-rwxr-xr-xsrc/initrd/samizdat-eject.sh92
-rwxr-xr-xsrc/initrd/squashfs-size88
-rwxr-xr-xsrc/initrd/umountall.sh126
-rwxr-xr-xsrc/initrd/vol_id2
-rwxr-xr-xsrc/keygen.sh122
-rwxr-xr-xsrc/patchroot.sh43
-rwxr-xr-xsrc/qemu.sh34
-rw-r--r--src/samizdat-paths.sh5
-rw-r--r--src/var.sh75
-rwxr-xr-xsrc/xorriso-layer.sh38
-rw-r--r--src/xorriso-usb.sh182
-rwxr-xr-xsrc/xorriso.sh66
-rwxr-xr-xsrc/xorriso.test-efi.sh65
30 files changed, 3586 insertions, 0 deletions
diff --git a/src/btrfs-functions.sh b/src/btrfs-functions.sh
new file mode 100644
index 0000000..b83b94d
--- /dev/null
+++ b/src/btrfs-functions.sh
@@ -0,0 +1,161 @@
1push()
2{
3 $(ARGS_NE mnt src dst_dir)
4
5 now=$(date +%F.%H%M%S) || die
6 snap_dir=$mnt/snapshot.$now
7 prev_dir=$mnt/snapshot.prev
8
9 local BTRFS_RECEIVE_DESTINATION_PATH="$dst_dir"
10 push_helper true "$snap_dir" "$prev_dir" "$src" local_btrfs_receiver
11}
12
13push_simple()
14{
15 $(ARGS_NE mnt src dst_dir)
16 local BTRFS_RECEIVE_DESTINATION_PATH="$dst_dir"
17 push_helper false "$mnt" "$src" local_btrfs_receiver
18}
19
20sex()
21{
22 (set -x; "$@")
23}
24
25local_btrfs_receiver()
26{
27 btrfs receive "$BTRFS_RECEIVE_DESTINATION_PATH"
28}
29
30shellescape()
31{
32 if [ "$BASH_VERSION" ]; then
33 printf %q "$1"
34 else
35 bash -c 'printf %q "$1"' bash "$1"
36 fi
37}
38
39remote_btrfs_receiver()
40{
41 ssh "$BTRFS_RECEIVE_DESTINATION_HOST" -- "btrfs receive $(shellescape "$BTRFS_RECEIVE_DESTINATION_PATH")"
42}
43
44push_helper()
45{
46 $(ARGS keep_as_prev snap_dir prev_dir src dst_pipe)
47 $(NONEMPTY keep_as_prev snap_dir src dst_pipe)
48
49 local full_dest rw_dest
50
51 btrfs subvolume snapshot -r "$src" "$snap_dir" || die
52
53 if [ "$prev_dir" -a -d "$prev_dir" ]; then
54 btrfs send -p "$prev_dir" "$snap_dir"
55 else
56 btrfs send "$snap_dir"
57 fi | "$dst_pipe" || die
58
59 if [ "$dst_pipe" = local_btrfs_receiver ]; then
60 local dst="$BTRFS_RECEIVE_DESTINATION_PATH"
61 full_dest=$dst/$(basename "$snap_dir")
62 rw_dest=$full_dest.rw
63 btrfs subvolume snapshot "$full_dest" "$rw_dest" || die
64 btrfs_replace_default_subvolume_with "$rw_dest"
65 fi
66
67 if $keep_as_prev && [ "$prev_dir" ]
68 then
69 # keep the pushed snapshot in order to reuse it on subsequent pushes.
70 with_dir "$prev_dir" btrfs subvolume delete || die
71 sex mv "$snap_dir" "$prev_dir" || die
72 else
73 btrfs subvolume delete "$snap_dir"
74 fi
75}
76
77btrfs_mountpoint()
78{
79 $(ARGS_NE dir)
80 btrfs filesystem show -m "$dir" >/dev/null 2>&1
81}
82
83btrfs_get_mountpoint()
84{
85 $(ARGS_NE dir)
86 while [ "$dir" -a "$dir" != '.' ]; do
87 if btrfs_mountpoint "$dir"
88 then printf '%s\n' "$dir"
89 return
90 fi
91 dir=$(dirname "$dir")
92 done
93 false
94}
95
96btrfs_show_default_path()
97{
98 $(ARGS_NE mp)
99 local path
100 mp=$(btrfs_get_mountpoint "$mp") || die # TODO: fix caller?
101 btrfs_mountpoint "$mp" || die "not a mountpoint: $mp"
102 path=$(btrfs subvolume get-default "$mp"/|sed -n -e 's/.* path //p')
103 if [ "$path" ]; then
104 printf '%s\n' "$mp/$path"
105 else
106 printf '%s\n' "$mp"
107 fi
108}
109
110btrfs_show_default_id()
111{
112 $(ARGS_NE mp)
113 local id
114 mp=$(btrfs_get_mountpoint "$mp") || die # TODO: fix caller?
115 btrfs_mountpoint "$mp" || die "not a mountpoint: $mp"
116 id=$(btrfs subvolume get-default "$mp"/|sed -n -e 's/^ID \([^ ]*\) .*/\1/p')
117 [ "$id" ] || return
118 echo $id
119}
120
121btrfs_replace_default_subvolume_with()
122{
123 $(ARGS_NE new_default)
124 local old_default old_default_id new_default_id
125 old_default_id=$(btrfs_show_default_id "$new_default") || die
126 new_default_id=$(btrfs_show_subvolume_id "$new_default") || die
127
128 [ "$new_default_id" = "$old_default_id" ] && return
129
130 if [ "$old_default_id" != 5 ]; then
131 old_default=$(btrfs_show_default_path "$new_default") || die
132 else
133 old_default=
134 fi
135
136 btrfs subvolume set-default "$new_default_id" "$new_default" || die
137
138 if [ "$old_default" ]; then
139 btrfs subvolume delete "$old_default"
140 sex mv "$new_default" "$old_default"
141 fi
142}
143
144btrfs_show_subvolume_id()
145{
146 $(ARGS_NE path)
147 local result
148 result=$(btrfs subvolume show "$path" | sed -n -e 's/^[ \t]*Subvolume ID:[ \t]*//p; s/.*is toplevel subvolume/5/p')
149 if [ "$result" ]
150 then printf '%s\n' "$result"
151 else false
152 fi
153}
154
155with_dir()
156{
157 $(ARGS_NE d)
158 shift
159 [ -d "$d" ] || return 0
160 "$@" "$d"
161}
diff --git a/src/btrfs-receive-root.sh b/src/btrfs-receive-root.sh
new file mode 100644
index 0000000..f553c2c
--- /dev/null
+++ b/src/btrfs-receive-root.sh
@@ -0,0 +1,55 @@
1#!/bin/sh
2
3. sami/btrfs-functions.sh
4. sami/var.sh
5
6disable_stdout() { exec 3>&1; exec >&2; }
7enable_stdout() { exec >&3; }
8
9with_stdout() { enable_stdout; "$@"; disable_stdout; }
10
11create_layer_filesystem()
12{
13 [ ! -e "$layer_file" ] || return
14 ! mountpoint "$mountpoint" || return
15 mkdir -p "$mountpoint" &&
16 sex dd if=/dev/zero of="$layer_file" bs=1M count="$layer_size" &&
17 sex mount -o subvol=/,compress "$seed_file" "$mountpoint" &&
18 layer_dev=$(losetup -f --show "$layer_file") &&
19 sex btrfs device add "$layer_dev" "$mountpoint" &&
20 mount -o rw,remount "$mountpoint"
21}
22
23finish()
24{
25 local subv_id
26 sex mv "$mountpoint"/ROOT "$mountpoint"/ROOT.old || return
27 sex btrfs subvolume snapshot "$mountpoint"/"$receive_subv" "$mountpoint"/ROOT || return
28 subv_id=$(btrfs_show_subvolume_id "$mountpoint"/ROOT) || return
29 sex btrfs subvolume set-default "$subv_id" "$mountpoint" || return
30 sex btrfs subvolume delete "$mountpoint"/ROOT.old || return
31 umount "$mountpoint" || return
32 sex btrfstune -S1 "$layer_file" || return
33 losetup -d "$layer_dev"
34}
35
36set -e
37disable_stdout
38
39receive_dest=$1
40receive_subv=$2
41
42[ "$receive_subv" ]
43[ "$receive_dest" ]
44
45mountpoint=$(realpath -m --relative-base=. "$receive_dest")
46
47seed_file=sami/debian-live-8.4.0-amd64-standard.btrfs
48layer_file_FINAL=sami/debian-live-8.4.0-amd64-standard.layer.$receive_subv.btrfs
49layer_file=$layer_file_FINAL.part
50layer_size=1000
51
52create_layer_filesystem
53with_stdout sex btrfs receive "$mountpoint"
54finish
55mv "$layer_file" "$layer_file_FINAL"
diff --git a/src/btrfs-send-root.sh b/src/btrfs-send-root.sh
new file mode 100644
index 0000000..8a3a513
--- /dev/null
+++ b/src/btrfs-send-root.sh
@@ -0,0 +1,45 @@
1#!/bin/sh
2. samizdat-paths.sh
3. var.sh
4. btrfs-functions.sh
5
6rootfs_uuid ()
7{
8 btrfs filesystem show / | sed -ne 's/.*uuid: //p'
9}
10
11remote_btrfs_receiver()
12{
13# ssh "$BTRFS_RECEIVE_DESTINATION_HOST" -- "sudo btrfs receive $(shellescape "$BTRFS_RECEIVE_DESTINATION_PATH")"
14 ssh "$BTRFS_RECEIVE_DESTINATION_HOST" -- \
15 "sudo sh sami/btrfs-receive-root.sh $(shellescape "$BTRFS_RECEIVE_DESTINATION_PATH") $(shellescape "$BTRFS_RECEIVE_SUBVOLUME_NAME")"
16}
17
18dummy_receiver()
19{
20 true
21}
22
23push_remote()
24{
25 $(ARGS_NE mnt src ssh_dst)
26
27 now=$(date +%F.%H%M%S) || die
28 snap_dir=$mnt/snapshot.$now
29 prev_dir=$mnt/SEED
30
31 case "$ssh_dst" in
32 *:*) ;;
33 *) return 1;;
34 esac
35 local BTRFS_RECEIVE_DESTINATION_PATH="${ssh_dst#*:}"
36 local BTRFS_RECEIVE_DESTINATION_HOST="${ssh_dst%%:*}"
37 local BTRFS_RECEIVE_SUBVOLUME_NAME="${snap_dir#$mnt/}"
38 push_helper false "$snap_dir" "$prev_dir" "$src" remote_btrfs_receiver
39}
40
41ssh_dst=d@fifty.local:sami/test_dest
42
43mkdir -p /mnt/rootfs || die
44mountpoint -q /mnt/rootfs || mount -o subvol=/ UUID=$(rootfs_uuid) /mnt/rootfs || die
45push_remote /mnt/rootfs / "$ssh_dst"
diff --git a/src/grub-efi.sh b/src/grub-efi.sh
new file mode 100755
index 0000000..e2d50f6
--- /dev/null
+++ b/src/grub-efi.sh
@@ -0,0 +1,50 @@
1#!/bin/sh
2. samizdat-paths.sh
3
4grub_config()
5{
6 cat <<EOF
7insmod echo
8echo GRUB
9insmod part_acorn
10insmod part_amiga
11insmod part_apple
12insmod part_bsd
13insmod part_dvh
14insmod part_gpt
15insmod part_msdos
16insmod part_plan
17insmod part_sun
18insmod part_sunpc
19
20insmod linux
21insmod iso9660
22
23echo Loading vmlinuz...
24linux /linux/vmlinuz boot=samizdat components quiet splash
25echo Loading initrd.img...
26initrd /linux/initrd.img
27echo Booting.
28echo
29boot
30
31EOF
32}
33
34real_destdir=$samizdat_grub_efi_dir
35destdir=$real_destdir.tmp
36
37set -e
38rm -r "${destdir}" 2>/dev/null || true
39mkdir -p "${destdir}"/grub/i386-pc/
40cp -r /usr/lib/grub/i386-pc/* "${destdir}"/grub/i386-pc/
41rm "${destdir}"/grub/i386-pc/*.img || true
42
43grub_config > "${destdir}"/load_cfg
44set -x
45grub-mkimage -O i386-pc -d /usr/lib/grub/i386-pc/ -o "${destdir}"/core.img -c "${destdir}"/load_cfg --prefix=/grub iso9660 biosdisk
46cat /usr/lib/grub/i386-pc/cdboot.img "${destdir}"/core.img > "${destdir}"/grub/i386-pc/eltorito.img
47cat /usr/lib/grub/i386-pc/boot.img "${destdir}"/core.img > "${destdir}"/embedded.img
48
49rm -r "$real_destdir" 2>/dev/null || true
50mv -T "$destdir" "$real_destdir"
diff --git a/src/initrd.sh b/src/initrd.sh
new file mode 100755
index 0000000..8cc8ea1
--- /dev/null
+++ b/src/initrd.sh
@@ -0,0 +1,36 @@
1#!/bin/sh
2
3initrd=${samizdat_isolinux_dir}/linux/initrd.img
4vmlinuz=${samizdat_isolinux_dir}/linux/vmlinuz
5
6version=$(uname -r)
7version=4.5.0-0.bpo.1-amd64
8conf_dir=initramfs-tools
9
10apt_dependencies=initrd-dependencies.txt
11
12find_source_dirs() {
13 set -- find "$conf_dir" ./old-school "$@"
14 "$@"
15}
16
17force_rebuild()
18{
19 touch "$conf_dir"
20 return 1
21}
22
23rebuild()
24{
25 [ ! -f "$apt_dependencies" ] || sudo apt-get install -q=10 --no-upgrade -y $(cat "$apt_dependencies")
26
27 set -ex
28 cp -f /boot/vmlinuz-${version} "$vmlinuz"
29 /usr/sbin/mkinitramfs -d "$conf_dir" -o "$initrd" ${version} || force_rebuild
30}
31
32if [ ! -e "$initrd" -o ! -e "$vmlinuz" ]; then
33 rebuild
34elif [ "$(find_source_dirs -newer "$initrd" -print -quit)" ]; then
35 rebuild
36fi
diff --git a/src/initrd/common.sh b/src/initrd/common.sh
new file mode 100644
index 0000000..4aa8528
--- /dev/null
+++ b/src/initrd/common.sh
@@ -0,0 +1,143 @@
1#!/bin/sh
2REQUIRED_MB=250 # minimum megabytes available to offer install
3MENUFIFO=/menu.fifo
4DEBUG=y
5LOGBASE=/var/log
6
7debug_log()
8{
9 if [ -n "$DEBUG" ]; then
10 if [ -n "$1" ]; then
11 DEBUG_LOG=$LOGBASE/"$1".$$.log
12 else
13 DEBUG_LOG=$LOGBASE/$(basename $0).$$.log
14 fi
15 mkdir -p $LOGBASE
16 exec >>$DEBUG_LOG 2>&1
17 set -x
18 fi
19}
20addmenu()
21{
22 cat <<END >>$MENUFIFO # mind the tabs
23setItem "$1" "dummy" "$2" "$3"
24END
25}
26menutitle()
27{
28 printf 'setTitle "%s"\n' "$1" >>$MENUFIFO
29 printf 'setWelcomeText "%s"\n' "$2" >>$MENUFIFO
30}
31bootmenu()
32{
33 local do_trigger="$1" no_panic="$2"
34 OpenVT -f -c 7 -- dynmenu "$MENUFIFO" &&
35 chvt 7 &&
36 menutitle 'Samizdat\n\nAs the Internet develops there are\ntransitions in the management arrangements.\nThe time has come to take\na small step in one of those transitions.' 'Choose an installation target.'
37# menutitle 'Samizdat\nfreedom from surveillance\nno trusted authorities' 'Choose an installation target.'
38 addmenu "ramdisk" "[ Boot to RAM without installing anything ]" "menu-select boot-ram"
39 if [ $? != 0 -a ! "$no_panic" ]; then
40 panic "error loading boot menu! the system won't be usable :("
41 fi
42 if [ "$do_trigger" ]; then
43 udevadm trigger --subsystem-match=block --action=add
44 fi
45}
46find_squashfs_root()
47{
48 # TODO: "make" puts the correct location in $iso_squashfs_dir. Get
49 # information into this function!
50
51 bootwait samizdat-cdrom
52 for dir in /cdrom/live /cdrom/liveos /cdrom/aptosid /cdrom/*
53 do
54 [ -d "$dir" ] || continue;
55 if [ -f "$dir"/filesystem.module ]; then
56 while read fs; do
57 [ -f "$dir"/"$fs" ] && echo "$dir" "$fs"
58 done < "$dir"/filesystem.module
59 return
60 fi
61 done
62 for fs in /cdrom/live/filesystem.squashfs /cdrom/live/grml-small.squashfs /cdrom/liveos/squashfs.img /cdrom/aptosid/aptosid.* /cdrom/*/*.squashfs
63 do
64 if [ -f "$fs" ]; then
65 echo "${fs%/*}" "${fs##*/}"
66 break
67 fi
68 done
69}
70xtrace()
71{
72 case "$-" in
73 *x*) "$@" ;;
74 *) set -x; "$@"; set +x ;;
75 esac
76}
77sleepcmd() {
78 local t=$1
79 shift
80 echo "about to run '$*' (in $t)"
81 sleep $t
82 "$@"
83}
84sleep_forever_verbose() {
85 sleep 4294967295 &
86 local sleep=$!
87 warn "sleeping until you kill $sleep..."
88 wait $sleep
89}
90warn() { [ -z "$warnings" ] || echo "$@" >&2; }
91panic()
92{
93 set +x
94 exec </dev/tty1 >/dev/tty1 2>&1
95 reset
96 echo "[p$$] initramfs /init: fatal error: $@"
97 echo "[p$$] will now exec emergency shell"
98 export PS1="[p$$ \\w]# "
99 chvt 1
100 exec /bin/sh -i
101}
102bootwait()
103{
104 mkdir -p /bootwait
105 local i=$#; while [ $i -gt 0 ]; do
106 i=$((i-1))
107 local f="$1"; shift; set -- "$@" "/bootwait/$f"
108 done
109 wait_for_files "$@"
110}
111bootdone()
112{
113 mkdir -p /bootwait
114 local i=$#; while [ $i -gt 0 ]; do
115 i=$((i-1))
116 local f="$1"; shift; set -- "$@" "/bootwait/$f"
117 done
118 touch "$@"
119}
120my_openvt()
121{
122 /bin/openvt -c "$@"
123}
124
125# This runs before way before NTP and on a LiveCD we have no
126# reason to trust the system clock.
127gpg2_nobatch() { GPG_TTY=$(tty) command gpg2 --ignore-time-conflict --ignore-valid-from "$@"; }
128gpg2() { gpg2_nobatch --batch "$@"; }
129
130xcp() { if [ -f "$1" -a ! -f "$2" ]; then cp "$1" "$2"; fi; }
131
132mountsquashes()
133{
134 local name dirname basename
135 while read dirname basename && [ -d "$dirname" -a -f "$dirname/$basename" ]; do
136 name=${basename%.squashfs}
137 mkdir -p "/squashes/$name" || return 1
138 xcp "$dirname"/filesystem.module /squashes/filesystem.module || return 1
139 mountpoint -q "/squashes/$name" ||
140 mount -o ro,loop "$dirname/$basename" "/squashes/$name" || return 1
141 done
142}
143
diff --git a/src/initrd/grok-block b/src/initrd/grok-block
new file mode 100755
index 0000000..75d5120
--- /dev/null
+++ b/src/initrd/grok-block
@@ -0,0 +1,182 @@
1#!/bin/sh
2. common.sh
3
4DEVNAME=$1
5case "$DEVNAME" in /dev/loop*|/dev/ram*|/dev/dm-*|/dev/md*|/dev/fd*) exit ;; esac
6[ -b "$DEVNAME" ] || exit
7
8debug_log "grok-block.${DEVNAME##*/}"
9
10addmenu_choosekey()
11{
12 dev=$1
13 dir=$2
14 addmenu "$dev//$dir" \
15 "[ Use the GPG key on $dev ]" \
16 "menu-select boot-gpg $dev $dir"
17}
18
19addmenu_repairhfs()
20{
21 local device="$1"
22 addmenu "$device//reboot" \
23 "[ Reboot into Mac OS X in order to repair disk $device ]" \
24 "eject /cdrom; sleep 2; reboot -f"
25 addmenu "$device//fsck" \
26 "[ (DANGEROUS) Try to repair errors on $device with fsck.hfsplus ]" \
27 "/bin/openvt -sw -- sh -c 'fsck.hfsplus $device && remenu'"
28}
29
30addmenu_chooseroot()
31{
32 local device="$1" loopfile="$2"
33
34 addmenu "$device//$loopfile" \
35 "[ Boot the system on $device${loopfile:+ in file $(basename $loopfile)} ]" \
36 "menu-select --fs=$ID_FS_TYPE boot-luks $device ${loopfile:-$device}"
37}
38
39addmenu_makeroot()
40{
41 local device="$1" loopfile="$2" megs="$3" copy_cdrom="$4"
42 (
43 addmenu "$device//$loopfile" \
44 "[ Install Samizdat to $device (in file $(basename $loopfile)) ]" \
45 "menu-select --fs=$ID_FS_TYPE boot-new $device $loopfile $megs $copy_cdrom"
46 ) &
47}
48
49retry_mount()
50{
51 tries=20
52 until mntout="$(mount "$@" 2>&1)"
53 do
54 tries=$(( tries - 1 ))
55 case "$mntout" in
56 *"Device or resource busy"*)
57 if [ $tries -le 0 ]; then
58 warn "mount $@ failed: $mntout"
59 return 1
60 else
61 sleep 1
62 continue
63 fi
64 ;;
65 *)
66 warn "mount $@ failed: $mntout"
67 break ;;
68 esac
69 done
70}
71
72gpg_verify()
73{
74 bootwait samizdat-cdrom
75 gpg2 --lock-never --no-permission-warning --no-auto-check-trustdb --no-options --homedir /cdrom/gnupghome --verify "$1"
76}
77is_lvm()
78{
79 for n in 0 1 2 3; do
80 [ "LVM2 001" = "$(dd if="$1" bs=1 skip=$((512*n+24)) count=8 2>/dev/null)" ] && return 0
81 done
82 return 1
83}
84
85grok_block()
86{
87 local mountpoint="/mnt/${DEVNAME##*/}"
88
89 mkdir -p "$mountpoint"
90
91 case "$ID_FS_TYPE" in
92 ntfs) mount_type='-t ntfs-3g' ;;
93 "") mount_type= ;;
94 *) mount_type="-t $ID_FS_TYPE" ;;
95 esac
96
97 if [ "$ID_FS_TYPE" = hfsplus ] && ! fsck.hfsplus -q "$DEVNAME"; then
98 (if fsck.hfsplus "$DEVNAME"; then
99 grok-block "$DEVNAME"
100 else
101 addmenu_repairhfs "$DEVNAME"
102 fi) &
103 return
104 fi
105
106 if ! mountpoint -q "$mountpoint"; then
107 retry_mount $mount_type -o ro "$DEVNAME" "$mountpoint"
108 fi
109
110 if mountpoint -q "$mountpoint"; then
111 umount=true
112 # Device has an unencrypted filesystem on it.
113 # So we mount it and look for loop-back overlays.
114
115 if [ -d "$mountpoint/samizdat.gpg" ]; then
116 # check the key somehow?
117 addmenu_choosekey "$DEVNAME" "$mountpoint/samizdat.gpg"
118 fi
119
120 N=1; while [ -e "$mountpoint/samizdat.$N" ]
121 do
122 if gpg_verify "$mountpoint/samizdat.$N"k; then
123 addmenu_chooseroot "$DEVNAME" "$mountpoint/samizdat.$N"
124 # this menu entry chooses the root fs, and should prompt and wait for the matching key
125 umount=false
126 fi
127 N=$((N+1))
128 done
129
130 freeblocks=$(stat -f -c %f "$mountpoint")
131 blocksize=$(stat -f -c %S "$mountpoint")
132 freemegs=$((freeblocks * blocksize / 1024 / 1024))
133
134 if [ "$freemegs" -ge 300 ]; then
135
136 umount=false
137 bootwait samizdat-cdrom
138 cdromblocks=$(stat -f -c %b /cdrom)
139 cdromblocksize=$(stat -f -c %S /cdrom)
140 cdrommegs=$((cdromblocks * cdromblocksize / 1024 / 1024))
141
142 if [ "$freemegs" -ge "$((cdrommegs * 3))" ]; then
143 addmenu_makeroot "$DEVNAME" "${mountpoint}/samizdat.$N" "$((cdrommegs * 3))" 1
144 elif [ "$freemegs" -ge "$((cdrommegs * 2))" ]; then
145 addmenu_makeroot "$DEVNAME" "${mountpoint}/samizdat.$N" "$((cdrommegs * 2))" 1
146 elif [ "$freemegs" -ge "$cdrommegs" ]; then
147 addmenu_makeroot "$DEVNAME" "${mountpoint}/samizdat.$N" "$((freemegs / 2))" 0
148 else
149 addmenu_makeroot "$DEVNAME" "${mountpoint}/samizdat.$N" 256 0
150 fi
151 fi
152
153 if $umount; then
154 umount "$mountpoint"
155 rmdir "$mountpoint"
156 fi
157 else
158 rmdir "$mountpoint"
159 fi
160}
161
162# Get me all them nice udev variables
163eval "$(PATH=$PATH:/lib/udev vol_id "$DEVNAME" |
164 sed "s/'/'\\\\''/; s/=\(.*\)/='\1'/"
165)"
166
167CDROM_ID_FS_UUID_ENC='73256269-4002-4e42-adbd-0e49ed1c7438'
168CDROM_ID_FS_LABEL_ENC=$(sed 's/ /\\x20/g' /lib/samizdat/vol_id.txt)
169if [ "$ID_FS_UUID_ENC" = "$CDROM_ID_FS_UUID_ENC" -o \
170 "$ID_FS_LABEL_ENC" = "$CDROM_ID_FS_LABEL_ENC" ]
171then
172 # Recognize and mount the Samizdat
173 if ! mountpoint -q /cdrom; then
174 mkdir -p /cdrom
175 . mdadm-dup.sh
176 dup_mount_cdrom "$DEVNAME" /cdrom && bootdone samizdat-cdrom
177 fi
178else
179 grok_block &
180fi
181
182# vim:set et sw=2:
diff --git a/src/initrd/halt.montecarlo b/src/initrd/halt.montecarlo
new file mode 100755
index 0000000..67dac17
--- /dev/null
+++ b/src/initrd/halt.montecarlo
@@ -0,0 +1,39 @@
1#!/bin/bash
2
3cmd=${0##*/}
4dashf=
5for arg in "$@"; do
6 case "$arg" in -*f*) dashf=1 ;; esac
7 case "$arg" in -*p*) [ "$cmd" = halt ] && cmd=poweroff ;; esac
8done
9
10[ "$dashf" ] || exec -a "$0" /sbin/halt.distrib "$@"
11
12read pids < /run/sendsigs.omit.d/samizdat
13for p in $pids; do
14 if [ -e /proc/$p/root -a ! /proc/$p/root -ef / ]; then
15 initramfs=/proc/$p/root
16 break
17 fi
18done
19
20panic()
21{
22 set -x
23 sync
24 exec -a "$0" /sbin/halt.distrib "$@"
25}
26
27[ "$initramfs" ] || panic
28
29cp /sbin/init $initramfs/telinit
30
31# Apparently, linux does not allow a direct bind mount of a file on
32# the initramfs. Therefore, copy the file from the initramfs and bind
33# mount the copy.
34
35mount -o remount,exec /run
36cp $initramfs/lib/samizdat/init.shutdown /run/ && mount --bind /run/init.shutdown /sbin/init || panic
37
38echo $cmd -f > $initramfs/halt
39$initramfs/telinit u
diff --git a/src/initrd/init b/src/initrd/init
new file mode 100755
index 0000000..3b62c0a
--- /dev/null
+++ b/src/initrd/init
@@ -0,0 +1,60 @@
1#!/bin/sh
2PATH=$PATH:/usr/lib/klibc/bin
3#if [ $$ = 1 ]; then
4# "$0" "$@"
5# exec sh -i
6#fi
7. init.functions
8warnings=y
9
10debug_log init
11mountvirt
12klogd -c1 # no kernel messages
13
14mkdir -p "$LOGBASE"
15sh -c "syslogd -O '$LOGBASE'/"'syslogd.$$.log';
16if [ "$DEBUG" != y ]; then
17 echo 0 > /proc/sys/kernel/printk
18fi
19
20makedev
21loadenv
22
23if [ -x /bin/kmod ]; then
24 ln -sf /bin/kmod /bin/depmod
25 /bin/depmod -a
26else
27 depmod -a
28fi
29
30PS1='[$$ \w]# ' my_openvt 8 -- sh -i
31
32mkfifo "$MENUFIFO" || panic "mkfifo '$MENUFIFO' failed"
33bootmenu
34mkdir -p /etc/udev/rules.d
35cat <<END >/etc/udev/rules.d/z00_blockdev_mountroot.rules
36ACTION=="add", SUBSYSTEM=="block", RUN+="/bin/grok-block \$env{DEVNAME}"
37END
38
39start_udev
40mountunionroot
41
42bootwait rw-overlay
43# killeverything
44# nuke /dev/.udev/queue/
45stop_udev
46insertoverlay
47
48movemounts
49gpg_agent_chroot
50patchroot
51clear >/dev/tty1
52chvt 1
53[ -e /do-delay-boot ] && bootwait 'launch-init-ready'
54launch_init "$@"
55
56# unreachable since launch_init will panic on failure
57panic 'inconceivable!'
58exec >/dev/tty1 2>&1 <&1
59reset
60exec sh -i
diff --git a/src/initrd/init.functions b/src/initrd/init.functions
new file mode 100644
index 0000000..7209b04
--- /dev/null
+++ b/src/initrd/init.functions
@@ -0,0 +1,345 @@
1#!/bin/sh
2. common.sh
3mountvirt()
4{
5 # TODO: simply put these dirs on the initrd itself
6 mkdir -m 0755 -p /dev /sys /proc /tmp /var /run
7 mkdir -m 0700 -p /root
8
9 mount -t sysfs -o nodev,noexec,nosuid none /sys
10 mount -t proc -o nodev,noexec,nosuid none /proc
11 tmpfs_size="10M"
12# [ -f /etc/udev/udev.conf ] && . /etc/udev/udev.conf
13 mount -t tmpfs -o size=$tmpfs_size,mode=0755 udev /dev
14 mount -t tmpfs -o size=64M,mode=0755 run /run
15 mkdir -m 0755 /dev/pts /run/lock
16 mount -t devpts devpts /dev/pts
17 ln -s /run /run/lock /var/
18}
19makedev()
20{
21 # TODO: simply put these nodes on the initrd itself
22 mkdir -m 0755 -p /dev
23 mknod /dev/null c 1 3
24 mknod /dev/zero c 1 5
25 mknod /dev/tty c 5 0
26 if [ "$FUCK_devconsole" ]; then # FUCK /dev/console
27 mknod /dev/console c 4 1 # tty1 is console; a saner alternative (TODO: fix shutdown to chvt)
28 else
29 mknod /dev/console c 5 1
30 fi
31 for i in 0 1 2 3 4 5 6 7 8; do
32 mknod /dev/tty${i} c 4 ${i}
33 done
34 # TODO: wait for udev? pft.
35 for i in 0 1 2 3 4 5 6 7; do
36 mknod /dev/loop${i} b 7 ${i}
37 done
38}
39loadenv()
40{
41 # TODO: filter the wheat from the chaff here; most of this is unused.
42 # TODO: implement the various boot args
43
44 # Load config files
45# export DPKG_ARCH=
46# . /conf/arch.conf
47# export ROOT=
48# . /conf/initramfs.conf
49# for conf in conf/conf.d/*; do
50# [ -f ${conf} ] && . ${conf}
51# done
52 # Make modprobe quiet
53 export MODPROBE_OPTIONS="-qb"
54 # Export constants
55 export rootmnt=/root
56 # Export bootparam variables
57 export init=/sbin/init
58 export readonly=y
59 export blacklist=
60
61 # Parse command line options
62 for x in $(cat /proc/cmdline); do
63 case $x in
64 init=*) init=${x#init=} ;;
65 root=*)
66 ROOT=${x#root=}
67 case $ROOT in
68 LABEL=*) ROOT="/dev/disk/by-label/${ROOT#LABEL=}" ;;
69 UUID=*) ROOT="/dev/disk/by-uuid/${ROOT#UUID=}" ;;
70 /dev/nfs) [ -z "${BOOT}" ] && BOOT=nfs ;;
71 esac
72 ;;
73 rootflags=*) ROOTFLAGS="-o ${x#rootflags=}" ;;
74 rootfstype=*) ROOTFSTYPE="${x#rootfstype=}" ;;
75 ro) readonly=y ;;
76 rw) readonly=n ;;
77
78 nfsroot=*) NFSROOT="${x#nfsroot=}" ;;
79 ip=*) IPOPTS="${x#ip=}" ;;
80 boot=*) BOOT=${x#boot=} ;;
81
82 resume=*) RESUME="${x#resume=}" ;;
83 noresume) noresume=y ;;
84 blacklist=*) blacklist=${x#blacklist=} ;;
85
86 hostname=*)
87 hostname=${x#hostname=}
88 hostname "$hostname"
89 ;;
90 bootcd_device=*) bootcd_device=${x#bootcd_device=}
91 mkdir -p /cdrom &&
92 mount -r -t hostfs -o "${bootcd_device#hostfs=}" hostfs /cdrom &&
93 bootdone samizdat-cdrom
94 ;;
95 overlay_device=*) overlay_device=${x#overlay_device=}
96 mkdir -p /overlay &&
97 mount -t hostfs -o "${overlay_device#hostfs=}" hostfs /overlay &&
98 bootdone rw-overlay
99 ;;
100 uml_modules=*) uml_modules=${x#uml_modules=}
101 mount -t hostfs -o "${uml_modules#hostfs=}" hostfs /lib/modules ;;
102 esac
103 done
104
105 if [ -z "${noresume}" ]; then
106 export resume=${RESUME}
107 else
108 export noresume
109 fi
110}
111mountunionroot()
112{
113 bootwait samizdat-cdrom squashfs-root
114
115 ufs=
116 if grep -q aufs /proc/filesystems || modprobe aufs; then
117 ufs=aufs
118 elif grep -q unionfs /proc/filesystems || modprobe unionfs; then
119 ufs=unionfs
120 fi
121
122 case $ufs in
123 unionfs) ro=ro;;
124 aufs) ro=rr;;
125 *) panic "mountunionroot: unionfs module not found";;
126 esac
127
128 dirs=;
129 if [ -f /squashes/filesystem.module ]; then
130 while read img; do
131 d=/squashes/"${img%.squashfs}"
132 mountpoint -q /squashes/"${img%.squashfs}" || continue;
133 dirs="$d=$ro${dirs:+:$dirs}"
134 done < /squashes/filesystem.module
135 else
136 for d in /squashes/*; do
137 mountpoint -q "$d" || continue
138 dirs="$d=$ro${dirs:+:$dirs}"
139 done
140 fi
141 [ -n "$dirs" ] ||
142 panic "no squashes. missing/broken images on cdrom?"
143
144 if true; then
145# overlay_tmp=$(mktemp -d /overlay.XXXXXX) &&
146 overlay_tmp=/overlay.$$ && mkdir -p $overlay_tmp &&
147 mount -t tmpfs tmpfs $overlay_tmp &&
148 touch $overlay_tmp/samizdat-filesystem-is-new
149 dirs="$overlay_tmp:$dirs" ||
150 { rmdir $overlay_tmp;
151 panic "mountunionroot: failure creating tmpfs overlay"; }
152 fi
153
154 mount -t $ufs -o rw,dirs="$dirs" $ufs "$rootmnt" ||
155 panic "mountunionroot: $ufs: mount (dirs=$dirs): error: $?"
156}
157insertoverlay() # TODO: copy-up and umount tmpfs. MASSIVELY IMPORTANT!
158{
159 if ! mountpoint -q /overlay; then
160 # rw-overlay was signalled without a mount on /overlay
161 # thus, boot with the current tmpfs overlay
162 mkdir -p /overlay
163 mount -o move $overlay_tmp /overlay
164 return 0
165 fi
166
167 ufs=$(sed -ne 's?^[^ ]* '"$rootmnt"' \(unionfs\|aufs\) .*?\1?p' /proc/mounts)
168
169 case $ufs in
170 unionfs)
171 panic 'insertoverlay: TODO: implement unionfs support'
172
173 mount -o remount,rw,add=/overlay "$rootmnt" ||
174 panic "insertoverlay: remount unionfs (add=/overlay): error: $?"
175
176 #mount -o remount,del=$overlay_tmp && # NO, WRONG, COPY-UP FIRST
177 #umount $overlay_tmp && rmdir $overlay_tmp
178 ;;
179 aufs)
180 mount -o remount,rw,prepend:/overlay=rw "$rootmnt" ||
181 panic "insertoverlay: remount aufs (prepend:/overlay=rw): error: $?"
182
183 mount -o remount,mod:"$overlay_tmp"=ro+wh "$rootmnt" ||
184 panic "insertoverlay: couldn't set aufs branch read-only: $overlay_tmp"
185
186 # copy everything the user reads (not just writes) to the overlay
187 # (this is appropriate for CD-ROM but not testing. TODO: enable)
188 #mount -o remount,coo=all "$rootmnt"
189
190 mkdir -p "$rootmnt"/xino && mount -o move "$overlay_tmp" "$rootmnt"/xino ||
191 panic "insertoverlay: couldn't move mount $overlay_tmp to $rootmnt/xino"
192 ;;
193 *) panic "insertoverlay: unrecognized filesystem ($ufs)";;
194 esac
195
196 bootdone root-mounted
197}
198AppendIfNoSuchLine()
199{
200 local filename="$1"
201 shift
202 if grep -vqF "$1" < "$filename"; then
203 printf '%s\n' "$@" >> "$filename"
204 fi
205}
206gpg_agent_chroot()
207{
208 chroot "$rootmnt" sh -c \
209 'export PATH=/usr/local/sbin:/usr/local/bin:$PATH;
210 killall gpg-agent;
211 samizdat-gpg-agent;
212 killall -USR2 samizdat-pinentry;'
213}
214remove_squashfs_mistakes()
215{
216 # Workaround for bad samizdat-generated upstream squashfs:
217 rm -f "$rootmnt"/etc/ipsec.conf
218 rm -rf "$rootmnt"/etc/samizdat/samizdat-receive-hooks
219 rm -f "$rootmnt"/etc/adjtime
220}
221patchroot_UNUSED()
222{
223 test -e "$rootmnt"/samizdat-filesystem-is-new || return
224 echo Patching livecd root -- $(date) >> /dev/tty7
225 rm -f /dev/console; mknod /dev/console c 4 1
226
227 remove_squashfs_mistakes
228
229 if [ -e /etc/adjtime -a ! -e "$rootmnt"/etc/adjtime ]; then
230 cp /etc/adjtime "$rootmnt"/etc/adjtime
231 fi
232
233 if [ -f "$rootmnt"/cdrom/samizdat/skel.tgz ]; then
234 chroot "$rootmnt" bin/tar -C / --no-same-owner -zxf /cdrom/samizdat/skel.tgz
235 fi
236 chroot "$rootmnt" hostname -F /etc/hostname
237
238 chroot "$rootmnt" update-rc.d samizdat-pids start 15 S
239
240 # We need debian-tor user so that hidden service directory can have the right owner
241 chroot "$rootmnt" adduser --quiet --system --disabled-password --home /var/lib/tor \
242 --no-create-home --shell /bin/bash --group debian-tor
243
244 # TODO: check errors here
245 chroot "$rootmnt" sh -c \
246 'export PATH=/usr/local/sbin:/usr/local/bin:"$PATH" GNUPGHOME=/gpg/gnupghome verbose=1;
247 samizdat-receive -v < /cdrom/samizdat/secrets.mime && samizdat-receive -v < /cdrom/samizdat/public.mime'
248
249 for diversion in /etc/kernel/postinst.d/initramfs-tools /etc/init.d/live-boot /sbin/halt; do
250 chroot "$rootmnt" dpkg-divert --rename --package samizdat --add "$diversion"
251 done
252 cp /bin/halt.montecarlo "$rootmnt"/sbin/halt
253
254 if ! [ -f "$rootmnt"/var/lib/dpkg/info/linux-image-"$(uname -r)".list ]; then
255 chroot "$rootmnt" sh -c \
256 'dpkg --fsys-tarfile /cdrom/samizdat/debs/linux-image-$(uname -r)_*.deb | tar -C / -x; depmod -a'
257 fi
258
259 # disable some of GRML's many consoles.
260# sed -i -e 's/^\([3456789]\|1[012]\):/#\1:/' "$rootmnt"/etc/inittab
261# sed -i -e 's/^NUM_CONSOLES=12/NUM_CONSOLES=0/' "$rootmnt"/usr/bin/zsh-login
262
263 # these GRML scripts implement a "sendsigs" which does not respect omit.d
264 sed -i -e 's/^\(l0:.*\)grml-halt$/\1rc 0/' "$rootmnt"/etc/inittab
265 sed -i -e 's/^\(l6:.*\)grml-reboot$/\1rc 6/' "$rootmnt"/etc/inittab
266 chroot "$rootmnt" update-rc.d sendsigs stop 20 0 6
267
268 echo Done patching livecd root -- $(date) >>/dev/tty7
269 rm "$rootmnt"/samizdat-filesystem-is-new
270}
271movemounts()
272{
273 # Move mounted filesystems to the root filesystem
274 while read dev mp rest; do
275 case "$mp" in
276 "$rootmnt"|"$rootmnt"/*|/|/proc|/dev|/dev/pts|/sys) continue ;;
277 /mnt.samizdat.*)
278 #umount -l "$mp"
279 target="$rootmnt/media/${dev##*/}"
280 ;;
281 /overlay.*) umount -l $mp; continue ;;
282 *) target="$rootmnt$mp" ;;
283 esac
284 mkdir -p "$target"
285 mount -n -o move "$mp" "$target"
286 done </proc/mounts
287 mount --rbind /dev "$rootmnt"/dev
288 mount --bind /proc "$rootmnt"/proc
289 ln -sf /proc/mounts "$rootmnt"/etc/mtab
290}
291launch_init()
292{
293 # bad init= command line?
294 if [ ! -x "$rootmnt$init" ]; then
295 panic "init does not exist or is not executable (init=$init)"
296 fi
297 ln -sf /proc/mounts "$rootmnt"/etc/mtab
298 export CONSOLE=/dev/tty1
299 exec chroot "$rootmnt" "$init" "$@" <"$rootmnt$CONSOLE" >"$rootmnt$CONSOLE" 2>&1
300 panic "exec init failed (init=$init)"
301# exec run-init -c "$CONSOLE" "$rootmnt" "$init" "$@"
302# panic "exec run-init failed (init=$init)"
303}
304start_udev()
305{
306 echo > /proc/sys/kernel/hotplug
307 mkdir -p /dev/.udev/db/ /dev/.udev/queue/
308# mkdir -p "$LOGBASE"; sh -c "udevd --resolve-names=never --debug >$LOGBASE/udevd."'$$'".log 2>&1" &
309 udevd --resolve-names=never --daemon
310 udevadm trigger --action=add
311# udevadm settle
312}
313stop_udev()
314{
315 for proc in /proc/[0-9]*; do
316 [ -x $proc/exe ] || continue
317 [ "$(readlink $proc/exe)" = /sbin/udevd ] && kill ${proc#/proc/}
318 done
319 # ignore any failed event because the init script will trigger again all events
320 nuke /dev/.udev/queue/
321}
322killeverything()
323{
324 # TODO: exempt: interactive shell(s) (AND CHILDREN) (or: anything with
325 # a tty?), samizdat-agent, fsck(!!), ...?
326
327# exempt_cmdline="$(printf "sh\0-i\0")"
328 force=
329 while true; do
330 killme=
331 for proc in /proc/[0-9]*; do
332 [ $proc != /proc/1 -a $proc != /proc/$$ -a -x $proc/exe ] || continue
333# [ "$(cat $proc/cmdline)" != "$exempt_cmdline" ] || continue
334 read pid tcomm state ppid pgrp sid tty_nr tty_pgrp rest < $proc/stat
335 [ $tty_nr = 0 ] || continue
336 killme="$killme ${proc#/proc/}"
337 done
338 if [ -n "$killme" ]; then
339 kill $force $killme
340 else
341 break
342 fi
343 force=-KILL
344 done
345}
diff --git a/src/initrd/init.shutdown b/src/initrd/init.shutdown
new file mode 100755
index 0000000..6bfce84
--- /dev/null
+++ b/src/initrd/init.shutdown
@@ -0,0 +1,30 @@
1#!/bin/sh
2read omitpids < /run/sendsigs.omit.d/samizdat
3for pid in $omitpids; do
4 if [ -e /proc/$pid/root ]; then
5 initroot=/proc/$pid/root
6 break
7 fi
8done
9
10warn() { echo "$*" >/dev/console; }
11error() { umount /sbin/init; exec /sbin/init; }
12
13[ -e "$initroot" ] || error
14
15if [ $$ != 1 ]; then
16 exec $initroot/init "$@"
17else
18 set --
19 for pid in $omitpids; do
20 set -- "$@" -o $pid
21 done
22 if killall5 -15 "$@"; then
23 sleep 5
24 killall5 -9 "$@"
25 fi
26 exec <$initroot/dev/console >$initroot/dev/console 2>$initroot/dev/console
27 exec chroot $initroot umountall.sh
28
29 error
30fi
diff --git a/src/initrd/loop-layer.sh b/src/initrd/loop-layer.sh
new file mode 100644
index 0000000..7e08e12
--- /dev/null
+++ b/src/initrd/loop-layer.sh
@@ -0,0 +1,15 @@
1losetup_snapshot()
2{
3 local ro_dev rw_dev new_dev_name size persist chunksize
4 ro_file=$1
5 rw_file=$2
6
7 ro_dev=$(LoSetup -r -f --show "$ro_file") || return
8 rw_dev=$(LoSetup -f --show "$rw_file") || return
9 new_dev_name=${ro_dev##*/}
10 size=$(blockdev --getsz "$ro_dev") || return
11 persist=p
12 chunksize=16
13 dmsetup create "$new_dev_name" --table "0 $size snapshot $ro_dev $rw_dev $persist $chunksize" || return
14 echo /dev/mapper/"$new_dev_name"
15}
diff --git a/src/initrd/lvm-create.sh b/src/initrd/lvm-create.sh
new file mode 100644
index 0000000..d4a8bdf
--- /dev/null
+++ b/src/initrd/lvm-create.sh
@@ -0,0 +1,299 @@
1#!/bin/sh
2
3losetup() { /sbin/losetup "$@"; }
4
5luks_secret()
6{
7 local parms=$-; # this junk keeps set -x from being too annoying
8 set +x
9 [ -n "$luks_secret" ] || luks_secret="$(head -c256 /dev/urandom)"
10 printf %s "$luks_secret"
11 case $parms in *x*) set -x; set -x ;; esac
12}
13
14floor4()
15{
16 # Negatives round up, but aren't used.
17 echo $(($1 / 4 * 4))
18}
19
20ceil4()
21{
22 local x="$1"
23 [ $((x % 4)) -eq 0 ] || x=$((x + 4 - x % 4))
24 printf '%d\n' "$x"
25}
26
27. loop-layer.sh
28
29losetup_layers()
30{
31 bootwait samizdat-cdrom
32 local fs fs_rw
33 for fs in /cdrom/rootfs/*.btrfs; do
34 fs_rw=/"${fs##*/}".rw
35 dd if=/dev/zero of="$fs_rw" bs=1M count=10
36 losetup_snapshot "$fs" "$fs_rw" || return
37 done
38}
39
40init_samizdat()
41{
42 local blockdev="$1" imgfile="$2" uuid
43
44 losetup_layers || return
45 modprobe btrfs || return
46 btrfs device scan || return
47
48 uuid=$(choose_uuid) || return
49 [ "$uuid" ] || return
50
51 mount -t btrfs UUID="$uuid" /root || return
52
53 btrfs device add "$blockdev" /root || return
54 mount -o rw,remount /root || return
55 samizdat_movemounts "$imgfile" || return
56
57 initialize_root_filesystem || return
58
59 bootdone root-mounted
60}
61
62samizdat_movemounts()
63{
64 local imgfile="$1" mountpoint
65
66 if [ "$imgfile" ]; then
67 mountpoint=$(mountpoint_of "$imgfile") || return
68 mkdir /root/outerfs
69 mount -o move "$mountpoint" /root/outerfs
70 fi
71 mkdir /root/cdrom
72 mount -o move /cdrom /root/cdrom
73 mkdir -p /run/initramfs/samizdat/log
74 cp /var/log/* /run/initramfs/samizdat/log
75 true
76}
77
78mountpoint_of()
79{
80 local f="$1"
81 while ! mountpoint -q "$f"; do
82 f=$(dirname "$f")
83 [ "$f" != '.' ] || return 1
84 done
85 printf '%s\n' "$f"
86}
87
88initialize_root_filesystem()
89{
90 rm -r /root/root
91 btrfs subvolume create /root/root || return
92 mv /gpg/gnupghome /root/root/.gnupg || return
93
94 rmdir /root/srv
95 btrfs subvolume create /root/srv
96 rm -r /root/var/cache/apt/archives
97 btrfs subvolume create /root/var/cache/apt/archives || return
98
99 rmdir /root/home
100 btrfs subvolume create /root/home || return
101
102 [ -x /root/sbin/mdadm ] || cp /sbin/mdadm /root/sbin/
103 # Copy these over unconditionally, because they ought to remain in sync with
104 # the initrd.
105 cp /bin/mdadm-dup.sh /root/sbin/
106 cp /bin/samizdat-eject.sh /root/sbin/
107
108 sed -i -e 's/^root:x:/root::/' /root/etc/passwd
109 cp /patchroot/* /root/root/
110
111 true
112}
113
114# Get the uuid of the filesystem with the most devices,
115# excluding filesystems that don't incorporate loop devices.
116# This is used to choose the latest seed -- which should have
117# the most layers.
118choose_uuid()
119{
120 local seen_loop= seen_uuid= seen_devs=
121 btrfs filesystem show |
122 while read line; do
123 case "$line" in
124 Label*)
125 seen_uuid=${line##*uuid: }
126 seen_devs=
127 seen_loop=
128 ;;
129 *Total\ devices*)
130 seen_devs=${line#*Total devices }
131 seen_devs=${seen_devs%% *}
132 ;;
133 *path\ /dev/mapper/*)
134 seen_loop=t;;
135 esac
136 [ "$seen_loop" ] && echo "$seen_devs $seen_uuid"
137 done |
138 uniq | sort -nr | head -n1 | (read _ x; echo $x)
139}
140
141filesystem_incomplete()
142{
143 local n
144 n=$(btrfs filesystem show "$1" | sed -ne 's/.*Total devices \([^ ]*\) .*/\1/p')
145 [ "$n" != 1 ]
146}
147
148open_samizdat()
149{
150 local imgfile="$1" keyfile="$2"
151 open_samizdat_blockdev "$imgfile" "$keyfile" || return
152 local blockdev=/dev/mapper/samizdatcrypt fs
153
154 # For this part, we don't necessarily need the cdrom.
155 # Unfortunately the init_gpg code is still getting the GPG key there.
156 if filesystem_incomplete "$blockdev"; then
157 losetup_layers
158 fi
159 modprobe btrfs || return
160 btrfs device scan || return
161 mount -t btrfs "$blockdev" /root || return
162 samizdat_movemounts "$imgfile"
163 LoSetup -D
164 bootdone root-mounted
165}
166
167init_samizdat_lodev()
168{
169 local imgfile="$1" megs=$(ceil4 "$2") dev
170 truncate -s ${megs}M "$imgfile" || return
171 dev=$(losetup -f) && losetup "$dev" "$imgfile" || return
172 echo "$dev"
173}
174
175open_samizdat_blockdev()
176{
177 local imgfile="$1" keyfile="$2" dev
178 local cryptname=samizdatcrypt
179 dev=$(losetup -f) && losetup "$dev" "$imgfile" || return
180
181 gpg2 --verify "$keyfile" || return
182 # The first --decrypt merely strips the signature. The option is
183 # poorly named for that case.
184 gpg2 --decrypt "$keyfile" | gpg2 --decrypt | cryptsetup --key-file - luksOpen "$dev" "$cryptname" || return
185
186 [ -b /dev/mapper/"$cryptname" ] || return
187
188}
189
190init_samizdat_blockdev()
191{
192 local imgfile="$1" megs="$2" keyfile="$3" dev
193 local cryptname=samizdatcrypt
194
195 dev=$(init_samizdat_lodev "$imgfile" "$megs") || return
196
197 [ ! -b /dev/mapper/"$cryptname" ] || return
198
199 luks_secret >/dev/null
200 luks_secret | gpg2 --default-recipient-self --encrypt --armor | gpg2 --clearsign --output "$keyfile" || return
201
202 luks_secret | cryptsetup luksFormat "$dev" - || return
203 cryptsetup luksDump "$dev" >&2
204 luks_secret | cryptsetup --key-file - luksOpen "$dev" "$cryptname" || return
205
206 [ -b /dev/mapper/"$cryptname" ] || return
207}
208
209majmin()
210{
211 local dev="$1" major minor
212 eval $(stat -c 'major=%t minor=%T' "$dev") || return
213 [ "$major" -a "$minor" ] || return
214 printf '%d:%d\n' 0x$major 0x$minor
215}
216
217cryptdev_to_dev()
218{
219 local dev="$1" majmin
220 majmin=$(majmin "$dev") || return
221 set -- /sys/dev/block/$majmin/slaves/*
222 [ $# = 1 ] || return
223
224 cryptsetup status "$dev" |while read k v; do if [ "$k" = device: ]; then echo $v; break; fi; done
225}
226
227cryptdev_to_backing_file()
228{
229 local dev="$1" majmin result
230 majmin="$(majmin "$dev")" || return
231 set -- /sys/dev/block/$majmin/slaves/*
232 [ $# = 1 ] || return
233 read result < "$1"/loop/backing_file || return
234 printf '%s\n' "$result"
235}
236
237lodev_to_file()
238{
239 local result majmin dev="$1"
240 majmin="$(majmin "$dev")" || return
241 read result < /sys/dev/block/$majmin/loop/backing_file || return
242 printf '%s' "$result"
243}
244
245mountpoint_to_dev()
246{
247 local wantmp="$1" dev mp rest
248 mountpoint -q "$wantmp" || return
249 while read dev mp rest; do if [ "$mp" = "$wantmp" ]; then echo "$dev"; return; fi; done < /proc/mounts
250 return 1
251}
252
253get_cdrom_sizelimit()
254{
255 # returns bytes
256 local dev="$1" sectors
257 sectors=$(blockdev --getsz "$dev") || return
258 if dd count=2 if="$dev" bs=2048 skip=$((sectors/4 - 2)) of=/dev/null 2>/dev/null; then
259 return
260 else
261 echo $(((sectors-8)*512))
262 fi
263}
264
265init_gpg()
266{
267 bootwait samizdat-cdrom
268 export GNUPGHOME=/gpg/gnupghome
269 mkdir -p "$GNUPGHOME"
270 (umask 077; rsync --exclude '/luks-key*' --ignore-existing -rpP /cdrom/gnupghome/ "$GNUPGHOME")
271
272 if samizdat-password-agent >/var/log/samizdat-password-agent.log 2>&1; then
273 clear
274 true
275 else
276 false
277 fi
278}
279
280start_meter()
281{
282 local startmsg="$*"
283 (exec >&4
284 clear
285 echo -n $startmsg
286 set +x
287 while sleep 2; do
288 echo -n .
289 done) &
290 meterpid=$!
291}
292
293stop_meter()
294{
295 local endmsg="$*"
296 kill $meterpid
297 echo " $endmsg" >&4
298}
299
diff --git a/src/initrd/lvm.conf b/src/initrd/lvm.conf
new file mode 100644
index 0000000..0c1289f
--- /dev/null
+++ b/src/initrd/lvm.conf
@@ -0,0 +1,773 @@
1# This is an example configuration file for the LVM2 system.
2# It contains the default settings that would be used if there was no
3# /etc/lvm/lvm.conf file.
4#
5# Refer to 'man lvm.conf' for further information including the file layout.
6#
7# To put this file in a different directory and override /etc/lvm set
8# the environment variable LVM_SYSTEM_DIR before running the tools.
9#
10# N.B. Take care that each setting only appears once if uncommenting
11# example settings in this file.
12
13
14# This section allows you to configure which block devices should
15# be used by the LVM system.
16devices {
17
18 # Where do you want your volume groups to appear ?
19 dir = "/dev"
20
21 # An array of directories that contain the device nodes you wish
22 # to use with LVM2.
23 scan = [ "/dev" ]
24
25 # If set, the cache of block device nodes with all associated symlinks
26 # will be constructed out of the existing udev database content.
27 # This avoids using and opening any inapplicable non-block devices or
28 # subdirectories found in the device directory. This setting is applied
29 # to udev-managed device directory only, other directories will be scanned
30 # fully. LVM2 needs to be compiled with udev support for this setting to
31 # take effect. N.B. Any device node or symlink not managed by udev in
32 # udev directory will be ignored with this setting on.
33 obtain_device_list_from_udev = 1
34
35 # If several entries in the scanned directories correspond to the
36 # same block device and the tools need to display a name for device,
37 # all the pathnames are matched against each item in the following
38 # list of regular expressions in turn and the first match is used.
39 preferred_names = [ ]
40
41 # Try to avoid using undescriptive /dev/dm-N names, if present.
42 # preferred_names = [ "^/dev/mpath/", "^/dev/mapper/mpath", "^/dev/[hs]d" ]
43
44 # A filter that tells LVM2 to only use a restricted set of devices.
45 # The filter consists of an array of regular expressions. These
46 # expressions can be delimited by a character of your choice, and
47 # prefixed with either an 'a' (for accept) or 'r' (for reject).
48 # The first expression found to match a device name determines if
49 # the device will be accepted or rejected (ignored). Devices that
50 # don't match any patterns are accepted.
51
52 # Be careful if there there are symbolic links or multiple filesystem
53 # entries for the same device as each name is checked separately against
54 # the list of patterns. The effect is that if the first pattern in the
55 # list to match a name is an 'a' pattern for any of the names, the device
56 # is accepted; otherwise if the first pattern in the list to match a name
57 # is an 'r' pattern for any of the names it is rejected; otherwise it is
58 # accepted.
59
60 # Don't have more than one filter line active at once: only one gets used.
61
62 # Run vgscan after you change this parameter to ensure that
63 # the cache file gets regenerated (see below).
64 # If it doesn't do what you expect, check the output of 'vgscan -vvvv'.
65
66
67 # By default we accept every block device:
68 filter = [ "a/.*/" ]
69
70 # Exclude the cdrom drive
71 # filter = [ "r|/dev/cdrom|" ]
72
73 # When testing I like to work with just loopback devices:
74 # filter = [ "a/loop/", "r/.*/" ]
75
76 # Or maybe all loops and ide drives except hdc:
77 # filter =[ "a|loop|", "r|/dev/hdc|", "a|/dev/ide|", "r|.*|" ]
78
79 # Use anchors if you want to be really specific
80 # filter = [ "a|^/dev/hda8$|", "r/.*/" ]
81
82 # The results of the filtering are cached on disk to avoid
83 # rescanning dud devices (which can take a very long time).
84 # By default this cache is stored in the /etc/lvm/cache directory
85 # in a file called '.cache'.
86 # It is safe to delete the contents: the tools regenerate it.
87 # (The old setting 'cache' is still respected if neither of
88 # these new ones is present.)
89 cache_dir = "/run/lvm"
90 cache_file_prefix = ""
91
92 # You can turn off writing this cache file by setting this to 0.
93 write_cache_state = 1
94
95 # Advanced settings.
96
97 # List of pairs of additional acceptable block device types found
98 # in /proc/devices with maximum (non-zero) number of partitions.
99 # types = [ "fd", 16 ]
100
101 # If sysfs is mounted (2.6 kernels) restrict device scanning to
102 # the block devices it believes are valid.
103 # 1 enables; 0 disables.
104 sysfs_scan = 1
105
106 # By default, LVM2 will ignore devices used as component paths
107 # of device-mapper multipath devices.
108 # 1 enables; 0 disables.
109 multipath_component_detection = 1
110
111 # By default, LVM2 will ignore devices used as components of
112 # software RAID (md) devices by looking for md superblocks.
113 # 1 enables; 0 disables.
114 md_component_detection = 1
115
116 # By default, if a PV is placed directly upon an md device, LVM2
117 # will align its data blocks with the md device's stripe-width.
118 # 1 enables; 0 disables.
119 md_chunk_alignment = 1
120
121 # Default alignment of the start of a data area in MB. If set to 0,
122 # a value of 64KB will be used. Set to 1 for 1MiB, 2 for 2MiB, etc.
123 # default_data_alignment = 1
124
125 # By default, the start of a PV's data area will be a multiple of
126 # the 'minimum_io_size' or 'optimal_io_size' exposed in sysfs.
127 # - minimum_io_size - the smallest request the device can perform
128 # w/o incurring a read-modify-write penalty (e.g. MD's chunk size)
129 # - optimal_io_size - the device's preferred unit of receiving I/O
130 # (e.g. MD's stripe width)
131 # minimum_io_size is used if optimal_io_size is undefined (0).
132 # If md_chunk_alignment is enabled, that detects the optimal_io_size.
133 # This setting takes precedence over md_chunk_alignment.
134 # 1 enables; 0 disables.
135 data_alignment_detection = 1
136
137 # Alignment (in KB) of start of data area when creating a new PV.
138 # md_chunk_alignment and data_alignment_detection are disabled if set.
139 # Set to 0 for the default alignment (see: data_alignment_default)
140 # or page size, if larger.
141 data_alignment = 0
142
143 # By default, the start of the PV's aligned data area will be shifted by
144 # the 'alignment_offset' exposed in sysfs. This offset is often 0 but
145 # may be non-zero; e.g.: certain 4KB sector drives that compensate for
146 # windows partitioning will have an alignment_offset of 3584 bytes
147 # (sector 7 is the lowest aligned logical block, the 4KB sectors start
148 # at LBA -1, and consequently sector 63 is aligned on a 4KB boundary).
149 # But note that pvcreate --dataalignmentoffset will skip this detection.
150 # 1 enables; 0 disables.
151 data_alignment_offset_detection = 1
152
153 # If, while scanning the system for PVs, LVM2 encounters a device-mapper
154 # device that has its I/O suspended, it waits for it to become accessible.
155 # Set this to 1 to skip such devices. This should only be needed
156 # in recovery situations.
157 ignore_suspended_devices = 0
158
159 # During each LVM operation errors received from each device are counted.
160 # If the counter of a particular device exceeds the limit set here, no
161 # further I/O is sent to that device for the remainder of the respective
162 # operation. Setting the parameter to 0 disables the counters altogether.
163 disable_after_error_count = 0
164
165 # Allow use of pvcreate --uuid without requiring --restorefile.
166 require_restorefile_with_uuid = 1
167
168 # Minimum size (in KB) of block devices which can be used as PVs.
169 # In a clustered environment all nodes must use the same value.
170 # Any value smaller than 512KB is ignored.
171
172 # Ignore devices smaller than 2MB such as floppy drives.
173 pv_min_size = 2048
174
175 # The original built-in setting was 512 up to and including version 2.02.84.
176 # pv_min_size = 512
177
178 # Issue discards to a logical volumes's underlying physical volume(s) when
179 # the logical volume is no longer using the physical volumes' space (e.g.
180 # lvremove, lvreduce, etc). Discards inform the storage that a region is
181 # no longer in use. Storage that supports discards advertise the protocol
182 # specific way discards should be issued by the kernel (TRIM, UNMAP, or
183 # WRITE SAME with UNMAP bit set). Not all storage will support or benefit
184 # from discards but SSDs and thinly provisioned LUNs generally do. If set
185 # to 1, discards will only be issued if both the storage and kernel provide
186 # support.
187 # 1 enables; 0 disables.
188 issue_discards = 0
189}
190
191# This section allows you to configure the way in which LVM selects
192# free space for its Logical Volumes.
193#allocation {
194# When searching for free space to extend an LV, the "cling"
195# allocation policy will choose space on the same PVs as the last
196# segment of the existing LV. If there is insufficient space and a
197# list of tags is defined here, it will check whether any of them are
198# attached to the PVs concerned and then seek to match those PV tags
199# between existing extents and new extents.
200# Use the special tag "@*" as a wildcard to match any PV tag.
201#
202# Example: LVs are mirrored between two sites within a single VG.
203# PVs are tagged with either @site1 or @site2 to indicate where
204# they are situated.
205#
206# cling_tag_list = [ "@site1", "@site2" ]
207# cling_tag_list = [ "@*" ]
208#
209# Changes made in version 2.02.85 extended the reach of the 'cling'
210# policies to detect more situations where data can be grouped
211# onto the same disks. Set this to 0 to revert to the previous
212# algorithm.
213#
214# maximise_cling = 1
215#
216# Set to 1 to guarantee that mirror logs will always be placed on
217# different PVs from the mirror images. This was the default
218# until version 2.02.85.
219#
220# mirror_logs_require_separate_pvs = 0
221#
222# Set to 1 to guarantee that thin pool metadata will always
223# be placed on different PVs from the pool data.
224#
225# thin_pool_metadata_require_separate_pvs = 0
226#}
227
228# This section that allows you to configure the nature of the
229# information that LVM2 reports.
230log {
231
232 # Controls the messages sent to stdout or stderr.
233 # There are three levels of verbosity, 3 being the most verbose.
234 verbose = 0
235
236 # Should we send log messages through syslog?
237 # 1 is yes; 0 is no.
238 syslog = 1
239
240 # Should we log error and debug messages to a file?
241 # By default there is no log file.
242 #file = "/var/log/lvm2.log"
243
244 # Should we overwrite the log file each time the program is run?
245 # By default we append.
246 overwrite = 0
247
248 # What level of log messages should we send to the log file and/or syslog?
249 # There are 6 syslog-like log levels currently in use - 2 to 7 inclusive.
250 # 7 is the most verbose (LOG_DEBUG).
251 level = 0
252
253 # Format of output messages
254 # Whether or not (1 or 0) to indent messages according to their severity
255 indent = 1
256
257 # Whether or not (1 or 0) to display the command name on each line output
258 command_names = 0
259
260 # A prefix to use before the message text (but after the command name,
261 # if selected). Default is two spaces, so you can see/grep the severity
262 # of each message.
263 prefix = " "
264
265 # To make the messages look similar to the original LVM tools use:
266 # indent = 0
267 # command_names = 1
268 # prefix = " -- "
269
270 # Set this if you want log messages during activation.
271 # Don't use this in low memory situations (can deadlock).
272 # activation = 0
273}
274
275# Configuration of metadata backups and archiving. In LVM2 when we
276# talk about a 'backup' we mean making a copy of the metadata for the
277# *current* system. The 'archive' contains old metadata configurations.
278# Backups are stored in a human readeable text format.
279backup {
280
281 # Should we maintain a backup of the current metadata configuration ?
282 # Use 1 for Yes; 0 for No.
283 # Think very hard before turning this off!
284 backup = 1
285
286 # Where shall we keep it ?
287 # Remember to back up this directory regularly!
288 backup_dir = "/etc/lvm/backup"
289
290 # Should we maintain an archive of old metadata configurations.
291 # Use 1 for Yes; 0 for No.
292 # On by default. Think very hard before turning this off.
293 archive = 1
294
295 # Where should archived files go ?
296 # Remember to back up this directory regularly!
297 archive_dir = "/etc/lvm/archive"
298
299 # What is the minimum number of archive files you wish to keep ?
300 retain_min = 10
301
302 # What is the minimum time you wish to keep an archive file for ?
303 retain_days = 30
304}
305
306# Settings for the running LVM2 in shell (readline) mode.
307shell {
308
309 # Number of lines of history to store in ~/.lvm_history
310 history_size = 100
311}
312
313
314# Miscellaneous global LVM2 settings
315global {
316
317 # The file creation mask for any files and directories created.
318 # Interpreted as octal if the first digit is zero.
319 umask = 077
320
321 # Allow other users to read the files
322 #umask = 022
323
324 # Enabling test mode means that no changes to the on disk metadata
325 # will be made. Equivalent to having the -t option on every
326 # command. Defaults to off.
327 test = 0
328
329 # Default value for --units argument
330 units = "h"
331
332 # Since version 2.02.54, the tools distinguish between powers of
333 # 1024 bytes (e.g. KiB, MiB, GiB) and powers of 1000 bytes (e.g.
334 # KB, MB, GB).
335 # If you have scripts that depend on the old behaviour, set this to 0
336 # temporarily until you update them.
337 si_unit_consistency = 1
338
339 # Whether or not to communicate with the kernel device-mapper.
340 # Set to 0 if you want to use the tools to manipulate LVM metadata
341 # without activating any logical volumes.
342 # If the device-mapper kernel driver is not present in your kernel
343 # setting this to 0 should suppress the error messages.
344 activation = 1
345
346 # If we can't communicate with device-mapper, should we try running
347 # the LVM1 tools?
348 # This option only applies to 2.4 kernels and is provided to help you
349 # switch between device-mapper kernels and LVM1 kernels.
350 # The LVM1 tools need to be installed with .lvm1 suffices
351 # e.g. vgscan.lvm1 and they will stop working after you start using
352 # the new lvm2 on-disk metadata format.
353 # The default value is set when the tools are built.
354 # fallback_to_lvm1 = 0
355
356 # The default metadata format that commands should use - "lvm1" or "lvm2".
357 # The command line override is -M1 or -M2.
358 # Defaults to "lvm2".
359 # format = "lvm2"
360
361 # Location of proc filesystem
362 proc = "/proc"
363
364 # Type of locking to use. Defaults to local file-based locking (1).
365 # Turn locking off by setting to 0 (dangerous: risks metadata corruption
366 # if LVM2 commands get run concurrently).
367 # Type 2 uses the external shared library locking_library.
368 # Type 3 uses built-in clustered locking.
369 # Type 4 uses read-only locking which forbids any operations that might
370 # change metadata.
371 locking_type = 1
372
373 # Set to 0 to fail when a lock request cannot be satisfied immediately.
374 wait_for_locks = 1
375
376 # If using external locking (type 2) and initialisation fails,
377 # with this set to 1 an attempt will be made to use the built-in
378 # clustered locking.
379 # If you are using a customised locking_library you should set this to 0.
380 fallback_to_clustered_locking = 1
381
382 # If an attempt to initialise type 2 or type 3 locking failed, perhaps
383 # because cluster components such as clvmd are not running, with this set
384 # to 1 an attempt will be made to use local file-based locking (type 1).
385 # If this succeeds, only commands against local volume groups will proceed.
386 # Volume Groups marked as clustered will be ignored.
387 fallback_to_local_locking = 1
388
389 # Local non-LV directory that holds file-based locks while commands are
390 # in progress. A directory like /tmp that may get wiped on reboot is OK.
391 locking_dir = "/run/lock/lvm"
392
393 # Whenever there are competing read-only and read-write access requests for
394 # a volume group's metadata, instead of always granting the read-only
395 # requests immediately, delay them to allow the read-write requests to be
396 # serviced. Without this setting, write access may be stalled by a high
397 # volume of read-only requests.
398 # NB. This option only affects locking_type = 1 viz. local file-based
399 # locking.
400 prioritise_write_locks = 1
401
402 # Other entries can go here to allow you to load shared libraries
403 # e.g. if support for LVM1 metadata was compiled as a shared library use
404 # format_libraries = "liblvm2format1.so"
405 # Full pathnames can be given.
406
407 # Search this directory first for shared libraries.
408 # library_dir = "/lib/lvm2"
409
410 # The external locking library to load if locking_type is set to 2.
411 # locking_library = "liblvm2clusterlock.so"
412
413 # Treat any internal errors as fatal errors, aborting the process that
414 # encountered the internal error. Please only enable for debugging.
415 abort_on_internal_errors = 0
416
417 # Check whether CRC is matching when parsed VG is used multiple times.
418 # This is useful to catch unexpected internal cached volume group
419 # structure modification. Please only enable for debugging.
420 detect_internal_vg_cache_corruption = 0
421
422 # If set to 1, no operations that change on-disk metadata will be permitted.
423 # Additionally, read-only commands that encounter metadata in need of repair
424 # will still be allowed to proceed exactly as if the repair had been
425 # performed (except for the unchanged vg_seqno).
426 # Inappropriate use could mess up your system, so seek advice first!
427 metadata_read_only = 0
428
429 # 'mirror_segtype_default' defines which segtype will be used when the
430 # shorthand '-m' option is used for mirroring. The possible options are:
431 #
432 # "mirror" - The original RAID1 implementation provided by LVM2/DM. It is
433 # characterized by a flexible log solution (core, disk, mirrored)
434 # and by the necessity to block I/O while reconfiguring in the
435 # event of a failure. Snapshots of this type of RAID1 can be
436 # problematic.
437 #
438 # "raid1" - This implementation leverages MD's RAID1 personality through
439 # device-mapper. It is characterized by a lack of log options.
440 # (A log is always allocated for every device and they are placed
441 # on the same device as the image - no separate devices are
442 # required.) This mirror implementation does not require I/O
443 # to be blocked in the kernel in the event of a failure.
444 #
445 # Specify the '--type <mirror|raid1>' option to override this default
446 # setting.
447 mirror_segtype_default = "mirror"
448
449 # The default format for displaying LV names in lvdisplay was changed
450 # in version 2.02.89 to show the LV name and path separately.
451 # Previously this was always shown as /dev/vgname/lvname even when that
452 # was never a valid path in the /dev filesystem.
453 # Set to 1 to reinstate the previous format.
454 #
455 # lvdisplay_shows_full_device_path = 0
456
457 # Whether to use (trust) a running instance of lvmetad. If this is set to
458 # 0, all commands fall back to the usual scanning mechanisms. When set to 1
459 # *and* when lvmetad is running (it is not auto-started), the volume group
460 # metadata and PV state flags are obtained from the lvmetad instance and no
461 # scanning is done by the individual commands. In a setup with lvmetad,
462 # lvmetad udev rules *must* be set up for LVM to work correctly. Without
463 # proper udev rules, all changes in block device configuration will be
464 # *ignored* until a manual 'vgscan' is performed.
465 use_lvmetad = 0
466}
467
468activation {
469 # Set to 1 to perform internal checks on the operations issued to
470 # libdevmapper. Useful for debugging problems with activation.
471 # Some of the checks may be expensive, so it's best to use this
472 # only when there seems to be a problem.
473 checks = 0
474
475 # Set to 0 to disable udev synchronisation (if compiled into the binaries).
476 # Processes will not wait for notification from udev.
477 # They will continue irrespective of any possible udev processing
478 # in the background. You should only use this if udev is not running
479 # or has rules that ignore the devices LVM2 creates.
480 # The command line argument --nodevsync takes precedence over this setting.
481 # If set to 1 when udev is not running, and there are LVM2 processes
482 # waiting for udev, run 'dmsetup udevcomplete_all' manually to wake them up.
483 udev_sync = 1
484
485 # Set to 0 to disable the udev rules installed by LVM2 (if built with
486 # --enable-udev_rules). LVM2 will then manage the /dev nodes and symlinks
487 # for active logical volumes directly itself.
488 # N.B. Manual intervention may be required if this setting is changed
489 # while any logical volumes are active.
490 udev_rules = 1
491
492 # Set to 1 for LVM2 to verify operations performed by udev. This turns on
493 # additional checks (and if necessary, repairs) on entries in the device
494 # directory after udev has completed processing its events.
495 # Useful for diagnosing problems with LVM2/udev interactions.
496 verify_udev_operations = 1
497
498 # If set to 1 and if deactivation of an LV fails, perhaps because
499 # a process run from a quick udev rule temporarily opened the device,
500 # retry the operation for a few seconds before failing.
501 retry_deactivation = 1
502
503 # How to fill in missing stripes if activating an incomplete volume.
504 # Using "error" will make inaccessible parts of the device return
505 # I/O errors on access. You can instead use a device path, in which
506 # case, that device will be used to in place of missing stripes.
507 # But note that using anything other than "error" with mirrored
508 # or snapshotted volumes is likely to result in data corruption.
509 missing_stripe_filler = "error"
510
511 # The linear target is an optimised version of the striped target
512 # that only handles a single stripe. Set this to 0 to disable this
513 # optimisation and always use the striped target.
514 use_linear_target = 1
515
516 # How much stack (in KB) to reserve for use while devices suspended
517 # Prior to version 2.02.89 this used to be set to 256KB
518 reserved_stack = 64
519
520 # How much memory (in KB) to reserve for use while devices suspended
521 reserved_memory = 8192
522
523 # Nice value used while devices suspended
524 process_priority = -18
525
526 # If volume_list is defined, each LV is only activated if there is a
527 # match against the list.
528 # "vgname" and "vgname/lvname" are matched exactly.
529 # "@tag" matches any tag set in the LV or VG.
530 # "@*" matches if any tag defined on the host is also set in the LV or VG
531 #
532 # volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]
533
534 # If read_only_volume_list is defined, each LV that is to be activated
535 # is checked against the list, and if it matches, it as activated
536 # in read-only mode. (This overrides '--permission rw' stored in the
537 # metadata.)
538 # "vgname" and "vgname/lvname" are matched exactly.
539 # "@tag" matches any tag set in the LV or VG.
540 # "@*" matches if any tag defined on the host is also set in the LV or VG
541 #
542 # read_only_volume_list = [ "vg1", "vg2/lvol1", "@tag1", "@*" ]
543
544 # Size (in KB) of each copy operation when mirroring
545 mirror_region_size = 512
546
547 # Setting to use when there is no readahead value stored in the metadata.
548 #
549 # "none" - Disable readahead.
550 # "auto" - Use default value chosen by kernel.
551 readahead = "auto"
552
553 # 'raid_fault_policy' defines how a device failure in a RAID logical
554 # volume is handled. This includes logical volumes that have the following
555 # segment types: raid1, raid4, raid5*, and raid6*.
556 #
557 # In the event of a failure, the following policies will determine what
558 # actions are performed during the automated response to failures (when
559 # dmeventd is monitoring the RAID logical volume) and when 'lvconvert' is
560 # called manually with the options '--repair' and '--use-policies'.
561 #
562 # "warn" - Use the system log to warn the user that a device in the RAID
563 # logical volume has failed. It is left to the user to run
564 # 'lvconvert --repair' manually to remove or replace the failed
565 # device. As long as the number of failed devices does not
566 # exceed the redundancy of the logical volume (1 device for
567 # raid4/5, 2 for raid6, etc) the logical volume will remain
568 # usable.
569 #
570 # "allocate" - Attempt to use any extra physical volumes in the volume
571 # group as spares and replace faulty devices.
572 #
573 raid_fault_policy = "warn"
574
575 # 'mirror_image_fault_policy' and 'mirror_log_fault_policy' define
576 # how a device failure affecting a mirror (of "mirror" segment type) is
577 # handled. A mirror is composed of mirror images (copies) and a log.
578 # A disk log ensures that a mirror does not need to be re-synced
579 # (all copies made the same) every time a machine reboots or crashes.
580 #
581 # In the event of a failure, the specified policy will be used to determine
582 # what happens. This applies to automatic repairs (when the mirror is being
583 # monitored by dmeventd) and to manual lvconvert --repair when
584 # --use-policies is given.
585 #
586 # "remove" - Simply remove the faulty device and run without it. If
587 # the log device fails, the mirror would convert to using
588 # an in-memory log. This means the mirror will not
589 # remember its sync status across crashes/reboots and
590 # the entire mirror will be re-synced. If a
591 # mirror image fails, the mirror will convert to a
592 # non-mirrored device if there is only one remaining good
593 # copy.
594 #
595 # "allocate" - Remove the faulty device and try to allocate space on
596 # a new device to be a replacement for the failed device.
597 # Using this policy for the log is fast and maintains the
598 # ability to remember sync state through crashes/reboots.
599 # Using this policy for a mirror device is slow, as it
600 # requires the mirror to resynchronize the devices, but it
601 # will preserve the mirror characteristic of the device.
602 # This policy acts like "remove" if no suitable device and
603 # space can be allocated for the replacement.
604 #
605 # "allocate_anywhere" - Not yet implemented. Useful to place the log device
606 # temporarily on same physical volume as one of the mirror
607 # images. This policy is not recommended for mirror devices
608 # since it would break the redundant nature of the mirror. This
609 # policy acts like "remove" if no suitable device and space can
610 # be allocated for the replacement.
611
612 mirror_log_fault_policy = "allocate"
613 mirror_image_fault_policy = "remove"
614
615 # 'snapshot_autoextend_threshold' and 'snapshot_autoextend_percent' define
616 # how to handle automatic snapshot extension. The former defines when the
617 # snapshot should be extended: when its space usage exceeds this many
618 # percent. The latter defines how much extra space should be allocated for
619 # the snapshot, in percent of its current size.
620 #
621 # For example, if you set snapshot_autoextend_threshold to 70 and
622 # snapshot_autoextend_percent to 20, whenever a snapshot exceeds 70% usage,
623 # it will be extended by another 20%. For a 1G snapshot, using up 700M will
624 # trigger a resize to 1.2G. When the usage exceeds 840M, the snapshot will
625 # be extended to 1.44G, and so on.
626 #
627 # Setting snapshot_autoextend_threshold to 100 disables automatic
628 # extensions. The minimum value is 50 (A setting below 50 will be treated
629 # as 50).
630
631 snapshot_autoextend_threshold = 100
632 snapshot_autoextend_percent = 20
633
634 # 'thin_pool_autoextend_threshold' and 'thin_pool_autoextend_percent' define
635 # how to handle automatic pool extension. The former defines when the
636 # pool should be extended: when its space usage exceeds this many
637 # percent. The latter defines how much extra space should be allocated for
638 # the pool, in percent of its current size.
639 #
640 # For example, if you set thin_pool_autoextend_threshold to 70 and
641 # thin_pool_autoextend_percent to 20, whenever a pool exceeds 70% usage,
642 # it will be extended by another 20%. For a 1G pool, using up 700M will
643 # trigger a resize to 1.2G. When the usage exceeds 840M, the pool will
644 # be extended to 1.44G, and so on.
645 #
646 # Setting thin_pool_autoextend_threshold to 100 disables automatic
647 # extensions. The minimum value is 50 (A setting below 50 will be treated
648 # as 50).
649
650 thin_pool_autoextend_threshold = 100
651 thin_pool_autoextend_percent = 20
652
653 # Full path of the utility called to check that a thin metadata device
654 # is in a state that allows it to be used.
655 # Each time a thin pool needs to be activated, this utility is executed.
656 # The activation will only proceed if the utility has an exit status of 0.
657 # Set to "" to skip this check. (Not recommended.)
658 # The thin tools are available as part of the device-mapper-persistent-data
659 # package from https://github.com/jthornber/thin-provisioning-tools.
660 #
661 thin_check_executable = "/sbin/thin_check -q"
662
663 # While activating devices, I/O to devices being (re)configured is
664 # suspended, and as a precaution against deadlocks, LVM2 needs to pin
665 # any memory it is using so it is not paged out. Groups of pages that
666 # are known not to be accessed during activation need not be pinned
667 # into memory. Each string listed in this setting is compared against
668 # each line in /proc/self/maps, and the pages corresponding to any
669 # lines that match are not pinned. On some systems locale-archive was
670 # found to make up over 80% of the memory used by the process.
671 # mlock_filter = [ "locale/locale-archive", "gconv/gconv-modules.cache" ]
672
673 # Set to 1 to revert to the default behaviour prior to version 2.02.62
674 # which used mlockall() to pin the whole process's memory while activating
675 # devices.
676 use_mlockall = 0
677
678 # Monitoring is enabled by default when activating logical volumes.
679 # Set to 0 to disable monitoring or use the --ignoremonitoring option.
680 monitoring = 0
681
682 # When pvmove or lvconvert must wait for the kernel to finish
683 # synchronising or merging data, they check and report progress
684 # at intervals of this number of seconds. The default is 15 seconds.
685 # If this is set to 0 and there is only one thing to wait for, there
686 # are no progress reports, but the process is awoken immediately the
687 # operation is complete.
688 polling_interval = 15
689}
690
691
692####################
693# Advanced section #
694####################
695
696# Metadata settings
697#
698# metadata {
699 # Default number of copies of metadata to hold on each PV. 0, 1 or 2.
700 # You might want to override it from the command line with 0
701 # when running pvcreate on new PVs which are to be added to large VGs.
702
703 # pvmetadatacopies = 1
704
705 # Default number of copies of metadata to maintain for each VG.
706 # If set to a non-zero value, LVM automatically chooses which of
707 # the available metadata areas to use to achieve the requested
708 # number of copies of the VG metadata. If you set a value larger
709 # than the the total number of metadata areas available then
710 # metadata is stored in them all.
711 # The default value of 0 ("unmanaged") disables this automatic
712 # management and allows you to control which metadata areas
713 # are used at the individual PV level using 'pvchange
714 # --metadataignore y/n'.
715
716 # vgmetadatacopies = 0
717
718 # Approximate default size of on-disk metadata areas in sectors.
719 # You should increase this if you have large volume groups or
720 # you want to retain a large on-disk history of your metadata changes.
721
722 # pvmetadatasize = 255
723
724 # List of directories holding live copies of text format metadata.
725 # These directories must not be on logical volumes!
726 # It's possible to use LVM2 with a couple of directories here,
727 # preferably on different (non-LV) filesystems, and with no other
728 # on-disk metadata (pvmetadatacopies = 0). Or this can be in
729 # addition to on-disk metadata areas.
730 # The feature was originally added to simplify testing and is not
731 # supported under low memory situations - the machine could lock up.
732 #
733 # Never edit any files in these directories by hand unless you
734 # you are absolutely sure you know what you are doing! Use
735 # the supplied toolset to make changes (e.g. vgcfgrestore).
736
737 # dirs = [ "/etc/lvm/metadata", "/mnt/disk2/lvm/metadata2" ]
738#}
739
740# Event daemon
741#
742dmeventd {
743 # mirror_library is the library used when monitoring a mirror device.
744 #
745 # "libdevmapper-event-lvm2mirror.so" attempts to recover from
746 # failures. It removes failed devices from a volume group and
747 # reconfigures a mirror as necessary. If no mirror library is
748 # provided, mirrors are not monitored through dmeventd.
749
750 mirror_library = "libdevmapper-event-lvm2mirror.so"
751
752 # snapshot_library is the library used when monitoring a snapshot device.
753 #
754 # "libdevmapper-event-lvm2snapshot.so" monitors the filling of
755 # snapshots and emits a warning through syslog when the use of
756 # the snapshot exceeds 80%. The warning is repeated when 85%, 90% and
757 # 95% of the snapshot is filled.
758
759 snapshot_library = "libdevmapper-event-lvm2snapshot.so"
760
761 # thin_library is the library used when monitoring a thin device.
762 #
763 # "libdevmapper-event-lvm2thin.so" monitors the filling of
764 # pool and emits a warning through syslog when the use of
765 # the pool exceeds 80%. The warning is repeated when 85%, 90% and
766 # 95% of the pool is filled.
767
768 thin_library = "libdevmapper-event-lvm2thin.so"
769
770 # Full path of the dmeventd binary.
771 #
772 # executable = "/sbin/dmeventd"
773}
diff --git a/src/initrd/mdadm-dup.sh b/src/initrd/mdadm-dup.sh
new file mode 100644
index 0000000..70163a5
--- /dev/null
+++ b/src/initrd/mdadm-dup.sh
@@ -0,0 +1,217 @@
1LoSetup()
2{
3 local losetup_binary="$(which LoSetup)"
4 if [ "$losetup_binary" ]; then
5 "$losetup_binary" "$@"
6 else
7 losetup "$@"
8 fi
9}
10
11dm_snapshot()
12{
13 # TODO: eliminate duplication; this function exists elsewhere in a less generalized form
14 local ro_file rw_file cutoff_size
15 ro_file=$1
16 rw_file=$2
17 cutoff_size=$3
18
19 local ro_dev rw_dev size new_dev_name persist chunksize
20
21 if [ -b "$ro_file" ];
22 then ro_dev=$ro_file
23 else ro_dev=$(LoSetup -r -f --show "$ro_file") || return
24 fi
25
26 if [ -b "$rw_file" ];
27 then rw_dev=$rw_file
28 else rw_dev=$(LoSetup -f --show "$rw_file") || return
29 fi
30
31 if [ "$cutoff_size" -a "$cutoff_size" -gt 0 ]; then
32 size=$cutoff_size
33 else
34 size=$(blockdev --getsz "$ro_dev") || return
35 fi
36
37 new_dev_name=${ro_dev##*/}
38 persist=p
39 chunksize=16
40 dmsetup create "$new_dev_name" --table "0 $size snapshot $ro_dev $rw_dev $persist $chunksize" || return
41 wait_for_dm_device /dev/mapper/"$new_dev_name"
42 echo /dev/mapper/"$new_dev_name"
43}
44
45dm_snapshot_teardown()
46{
47 local dev="$1"
48 case "$dev" in
49 /dev/dm-*)
50 dmsetup table "$dev" | (
51 read _ _ snapshot ro_dev rw_dev _ crypt_dev _
52 case "$snapshot" in
53 snapshot)
54 dmsetup remove "$dev" || exit 1
55 # errors ignored because the loop dev can be configured to be
56 # automatically removed upon disuse
57 losetup -d /dev/block/"$rw_dev" || true
58 eject /dev/block/"$ro_dev" || true
59 ;;
60 crypt)
61 cryptsetup remove "$dev" || exit 1
62 losetup -d /dev/block/"$crypt_dev" || true
63 ;;
64 esac
65 ) || return
66 ;;
67 *) return 1 ;;
68 esac
69}
70
71wait_for_dm_device()
72{
73 # TODO: improve
74 while ! [ -e "$1" ]; do
75 sleep 1
76 done
77}
78
79dup_mount_cdrom()
80{
81 local cdrom_dev="$1" mountpoint="$2"
82
83 local sectors md_dev=/dev/md55 cdrom_rw_file=/"${cdrom_dev##*/}".rw
84
85 sectors=$(get_cdrom_sizelimit "$cdrom_dev") || return
86
87 # TODO: do we even need this backing file? We do need to trick mdadm into
88 # thinking that this is a RW device, but previously we got away with just
89 # creating a loopback device.
90 dd if=/dev/zero of="$cdrom_rw_file" bs=1K count=32 || return
91 cdrom_rw_dev=$(dm_snapshot "$cdrom_dev" "$cdrom_rw_file" "$sectors") || return
92 mdadm_dup "$cdrom_rw_dev" "$md_dev" "$sectors" || return
93 mount -t iso9660 -r $md_dev "$mountpoint"
94}
95
96get_cdrom_sizelimit()
97{
98 # returns 512-byte sectors
99 local dev="$1" sectors
100 sectors=$(blockdev --getsz "$dev") || return
101
102 # Check if we can read the last 8 sectors. With a TAO CDROM, we can't --
103 # these sectors are faux, and not part of the ISO fs. If mdadm is allowed to
104 # read them, it will mark the device failed.
105 if dd count=2 if="$dev" bs=2048 skip=$((sectors/4 - 2)) of=/dev/null 2>/dev/null; then
106 echo $sectors
107 else
108 echo $((sectors - 8))
109 fi
110}
111
112mdadm_dup()
113{
114 local input_dev="$1" md_name="$2" sectors="$3"
115
116 mdadm --build "$md_name" "${sectors:+--size=$((sectors / 2))}" \
117 --level=1 --raid-devices=1 --force --write-mostly "$input_dev" || return
118}
119
120mdadm_subdevices()
121{
122 local md_dev="$1"
123 mdadm -D "$md_dev" -Y | sed -ne 's/^MD_DEVICE_.*_DEV=//p'
124}
125
126cryptsetup_temp()
127{
128 local sectors="$1" cryptname="$2" temp_file="$3" parms=$- secret
129 set +x
130 # Add 4096 sectors for LUKS header
131 truncate -s $(((sectors + 4096) * 512)) "$temp_file" || return
132 cleartext_dev=$(LoSetup -f --show "$temp_file") || return
133 secret="$(head -c256 /dev/urandom)" || return
134 printf %s "$secret" |
135 cryptsetup luksFormat "$cleartext_dev" - || return
136 printf %s "$secret" |
137 cryptsetup --key-file - luksOpen "$cleartext_dev" "$cryptname" || return
138 unset secret
139 set "$parms"
140
141 wait_for_dm_device /dev/mapper/"$cryptname"
142 rm "$temp_file"
143 echo /dev/mapper/"$cryptname"
144}
145
146mdadm_copy_eject_crypt()
147{
148 local md_dev="$1" temp_file="$2"
149
150 [ -b "$md_dev" ] || return
151
152 local output_dev sectors
153
154 old_subdev=$(mdadm_subdevices "$md_dev"|head -n1) || return
155 [ -b "$old_subdev" ] || return
156 # TODO: truncate to the ISO fs size if the device is larger
157 sectors=$(blockdev --getsz "$md_dev") || return
158
159 output_dev=$(cryptsetup_temp "$sectors" samizdatiso "$temp_file") || return
160
161 mdadm "$md_dev" --add "$output_dev" || return
162 mdadm "$md_dev" --grow -n2 || return
163
164 mdadm_wait_remove "$md_dev" "$old_subdev" || return
165
166 mdadm "$md_dev" --grow -n1 --force || return
167 dm_snapshot_teardown "$old_subdev"
168}
169
170mdadm_copy_eject()
171{
172 local md_dev="$1" output_file="$2"
173
174 [ -b "$md_dev" ] || return
175 [ ! -e "$output_file" ] || return
176
177 local output_dev sectors
178
179 old_subdev=$(mdadm_subdevices "$md_dev"|head -n1) || return
180 [ -b "$old_subdev" ] || return
181 sectors=$(blockdev --getsz "$md_dev") || return
182
183 truncate -s $((sectors * 512)) "$output_file" || return
184 output_dev=$(LoSetup -f --show "$output_file") || return
185
186 mdadm "$md_dev" --add "$output_dev" || return
187 mdadm "$md_dev" --grow -n2 || return
188
189 mdadm_wait_remove "$md_dev" "$old_subdev" || return
190
191 mdadm "$md_dev" --grow -n1 --force || return
192 dm_snapshot_teardown "$old_subdev"
193}
194
195mdadm_wait_remove()
196{
197 # We should perhaps use mdadm --monitor's RebuildFinished event.
198
199 local dev="$1" disk="$2" tries
200 if ! mdadm --wait "$dev"; then
201 tries=1000
202 while ! mdadm --detail --test "$dev"; do
203 [ $tries -gt 0 ] || return 1
204 sleep 1
205 tries=$((tries-1))
206 done
207 fi
208
209 mdadm "$dev" --fail "$disk" || return 1
210 tries=100
211 while ! mdadm "$dev" --remove "$disk"; do
212 [ $tries -gt 0 ] || return 1
213 sleep 1
214 tries=$((tries-1))
215 done
216 return 0
217}
diff --git a/src/initrd/menu-select b/src/initrd/menu-select
new file mode 100755
index 0000000..f059052
--- /dev/null
+++ b/src/initrd/menu-select
@@ -0,0 +1,123 @@
1#!/bin/sh
2# usage:
3# $0 boot-ram - use memory-only overlay
4# $0 boot-new [dev name] [loop file] [megabytes] - create new luks-encrypted overlay
5# $0 boot-overwrite [dev name] [loop file] [megabytes] - overwrite with new luks overlay
6# $0 boot-luks [dev name] [loop file] - boot existing luks-encrypted overlay
7# $0 boot-gpg [key id] [gnupg homedir] [???] - boot any device signed with the key
8
9. lvm-create.sh
10. common.sh
11exec 4>&1
12debug_log
13
14error()
15{
16 local sleep=3
17
18 clear >&4
19 echo "error -- ${*:-:(}" >&4
20
21 if [ $sleep -gt 0 ]; then
22 echo "will try again in $sleep seconds..." >&4
23 sleep $sleep
24 fi
25 bootmenu do_trigger no_panic
26 exit
27}
28
29badopts=
30fs=
31while [ $# -ge 1 ]; do
32 case $1 in
33 --fs=*) fs="${1#--fs=}"; shift; continue ;;
34 --*) echo "error: unknown option $1"; badopts=true; shift; continue ;;
35 esac
36 break
37done
38[ -z "$badopts" ] || error 'usage error'
39
40[ $# -ge 2 -o "$1" = 'boot-ram' ] || error 'usage error'
41
42remountrw()
43{
44 local fs="$1" dev="$2" loopfile="$3"
45 if [ "$fs" = hfsplus ]; then
46 mountpoint="/mnt/${dev##*/}"
47 umount "$dev" || error
48 fsck.hfsplus -q "$dev" || error
49 mount -o force "$dev" "$mountpoint" || error
50 else
51 mount -o remount,rw "$dev" || error
52 fi
53}
54
55hwclock_to_system()
56{
57 local fs="$1" UTC=UTC
58 case "$fs" in ntfs|vfat) UTC=LOCAL ;; esac
59 printf '0.0 0 0.0\n0\n%s' $UTC > /etc/adjtime
60 hwclock --hctosys
61}
62
63case "$1" in
64 boot-ram)
65 read _ memtotal_kb _ < /proc/meminfo
66 # This doesn't make sense to me, but setting rd_size _lower_ than total
67 # memory seems to be what breaks things ('btrfs device add' hangs forever).
68 # Somehow you can fill up the filesystem and there's still space for
69 # programs and btrfs does not complain. I don't know what is going on here.
70
71 # BTW, I verified with blockdev that the device size really is being
72 # specified in KB here. I did not really believe it.
73 modprobe brd rd_nr=1 rd_size=$memtotal_kb
74
75 init_gpg || error
76 init_samizdat /dev/ram0 '' || {
77 umount /root/cdrom
78 umount /root/outerfs
79 umount /root
80 error
81 }
82 ;;
83 boot-overwrite|boot-new|boot-luks)
84 dev="$2"
85 loopfile="$3"
86 megs="$4"
87
88 [ "$1" != 'boot-new' -o ! -e "$loopfile" ] || error
89
90 remountrw "$fs" "$dev" "$loopfile" || error
91
92 hwclock_to_system "$fs"
93
94 if [ "$1" = 'boot-overwrite' ]; then
95 rm "$loopfile" "$loopfile"k
96 fi
97
98 init_gpg || error
99
100 if [ "$1" = 'boot-luks' ]; then
101 open_samizdat "$loopfile" "$loopfile"k || error
102 exit
103 fi
104
105 start_meter "Allocating ${megs}MB in '$loopfile' on $dev..."
106
107 if init_samizdat_blockdev "$loopfile" "$megs" "$loopfile"k &&
108 init_samizdat /dev/mapper/samizdatcrypt "$loopfile"; then
109 stop_meter done.
110 else
111 stop_meter error!
112 rm "$loopfile" "$loopfile"k
113 dmsetup remove samizdatcrypt
114 # TODO: more teardown
115 error
116 fi
117 ;;
118 *)
119 error "Unimplemented boot command: $*"
120 ;;
121esac
122
123# vim:ts=2 sw=2 et
diff --git a/src/initrd/samizdat-cdrom-copy b/src/initrd/samizdat-cdrom-copy
new file mode 100755
index 0000000..d4920b9
--- /dev/null
+++ b/src/initrd/samizdat-cdrom-copy
@@ -0,0 +1,75 @@
1#!/bin/sh
2md_name=$1
3lv_name=$2
4lv_dev=$3
5cdrom_loopdev=$4
6cdrom_dev=$5
7
8. lvm-create.sh
9
10mdadm_wait_remove()
11{
12 # We should perhaps use mdadm --monitor's RebuildFinished event.
13
14 local dev="$1" disk="$2" tries
15 if ! mdadm --wait "$dev"; then
16 tries=1000
17 while ! mdadm --detail --test "$dev"; do
18 [ $tries -gt 0 ] || return 1
19 sleep 1
20 tries=$((tries-1))
21 done
22 fi
23
24 mdadm "$dev" --fail "$disk" || return 1
25 tries=100
26 while ! mdadm "$dev" --remove "$disk"; do
27 [ $tries -gt 0 ] || return 1
28 sleep 1
29 tries=$((tries-1))
30 done
31 return 0
32}
33
34
35Done()
36{
37 mdadm --grow "$md_name" -n 1 --force
38 lvm lvrename "$lv_name".tmp "${lv_name#*/}"
39 losetup -d "$cdrom_loopdev"
40 [ -e /etc/mtab ] || ln -sf /proc/mounts /etc/mtab
41 eject "$cdrom_dev"
42 echo "[$$] Done."
43}
44
45exec >>/var/log/samizdat-cdrom-copy.log 2>&1
46echo "[$$] Waiting for $cdrom_loopdev ($cdrom_dev) to be removed from $md_name."
47
48if mdadm_wait_remove "$md_name" "$cdrom_loopdev"; then
49 Done;
50else
51 echo "[$$] Warning: mdadm_wait_remove() returned $?. Doing manual copy with sg_dd (using continue-on-error)."
52 mdadm -D "$md_name"
53 mdadm "$md_name" --fail "$lv_dev".tmp
54 mdadm -D "$md_name"
55 mdadm "$md_name" --remove "$lv_dev".tmp
56 mdadm -D "$md_name"
57 mdadm /dev/md55 --grow -n1 --force
58 mdadm -D "$md_name"
59
60 sizelimit=$(get_cdrom_sizelimit "$cdrom_dev")
61
62 if sg_dd bs=2048 ${sizelimit:+count=$((sizelimit/2048))} iflag=coe,coe,coe if="$cdrom_dev" of="$lv_dev".tmp retries=42; then
63 echo "[$$] sg_dd succeeded."
64 mdadm "$md_name" --grow -n 2 --assume-clean --add "$lv_dev".tmp
65 mdadm -D "$md_name"
66 if mdadm_wait_remove "$md_name" "$cdrom_loopdev"; then
67 Done;
68 else
69 echo "[$$] Error: mdadm_wait_remove() returned $? after sg_dd. Cannot eject CDROM!"
70 fi
71 else
72 echo "[$$] Error: sg_dd returned $?. Cannot eject CDROM!"
73 fi
74fi
75
diff --git a/src/initrd/samizdat-eject.sh b/src/initrd/samizdat-eject.sh
new file mode 100755
index 0000000..d95a49d
--- /dev/null
+++ b/src/initrd/samizdat-eject.sh
@@ -0,0 +1,92 @@
1#!/bin/sh
2die()
3{
4 printf '%s\n' "$*" >&2
5 exit 1
6}
7
8btrfs_subdevices()
9{
10 local mountpoint="$1"
11 btrfs filesystem show "$mountpoint" | sed -ne 's/^[ \t]*devid.* path //p'
12}
13
14btrfs_subdevice_count()
15{
16 btrfs_subdevices "$1" | wc -l
17}
18
19remove()
20{
21 for dev; do
22 (set -x; btrfs device remove "$dev" /)
23 dmsetup remove "$dev" 2>/dev/null
24 losetup -D
25 done
26}
27
28dm_name()
29{
30 dmsetup info "$1" | sed -ne 's/^Name: *//p'
31}
32
33md_ready()
34{
35 local mountpoint="$1" count dev
36 count=$(mdadm_subdevices /dev/md55|wc -l)
37 [ "$count" = 1 ] || return
38 dev=$(mdadm_subdevices /dev/md55)
39 [ "$(dm_name "$dev")" = samizdatiso ]
40}
41
42copy()
43{
44 temp_target=$(mktemp --tmpdir=/outerfs)
45 mdadm_copy_eject_crypt /dev/md55 "$temp_target"
46}
47
48. mdadm-dup.sh || exit 1
49
50target=$1
51
52if [ ! "$target" ] && mountpoint -q /srv && [ ! -e /srv/samizdat.iso ]; then
53 target=/srv/samizdat.iso
54fi
55
56[ "$target" ] || die "Usage: $0 <target filename>"
57[ ! -e "$target" ] || die "Error: file exists: $target"
58
59if ! mountpoint -q /outerfs; then
60 die "Error: /outerfs is not a mountpoint. Please mount a safe filesystem to temporarily store the ISO on /outerfs"
61fi
62
63devices=$(btrfs_subdevices /) || exit 1
64
65set --
66seen=
67for dev in $devices; do
68 [ -b "$dev" ] || exit 1
69 case "$dev" in
70 /dev/mapper/loop*) set -- "$@" "$dev" ;;
71 /dev/mapper/samizdatcrypt) seen=y ;;
72 esac
73done
74[ "$seen" ] || set -- # avoid messing up someone's btrfs!
75
76
77
78
79
80
81if ! md_ready; then
82 copy &
83fi
84
85remove "$@"
86
87wait
88
89if [ "$(btrfs_subdevice_count /)" = 1 ] && md_ready; then
90 mdadm_copy_eject /dev/md55 "$target".part &&
91 mv "$target".part "$target"
92fi
diff --git a/src/initrd/squashfs-size b/src/initrd/squashfs-size
new file mode 100755
index 0000000..74b67d7
--- /dev/null
+++ b/src/initrd/squashfs-size
@@ -0,0 +1,88 @@
1#!/bin/sh
2
3squashfs_size_ratio()
4{
5 local fn="$1"
6 #FSIZE="$(stat -c "%s" "$fn")"
7 word5() { echo $5; }
8 FSIZE="$(word5 `ls -l "$fn"`)"
9 echo $(( $FSIZE * 3367 / 1000 ))
10}
11
12squashfs_size_magicdb()
13{
14
15 get()
16 {
17 local len=$1
18 local off=$2
19 local fn="$3"
20 #local OUT=( $(od -t d$len -N$len -j $off "$fn") )
21 #echo "${OUT[1]}"
22 od -t u$len -N$len -j $off "$fn" | head -n1 | sed 's/.* //'
23 }
24
25# getReversedEndian()
26# {
27# local len=$1
28# local off=$2
29# local fn="$3"
30# #local B=( $(od -t x$len -N$len -j $off "$fn") )
31# #B="${B[1]}"
32# local B="$(od -t x$len -N$len -j $off "$fn" | head -n1 | cut -d' ' -f2)"
33# local D=
34# local C=$(( $len * 2 ))
35# while [ $C -gt 0 ]
36# do
37# C=$(( $C - 2 ))
38# D="$D${B:$C:2}"
39# done
40# D="0x$D"
41# echo $D
42# }
43 getReversedEndian()
44 {
45 local len=$1
46 local off=$2
47 local fn="$3"
48 local D=
49 local C=$len
50 while [ $C -gt 0 ]
51 do
52 C=$(( $C - 1 ))
53 D="$(od -t x1 -N1 -j $(($off+$C)) "$fn" | head -n1 | cut -d' ' -f2)$D"
54 done
55 D=$((0x$D))
56 echo $D
57 }
58
59
60 local fn="$1"
61
62 local M=$(get 4 0 "$fn")
63 local N=$(getReversedEndian 4 0 "$fn")
64 if [ $M -eq 1936814952 ]
65 then
66 # Proper endian.
67 local get=get
68 elif [ $N -eq 1936814952 ]
69 then
70 # Reversed endian.
71 local get=getReversedEndian
72 else
73 error not squashfs
74 fi
75
76 local T=$($get 2 28 "$fn")
77 if [ $T -lt 3 ]
78 then
79 local BC=$($get 4 8 "$fn")
80 else
81 local BC=$($get 8 63 "$fn")
82 fi
83
84 echo $BC
85}
86
87
88squashfs_size_ratio "$1"
diff --git a/src/initrd/umountall.sh b/src/initrd/umountall.sh
new file mode 100755
index 0000000..bf89838
--- /dev/null
+++ b/src/initrd/umountall.sh
@@ -0,0 +1,126 @@
1#!/bin/sh
2OPEN_SHELL_BEFORE_SHUTDOWN=
3
4movemount() {
5 if mountpoint -q "$1"; then
6 umount /root/"$1"
7 else
8 mkdir -p "$1"
9 mount --move /root/"$1" "$1"
10 fi
11}
12
13retry_n_delay() {
14 local n="$1" delay="$2"
15 shift 2
16 while [ "$n" -gt 0 ]; do "$@" && break; sleep $delay; n=$((n-1)); done
17}
18
19umount_all_novirtual()
20{
21 # EQUIVALENT: umount -a -t norootfs,nosysfs,noproc,notmpfs,nodevpts,nodevtmpfs
22 # busyboxy umount does not support -t, therefore:
23 tac /proc/mounts | {
24 errors=0
25 while read dev mp type opts _; do
26 case $type in
27 rootfs|sysfs|proc|tmpfs|devpts|devtmpfs) ;;
28 *) umount "$mp" || errors=$((errors+1)) ;;
29 esac
30 done
31 return $errors
32 }
33}
34
35losetup_delete_all()
36{
37 local f dev
38 for f in /sys/dev/block/7:*/loop; do
39 dev=${f#/sys/dev/block/7:}
40 dev=/dev/loop${dev%%/*}
41 losetup -d $dev
42 done
43}
44
45mdadm_stop_all()
46{
47 for md in /dev/md* /dev/md/*; do
48 test -b "$md" && mdadm --stop "$md"
49 done
50}
51
52lvm_deactivate() { lvm lvchange -v -an samizdat 11>&-; }
53
54killemdead() {
55 force= pids="$(pidof "$@")"
56 while [ "$pids" ]; do
57 kill $force $pids
58 living=
59 for p in $pids; do
60 if [ -e /proc/$p ]; then
61 living=1
62 break
63 fi
64 done
65 [ ! "$living" ] && break
66 force=-9
67 done
68}
69
70specials= movemounts= umounts=
71while read dev mp type opts _; do # N.B. order is reversed in variables
72case $mp in
73 /root/dev|/root/proc)
74 specials="$mp $specials" ;;
75 /root/sys|/root/cdrom|/root/mnt/*|/root/gpg|/root/overlay|/root/xino|/root/squashes/*)
76 movemounts="$mp $movemounts" ;;
77 /root/*)
78 umounts="$mp $umounts" ;;
79esac
80done < /proc/mounts
81
82# Unmount mounts under /root that we didn't put there
83while true; do
84 error=0; success=0
85 for m in $umounts; do
86 if umount $m; then
87 success=$((success+1))
88 else
89 error=$((error+1))
90 fi
91 done
92 [ $error = 0 ] && break
93 [ $success = 0 ] && break
94done
95
96# Move back mounts that we moved
97for m in $movemounts; do
98 movemount "${m#/root}" # TODO: error handling
99done
100
101killemdead gpg-agent samizdat-pinentry
102
103umount /root/dev
104umount /root/proc
105ln -sf /proc/mounts /etc/mtab
106
107umount_all_novirtual
108mdadm_stop_all
109losetup_delete_all
110lvm_deactivate
111cryptsetup remove samizdatcrypt
112losetup_delete_all
113umount_all_novirtual
114
115if [ "$OPEN_SHELL_BEFORE_SHUTDOWN" ]; then
116 read cmd < /halt
117 echo
118 echo "Remove cdrom and press ctrl-d to run '$cmd'."
119 /bin/sh -i
120fi
121
122read cmd < /halt && $cmd
123sleep 1
124
125echo "Error! Starting emergency shell with pid 1."
126exec /bin/sh -i
diff --git a/src/initrd/vol_id b/src/initrd/vol_id
new file mode 100755
index 0000000..5cd24a1
--- /dev/null
+++ b/src/initrd/vol_id
@@ -0,0 +1,2 @@
1#!/bin/sh
2exec blkid -p -o udev "$@"
diff --git a/src/keygen.sh b/src/keygen.sh
new file mode 100755
index 0000000..716359b
--- /dev/null
+++ b/src/keygen.sh
@@ -0,0 +1,122 @@
1#!/bin/sh
2
3gpg_set_ultimate_trust()
4{
5 local keygrip
6 keygrip=$(gpg -K --with-colons|sed -ne '/^sec:/{p;q}'|cut -d: -f5) || return
7
8 expect - -- "$keygrip" <<'END'
9
10 set keygrip "[lindex $argv 0]"
11
12 spawn gpg --edit-key "$keygrip" trust
13
14 expect "Your decision?"
15 send -- "5\n"
16 expect "Do you really want to set this key to ultimate trust?"
17 send -- "y\n"
18 expect "gpg>"
19 send -- "save\n"
20 send_tty "\r"
21
22END
23}
24
25add()
26{
27 kiki merge \
28 --flow=sync \
29 --home${2:+="$2"} \
30 --create=rsa:4096 \
31 --flow=spill,match="$1" \
32 --type=pem \
33 --access=secret \
34 nil
35}
36
37init()
38{
39 local root="$1"
40
41 if [ "$root" ]; then
42 mkdir -m0600 -p "$root"/root/.gnupg
43 fi
44
45 kiki init ${root:+--chroot "$root"}
46 add encrypt ${root:+"$root/root/.gnupg"}
47 add sign ${root:+"$root/root/.gnupg"}
48
49 (
50 [ "$root" ] && export GNUPGHOME="$root/root/.gnupg/"
51 gpg_set_ultimate_trust
52 )
53}
54
55sync()
56{
57 local home1="$1"/root/.gnupg home2="$2"/root/.gnupg
58 kiki sync-public \
59 --homedir "$home1" \
60 --passphrase-fd=0 \
61 --import-if-authentic \
62 --autosign \
63 --keyrings "$home2"/pubring.gpg
64 kiki sync-secret \
65 --homedir "$home1" \
66 --autosign --import
67}
68
69doublecheck()
70{
71 gpg2 --clearsign </dev/null | gpg2 --homedir "$1"/root/.gnupg --verify
72 gpg2 --clearsign --homedir "$1"/root/.gnupg </dev/null | gpg2 --verify
73}
74
75silent()
76{
77 exec 3>&1 4>&2
78 exec >/dev/null 2>&1
79}
80
81noisy()
82{
83 exec >&3 2>&1
84}
85
86new_child()
87{
88 local root="$1"
89 init "$root"
90
91 sync "$root" ''
92 sync '' "$root"
93
94 gpg2 --check-trustdb
95 gpg2 --check-trustdb --homedir "$root"/root/.gnupg
96
97 doublecheck "$root"
98}
99
100
101child_dir=$1
102
103set -e
104
105[ "$(id -u)" = 0 ]
106[ "$child_dir" ]
107[ ! -d "$child_dir" ]
108which expect >/dev/null
109
110mkdir "$child_dir"
111trap -- 'umount "$child_dir"; rmdir "$child_dir"' EXIT
112mount -t tmpfs -o mode=0700 tmpfs "$child_dir"
113
114silent
115init
116new_child "$child_dir"
117noisy
118
119trap EXIT
120
121# gpg2 -k
122# gpg2 -k --homedir "$child_dir"/root/.gnupg
diff --git a/src/patchroot.sh b/src/patchroot.sh
new file mode 100755
index 0000000..738beac
--- /dev/null
+++ b/src/patchroot.sh
@@ -0,0 +1,43 @@
1#!/bin/sh
2
3pkgs='avahi-daemon git tmux btrfs-tools/jessie-backports sshfs eject'
4pkgs="$pkgs $(cat initrd-dependencies.txt)"
5pkgs="$pkgs linux-image-$(uname -r)/jessie-backports"
6
7default_sources_list()
8{
9 cat <<'END'
10deb http://httpredir.debian.org/debian jessie main contrib non-free
11deb http://security.debian.org jessie/updates main contrib non-free
12deb http://httpredir.debian.org/debian jessie-backports main contrib non-free
13deb-src http://httpredir.debian.org/debian jessie main contrib non-free
14deb-src http://security.debian.org jessie/updates main contrib non-free
15deb-src http://httpredir.debian.org/debian jessie-backports main contrib non-free
16END
17}
18
19network_devs()
20{
21 ip -oneline link |
22 while read _ dev _; do
23 echo ${dev%:}
24 done
25}
26
27if [ -e /root/sources.list ]; then
28 cp /root/sources.list /etc/apt/sources.list
29else
30 default_sources_list > /etc/apt/sources.list
31fi
32
33if [ -e /sys/module/hid_apple/parameters/fnmode ]; then
34 echo 2 > /sys/module/hid_apple/parameters/fnmode
35fi
36echo options hid_apple fnmode=2 > /etc/modprobe.d/apple.conf
37
38if [ "$(ifquery -a --list)" = lo ]; then
39 # No configured interfaces. Do something!
40 dhclient $(network_devs)
41fi
42apt-get update
43apt-get -y install --no-upgrade $pkgs
diff --git a/src/qemu.sh b/src/qemu.sh
new file mode 100755
index 0000000..dfed521
--- /dev/null
+++ b/src/qemu.sh
@@ -0,0 +1,34 @@
1#!/bin/sh
2
3. samizdat-path.sh
4
5# iso=debian-live-8.4.0-amd64-gnome-desktop.iso
6# iso=debian-live-8.4.0-amd64-standard.iso
7# iso=debian-live-8.4.0-amd64-standard.btrfs.iso
8iso=${samizdat_iso_dir}/samizdat.iso
9disk=${samizdat_iso_dir}/debian-live-8.4.0-amd64-standard.btrfs.disk
10layered=${samizdat_iso_dir}/${iso%.iso}.layered.iso
11
12[ -f "$layered" ] && iso=$layered
13
14[ "$1" ] && iso=$1
15
16initrd.sh || { echo "initrd.sh failed" >&2; exit 1; };
17
18NET='tap,vlan=0,ifname=tap0,script=no,downscript=no'
19
20# To test local pxe boot server:
21# NET='user,tftp=isolinux,bootfile=/pxelinux.0'
22
23initrd=${samizdat_isolinux_dir}/linux/initrd.img
24kernel=${samizdat_isolinux_dir}/linux/vmlinuz
25kcmdline='boot=samizdat components quiet splash'
26
27sudo qemu-system-x86_64 -enable-kvm -smp 2 -m 640 -k en-us \
28 -vga qxl \
29 -net nic,vlan=0,model=virtio \
30 -net "$NET" \
31 -rtc base=localtime \
32 -cdrom "$iso" \
33 -hda "$disk" \
34 -initrd "$initrd" -kernel "$kernel" -append "$kcmdline"
diff --git a/src/samizdat-paths.sh b/src/samizdat-paths.sh
new file mode 100644
index 0000000..c437c5b
--- /dev/null
+++ b/src/samizdat-paths.sh
@@ -0,0 +1,5 @@
1samizdat_initrd_files_dir=/home/d/sami/src/initrd
2samizdat_execs_dir=/home/d/src/samizdat
3samizdat_child_dir=./child
4samizdat_isolinux_dir=/home/d/sami/isolinux
5PATH=${libexecdir}/${PACKAGE}/bin:${PATH}
diff --git a/src/var.sh b/src/var.sh
new file mode 100644
index 0000000..d0c7df5
--- /dev/null
+++ b/src/var.sh
@@ -0,0 +1,75 @@
1die()
2{
3 if [ "$*" ]; then
4 printf 'Error: %s\n' "$*" >&2
5 else
6 echo 'Error: fatal error' >&2
7 fi
8 exit 1
9}
10
11nosex()
12{
13 case $- in
14 *x*) set +x; "$@"; set -x;;
15 *) "$@";;
16 esac
17}
18
19_nonempty()
20{
21 printf '[ "${%s}" ] || die \"mandatory parameter is empty: %s\";\n' "$1" "$1"
22}
23
24_mandatory()
25{
26 printf '[ $# -ge %d ] || die \"mandatory parameter is missing: %s\";\n' "$2" "$1"
27}
28
29_assign()
30{
31 printf 'local %s="${%d}";\n' "$1" "$2"
32}
33
34_args()
35{
36 local v i=1 check="$1" assign="$2"
37 shift
38 shift
39 for v; do
40 $assign "$v" "$i"
41 $check "$v" "$i"
42 i=$((i+1))
43 done
44}
45
46_ARGS()
47{
48 echo eval "$(_args _mandatory _assign "$@")"
49}
50
51_ARGS_NONEMPTY()
52{
53 echo eval "$(_args _nonempty _assign "$@")"
54}
55
56_ARGS_OPTIONAL()
57{
58 echo eval "$(_args : _assign "$@")"
59}
60
61_NONEMPTY()
62{
63 echo eval "$(_args _nonempty : "$@")"
64}
65
66ARGS() { nosex _ARGS "$@"; }
67ARGS_NONEMPTY() { nosex _ARGS_NONEMPTY "$@"; }
68ARGS_OPTIONAL() { nosex _ARGS_OPTIONAL "$@"; }
69NONEMPTY() { nosex _NONEMPTY "$@"; }
70
71ARGS_NE() { ARGS_NONEMPTY "$@"; }
72
73if [ "${0#-}" = bash ]; then
74 export -f die _nonempty _mandatory _args ARGS ARGS_NONEMPTY ARGS_OPTIONAL
75fi
diff --git a/src/xorriso-layer.sh b/src/xorriso-layer.sh
new file mode 100755
index 0000000..7ce4776
--- /dev/null
+++ b/src/xorriso-layer.sh
@@ -0,0 +1,38 @@
1#!/bin/bash
2
3outdev=debian-live-8.4.0-amd64-standard.btrfs.layered.iso
4indev=debian-live-8.4.0-amd64-standard.btrfs.iso
5volid=SamizdatLive
6btrfs_layer_iso_path=live/layer%s.btrfs
7btrfs_layer_filesystem="$1"
8
9die() { printf '%s\n' "$*"; exit 1; }
10
11[ -f "$btrfs_layer_filesystem" ] || die "Usage: $0 <layer.btrfs> [layer2.btrfs ...]"
12
13i=0
14while [ $i -lt $# ]; do
15 arg=$1
16 [ $i -eq 0 ] && n='' || n=$((i + 1))
17 arg=$(printf "${btrfs_layer_iso_path}=%s" "$n" "$arg")
18 shift
19 set -- "$@" "$arg"
20 i=$((i + 1))
21done
22
23for arg; do echo "a=$arg"; done; exit;
24
25set -ex
26
27cp --reflink "$indev" "$outdev"~
28time xorriso \
29 -drive_class clear_list all \
30 -outdev "$outdev"~ -indev "$outdev"~ \
31 -report_about mishap \
32 -volid "$volid" \
33 -return_with sorry 0 \
34 -pathspecs on -overwrite on \
35 -add_plainly any \
36 "$@"
37
38mv -f "$outdev"~ "$outdev"
diff --git a/src/xorriso-usb.sh b/src/xorriso-usb.sh
new file mode 100644
index 0000000..61fcda0
--- /dev/null
+++ b/src/xorriso-usb.sh
@@ -0,0 +1,182 @@
1#!/bin/bash
2
3. samizdat-paths.sh || exit 1
4
5outdev=
6volid=SamizdatLive
7gpg_iso_path=gnupghome
8gnupghome=
9child_dir=$samizdat_child_dir
10vmlinuz_dir=$samizdat_isolinux_dir
11efi_dir=$samizdat_grub_efi_dir
12
13die() { printf "%s: Error: %s\n" "$0" "$*" >&2; exit 1; }
14
15TEMP="$(getopt -o '' --long adam,usb,detach,out:,test -n "$0" -- "$@")" ||
16 die 'getopt error'
17eval set -- "$TEMP"
18
19ADAM=; DETACH=; USB=
20while [ $# -gt 0 ]; do
21 case "$1" in
22 --adam) shift; ADAM=y;;
23 --usb) shift; USB=y;;
24 --detach) shift; DETACH=y;;
25 --test) shift; QUICK_TEST=y;;
26 --out) CMDLINE_OUTDEV="$2"; shift 2;;
27 --) shift; break;;
28 *) die 'getopt error';;
29 esac
30done
31
32if [ $# = 0 ]; then
33 set -- debian-live-8.4.0-amd64-standard.btrfs layer.btrfs
34fi
35
36for fs; do
37 [ -f "$fs" ] || die "not a file: $fs"
38 shift
39 set -- "$@" "rootfs/${fs##*/}=$fs"
40done
41
42
43whole_device()
44{
45 case "$1" in
46 *-part?) false ;;
47 *-part??) false ;;
48 *-part???) false ;;
49 */usb\*) false ;;
50 *) true ;;
51 esac
52}
53
54confirm_usb()
55{
56 local msg="This will completely overwrite device:\n\n\t%s\n\nType 'yes' to confirm.\nContinue? "
57 printf "$msg" "$1" >&2
58 read line
59 case "$line" in
60 [yY][eE][sS]) return ;;
61 *) die "Aborted by user." ;;
62 esac
63}
64
65choose_usb()
66{
67 local devs maj
68 set -- /dev/disk/by-id/usb*
69 for dev; do
70 shift
71 whole_device "$dev" || continue
72 set -- "$@" "$dev"
73 done
74 if [ $# = 0 ]; then
75 die "no usb device found"
76 elif [ $# = 1 ]; then
77 confirm_usb "$1" || die impossible
78 outdev="$1"
79 else
80 die "multiple USB devices connected and choice between them is unimplemented. ($*)"
81 fi
82}
83
84choose_cdrom()
85{
86 die 'choose_cdrom: unimplemented'
87}
88
89choose_outdev()
90{
91 if [ "$CMDLINE_OUTDEV" ]; then
92 outdev=$CMDLINE_OUTDEV~
93 NEED_STDIO=y
94 elif [ "$USB" ]; then
95 choose_usb
96 NEED_STDIO=y
97 else
98 choose_cdrom
99 NEED_STDIO=
100 fi
101}
102
103generate_keys()
104{
105 if [ "$ADAM" ]; then
106 kiki init || die 'kiki init failed'
107 gnupghome=/root/.gnupg
108 else
109 keygen.sh "$child_dir" || die "keygen.sh failed"
110 gnupghome=$child_dir/root/.gnupg
111 trap 'umount "$child_dir"; rmdir "$child_dir"' EXIT
112 fi
113}
114
115
116[ "$(id -u)" = 0 ] || die "you are not root."
117
118grub-efi.sh || die "grub-efi.sh failed"
119
120choose_outdev
121
122generate_keys
123
124if [ "$INPUT_DEVICE" ]; then
125 REPLACE_INITRD=
126 REMOVE_BTRFS=
127 ADD_BTRFS=
128else
129 REPLACE_INITRD=y
130 REMOVE_BTRFS=y
131 ADD_BTRFS=y
132fi
133
134if [ "$QUICK_TEST" ]; then
135 REMOVE_BTRFS=y
136 ADD_BTRFS=
137fi
138
139if [ "$REPLACE_INITRD" ]; then
140 initrd.sh
141fi
142
143(set -x
144xorriso \
145 ${INPUT_DEVICE:+ -indev "$INPUT_DEVICE" } \
146 -outdev ${NEED_STDIO:+stdio:}"$outdev" \
147 -blank as_needed \
148 -report_about mishap \
149 -return_with sorry 0 \
150 -volid "$volid" \
151 -pathspecs on \
152 \
153 \
154 ${REPLACE_INITRD:+ -rm_r linux -- -add linux="${vmlinuz_dir}" -- } \
155 ${REMOVE_BTRFS:+ -rm_r btrfs -- } \
156 ${ADD_BTRFS:+ -follow link -add "$@" -- -follow default } \
157 \
158 \
159 -rm_r "${gpg_iso_path}" -- \
160 -add "${gpg_iso_path}=${gnupghome}" -- \
161 \
162 \
163 -chown_r 0 / -- \
164 -chgrp_r 0 / -- \
165 -chmod_r go-rwx "${gpg_iso_path}" -- \
166 \
167 \
168 -as mkisofs -graft-points \
169 -b grub/i386-pc/eltorito.img \
170 -no-emul-boot -boot-info-table \
171 --embedded-boot "${efi_dir}"/embedded.img \
172 --protective-msdos-label \
173 grub="${efi_dir}"/grub
174) || die "xorriso exited $?"
175
176case "$outdev" in
177 *~) [ -f "$outdev" ] && mv "$outdev" "${outdev%\~}" ;;
178esac
179
180if [ "$USB" -a "$DETACH" -a $? = 0 ]; then
181 udisks --detach "$outdev"
182fi
diff --git a/src/xorriso.sh b/src/xorriso.sh
new file mode 100755
index 0000000..5068d4b
--- /dev/null
+++ b/src/xorriso.sh
@@ -0,0 +1,66 @@
1#!/bin/sh
2
3outdev=samizdat.iso
4indev=debian-live-8.4.0-amd64-standard.iso
5volid=SamizdatLive
6gpg_iso_path=gnupghome
7gnupghome=gnupghome
8secrets=secrets
9
10if [ $# = 0 ]; then
11 set -- debian-live-8.4.0-amd64-standard.btrfs layer.btrfs
12fi
13
14for fs; do
15 [ -f "$fs" ] || exit 1
16 shift
17 set -- "$@" "rootfs/${fs##*/}=$fs"
18done
19
20die() { printf '%s\n' "$*"; exit 1; }
21
22make_gnupghome()
23{
24 [ -d "$gnupghome" ] && return
25 local reset=$-
26 set -e
27 [ ! -d "$gnupghome".tmp ] || die "Error: refusing to overwrite $gnupghome.tmp"
28 [ ! -d "$secrets".tmp ] || die "Error: refusing to overwrite $secrets.tmp"
29 mkdir -p "$gnupghome".tmp "$secrets".tmp
30 local PATH="$HOME"/src/samizdat/src:"$PATH" NO_USE_RAMFS=y
31 NEW_GNUPGHOME="$gnupghome".tmp SECRETS_DIRECTORY="$secrets".tmp ~/src/samizdat/src/samizdat-make-key --adam
32 mv "$secrets".tmp "$secrets"
33 mv "$gnupghome".tmp "$gnupghome"
34 set -$reset
35}
36
37make_gnupghome
38
39if [ grub-efi.sh -nt grub-efi ]; then
40 ./grub-efi.sh || die "Error: grub-efi.sh failed"
41fi
42
43set -ex
44
45xorriso \
46 -drive_class clear_list all \
47 -outdev "$outdev"~ \
48 -report_about mishap \
49 -return_with sorry 0 \
50 -volid "$volid" \
51 -pathspecs on \
52 \
53 \
54 -add "${gpg_iso_path}=${gnupghome}" -- \
55 -add linux=isolinux/linux -- \
56 -follow link -add "$@" -- -follow default \
57 \
58 \
59 -as mkisofs -graft-points \
60 -b grub/i386-pc/eltorito.img \
61 -no-emul-boot -boot-info-table \
62 --embedded-boot grub-efi/embedded.img \
63 --protective-msdos-label \
64 grub=grub-efi/grub
65
66mv -f "$outdev"~ "$outdev"
diff --git a/src/xorriso.test-efi.sh b/src/xorriso.test-efi.sh
new file mode 100755
index 0000000..3591528
--- /dev/null
+++ b/src/xorriso.test-efi.sh
@@ -0,0 +1,65 @@
1#!/bin/sh
2
3outdev=samizdat.iso
4indev=debian-live-8.4.0-amd64-standard.iso
5volid=SamizdatLive
6gpg_iso_path=gnupghome
7gnupghome=gnupghome
8secrets=secrets
9
10if [ $# = 0 ]; then
11 set -- debian-live-8.4.0-amd64-standard.btrfs layer.btrfs
12fi
13
14for fs; do
15 [ -f "$fs" ] || exit 1
16 shift
17 set -- "$@" "rootfs/${fs##*/}=$fs"
18done
19
20die() { printf '%s\n' "$*"; exit 1; }
21
22make_gnupghome()
23{
24 [ -d "$gnupghome" ] && return
25 local reset=$-
26 set -e
27 [ ! -d "$gnupghome".tmp ] || die "Error: refusing to overwrite $gnupghome.tmp"
28 [ ! -d "$secrets".tmp ] || die "Error: refusing to overwrite $secrets.tmp"
29 mkdir -p "$gnupghome".tmp "$secrets".tmp
30 local PATH="$HOME"/src/samizdat/src:"$PATH" NO_USE_RAMFS=y
31 NEW_GNUPGHOME="$gnupghome".tmp SECRETS_DIRECTORY="$secrets".tmp ~/src/samizdat/src/samizdat-make-key --adam
32 mv "$secrets".tmp "$secrets"
33 mv "$gnupghome".tmp "$gnupghome"
34 set -$reset
35}
36
37make_gnupghome
38
39if [ grub-efi.sh -nt grub-efi ]; then
40 ./grub-efi.sh || die "Error: grub-efi.sh failed"
41fi
42
43set -ex
44
45xorriso \
46 -drive_class clear_list all \
47 -outdev "$outdev"~ \
48 -report_about mishap \
49 -return_with sorry 0 \
50 -volid "$volid" \
51 -pathspecs on \
52 \
53 \
54 -add "${gpg_iso_path}=${gnupghome}" -- \
55 -add linux=isolinux/linux -- \
56 \
57 \
58 -as mkisofs -graft-points \
59 -b grub/i386-pc/eltorito.img \
60 -no-emul-boot -boot-info-table \
61 --embedded-boot grub-efi/embedded.img \
62 --protective-msdos-label \
63 grub=grub-efi/grub
64
65mv -f "$outdev"~ "$outdev"