]> CyberLeo.Net >> Repos - CDN/j.git/blob - enter
enter: use jail_params to probe for a usable shell instead of hardcoding
[CDN/j.git] / enter
1 #!/bin/sh
2 # Copyright 2011 CyberLeo, All Rights Reserved
3 # http://wiki.cyberleo.net/wiki/CyberLeo/COPYRIGHT
4
5 meh() { printf " \033[1;32m*\033[0m %s%s\n" "${jail:+${jail}: }" "${*}"; }
6 omg() { printf " \033[1;33m*\033[0m %s%s\n" "${jail:+${jail}: }" "${*}"; }
7 wtf() { printf " \033[1;31m*\033[0m %s%s\n" "${jail:+${jail}: }" "${*}"; exit 1; }
8 pebkac() {
9   [ "${*}" ] && printf "%s\n\n" "${*}"
10   cat <<EOF
11 Usage: <start|enter|stop> <jailname>
12 EOF
13   exit 1
14 }
15
16 cmd="$(basename "${0}")"
17 base="$(realpath "$(dirname "${0}")")"
18 jail="$(basename "${1:-DebianChroot}")"
19 jdir="${base}/${jail}"
20 jail_shell=""
21
22 # Propagate certain environment variables; sterilize the rest of the environment
23 env="
24   TERM=${TERM}
25   USER=${USER}
26 "
27
28 # Create a new jail (Will not work, since a new jail will not exist and will not pass the 'not a jail' check above)
29 jail_new() {
30   DEBOOTSTRAP_DIR="$(base)/debootstrap" "${DEBOOTSTRAP_DIR}/debootstrap" --arch=amd64 squeeze "${jdir}"
31 }
32
33 # Figure out jail parameters
34 jail_params() {
35   # Where is the shell?
36   for shell in /bin/bash /usr/bin/bash /usr/local/bin/bash /bin/sh
37   do
38     if [ -f "${jdir}/${shell}" ]
39     then
40       jail_shell=${shell}
41       break
42     fi
43     wtf "cannot locate usable shell; is this a real jail?"
44   done
45 }
46
47 # Jail is 'up' if /dev/pts and /proc are mounted
48 jail_up() {
49   grep -q "^devpts ${jdir}/dev/pts devpts" /proc/mounts || return 1
50   grep -q "^proc ${jdir}/proc proc" /proc/mounts || return 1
51   return 0
52 }
53
54 # Mount /dev/pts and /proc in the jail
55 jail_start() {
56   jail_up && return 0
57   meh "starting ${jail} ..."
58   mount -t devpts devpts "${jdir}/dev/pts"
59   mount -t proc proc "${jdir}/proc"
60 }
61
62 # Enter jail
63 jail_enter() {
64   jail_up || wtf "jail not up"
65   meh "entering ${jail} ..."
66   env -i ${env} /usr/bin/chroot "${jdir}" /bin/su "${USER}" -c "${jail_shell}" -l
67 }
68
69 # Unmount /dev/pts and /proc in the jail
70 jail_stop() {
71   jail_up || return 0
72   meh "stopping ${jail} ..."
73   umount "${jdir}/proc"
74   umount "${jdir}/dev/pts"
75 }
76
77 # Need root beyond here
78 [ "$(id -u)" -eq 0 ] || exec sudo env ${env} "${0}" "${@}"
79
80 jail_params
81
82 case "${cmd}" in
83 start) jail_start ;;
84 enter) jail_enter ;;
85 stop)  jail_stop  ;;
86 *) pebkac ;;
87 esac