lib: Removed the surely redundant struct timeentry from the mtio-epoll.
[ashd.git] / python3 / ashd-wsgi3
1 #!/usr/bin/python3
2
3 import sys, os, getopt, socket, logging, time, locale, collections, signal
4 import ashd.util, ashd.serve, ashd.htlib
5 try:
6     import pdm.srv
7 except:
8     pdm = None
9
10 def usage(out):
11     out.write("usage: ashd-wsgi3 [-hAL] [-m PDM-SPEC] [-p MODPATH] [-t REQUEST-HANDLER[:PAR[=VAL](,PAR[=VAL])...]] HANDLER-MODULE [ARGS...]\n")
12
13 hspec = "free", {}
14 modwsgi_compat = False
15 setlog = True
16 opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:l:m:")
17 for o, a in opts:
18     if o == "-h":
19         usage(sys.stdout)
20         sys.exit(0)
21     elif o == "-p":
22         sys.path.insert(0, a)
23     elif o == "-L":
24         setlog = False
25     elif o == "-A":
26         modwsgi_compat = True
27     elif o == "-l":
28         hspec = "free", {"max": a, "abort": "10"}
29     elif o == "-t":
30         hspec = ashd.serve.parsehspec(a)
31     elif o == "-m":
32         if pdm is not None:
33             pdm.srv.listen(a)
34 if len(args) < 1:
35     usage(sys.stderr)
36     sys.exit(1)
37 if setlog:
38     logging.basicConfig(format="ashd-wsgi3(%(name)s): %(levelname)s: %(message)s")
39 log = logging.getLogger("ashd-wsgi3")
40
41 try:
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]))
45     sys.exit(1)
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])
49         sys.exit(1)
50     handler = handlermod.wmain(*args[1:])
51 else:
52     if not hasattr(handlermod, "application"):
53         sys.stderr.write("ashd-wsgi3: handler %s has no `application' object\n" % args[0])
54         sys.exit(1)
55     handler = handlermod.application
56
57 cwd = os.getcwd()
58 def absolutify(path):
59     if path[0] != '/':
60         return os.path.join(cwd, path)
61     return path
62
63 def unquoteurl(url):
64     buf = bytearray()
65     i = 0
66     while i < len(url):
67         c = url[i]
68         i += 1
69         if c == ord(b'%'):
70             if len(url) >= i + 2:
71                 c = 0
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
78                 else:
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
86                 else:
87                     raise ValueError("Illegal URL escape character")
88                 buf.append(c)
89                 i += 2
90             else:
91                 raise ValueError("Incomplete URL escape character")
92         else:
93             buf.append(c)
94     return buf
95
96 def mkenv(req):
97     env = {}
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")
105     try:
106         rawpi = unquoteurl(req.rest)
107     except:
108         rawpi = req.rest
109     try:
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
116     p = name.find('?')
117     if p >= 0:
118         env["QUERY_STRING"] = name[p + 1:]
119         name = name[:p]
120     else:
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)]
125     if name == "/":
126         # This seems to be normal CGI behavior, but see callcgi.c for
127         # details.
128         pi = "/" + pi
129         name = ""
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
148     return env
149
150 def recode(thing):
151     if isinstance(thing, collections.ByteString):
152         return thing
153     else:
154         return str(thing).encode("latin-1")
155
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
161
162     def mkenv(self):
163         return mkenv(self.bkreq)
164
165     def handlewsgi(self, env, startreq):
166         return handler(env, startreq)
167
168     def fileno(self):
169         return self.bkreq.bsk.fileno()
170
171     def writehead(self, status, headers):
172         headers = list(headers)
173         for header in headers:
174             nm, val = header
175             if nm.lower() == "x-ash-send-rights":
176                 self.sendrights = val
177                 headers.remove(header)
178                 break
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")
183         w(b"\n")
184
185     def flush(self):
186         try:
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
191             else:
192                 ret = self.bkreq.bsk.send(self.buffer, socket.MSG_DONTWAIT)
193             self.buffer[:ret] = b""
194         except IOError:
195             raise ashd.serve.closed()
196
197     def close(self):
198         try:
199             self.bkreq.close()
200         finally:
201             if self.sendrights is not None:
202                 self.sendrights.close()
203
204 def handle(req):
205     reqhandler.handle(request(bkreq=req, handler=reqhandler))
206
207 if hspec[0] not in ashd.serve.names:
208     sys.stderr.write("ashd-wsgi3: no such request handler: %s\n" % hspec[0])
209     sys.exit(1)
210 hclass = ashd.serve.names[hspec[0]]
211 try:
212     hargs = hclass.parseargs(**hspec[1])
213 except ValueError as exc:
214     sys.stderr.write("ashd-wsgi3: %s\n" % exc)
215     sys.exit(1)
216
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)
221
222 reqhandler = hclass(**hargs)
223 try:
224     ashd.util.serveloop(handle)
225 finally:
226     reqhandler.close()