3 import sys, os, getopt, threading, logging, time, locale, collections
4 import ashd.proto, ashd.util, ashd.perf
11 out.write("usage: ashd-wsgi3 [-hAL] [-m PDM-SPEC] [-p MODPATH] [-l REQLIMIT] HANDLER-MODULE [ARGS...]\n")
14 modwsgi_compat = False
16 opts, args = getopt.getopt(sys.argv[1:], "+hALp:l:m:")
36 logging.basicConfig(format="ashd-wsgi3(%(name)s): %(levelname)s: %(message)s")
37 log = logging.getLogger("ashd-wsgi3")
40 handlermod = __import__(args[0], fromlist = ["dummy"])
41 except ImportError as exc:
42 sys.stderr.write("ashd-wsgi3: handler %s not found: %s\n" % (args[0], exc.args[0]))
44 if not modwsgi_compat:
45 if not hasattr(handlermod, "wmain"):
46 sys.stderr.write("ashd-wsgi3: handler %s has no `wmain' function\n" % args[0])
48 handler = handlermod.wmain(*args[1:])
50 if not hasattr(handlermod, "application"):
51 sys.stderr.write("ashd-wsgi3: handler %s has no `application' object\n" % args[0])
53 handler = handlermod.application
55 class closed(IOError):
57 super().__init__("The client has closed the connection.")
62 return os.path.join(cwd, path)
74 if ord(b'0') <= url[i] <= ord(b'9'):
75 c |= (url[i] - ord(b'0')) << 4
76 elif ord(b'a') <= url[i] <= ord(b'f'):
77 c |= (url[i] - ord(b'a') + 10) << 4
78 elif ord(b'A') <= url[i] <= ord(b'F'):
79 c |= (url[i] - ord(b'A') + 10) << 4
81 raise ValueError("Illegal URL escape character")
82 if ord(b'0') <= url[i + 1] <= ord(b'9'):
83 c |= url[i + 1] - ord('0')
84 elif ord(b'a') <= url[i + 1] <= ord(b'f'):
85 c |= url[i + 1] - ord(b'a') + 10
86 elif ord(b'A') <= url[i + 1] <= ord(b'F'):
87 c |= url[i + 1] - ord(b'A') + 10
89 raise ValueError("Illegal URL escape character")
93 raise ValueError("Incomplete URL escape character")
100 env["wsgi.version"] = 1, 0
101 for key, val in req.headers:
102 env["HTTP_" + key.upper().replace(b"-", b"_").decode("latin-1")] = val.decode("latin-1")
103 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
104 env["GATEWAY_INTERFACE"] = "CGI/1.1"
105 env["SERVER_PROTOCOL"] = req.ver.decode("latin-1")
106 env["REQUEST_METHOD"] = req.method.decode("latin-1")
108 rawpi = unquoteurl(req.rest)
112 name, rest, pi = (v.decode("utf-8") for v in (req.url, req.rest, rawpi))
113 env["wsgi.uri_encoding"] = "utf-8"
114 except UnicodeError as exc:
115 name, rest, pi = (v.decode("latin-1") for v in (req.url, req.rest, rawpi))
116 env["wsgi.uri_encoding"] = "latin-1"
117 env["REQUEST_URI"] = name
120 env["QUERY_STRING"] = name[p + 1:]
123 env["QUERY_STRING"] = ""
124 if name[-len(rest):] == rest:
125 # This is the same hack used in call*cgi.
126 name = name[:-len(rest)]
128 # This seems to be normal CGI behavior, but see callcgi.c for
132 env["SCRIPT_NAME"] = name
133 env["PATH_INFO"] = pi
134 for src, tgt in [("HTTP_HOST", "SERVER_NAME"), ("HTTP_X_ASH_PROTOCOL", "wsgi.url_scheme"),
135 ("HTTP_X_ASH_SERVER_ADDRESS", "SERVER_ADDR"), ("HTTP_X_ASH_SERVER_PORT", "SERVER_PORT"),
136 ("HTTP_X_ASH_ADDRESS", "REMOTE_ADDR"), ("HTTP_X_ASH_PORT", "REMOTE_PORT"),
137 ("HTTP_CONTENT_TYPE", "CONTENT_TYPE"), ("HTTP_CONTENT_LENGTH", "CONTENT_LENGTH")]:
138 if src in env: env[tgt] = env[src]
139 for key in ["HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"]:
140 # The CGI specification does not strictly require this, but
141 # many actualy programs and libraries seem to.
142 if key in env: del env[key]
143 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == b"https": env["HTTPS"] = "on"
144 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"].decode(locale.getpreferredencoding()))
145 env["wsgi.input"] = req.sk
146 env["wsgi.errors"] = sys.stderr
147 env["wsgi.multithread"] = True
148 env["wsgi.multiprocess"] = False
149 env["wsgi.run_once"] = False
155 if isinstance(thing, collections.ByteString):
158 return str(thing).encode("latin-1")
163 raise Exception("Trying to write data before starting response.")
164 status, headers = resp
167 buf += b"HTTP/1.1 " + recode(status) + b"\n"
168 for nm, val in headers:
169 buf += recode(nm) + b": " + recode(val) + b"\n"
186 def startreq(status, headers, exc_info = None):
188 if exc_info: # Interesting, this...
193 exc_info = None # CPython GC bug?
195 raise Exception("Can only start responding once.")
196 resp[:] = status, headers
199 with ashd.perf.request(env) as reqevent:
201 respiter = handler(env, startreq)
203 for data in respiter:
208 if hasattr(respiter, "close"):
213 reqevent.response(resp)
215 flightlock = threading.Condition()
218 class reqthread(threading.Thread):
219 def __init__(self, req):
220 super().__init__(name = "Request handler")
229 while inflight >= reqlimit:
231 if time.time() - start > 10:
241 log.error("exception occurred in handler thread", exc_info=True)
247 reqthread(req).start()
249 ashd.util.serveloop(handle)