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