1255670Sdes#	$OpenBSD: dynamic-forward.sh,v 1.10 2013/05/17 04:29:14 dtucker Exp $
2124208Sdes#	Placed in the Public Domain.
3124208Sdes
4124208Sdestid="dynamic forwarding"
5124208Sdes
6137015SdesFWDPORT=`expr $PORT + 1`
7137015Sdes
8128456Sdesif have_prog nc && nc -h 2>&1 | grep "proxy address" >/dev/null; then
9124208Sdes	proxycmd="nc -x 127.0.0.1:$FWDPORT -X"
10124208Sdeselif have_prog connect; then
11124208Sdes	proxycmd="connect -S 127.0.0.1:$FWDPORT -"
12124208Sdeselse
13124208Sdes	echo "skipped (no suitable ProxyCommand found)"
14124208Sdes	exit 0
15124208Sdesfi
16124208Sdestrace "will use ProxyCommand $proxycmd"
17124208Sdes
18124208Sdesstart_sshd
19124208Sdes
20124208Sdesfor p in 1 2; do
21225825Sdes	n=0
22225825Sdes	error="1"
23124208Sdes	trace "start dynamic forwarding, fork to background"
24225825Sdes	while [ "$error" -ne 0 -a "$n" -lt 3 ]; do
25225825Sdes		n=`expr $n + 1`
26225825Sdes		${SSH} -$p -F $OBJ/ssh_config -f -D $FWDPORT -q \
27225825Sdes		    -oExitOnForwardFailure=yes somehost exec sh -c \
28225825Sdes			\'"echo \$\$ > $OBJ/remote_pid; exec sleep 444"\'
29225825Sdes		error=$?
30225825Sdes		if [ "$error" -ne 0 ]; then
31225825Sdes			trace "forward failed proto $p attempt $n err $error"
32225825Sdes			sleep $n
33225825Sdes		fi
34225825Sdes	done
35225825Sdes	if [ "$error" -ne 0 ]; then
36225825Sdes		fatal "failed to start dynamic forwarding proto $p"
37225825Sdes	fi
38124208Sdes
39124208Sdes	for s in 4 5; do
40124208Sdes	    for h in 127.0.0.1 localhost; do
41124208Sdes		trace "testing ssh protocol $p socks version $s host $h"
42124208Sdes		${SSH} -F $OBJ/ssh_config \
43124208Sdes			-o "ProxyCommand ${proxycmd}${s} $h $PORT" \
44124208Sdes			somehost cat $DATA > $OBJ/ls.copy
45124208Sdes		test -f $OBJ/ls.copy	 || fail "failed copy $DATA"
46124208Sdes		cmp $DATA $OBJ/ls.copy || fail "corrupted copy of $DATA"
47124208Sdes	    done
48124208Sdes	done
49124208Sdes
50124208Sdes	if [ -f $OBJ/remote_pid ]; then
51124208Sdes		remote=`cat $OBJ/remote_pid`
52124208Sdes		trace "terminate remote shell, pid $remote"
53124208Sdes		if [ $remote -gt 1 ]; then
54124208Sdes			kill -HUP $remote
55124208Sdes		fi
56124208Sdes	else
57124208Sdes		fail "no pid file: $OBJ/remote_pid"
58124208Sdes	fi
59124208Sdesdone
60