Version 1.8.0.0
[socat.git] / socks4echo.sh
blob48ea536608971f26ea24bd1048836d82ccbaf469
1 #! /usr/bin/env bash
2 # source: socks4echo.sh
4 # Copyright Gerhard Rieger and contributors (see file CHANGES)
5 # Published under the GNU General Public License V.2, see file COPYING
7 # perform primitive simulation of a socks4 server with echo function via stdio.
8 # accepts and answers correct SOCKS4 requests, but then just echoes data.
9 # it is required for test.sh
10 # for TCP, use this script as:
11 # socat tcp-l:1080,reuseaddr,crlf system:"socks4echo.sh"
13 # older bash and ksh do not have -n option to read command; we try dd then
14 #if echo a |read -n 1 null >/dev/null 2>&1; then
15 # HAVE_READ_N=1
16 #else
17 # and newer bash (4.3) has some other problem with read -n
18 HAVE_READ_N=
19 #fi
21 if type socat >/dev/null 2>&1; then
22 SOCAT=socat
23 else
24 SOCAT=./socat
27 case `uname` in
28 HP-UX|OSF1)
29 CAT="$SOCAT -u stdin stdout"
32 CAT=cat
34 esac
36 if [ $(echo "x\c") = "x" ]; then E=""
37 elif [ $(echo -e "x\c") = "x" ]; then E="-e"
38 else
39 echo "cannot suppress trailing newline on echo" >&2
40 exit 1
42 ECHO="echo $E"
44 if [ $($ECHO "\0101") = "A" ]; then
45 SOCKSREPLY_FAILED="\0\0133\0\0\0\0\0\0\c"
46 SOCKSREPLY_OK="\0\0132\0\0\0\0\0\0\c"
47 else
48 SOCKSREPLY_FAILED="\0\133\0\0\0\0\0\0\c"
49 SOCKSREPLY_OK="\0\132\0\0\0\0\0\0\c"
52 # read and parse SOCKS4 header
53 if [ "$HAVE_READ_N" ]; then
54 read -r -n 1 vn # bash 2.0.3 does not support -n
55 else
56 vn=$(dd bs=1 count=1 2>/dev/null)
58 if [ "$vn" != $($ECHO "\04") ]; then
59 $ECHO "$SOCKSREPLY_FAILED"
60 echo "invalid socks version requested" >&2
61 exit
64 if [ "$HAVE_READ_N" ]; then
65 read -r -n 1 cd
66 else
67 cd=$(dd bs=1 count=1 2>/dev/null)
69 if [ "$cd" != $($ECHO "\01") ]; then
70 $ECHO "$SOCKSREPLY_FAILED"
71 echo "invalid socks operation requested" >&2
72 exit
75 if [ "$HAVE_READ_N" ]; then
76 read -r -n 6 a
77 else
78 a=$(dd bs=1 count=6 2>/dev/null)
80 if [ "$a" != "$($ECHO "}m bL6")" ]; then
81 $ECHO "$SOCKSREPLY_FAILED"
82 echo "$0: wrong socks address or port requested" >&2
83 echo "$0: expected $($ECHO "}m bL6"|od -t x1), received $($ECHO "$a"|od -t x1)" >&2
84 exit
87 if [ "$HAVE_READ_N" ]; then
88 read -r -n 7 u
89 else
90 u=$(dd bs=1 count=7 2>/dev/null)
92 if [ "$u" != "nobody" ]; then
93 $ECHO "$SOCKSREPLY_FAILED"
94 echo "wrong socks user requested (expected \"nobody\")" >&2
95 exit
98 # send ok status
99 $ECHO "$SOCKSREPLY_OK"
101 # perform echo function
102 $CAT