Version 1.8.0.0
[socat.git] / proxy.sh
blob9f3c53eedf2a811ec7e13065a5ce903b95a607c3
1 #! /usr/bin/env bash
2 # source: proxy.sh
3 # Copyright Gerhard Rieger and contributors (see file CHANGES)
4 # Published under the GNU General Public License V.2, see file COPYING
6 # perform primitive simulation of a proxy server.
7 # accepts and answers correct HTTP CONNECT requests on stdio, and tries to
8 # establish the connection to the given server.
9 # it is required for socats test.sh
10 # for TCP, use this script like:
11 # socat TCP-L:8080,reuseaddr,fork EXEC:"proxy.sh",nofork
13 # 20130622 GR allow hostnames, not only IP addresses
15 if [ -z "$SOCAT" ]; then
16 if type socat >/dev/null 2>&1; then
17 SOCAT=socat
18 else
19 SOCAT="./socat"
23 if [ $(echo "x\c") = "x" ]; then E=""
24 elif [ $(echo -e "x\c") = "x" ]; then E="-e"
25 else
26 echo "cannot suppress trailing newline on echo" >&2
27 exit 1
29 ECHO="echo $E"
30 CR=$($ECHO "\r")
31 #echo "CR=$($ECHO "$CR\c" |od -c)" >&2
33 case `uname` in
34 HP-UX|OSF1)
35 # their cats are too stupid to work with unix domain sockets
36 CAT="$SOCAT -u stdin stdout"
39 CAT=cat
41 esac
43 SPACES=" "
44 while [ -n "$1" ]; do
45 case "$1" in
46 -w) n="$2"; while [ "$n" -gt 0 ]; do SPACES="$SPACES "; n=$((n-1)); done
47 shift ;;
48 #-s) STAT="$2"; shift ;;
49 esac
50 shift
51 done
53 badrequest () {
54 $ECHO "HTTP/1.0${SPACES}500 Bad Request$CR"
55 $ECHO "$CR"
58 # read and parse HTTP request
59 read m a h
60 #echo "\"$m\" \"$a\" \"$h\"" >&2
61 if [ "$m" != 'CONNECT' ]; then
62 badrequest; exit 1
64 if [[ "$a" == [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+ ]]; then
65 : go on below
66 elif [[ "$a" == [0-9a-zA-Z-.][0-9a-zA-Z-.]*:[0-9][0-9]* ]]; then
67 : go on below
68 else
69 badrequest; exit 1
72 if [[ "$h" == HTTP/1.[01][[:space:]]* ]]; then
73 : go on below
74 else
75 badrequest; exit 1
78 # read more headers until empty line
79 while [ "$l" != "$CR" ]; do
80 read l
81 done
83 # send status
84 $ECHO "HTTP/1.0${SPACES}200 OK$CR"
85 # send empty line
86 $ECHO "$CR"
88 # perform proxy (relay) function
89 $SOCAT $SOCAT_OPTS - tcp:$a || {
90 $ECHO "HTTP/1.0${SPACES}500 Failed to connect to $a$CR"
91 $ECHO $CR