3 import sys, os, getopt, threading, time, locale, collections
4 import ashd.proto, ashd.util, ashd.perf
11 out.write("usage: ashd-wsgi3 [-hA] [-m PDM-SPEC] [-p MODPATH] [-l REQLIMIT] HANDLER-MODULE [ARGS...]\n")
14 modwsgi_compat = False
15 opts, args = getopt.getopt(sys.argv[1:], "+hAp:l:m:")
34 handlermod = __import__(args[0], fromlist = ["dummy"])
35 except ImportError as exc:
36 sys.stderr.write("ashd-wsgi3: handler %s not found: %s\n" % (args[0], exc.args[0]))
38 if not modwsgi_compat:
39 if not hasattr(handlermod, "wmain"):
40 sys.stderr.write("ashd-wsgi3: handler %s has no `wmain' function\n" % args[0])
42 handler = handlermod.wmain(*args[1:])
44 if not hasattr(handlermod, "application"):
45 sys.stderr.write("ashd-wsgi3: handler %s has no `application' object\n" % args[0])
47 handler = handlermod.application
49 class closed(IOError):
51 super().__init__("The client has closed the connection.")
56 return os.path.join(cwd, path)
68 if ord(b'0') <= url[i] <= ord(b'9'):
69 c |= (url[i] - ord(b'0')) << 4
70 elif ord(b'a') <= url[i] <= ord(b'f'):
71 c |= (url[i] - ord(b'a') + 10) << 4
72 elif ord(b'A') <= url[i] <= ord(b'F'):
73 c |= (url[i] - ord(b'A') + 10) << 4
75 raise ValueError("Illegal URL escape character")
76 if ord(b'0') <= url[i + 1] <= ord(b'9'):
77 c |= url[i + 1] - ord('0')
78 elif ord(b'a') <= url[i + 1] <= ord(b'f'):
79 c |= url[i + 1] - ord(b'a') + 10
80 elif ord(b'A') <= url[i + 1] <= ord(b'F'):
81 c |= url[i + 1] - ord(b'A') + 10
83 raise ValueError("Illegal URL escape character")
87 raise ValueError("Incomplete URL escape character")
94 env["wsgi.version"] = 1, 0
95 for key, val in req.headers:
96 env["HTTP_" + key.upper().replace(b"-", b"_").decode("latin-1")] = val.decode("latin-1")
97 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
98 env["GATEWAY_INTERFACE"] = "CGI/1.1"
99 env["SERVER_PROTOCOL"] = req.ver.decode("latin-1")
100 env["REQUEST_METHOD"] = req.method.decode("latin-1")
102 rawpi = unquoteurl(req.rest)
106 name, rest, pi = (v.decode("utf-8") for v in (req.url, req.rest, rawpi))
107 env["wsgi.uri_encoding"] = "utf-8"
108 except UnicodeError as exc:
109 name, rest, pi = (v.decode("latin-1") for v in (req.url, req.rest, rawpi))
110 env["wsgi.uri_encoding"] = "latin-1"
111 env["REQUEST_URI"] = name
114 env["QUERY_STRING"] = name[p + 1:]
117 env["QUERY_STRING"] = ""
118 if name[-len(rest):] == rest:
119 # This is the same hack used in call*cgi.
120 name = name[:-len(rest)]
122 # This seems to be normal CGI behavior, but see callcgi.c for
126 env["SCRIPT_NAME"] = name
127 env["PATH_INFO"] = pi
128 for src, tgt in [("HTTP_HOST", "SERVER_NAME"), ("HTTP_X_ASH_SERVER_PORT", "SERVER_PORT"),
129 ("HTTP_X_ASH_ADDRESS", "REMOTE_ADDR"), ("HTTP_CONTENT_TYPE", "CONTENT_TYPE"),
130 ("HTTP_CONTENT_LENGTH", "CONTENT_LENGTH"), ("HTTP_X_ASH_PROTOCOL", "wsgi.url_scheme")]:
131 if src in env: env[tgt] = env[src]
132 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == b"https": env["HTTPS"] = "on"
133 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"].decode(locale.getpreferredencoding()))
134 env["wsgi.input"] = req.sk
135 env["wsgi.errors"] = sys.stderr
136 env["wsgi.multithread"] = True
137 env["wsgi.multiprocess"] = False
138 env["wsgi.run_once"] = False
144 if isinstance(thing, collections.ByteString):
147 return str(thing).encode("latin-1")
152 raise Exception("Trying to write data before starting response.")
153 status, headers = resp
156 buf += b"HTTP/1.1 " + recode(status) + b"\n"
157 for nm, val in headers:
158 buf += recode(nm) + b": " + recode(val) + b"\n"
175 def startreq(status, headers, exc_info = None):
177 if exc_info: # Interesting, this...
182 exc_info = None # CPython GC bug?
184 raise Exception("Can only start responding once.")
185 resp[:] = status, headers
188 with ashd.perf.request(env) as reqevent:
189 respiter = handler(env, startreq)
192 for data in respiter:
199 if hasattr(respiter, "close"):
202 reqevent.response(resp)
204 flightlock = threading.Condition()
207 class reqthread(threading.Thread):
208 def __init__(self, req):
209 super().__init__(name = "Request handler")
218 while inflight >= reqlimit:
220 if time.time() - start > 10:
234 reqthread(req).start()
236 ashd.util.serveloop(handle)