Version 1.8.0.1
[socat.git] / socks4a-echo.sh
blob7360366c5c469c8392d05f871f6b624b5fda7e31
1 #! /usr/bin/env bash
2 # source: socks4a-echo.sh
3 #set -vx
5 # Copyright Gerhard Rieger and contributors (see file CHANGES)
6 # Published under the GNU General Public License V.2, see file COPYING
8 # perform primitive simulation of a socks4a server with echo function via stdio.
9 # accepts and answers correct SOCKS4a requests, but then just echoes data.
10 # it is required for test.sh
11 # for TCP, use this script as:
12 # socat tcp-l:1080,reuseaddr,crlf system:"socks4a-echo.sh"
14 # older bash and ksh do not have -n option to read command; we try dd then
15 #if echo a |read -n 1 null >/dev/null 2>&1; then
16 # HAVE_READ_N=1
17 #else
18 # and newer bash (4.3) has some other problem with read -n
19 HAVE_READ_N=
20 #fi
22 if type socat >/dev/null 2>&1; then
23 SOCAT=socat
24 else
25 SOCAT=./socat
28 case `uname` in
29 HP-UX|OSF1)
30 CAT="$SOCAT -u stdin stdout"
33 CAT=cat
35 esac
37 if [ $(echo "x\c") = "x" ]; then E=""
38 elif [ $(echo -e "x\c") = "x" ]; then E="-e"
39 else
40 echo "cannot suppress trailing newline on echo" >&2
41 exit 1
43 ECHO="echo $E"
45 if [ $($ECHO "\0101") = "A" ]; then
46 SOCKSREPLY_FAILED="\0\0133\0\0\0\0\0\0\c"
47 SOCKSREPLY_OK="\0\0132\0\0\0\0\0\0\c"
48 else
49 SOCKSREPLY_FAILED="\0\133\0\0\0\0\0\0\c"
50 SOCKSREPLY_OK="\0\132\0\0\0\0\0\0\c"
53 # read and parse SOCKS4a header
54 if [ "$HAVE_READ_N" ]; then
55 read -r -n 1 vn # bash 2.0.3 does not support -n
56 else
57 vn=$(dd bs=1 count=1 2>/dev/null)
59 if [ "$vn" != $($ECHO "\04") ]; then
60 $ECHO "$SOCKSREPLY_FAILED"
61 echo "invalid socks version requested" >&2
62 exit
65 if [ "$HAVE_READ_N" ]; then
66 read -r -n 1 cd
67 else
68 cd=$(dd bs=1 count=1 2>/dev/null)
70 if [ "$cd" != $($ECHO "\01") ]; then
71 $ECHO "$SOCKSREPLY_FAILED"
72 echo "invalid socks operation requested" >&2
73 exit
76 a=$(dd bs=1 count=6 2>/dev/null)
77 #echo a a a >/dev/tty
78 #echo "$a" |od -c >/dev/tty
79 #$ECHO "$a" |od -c >/dev/tty
80 #echo>/dev/tty
81 #echo a a a >/dev/tty
82 if [ "$a" != "$($ECHO "}m\0\0\0\01")" ]; then
83 sleep 1
84 $ECHO "$SOCKSREPLY_FAILED"
85 echo "wrong socks address or port requested" >&2
86 exit
89 if [ "$HAVE_READ_N" ]; then
90 read -r -n 7 u
91 else
92 u=$(dd bs=1 count=7 2>/dev/null)
94 if [ "$u" != "nobody" ]; then
95 $ECHO "$SOCKSREPLY_FAILED"
96 echo "wrong socks user requested" >&2
97 exit
100 if [ "$HAVE_READ_N" ]; then
101 read -r -n 10 h
102 else
103 h=$(dd bs=1 count=10 2>/dev/null)
105 if [ "$h" != "localhost" ]; then
106 $ECHO "$SOCKSREPLY_FAILED"
107 echo "wrong socks address requested" >&2
108 exit
111 # send ok status
112 $ECHO "$SOCKSREPLY_OK"
114 # perform echo function
115 $CAT