Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Websocket Server in Bash [poc]
#!/usr/bin/env bash
IN_PIPE=$1;
_hex() {
typeset num=`echo 'obase=16; ibase=10; '"$1" | bc`
if ((${#num} == 1)); then
num=0"$num"
fi
printf "0x%s" $num
}
_send_frame() {
typeset data="$1"
typeset first_byte="0x81"
typeset payload_length=${#data}
typeset second_byte=`_hex $payload_length` # no mask
printf "%s%s" $first_byte $second_byte | xxd -r -p
printf "%s" "$data"
}
_connect() {
rm -rf t
while true
do
read packet
echo $packet >> t
cnt=`echo $packet | wc -c`
if [ $cnt == 2 ] #end of message
then
key=`cat t | grep "Sec-WebSocket-Key:" | cut -f2 -d " "`
keylen=`echo -n $key | wc -c`
keylen=`expr $keylen - 1`
key2=`echo -n $key | cut -c -$keylen`
magic="258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
resp=`echo -n $key2$magic | openssl sha1 -binary | base64`
echo -ne "HTTP/1.1 101 Switching Protocols\r\n"
echo -ne "Connection: Upgrade\r\n"
echo -ne "Upgrade: websocket\r\n"
echo -ne "Sec-WebSocket-Accept: $resp\r\n\r\n"
break
fi
done
rm -rf t
}
# perform handshake
_connect;
# input loop
while true
do
read input < $IN_PIPE;
_send_frame "$input";
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment