1#	$OpenBSD: dynamic-forward.sh,v 1.13 2017/09/21 19:18:12 markus Exp $
2#	Placed in the Public Domain.
3
4tid="dynamic forwarding"
5
6FWDPORT=`expr $PORT + 1`
7
8if have_prog nc && nc -h 2>&1 | grep "proxy address" >/dev/null; then
9	proxycmd="nc -x 127.0.0.1:$FWDPORT -X"
10elif have_prog connect; then
11	proxycmd="connect -S 127.0.0.1:$FWDPORT -"
12else
13	echo "skipped (no suitable ProxyCommand found)"
14	exit 0
15fi
16trace "will use ProxyCommand $proxycmd"
17
18start_sshd
19
20for d in D R; do
21	n=0
22	error="1"
23	trace "start dynamic forwarding, fork to background"
24
25	while [ "$error" -ne 0 -a "$n" -lt 3 ]; do
26		n=`expr $n + 1`
27		${SSH} -F $OBJ/ssh_config -f -$d $FWDPORT -q \
28		    -oExitOnForwardFailure=yes somehost exec sh -c \
29			\'"echo \$\$ > $OBJ/remote_pid; exec sleep 444"\'
30		error=$?
31		if [ "$error" -ne 0 ]; then
32			trace "forward failed attempt $n err $error"
33			sleep $n
34		fi
35	done
36	if [ "$error" -ne 0 ]; then
37		fatal "failed to start dynamic forwarding"
38	fi
39
40	for s in 4 5; do
41	    for h in 127.0.0.1 localhost; do
42		trace "testing ssh socks version $s host $h (-$d)"
43		${SSH} -F $OBJ/ssh_config \
44			-o "ProxyCommand ${proxycmd}${s} $h $PORT" \
45			somehost cat ${DATA} > ${COPY}
46		test -f ${COPY}	 || fail "failed copy ${DATA}"
47		cmp ${DATA} ${COPY} || fail "corrupted copy of ${DATA}"
48	    done
49	done
50
51	if [ -f $OBJ/remote_pid ]; then
52		remote=`cat $OBJ/remote_pid`
53		trace "terminate remote shell, pid $remote"
54		if [ $remote -gt 1 ]; then
55			kill -HUP $remote
56		fi
57	else
58		fail "no pid file: $OBJ/remote_pid"
59	fi
60
61done
62