3 import sys, os, getopt, threading, logging, time, locale, collections
4 import ashd.proto, ashd.util, ashd.perf, ashd.serve
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
58 return os.path.join(cwd, path)
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
77 raise ValueError("Illegal URL escape character")
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
85 raise ValueError("Illegal URL escape character")
89 raise ValueError("Incomplete URL escape character")
96 env["wsgi.version"] = 1, 0
97 for key, val in req.headers:
98 env["HTTP_" + key.upper().replace(b"-", b"_").decode("latin-1")] = val.decode("latin-1")
99 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
100 env["GATEWAY_INTERFACE"] = "CGI/1.1"
101 env["SERVER_PROTOCOL"] = req.ver.decode("latin-1")
102 env["REQUEST_METHOD"] = req.method.decode("latin-1")
104 rawpi = unquoteurl(req.rest)
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
116 env["QUERY_STRING"] = name[p + 1:]
119 env["QUERY_STRING"] = ""
120 if name[-len(rest):] == rest:
121 # This is the same hack used in call*cgi.
122 name = name[:-len(rest)]
124 # This seems to be normal CGI behavior, but see callcgi.c for
128 env["SCRIPT_NAME"] = name
129 env["PATH_INFO"] = pi
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")]:
134 if src in env: env[tgt] = env[src]
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]
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()))
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
149 guard = ashd.serve.abortlimiter(reqlimit).call
151 guard = lambda fun: fun()
154 if isinstance(thing, collections.ByteString):
157 return str(thing).encode("latin-1")
159 class reqthread(ashd.serve.wsgithread):
160 def __init__(self, req):
164 def handlewsgi(self):
165 return handler(self.env, self.startreq)
167 def writehead(self, status, headers):
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"
174 self.req.sk.write(buf)
176 raise ashd.serve.closed()
178 def writedata(self, data):
180 self.req.sk.write(data)
183 raise ashd.serve.closed()
186 self.env = mkenv(self.req)
187 with ashd.perf.request(self.env) as reqevent:
190 reqevent.response([self.status, self.headers])
200 reqthread(req).start()
202 ashd.util.serveloop(handle)