doc: Fixed typo.
[ashd.git] / python / ashd-wsgi
CommitLineData
173e0e9e 1#!/usr/bin/python
c270f222 2
fd0303c3 3import sys, os, getopt, socket, logging, time, signal
8f410ce7 4import ashd.util, ashd.serve
d5ee5cde
FT
5try:
6 import pdm.srv
7except:
8 pdm = None
c270f222
FT
9
10def usage(out):
31466b18 11 out.write("usage: ashd-wsgi [-hAL] [-m PDM-SPEC] [-p MODPATH] [-t REQUEST-HANDLER[:PAR[=VAL](,PAR[=VAL])...]] HANDLER-MODULE [ARGS...]\n")
c270f222 12
8f410ce7 13hspec = "free", {}
c270f222 14modwsgi_compat = False
14640dcc 15setlog = True
8f410ce7 16opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:l:m:")
c270f222
FT
17for 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)
14640dcc
FT
23 elif o == "-L":
24 setlog = False
c270f222
FT
25 elif o == "-A":
26 modwsgi_compat = True
3e11d7ed 27 elif o == "-l":
8f410ce7
FT
28 hspec = "free", {"max": a, "abort": "10"}
29 elif o == "-t":
30 hspec = ashd.serve.parsehspec(a)
d5ee5cde
FT
31 elif o == "-m":
32 if pdm is not None:
33 pdm.srv.listen(a)
c270f222
FT
34if len(args) < 1:
35 usage(sys.stderr)
36 sys.exit(1)
14640dcc
FT
37if setlog:
38 logging.basicConfig(format="ashd-wsgi(%(name)s): %(levelname)s: %(message)s")
64a8cd9f 39log = logging.getLogger("ashd-wsgi")
c270f222
FT
40
41try:
42 handlermod = __import__(args[0], fromlist = ["dummy"])
173e0e9e
FT
43except ImportError, exc:
44 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
c270f222
FT
45 sys.exit(1)
46if not modwsgi_compat:
47 if not hasattr(handlermod, "wmain"):
48 sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
49 sys.exit(1)
adb11d5f 50 handler = handlermod.wmain(*args[1:])
c270f222
FT
51else:
52 if not hasattr(handlermod, "application"):
53 sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
54 sys.exit(1)
55 handler = handlermod.application
56
70d942a7
FT
57cwd = os.getcwd()
58def absolutify(path):
59 if path[0] != '/':
60 return os.path.join(cwd, path)
61 return path
62
09c82f9c 63def unquoteurl(url):
173e0e9e 64 buf = ""
09c82f9c
FT
65 i = 0
66 while i < len(url):
67 c = url[i]
68 i += 1
173e0e9e 69 if c == '%':
370d235f 70 if len(url) >= i + 2:
09c82f9c 71 c = 0
173e0e9e
FT
72 if '0' <= url[i] <= '9':
73 c |= (ord(url[i]) - ord('0')) << 4
74 elif 'a' <= url[i] <= 'f':
75 c |= (ord(url[i]) - ord('a') + 10) << 4
76 elif 'A' <= url[i] <= 'F':
77 c |= (ord(url[i]) - ord('A') + 10) << 4
09c82f9c
FT
78 else:
79 raise ValueError("Illegal URL escape character")
173e0e9e
FT
80 if '0' <= url[i + 1] <= '9':
81 c |= ord(url[i + 1]) - ord('0')
82 elif 'a' <= url[i + 1] <= 'f':
83 c |= ord(url[i + 1]) - ord('a') + 10
84 elif 'A' <= url[i + 1] <= 'F':
85 c |= ord(url[i + 1]) - ord('A') + 10
09c82f9c
FT
86 else:
87 raise ValueError("Illegal URL escape character")
173e0e9e 88 buf += chr(c)
09c82f9c
FT
89 i += 2
90 else:
91 raise ValueError("Incomplete URL escape character")
92 else:
173e0e9e 93 buf += c
09c82f9c 94 return buf
81a0ca30 95
761e7292 96def mkenv(req):
c270f222
FT
97 env = {}
98 env["wsgi.version"] = 1, 0
99 for key, val in req.headers:
173e0e9e 100 env["HTTP_" + key.upper().replace("-", "_")] = val
c270f222
FT
101 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
102 env["GATEWAY_INTERFACE"] = "CGI/1.1"
173e0e9e
FT
103 env["SERVER_PROTOCOL"] = req.ver
104 env["REQUEST_METHOD"] = req.method
105 env["REQUEST_URI"] = req.url
106 name = req.url
c270f222
FT
107 p = name.find('?')
108 if p >= 0:
c270f222 109 env["QUERY_STRING"] = name[p + 1:]
8498ab28 110 name = name[:p]
c270f222
FT
111 else:
112 env["QUERY_STRING"] = ""
173e0e9e 113 if name[-len(req.rest):] == req.rest:
53d666ca 114 # This is the same hack used in call*cgi.
173e0e9e
FT
115 name = name[:-len(req.rest)]
116 try:
117 pi = unquoteurl(req.rest)
118 except:
119 pi = req.rest
120 if name == '/':
53d666ca
FT
121 # This seems to be normal CGI behavior, but see callcgi.c for
122 # details.
123 pi = "/" + pi
124 name = ""
c270f222 125 env["SCRIPT_NAME"] = name
53d666ca 126 env["PATH_INFO"] = pi
173e0e9e 127 if "Host" in req: env["SERVER_NAME"] = req["Host"]
1af656d2 128 if "X-Ash-Server-Address" in req: env["SERVER_ADDR"] = req["X-Ash-Server-Address"]
173e0e9e
FT
129 if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
130 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
131 if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
1af656d2 132 if "X-Ash-Port" in req: env["REMOTE_PORT"] = req["X-Ash-Port"]
0bf0720d
FT
133 if "Content-Type" in req:
134 env["CONTENT_TYPE"] = req["Content-Type"]
135 # The CGI specification does not strictly require this, but
136 # many actualy programs and libraries seem to.
137 del env["HTTP_CONTENT_TYPE"]
138 if "Content-Length" in req:
139 env["CONTENT_LENGTH"] = req["Content-Length"]
75c134b6 140 del env["HTTP_CONTENT_LENGTH"]
173e0e9e
FT
141 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
142 if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
c270f222
FT
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
761e7292 148 return env
c270f222 149
8f410ce7
FT
150class request(ashd.serve.wsgirequest):
151 def __init__(self, bkreq, **kw):
152 super(request, self).__init__(**kw)
153 self.bkreq = bkreq.dup()
154
155 def mkenv(self):
156 return mkenv(self.bkreq)
c270f222 157
8f410ce7
FT
158 def handlewsgi(self, env, startreq):
159 return handler(env, startreq)
160
161 def fileno(self):
162 return self.bkreq.bsk.fileno()
699754de 163
761e7292 164 def writehead(self, status, headers):
8f410ce7
FT
165 w = self.buffer.extend
166 w("HTTP/1.1 %s\n" % status)
167 for nm, val in headers:
168 w("%s: %s\n" % (nm, val))
169 w("\n")
c270f222 170
8f410ce7 171 def flush(self):
8bb0e3c1 172 try:
8f410ce7
FT
173 ret = self.bkreq.bsk.send(self.buffer, socket.MSG_DONTWAIT)
174 self.buffer[:ret] = ""
761e7292
FT
175 except IOError:
176 raise ashd.serve.closed()
c270f222 177
8f410ce7
FT
178 def close(self):
179 self.bkreq.close()
180
c270f222 181def handle(req):
8f410ce7 182 reqhandler.handle(request(bkreq=req, handler=reqhandler))
c270f222 183
8f410ce7
FT
184if hspec[0] not in ashd.serve.names:
185 sys.stderr.write("ashd-wsgi: no such request handler: %s\n" % hspec[0])
186 sys.exit(1)
187hclass = ashd.serve.names[hspec[0]]
188try:
189 hargs = hclass.parseargs(**hspec[1])
190except ValueError as exc:
191 sys.stderr.write("ashd-wsgi: %s\n" % exc)
192 sys.exit(1)
193
fd0303c3
FT
194def sigterm(sig, frame):
195 socket.fromfd(0, socket.AF_UNIX, socket.SOCK_SEQPACKET).shutdown(socket.SHUT_RDWR) # :P
196for signum in [signal.SIGINT, signal.SIGTERM]:
197 signal.signal(signum, sigterm)
198
8f410ce7
FT
199reqhandler = hclass(**hargs)
200try:
201 ashd.util.serveloop(handle)
202finally:
203 reqhandler.close()