aboutsummaryrefslogtreecommitdiffhomepage
path: root/snippets/bash_server
diff options
context:
space:
mode:
Diffstat (limited to 'snippets/bash_server')
-rw-r--r--snippets/bash_server90
1 files changed, 90 insertions, 0 deletions
diff --git a/snippets/bash_server b/snippets/bash_server
new file mode 100644
index 0000000..f008d11
--- /dev/null
+++ b/snippets/bash_server
@@ -0,0 +1,90 @@
1#!/bin/bash
2
3## Create the response FIFO
4rm -f response
5mkfifo response
6
7function handle_GET_home() {
8 RESPONSE=$(cat home.html | \
9 sed "s/{{$COOKIE_NAME}}/$COOKIE_VALUE/")
10}
11
12function handle_GET_login() {
13 RESPONSE=$(cat login.html)
14}
15
16function handle_POST_login() {
17 RESPONSE=$(cat post-login.http | \
18 sed "s/{{cookie_name}}/$INPUT_NAME/" | \
19 sed "s/{{cookie_value}}/$INPUT_VALUE/")
20}
21
22function handle_POST_logout() {
23 RESPONSE=$(cat post-logout.http | \
24 sed "s/{{cookie_name}}/$COOKIE_NAME/" | \
25 sed "s/{{cookie_value}}/$COOKIE_VALUE/")
26}
27
28function handle_not_found() {
29 RESPONSE=$(cat 404.html)
30}
31
32function handleRequest() {
33 ## Read request
34 while read line; do
35 echo $line
36 trline=$(echo $line | tr -d '[\r\n]')
37
38 [ -z "$trline" ] && break
39
40 HEADLINE_REGEX='(.*?)\s(.*?)\sHTTP.*?'
41 [[ "$trline" =~ $HEADLINE_REGEX ]] &&
42 REQUEST=$(echo $trline | sed -E "s/$HEADLINE_REGEX/\1 \2/")
43
44 CONTENT_LENGTH_REGEX='Content-Length:\s(.*?)'
45 [[ "$trline" =~ $CONTENT_LENGTH_REGEX ]] &&
46 CONTENT_LENGTH=$(echo $trline | sed -E "s/$CONTENT_LENGTH_REGEX/\1/")
47
48 COOKIE_REGEX='Cookie:\s(.*?)\=(.*?).*?'
49 [[ "$trline" =~ $COOKIE_REGEX ]] &&
50 read COOKIE_NAME COOKIE_VALUE <<< $(echo $trline | sed -E "s/$COOKIE_REGEX/\1 \2/")
51 done
52
53 ## Read body
54 if [ ! -z "$CONTENT_LENGTH" ]; then
55 BODY_REGEX='(.*?)=(.*?)'
56
57 while read -n$CONTENT_LENGTH -t1 line; do
58 echo $line
59 trline=`echo $line | tr -d '[\r\n]'`
60
61 [ -z "$trline" ] && break
62
63 read INPUT_NAME INPUT_VALUE <<< $(echo $trline | sed -E "s/$BODY_REGEX/\1 \2/")
64 done
65 fi
66
67 ## Route to the response handlers
68 case "$REQUEST" in
69 "GET /login") handle_GET_login ;;
70 "GET /") handle_GET_home ;;
71 "POST /login") handle_POST_login ;;
72 "POST /logout") handle_POST_logout ;;
73 *) handle_not_found ;;
74 esac
75
76 echo -e "$RESPONSE" > response
77}
78
79echo 'Listening on 3000...'
80
81## Keep server running forever
82while true; do
83 ## 1. wait for FIFO
84 ## 2. creates a socket and listens to the port 3000
85 ## 3. as soon as a request message arrives to the socket, pipes it to the handleRequest function
86 ## 4. the handleRequest function processes the request message and routes it to the response handler, which writes to the FIFO
87 ## 5. as soon as the FIFO receives a message, it's sent to the socket
88 ## 6. closes the connection (`-N`), closes the socket and repeat the loop
89 cat response | nc -lN 3000 | handleRequest
90done