]> git.plutz.net Git - cgilite/blob - server.sh
f8760696dd4f75bf5cfdcdac1439899e0b77e298
[cgilite] / server.sh
1 #!/bin/zsh
2
3 # Copyright 2016 Paul Hänsch
4 #
5 # This file is part of shcgi.
6
7 # shcgi is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # shcgi is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with shcgi.  If not, see <http://www.gnu.org/licenses/>. 
19
20 if [ "$1" = '--server' ]; then
21   shift 1
22   ncat -klc "$call --ncat" $@
23   exit $?
24 fi
25
26 export REMOTE_ADDR="${NCAT_REMOTE_ADDR}"
27 export SERVER_NAME="${NCAT_LOCAL_ADDR}"
28 export SERVER_PORT="${NCAT_LOCAL_PORT}"
29
30 eval $(
31 sed -unr '
32   w/dev/stderr
33   /^(GET|HEAD|POST) ([^\?]*)\??(.+)? (HTTP\/[0-9]\.[0-9])\r?$/{
34     h
35     s;^(GET|HEAD|POST) ([^\?]*)\??(.+)? (HTTP\/[0-9]\.[0-9])\r?$;export REQUEST_METHOD='\''\1'\'';p
36     g
37     s;^(GET|HEAD|POST) ([^\?]*\??.*) (HTTP\/[0-9]\.[0-9])\r?$;\2;
38     s;'\'';'\''\\'\'''\'';g
39     s;^.*$;export REQUEST_URI='\''&'\'';p
40     g
41     s;^(GET|HEAD|POST) ([^\?]*)\??(.+)? (HTTP\/[0-9]\.[0-9])\r?$;\2;
42     s;'\'';'\''\\'\'''\'';g
43     s;^.*$;export PATH_INFO='\''&'\'';p
44     g
45     s;^(GET|HEAD|POST) ([^\?]*)\??(.+)? (HTTP\/[0-9]\.[0-9])\r?$;\3;
46     s;'\'';'\''\\'\'''\'';g
47     s;^.*$;export QUERY_STRING='\''&'\'';p
48     g
49     s;^(GET|HEAD|POST) ([^\?]*)\??(.+)? (HTTP\/[0-9]\.[0-9])\r?$;export SERVER_PROTOCOL='\''\4'\'';p
50     g
51   }
52
53   /^[Pp][Rr][Oo][Xx][Yy]: /d
54
55   /^[a-zA-Z_-]+: .*$/{
56     h
57     s;^[^:]+: (.*)\r$;\1;
58     s;'\'';'\''\\'\'''\'';g
59     s;^.*$;'\''&'\'';
60     x
61     s;: .*$;;
62     y;abcdefghijklmnopqrstuvwxyz-;ABCDEFGHIJKLMNOPQRSTUVWXYZ_;
63     s;^.+$;export HTTP_&=;
64     G
65     s;\n;;
66     p
67   }
68   /^\r?$/q
69 '
70 )
71
72 HTTP_format(){
73   LC_ALL=C sed -urn '
74   :A
75   /^\r?$/!{H;n;bA}
76   
77   g
78   s;^(\r?\n)*;;;
79   s;([^\r])\n;\1\r\n;g;
80   aConnection: close\r\n\r
81   /^Status: *[1-5][0-9][0-9] .*/{s;^Status: *;HTTP/1.1 ;; bX}
82   s;^(.+\n)?Location: .*$;HTTP/1.1 302 Found\r\n&;
83   s;^(.+\n)?Content-Type: .*$;HTTP/1.1 200 OK\r\n&;
84   
85   :X
86   p
87   $q
88   n
89   bX
90   '
91 }
92
93
94 if [ -z "$QUERY_STRING" ]; then
95   PATH_INFO="$(printf "$(printf %s "$PATH_INFO" |sed 's:+: :g;s:\\:\\\\:g;s:%:\\x:g')")"
96   PATH_INFO="$(invalidate "${PATH_INFO}" '(^|.*/)\.\./.*' '')"
97   [ -f "$_DATA/$PATH_INFO" ] && . "$_EXEC/shcgi/static.sh" "$_DATA/$PATH_INFO"
98   exit 0
99 fi |HTTP_format