lib: Added bufio I/O-less copy function.
[ashd.git] / python3 / ashd-wsgi3
CommitLineData
55fa3f63 1#!/usr/bin/python3
c270f222 2
fd0303c3 3import sys, os, getopt, socket, logging, time, locale, collections, signal
19ff507b 4import ashd.util, ashd.serve
d5ee5cde
FT
5try:
6 import pdm.srv
7except:
8 pdm = None
c270f222
FT
9
10def usage(out):
31466b18 11 out.write("usage: ashd-wsgi3 [-hAL] [-m PDM-SPEC] [-p MODPATH] [-t REQUEST-HANDLER[:PAR[=VAL](,PAR[=VAL])...]] HANDLER-MODULE [ARGS...]\n")
c270f222 12
8db41888 13hspec = "free", {}
c270f222 14modwsgi_compat = False
14640dcc 15setlog = True
e361dba1 16opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:l:m:")
c270f222
FT
17for o, a in opts:
18 if o == "-h":
19 usage(sys.stdout)
20 sys.exit(0)
21 elif o == "-p":
22 sys.path.insert(0, a)
14640dcc
FT
23 elif o == "-L":
24 setlog = False
c270f222
FT
25 elif o == "-A":
26 modwsgi_compat = True
e361dba1 27 elif o == "-l":
19ff507b 28 hspec = "free", {"max": a, "abort": "10"}
8db41888
FT
29 elif o == "-t":
30 hspec = ashd.serve.parsehspec(a)
d5ee5cde
FT
31 elif o == "-m":
32 if pdm is not None:
33 pdm.srv.listen(a)
c270f222
FT
34if len(args) < 1:
35 usage(sys.stderr)
36 sys.exit(1)
14640dcc
FT
37if setlog:
38 logging.basicConfig(format="ashd-wsgi3(%(name)s): %(levelname)s: %(message)s")
64a8cd9f 39log = logging.getLogger("ashd-wsgi3")
c270f222
FT
40
41try:
42 handlermod = __import__(args[0], fromlist = ["dummy"])
55fa3f63 43except ImportError as exc:
1f3d7aa3 44 sys.stderr.write("ashd-wsgi3: handler %s not found: %s\n" % (args[0], exc.args[0]))
c270f222
FT
45 sys.exit(1)
46if not modwsgi_compat:
47 if not hasattr(handlermod, "wmain"):
1f3d7aa3 48 sys.stderr.write("ashd-wsgi3: handler %s has no `wmain' function\n" % args[0])
c270f222 49 sys.exit(1)
adb11d5f 50 handler = handlermod.wmain(*args[1:])
c270f222
FT
51else:
52 if not hasattr(handlermod, "application"):
1f3d7aa3 53 sys.stderr.write("ashd-wsgi3: handler %s has no `application' object\n" % args[0])
c270f222
FT
54 sys.exit(1)
55 handler = handlermod.application
56
70d942a7
FT
57cwd = os.getcwd()
58def absolutify(path):
59 if path[0] != '/':
60 return os.path.join(cwd, path)
61 return path
62
09c82f9c 63def unquoteurl(url):
55fa3f63 64 buf = bytearray()
09c82f9c
FT
65 i = 0
66 while i < len(url):
67 c = url[i]
68 i += 1
55fa3f63 69 if c == ord(b'%'):
370d235f 70 if len(url) >= i + 2:
09c82f9c 71 c = 0
55fa3f63
FT
72 if ord(b'0') <= url[i] <= ord(b'9'):
73 c |= (url[i] - ord(b'0')) << 4
74 elif ord(b'a') <= url[i] <= ord(b'f'):
75 c |= (url[i] - ord(b'a') + 10) << 4
76 elif ord(b'A') <= url[i] <= ord(b'F'):
77 c |= (url[i] - ord(b'A') + 10) << 4
09c82f9c
FT
78 else:
79 raise ValueError("Illegal URL escape character")
55fa3f63
FT
80 if ord(b'0') <= url[i + 1] <= ord(b'9'):
81 c |= url[i + 1] - ord('0')
82 elif ord(b'a') <= url[i + 1] <= ord(b'f'):
83 c |= url[i + 1] - ord(b'a') + 10
84 elif ord(b'A') <= url[i + 1] <= ord(b'F'):
85 c |= url[i + 1] - ord(b'A') + 10
09c82f9c
FT
86 else:
87 raise ValueError("Illegal URL escape character")
55fa3f63 88 buf.append(c)
09c82f9c
FT
89 i += 2
90 else:
91 raise ValueError("Incomplete URL escape character")
92 else:
55fa3f63 93 buf.append(c)
09c82f9c 94 return buf
81a0ca30 95
4881876d 96def mkenv(req):
c270f222
FT
97 env = {}
98 env["wsgi.version"] = 1, 0
99 for key, val in req.headers:
55fa3f63 100 env["HTTP_" + key.upper().replace(b"-", b"_").decode("latin-1")] = val.decode("latin-1")
c270f222
FT
101 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
102 env["GATEWAY_INTERFACE"] = "CGI/1.1"
55fa3f63
FT
103 env["SERVER_PROTOCOL"] = req.ver.decode("latin-1")
104 env["REQUEST_METHOD"] = req.method.decode("latin-1")
105 try:
106 rawpi = unquoteurl(req.rest)
107 except:
108 rawpi = req.rest
109 try:
110 name, rest, pi = (v.decode("utf-8") for v in (req.url, req.rest, rawpi))
111 env["wsgi.uri_encoding"] = "utf-8"
112 except UnicodeError as exc:
113 name, rest, pi = (v.decode("latin-1") for v in (req.url, req.rest, rawpi))
114 env["wsgi.uri_encoding"] = "latin-1"
115 env["REQUEST_URI"] = name
c270f222
FT
116 p = name.find('?')
117 if p >= 0:
c270f222 118 env["QUERY_STRING"] = name[p + 1:]
8498ab28 119 name = name[:p]
c270f222
FT
120 else:
121 env["QUERY_STRING"] = ""
55fa3f63 122 if name[-len(rest):] == rest:
53d666ca 123 # This is the same hack used in call*cgi.
55fa3f63
FT
124 name = name[:-len(rest)]
125 if name == "/":
53d666ca
FT
126 # This seems to be normal CGI behavior, but see callcgi.c for
127 # details.
128 pi = "/" + pi
129 name = ""
c270f222 130 env["SCRIPT_NAME"] = name
53d666ca 131 env["PATH_INFO"] = pi
1af656d2
FT
132 for src, tgt in [("HTTP_HOST", "SERVER_NAME"), ("HTTP_X_ASH_PROTOCOL", "wsgi.url_scheme"),
133 ("HTTP_X_ASH_SERVER_ADDRESS", "SERVER_ADDR"), ("HTTP_X_ASH_SERVER_PORT", "SERVER_PORT"),
134 ("HTTP_X_ASH_ADDRESS", "REMOTE_ADDR"), ("HTTP_X_ASH_PORT", "REMOTE_PORT"),
135 ("HTTP_CONTENT_TYPE", "CONTENT_TYPE"), ("HTTP_CONTENT_LENGTH", "CONTENT_LENGTH")]:
55fa3f63 136 if src in env: env[tgt] = env[src]
0bf0720d
FT
137 for key in ["HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"]:
138 # The CGI specification does not strictly require this, but
139 # many actualy programs and libraries seem to.
140 if key in env: del env[key]
55fa3f63
FT
141 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == b"https": env["HTTPS"] = "on"
142 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"].decode(locale.getpreferredencoding()))
c270f222
FT
143 env["wsgi.input"] = req.sk
144 env["wsgi.errors"] = sys.stderr
145 env["wsgi.multithread"] = True
146 env["wsgi.multiprocess"] = False
147 env["wsgi.run_once"] = False
4881876d 148 return env
c270f222 149
4881876d
FT
150def recode(thing):
151 if isinstance(thing, collections.ByteString):
152 return thing
153 else:
154 return str(thing).encode("latin-1")
155
46adc298
FT
156class request(ashd.serve.wsgirequest):
157 def __init__(self, *, bkreq, **kw):
158 super().__init__(**kw)
159 self.bkreq = bkreq.dup()
160
161 def mkenv(self):
162 return mkenv(self.bkreq)
163
164 def handlewsgi(self, env, startreq):
165 return handler(env, startreq)
166
167 def fileno(self):
168 return self.bkreq.bsk.fileno()
699754de 169
4881876d 170 def writehead(self, status, headers):
46adc298
FT
171 w = self.buffer.extend
172 w(b"HTTP/1.1 " + recode(status) + b"\n")
4881876d 173 for nm, val in headers:
46adc298
FT
174 w(recode(nm) + b": " + recode(val) + b"\n")
175 w(b"\n")
c270f222 176
46adc298 177 def flush(self):
8bb0e3c1 178 try:
46adc298
FT
179 ret = self.bkreq.bsk.send(self.buffer, socket.MSG_DONTWAIT)
180 self.buffer[:ret] = b""
4881876d
FT
181 except IOError:
182 raise ashd.serve.closed()
183
46adc298
FT
184 def close(self):
185 self.bkreq.close()
186
c270f222 187def handle(req):
46adc298 188 reqhandler.handle(request(bkreq=req, handler=reqhandler))
c270f222 189
8db41888
FT
190if hspec[0] not in ashd.serve.names:
191 sys.stderr.write("ashd-wsgi3: no such request handler: %s\n" % hspec[0])
192 sys.exit(1)
193hclass = ashd.serve.names[hspec[0]]
194try:
195 hargs = hclass.parseargs(**hspec[1])
196except ValueError as exc:
197 sys.stderr.write("ashd-wsgi3: %s\n" % exc)
198 sys.exit(1)
199
fd0303c3
FT
200def sigterm(sig, frame):
201 socket.fromfd(0, socket.AF_UNIX, socket.SOCK_SEQPACKET).shutdown(socket.SHUT_RDWR) # :P
202for signum in [signal.SIGINT, signal.SIGTERM]:
203 signal.signal(signum, sigterm)
204
8db41888 205reqhandler = hclass(**hargs)
c67f9f8b
FT
206try:
207 ashd.util.serveloop(handle)
208finally:
209 reqhandler.close()