3 import sys, os, getopt, socket, logging, time, locale, collections.abc, signal
4 import ashd.util, ashd.serve, ashd.htlib
11 out.write("usage: ashd-wsgi3 [-hAL] [-m PDM-SPEC] [-p MODPATH] [-t REQUEST-HANDLER[:PAR[=VAL](,PAR[=VAL])...]] HANDLER-MODULE [ARGS...]\n")
14 modwsgi_compat = False
16 opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:l:m:")
28 hspec = "free", {"max": a, "abort": "10"}
30 hspec = ashd.serve.parsehspec(a)
38 logging.basicConfig(format="ashd-wsgi3(%(name)s): %(levelname)s: %(message)s")
39 log = logging.getLogger("ashd-wsgi3")
42 handlermod = __import__(args[0], fromlist = ["dummy"])
43 except ImportError as exc:
44 sys.stderr.write("ashd-wsgi3: handler %s not found: %s\n" % (args[0], exc.args[0]))
46 if not modwsgi_compat:
47 if not hasattr(handlermod, "wmain"):
48 sys.stderr.write("ashd-wsgi3: handler %s has no `wmain' function\n" % args[0])
50 handler = handlermod.wmain(*args[1:])
52 if not hasattr(handlermod, "application"):
53 sys.stderr.write("ashd-wsgi3: handler %s has no `application' object\n" % args[0])
55 handler = handlermod.application
60 return os.path.join(cwd, path)
72 if ord(b'0') <= url[i] <= ord(b'9'):
73 c |= (url[i] - ord(b'0')) << 4
74 elif ord(b'a') <= url[i] <= ord(b'f'):
75 c |= (url[i] - ord(b'a') + 10) << 4
76 elif ord(b'A') <= url[i] <= ord(b'F'):
77 c |= (url[i] - ord(b'A') + 10) << 4
79 raise ValueError("Illegal URL escape character")
80 if ord(b'0') <= url[i + 1] <= ord(b'9'):
81 c |= url[i + 1] - ord('0')
82 elif ord(b'a') <= url[i + 1] <= ord(b'f'):
83 c |= url[i + 1] - ord(b'a') + 10
84 elif ord(b'A') <= url[i + 1] <= ord(b'F'):
85 c |= url[i + 1] - ord(b'A') + 10
87 raise ValueError("Illegal URL escape character")
91 raise ValueError("Incomplete URL escape character")
98 env["wsgi.version"] = 1, 0
99 for key, val in req.headers:
100 env["HTTP_" + key.upper().replace(b"-", b"_").decode("latin-1")] = val.decode("latin-1")
101 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
102 env["GATEWAY_INTERFACE"] = "CGI/1.1"
103 env["SERVER_PROTOCOL"] = req.ver.decode("latin-1")
104 env["REQUEST_METHOD"] = req.method.decode("latin-1")
106 rawpi = unquoteurl(req.rest)
110 name, rest, pi = (v.decode("utf-8") for v in (req.url, req.rest, rawpi))
111 env["wsgi.uri_encoding"] = "utf-8"
112 except UnicodeError as exc:
113 name, rest, pi = (v.decode("latin-1") for v in (req.url, req.rest, rawpi))
114 env["wsgi.uri_encoding"] = "latin-1"
115 env["REQUEST_URI"] = name
118 env["QUERY_STRING"] = name[p + 1:]
121 env["QUERY_STRING"] = ""
122 if name[-len(rest):] == rest:
123 # This is the same hack used in call*cgi.
124 name = name[:-len(rest)]
126 # This seems to be normal CGI behavior, but see callcgi.c for
130 env["SCRIPT_NAME"] = name
131 env["PATH_INFO"] = pi
132 for src, tgt in [("HTTP_HOST", "SERVER_NAME"), ("HTTP_X_ASH_PROTOCOL", "wsgi.url_scheme"),
133 ("HTTP_X_ASH_SERVER_ADDRESS", "SERVER_ADDR"), ("HTTP_X_ASH_SERVER_PORT", "SERVER_PORT"),
134 ("HTTP_X_ASH_ADDRESS", "REMOTE_ADDR"), ("HTTP_X_ASH_PORT", "REMOTE_PORT"),
135 ("HTTP_CONTENT_TYPE", "CONTENT_TYPE"), ("HTTP_CONTENT_LENGTH", "CONTENT_LENGTH")]:
136 if src in env: env[tgt] = env[src]
137 for key in ["HTTP_CONTENT_TYPE", "HTTP_CONTENT_LENGTH"]:
138 # The CGI specification does not strictly require this, but
139 # many actualy programs and libraries seem to.
140 if key in env: del env[key]
141 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == b"https": env["HTTPS"] = "on"
142 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"].decode(locale.getpreferredencoding()))
143 env["wsgi.input"] = req.sk
144 env["wsgi.errors"] = sys.stderr
145 env["wsgi.multithread"] = True
146 env["wsgi.multiprocess"] = False
147 env["wsgi.run_once"] = False
151 if isinstance(thing, collections.abc.ByteString):
154 return str(thing).encode("latin-1")
156 class request(ashd.serve.wsgirequest):
157 def __init__(self, *, bkreq, **kw):
158 super().__init__(**kw)
159 self.bkreq = bkreq.dup()
160 self.sendrights = None
163 return mkenv(self.bkreq)
165 def handlewsgi(self, env, startreq):
166 return handler(env, startreq)
169 return self.bkreq.bsk.fileno()
171 def writehead(self, status, headers):
172 headers = list(headers)
173 for header in headers:
175 if nm.lower() == "x-ash-send-rights":
176 self.sendrights = val
177 headers.remove(header)
179 w = self.buffer.extend
180 w(b"HTTP/1.1 " + recode(status) + b"\n")
181 for nm, val in headers:
182 w(recode(nm) + b": " + recode(val) + b"\n")
187 if self.sendrights is not None:
188 ret = ashd.htlib.sendfd(self.bkreq.bsk.fileno(), self.sendrights.fileno(), self.buffer)
189 self.sendrights.close()
190 self.sendrights = None
192 ret = self.bkreq.bsk.send(self.buffer, socket.MSG_DONTWAIT)
193 self.buffer[:ret] = b""
195 raise ashd.serve.closed()
201 if self.sendrights is not None:
202 self.sendrights.close()
205 reqhandler.handle(request(bkreq=req, handler=reqhandler))
207 if hspec[0] not in ashd.serve.names:
208 sys.stderr.write("ashd-wsgi3: no such request handler: %s\n" % hspec[0])
210 hclass = ashd.serve.names[hspec[0]]
212 hargs = hclass.parseargs(**hspec[1])
213 except ValueError as exc:
214 sys.stderr.write("ashd-wsgi3: %s\n" % exc)
217 def sigterm(sig, frame):
218 socket.fromfd(0, socket.AF_UNIX, socket.SOCK_SEQPACKET).shutdown(socket.SHUT_RDWR) # :P
219 for signum in [signal.SIGINT, signal.SIGTERM]:
220 signal.signal(signum, sigterm)
222 reqhandler = hclass(**hargs)
224 ashd.util.serveloop(handle)