jib revision 295546
1#!/bin/sh
2#-
3# Copyright (c) 2016 Devin Teske
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions
8# are met:
9# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer.
11# 2. Redistributions in binary form must reproduce the above copyright
12#    notice, this list of conditions and the following disclaimer in the
13#    documentation and/or other materials provided with the distribution.
14#
15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25# SUCH DAMAGE.
26#
27# $FreeBSD: head/share/examples/jails/jib 295546 2016-02-11 21:28:34Z dteske $
28#
29############################################################ IDENT(1)
30#
31# $Title: if_bridge(4) management script for vnet jails $
32#
33############################################################ INFORMATION
34#
35# Use this tool with jail.conf(5) (or rc.conf(5) ``legacy'' configuration) to
36# manage `vnet' interfaces for jails. Designed to automate the creation of vnet
37# interface(s) during jail `prestart' and destroy said interface(s) during jail
38# `poststop'.
39#
40# In jail.conf(5) format:
41#
42# ### BEGIN EXCERPT ###
43#
44# xxx {
45# 	host.hostname = "xxx.yyy";
46# 	path = "/vm/xxx";
47# 
48# 	#
49# 	# NB: Below 2-lines required
50# 	# NB: The number of eNb_xxx interfaces should match the number of
51# 	#     arguments given to `jib addm xxx' in exec.prestart value.
52# 	#
53# 	vnet;
54# 	vnet.interface = "e0b_xxx e1b_xxx ...";
55# 
56# 	exec.clean;
57# 	exec.system_user = "root";
58# 	exec.jail_user = "root";
59# 
60# 	#
61# 	# NB: Below 2-lines required
62# 	# NB: The number of arguments after `jib addm xxx' should match
63# 	#     the number of eNb_xxx arguments in vnet.interface value.
64# 	#
65# 	exec.prestart += "jib addm xxx em0 em1 ...";
66# 	exec.poststop += "jib destroy xxx";
67# 
68# 	# Standard recipe
69# 	exec.start += "/bin/sh /etc/rc";
70# 	exec.stop = "/bin/sh /etc/rc.shutdown";
71# 	exec.consolelog = "/var/log/jail_xxx_console.log";
72# 	mount.devfs;
73#
74# 	# Optional (default off)
75# 	#allow.mount;
76# 	#allow.set_hostname = 1;
77# 	#allow.sysvipc = 1;
78# 	#devfs_ruleset = "11"; # rule to unhide bpf for DHCP
79# }
80#
81# ### END EXCERPT ###
82#
83# In rc.conf(5) ``legacy'' format (used when /etc/jail.conf does not exist):
84#
85# ### BEGIN EXCERPT ###
86#
87# jail_enable="YES"
88# jail_list="xxx"
89#
90# #
91# # Global presets for all jails
92# #
93# jail_devfs_enable="YES"	# mount devfs
94#
95# #
96# # Global options (default off)
97# #
98# #jail_mount_enable="YES"		# mount /etc/fstab.{name}
99# #jail_set_hostname_allow="YES"	# Allow hostname to change
100# #jail_sysvipc_allow="YES"		# Allow SysV Interprocess Comm.
101# 
102# # xxx
103# jail_xxx_hostname="xxx.shxd.cx"		# hostname
104# jail_xxx_rootdir="/vm/xxx"			# root directory
105# jail_xxx_vnet_interfaces="e0b_xxx e1bxxx ..."	# vnet interface(s)
106# jail_xxx_exec_prestart0="jib addm xxx em0 em1 ..."	# bridge interface(s)
107# jail_xxx_exec_poststop0="jib destroy xxx"	# destroy interface(s)
108# #jail_xxx_mount_enable="YES"			# mount /etc/fstab.xxx
109# #jail_xxx_devfs_ruleset="11"			# rule to unhide bpf for DHCP
110#
111# ### END EXCERPT ###
112#
113# Note that the legacy rc.conf(5) format is converted to
114# /var/run/jail.{name}.conf by /etc/rc.d/jail if jail.conf(5) is missing.
115#
116# ASIDE: dhclient(8) inside a vnet jail...
117#
118# To allow dhclient(8) to work inside a vnet jail, make sure the following
119# appears in /etc/devfs.rules (which should be created if it doesn't exist):
120#
121# 	[devfsrules_jail=11]
122# 	add include $devfsrules_hide_all
123# 	add include $devfsrules_unhide_basic
124# 	add include $devfsrules_unhide_login
125# 	add path 'bpf*' unhide
126#
127# And set ether devfs.ruleset="11" (jail.conf(5)) or
128# jail_{name}_devfs_ruleset="11" (rc.conf(5)).
129#
130# NB: While this tool can't create every type of desirable topology, it should
131# handle most setups, minus some which considered exotic or purpose-built.
132#
133############################################################ GLOBALS
134
135pgm="${0##*/}" # Program basename
136
137#
138# Global exit status
139#
140SUCCESS=0
141FAILURE=1
142
143############################################################ FUNCTIONS
144
145usage()
146{
147	local action usage descr
148	exec >&2
149	echo "Usage: $pgm action [arguments]"
150	echo "Actions:"
151	for action in \
152		addm		\
153		show		\
154		show1		\
155		destroy		\
156	; do
157		eval usage=\"\$jib_${action}_usage\"
158		[ "$usage" ] || continue
159		eval descr=\"\$jib_${action}_descr\"
160		printf "\t%s\n\t\t%s\n" "$usage" "$descr"
161	done
162	exit $FAILURE
163}
164
165action_usage()
166{
167	local usage action="$1"
168	eval usage=\"\$jib_${action}_usage\"
169	echo "Usage: $pgm $usage" >&2
170	exit $FAILURE
171}
172
173derive_mac()
174{
175	local OPTIND=1 OPTARG __flag
176	local __mac_num= __make_pair=
177	while getopts 2n: __flag; do
178		case "$__flag" in
179		2) __make_pair=1 ;;
180		n) __mac_num=${OPTARG%%[^0-9]*} ;;
181		esac
182	done
183	shift $(( $OPTIND - 1 ))
184
185	if [ ! "$__mac_num" ]; then
186		eval __mac_num=\${_${iface}_num:--1}
187		__mac_num=$(( $__mac_num + 1 ))
188		eval _${iface}_num=\$__mac_num
189	fi
190
191	local __iface="$1" __name="$2" __var_to_set="$3" __var_to_set_b="$4"
192	local __iface_devid __new_devid __num __new_devid_b
193	#
194	# Calculate MAC address derived from given iface.
195	#
196	# The formula I'm using is ``NP:SS:SS:II:II:II'' where:
197	# + N denotes 4 bits used as a counter to support branching
198	#   each parent interface up to 15 times under the same jail
199	#   name (see S below).
200	# + P denotes the special nibble whose value, if one of
201	#   2, 6, A, or E (but usually 2) denotes a privately
202	#   administered MAC address (while remaining routable).
203	# + S denotes 16 bits, the sum(1) value of the jail name.
204	# + I denotes bits that are inherited from parent interface.
205	#
206	# The S bits are a CRC-16 checksum of NAME, allowing the jail
207	# to change link numbers in ng_bridge(4) without affecting the
208	# MAC address. Meanwhile, if...
209	#   + the jail NAME changes (e.g., it was duplicated and given
210	#     a new name with no other changes)
211	#   + the underlying network interface changes
212	#   + the jail is moved to another host
213	# the MAC address will be recalculated to a new, similarly
214	# unique value preventing conflict.
215	#
216	__iface_devid=$( ifconfig $__iface ether | awk '/ether/,$0=$2' )
217	__new_devid=${__iface_devid#??:??:??}
218	# :II:II:II => S:II:II:II
219	__num=$( set -- `echo -n "$__name" | sum` && echo $1 )
220	__new_devid=$( printf %x $(( $__num & 15 )) )$__new_devid
221	# S:II:II:II => :SS:II:II:II
222	__num=$(( $__num >> 4 ))
223	__new_devid=:$( printf %x $(( $__num & 15 )) )$__new_devid
224	# :SS:II:II:II => S:SS:II:II:II
225	__num=$(( $__num >> 4 ))
226	__new_devid=$( printf %x $(( $__num & 15 )) )$__new_devid
227	# S:SS:II:II:II => :SS:SS:II:II:II
228	__new_devid=:$( printf %x $(( $__num & 15 )) )$__new_devid
229	# :SS:SS:II:II:II => P:SS:SS:II:II:II
230	case "$__iface_devid" in
231	   ?2:*) __new_devid=a$__new_devid __new_devid_b=e$__new_devid ;;
232	?[Ee]:*) __new_devid=2$__new_devid __new_devid_b=6$__new_devid ;;
233	      *) __new_devid=2$__new_devid __new_devid_b=e$__new_devid
234	esac
235	# P:SS:SS:II:II:II => NP:SS:SS:II:II:II
236	__new_devid=$( printf %x $(( $__mac_num & 15 )) )$__new_devid
237	__new_devid_b=$( printf %x $(( $__mac_num & 15 )) )$__new_devid_b
238
239	#
240	# Return derivative MAC address(es)
241	#
242	if [ "$__make_pair" ]; then
243		if [ "$__var_to_set" -a "$__var_to_set_b" ]; then
244			eval $__var_to_set=\$__new_devid
245			eval $__var_to_set_b=\$__new_devid_b
246		else
247			echo $__new_devid $__new_devid_b
248		fi
249	else
250		if [ "$__var_to_set" ]; then
251			eval $__var_to_set=\$__new_devid
252		else
253			echo $__new_devid
254		fi
255	fi
256}
257
258mustberoot_to_continue()
259{
260	if [ "$( id -u )" -ne 0 ]; then
261		echo "Must run as root!" >&2
262		exit $FAILURE
263	fi
264}
265
266jib_addm_usage="addm [-b BRIDGE_NAME] NAME interface0 [interface1 ...]"
267jib_addm_descr="Creates e0b_NAME [e1b_NAME ...]"
268jib_addm()
269{
270	local OPTIND=1 OPTARG flag bridge=bridge
271	while getopts b: flag; do
272		case "$flag" in
273		b) bridge="${OPTARG:-bridge}" ;;
274		*) action_usage addm # NOTREACHED
275		esac
276	done
277	shift $(( $OPTIND - 1 ))
278
279	local name="$1"
280	[ "${name:-x}" = "${name#*[!0-9a-zA-Z_]}" -a $# -gt 1 ] ||
281		action_usage addm # NOTREACHED
282	shift 1 # name
283
284	mustberoot_to_continue
285
286	local iface eiface_devid_a eiface_devid_b
287	local new num quad i=0
288	for iface in $*; do
289
290		# 1. Make sure the interface doesn't exist already
291		ifconfig "e${i}a_$name" > /dev/null 2>&1 && continue
292
293		# 2. Bring the interface up
294		ifconfig $iface up || return
295
296		# 3. Make sure the interface has been bridged
297		if ! ifconfig "$iface$bridge" > /dev/null 2>&1; then
298			new=$( ifconfig bridge create ) || return
299			ifconfig $new addm $iface || return
300			ifconfig $new name "$iface$bridge" || return
301			ifconfig "$iface$bridge" up || return
302		fi
303
304		# 4. Create a new interface to the bridge
305		new=$( ifconfig epair create ) || return
306		ifconfig "$iface$bridge" addm $new || return
307
308		# 5. Rename the new interface
309		ifconfig $new name "e${i}a_$name" || return
310		ifconfig ${new%a}b name "e${i}b_$name" || return
311		ifconfig "e${i}a_$name" up || return
312		ifconfig "e${i}b_$name" up || return
313
314		#
315		# 6. Set the MAC address of the new interface using a sensible
316		# algorithm to prevent conflicts on the network.
317		#
318		derive_mac -2 $iface "$name" eiface_devid_a eiface_devid_b
319		ifconfig "e${i}a_$name" ether $eiface_devid_a > /dev/null 2>&1
320		ifconfig "e${i}b_$name" ether $eiface_devid_b > /dev/null 2>&1
321
322		i=$(( $i + 1 )) # on to next e{i}b_name
323	done # for iface
324}
325
326jib_show_usage="show"
327jib_show_descr="List possible NAME values for \`show NAME'"
328jib_show1_usage="show NAME"
329jib_show1_descr="Lists e0b_NAME [e1b_NAME ...]"
330jib_show2_usage="show [NAME]"
331jib_show()
332{
333	local OPTIND=1 OPTARG flag
334	while getopts "" flag; do
335		case "$flag" in
336		*) action_usage show2 # NOTREACHED
337		esac
338	done
339	shift $(( $OPTIND - 1 ))
340	if [ $# -eq 0 ]; then
341		ifconfig | awk '
342			/^[^:[:space:]]+:/ {
343				iface = $1
344				sub(/:.*/, "", iface)
345				next
346			}
347			$1 == "groups:" {
348				for (n = split($0, group); n > 1; n--) {
349					if (group[n] != "bridge") continue
350					print iface
351					next
352				}
353			}' |
354			xargs -rn1 ifconfig |
355			awk '$1 == "member:" &&
356				sub(/^e[[:digit:]]+a_/, "", $2), $0 = $2' |
357			sort -u
358		return
359	fi
360	ifconfig | awk -v name="$1" '
361		match($0, /^e[[:digit:]]+a_/) && sub(/:.*/, "") &&
362			substr($1, RSTART + RLENGTH) == name
363	' | sort
364}
365
366jib_destroy_usage="destroy NAME"
367jib_destroy_descr="Destroy e0b_NAME [e1b_NAME ...]"
368jib_destroy()
369{
370	local OPTIND=1 OPTARG flag
371	while getopts "" flag; do
372		case "$flag" in
373		*) action_usage destroy # NOTREACHED
374		esac
375	done
376	shift $(( $OPTIND -1 ))
377	local name="$1"
378	[ "${name:-x}" = "${name#*[!0-9a-zA-Z_]}" -a $# -eq 1 ] ||
379		action_usage destroy # NOTREACHED
380	mustberoot_to_continue
381	jib_show "$name" | xargs -rn1 -I eiface ifconfig eiface destroy
382}
383
384############################################################ MAIN
385
386#
387# Command-line arguments
388#
389action="$1"
390[ "$action" ] || usage # NOTREACHED
391
392#
393# Validate action argument
394#
395if [ "$BASH_VERSION" ]; then
396	type="$( type -t "jib_$action" )" || usage # NOTREACHED
397else
398	type="$( type "jib_$action" 2> /dev/null )" || usage # NOTREACHED
399fi
400case "$type" in
401*function)
402	shift 1 # action
403	eval "jib_$action" \"\$@\"
404	;;
405*) usage # NOTREACHED
406esac
407
408################################################################################
409# END
410################################################################################
411