3 import sys, os, getopt, threading, time, locale, collections
4 import ashd.proto, ashd.util
7 out.write("usage: ashd-wsgi [-hA] [-p MODPATH] [-l REQLIMIT] HANDLER-MODULE [ARGS...]\n")
10 modwsgi_compat = False
11 opts, args = getopt.getopt(sys.argv[1:], "+hAp:l:")
27 handlermod = __import__(args[0], fromlist = ["dummy"])
28 except ImportError as exc:
29 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.args[0]))
31 if not modwsgi_compat:
32 if not hasattr(handlermod, "wmain"):
33 sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
35 handler = handlermod.wmain(*args[1:])
37 if not hasattr(handlermod, "application"):
38 sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
40 handler = handlermod.application
42 class closed(IOError):
44 super().__init__("The client has closed the connection.")
49 return os.path.join(cwd, path)
61 if ord(b'0') <= url[i] <= ord(b'9'):
62 c |= (url[i] - ord(b'0')) << 4
63 elif ord(b'a') <= url[i] <= ord(b'f'):
64 c |= (url[i] - ord(b'a') + 10) << 4
65 elif ord(b'A') <= url[i] <= ord(b'F'):
66 c |= (url[i] - ord(b'A') + 10) << 4
68 raise ValueError("Illegal URL escape character")
69 if ord(b'0') <= url[i + 1] <= ord(b'9'):
70 c |= url[i + 1] - ord('0')
71 elif ord(b'a') <= url[i + 1] <= ord(b'f'):
72 c |= url[i + 1] - ord(b'a') + 10
73 elif ord(b'A') <= url[i + 1] <= ord(b'F'):
74 c |= url[i + 1] - ord(b'A') + 10
76 raise ValueError("Illegal URL escape character")
80 raise ValueError("Incomplete URL escape character")
87 env["wsgi.version"] = 1, 0
88 for key, val in req.headers:
89 env["HTTP_" + key.upper().replace(b"-", b"_").decode("latin-1")] = val.decode("latin-1")
90 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
91 env["GATEWAY_INTERFACE"] = "CGI/1.1"
92 env["SERVER_PROTOCOL"] = req.ver.decode("latin-1")
93 env["REQUEST_METHOD"] = req.method.decode("latin-1")
95 rawpi = unquoteurl(req.rest)
99 name, rest, pi = (v.decode("utf-8") for v in (req.url, req.rest, rawpi))
100 env["wsgi.uri_encoding"] = "utf-8"
101 except UnicodeError as exc:
102 name, rest, pi = (v.decode("latin-1") for v in (req.url, req.rest, rawpi))
103 env["wsgi.uri_encoding"] = "latin-1"
104 env["REQUEST_URI"] = name
107 env["QUERY_STRING"] = name[p + 1:]
110 env["QUERY_STRING"] = ""
111 if name[-len(rest):] == rest:
112 # This is the same hack used in call*cgi.
113 name = name[:-len(rest)]
115 # This seems to be normal CGI behavior, but see callcgi.c for
119 env["SCRIPT_NAME"] = name
120 env["PATH_INFO"] = pi
121 for src, tgt in [("HTTP_HOST", "SERVER_NAME"), ("HTTP_X_ASH_SERVER_PORT", "SERVER_PORT"),
122 ("HTTP_X_ASH_ADDRESS", "REMOTE_ADDR"), ("HTTP_CONTENT_TYPE", "CONTENT_TYPE"),
123 ("HTTP_CONTENT_LENGTH", "CONTENT_LENGTH"), ("HTTP_X_ASH_PROTOCOL", "wsgi.url_scheme")]:
124 if src in env: env[tgt] = env[src]
125 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == b"https": env["HTTPS"] = "on"
126 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"].decode(locale.getpreferredencoding()))
127 env["wsgi.input"] = req.sk
128 env["wsgi.errors"] = sys.stderr
129 env["wsgi.multithread"] = True
130 env["wsgi.multiprocess"] = False
131 env["wsgi.run_once"] = False
137 if isinstance(thing, collections.ByteString):
140 return str(thing).encode("latin-1")
145 raise Exception("Trying to write data before starting response.")
146 status, headers = resp
149 buf += b"HTTP/1.1 " + recode(status) + b"\n"
150 for nm, val in headers:
151 buf += recode(nm) + b": " + recode(val) + b"\n"
168 def startreq(status, headers, exc_info = None):
170 if exc_info: # Interesting, this...
175 exc_info = None # CPython GC bug?
177 raise Exception("Can only start responding once.")
178 resp[:] = status, headers
181 respiter = handler(env, startreq)
184 for data in respiter:
191 if hasattr(respiter, "close"):
194 flightlock = threading.Condition()
197 class reqthread(threading.Thread):
198 def __init__(self, req):
199 super().__init__(name = "Request handler")
208 while inflight >= reqlimit:
210 if time.time() - start > 10:
223 reqthread(req).start()
225 ashd.util.serveloop(handle)