lib: Split epoll and select loops into separate files.
[ashd.git] / python / ashd-wsgi
CommitLineData
c270f222
FT
1#!/usr/bin/python
2
3import sys, os, getopt, threading
4e7888f7 4import ashd.proto, ashd.util
c270f222
FT
5
6def usage(out):
7 out.write("usage: ashd-wsgi [-hA] [-p MODPATH] HANDLER-MODULE [ARGS...]\n")
8
9modwsgi_compat = False
10opts, args = getopt.getopt(sys.argv[1:], "+hAp:")
11for o, a in opts:
12 if o == "-h":
13 usage(sys.stdout)
14 sys.exit(0)
15 elif o == "-p":
16 sys.path.insert(0, a)
17 elif o == "-A":
18 modwsgi_compat = True
19if len(args) < 1:
20 usage(sys.stderr)
21 sys.exit(1)
22
23try:
24 handlermod = __import__(args[0], fromlist = ["dummy"])
25except ImportError, exc:
26 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
27 sys.exit(1)
28if not modwsgi_compat:
29 if not hasattr(handlermod, "wmain"):
30 sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
31 sys.exit(1)
adb11d5f 32 handler = handlermod.wmain(*args[1:])
c270f222
FT
33else:
34 if not hasattr(handlermod, "application"):
35 sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
36 sys.exit(1)
37 handler = handlermod.application
38
70d942a7
FT
39cwd = os.getcwd()
40def absolutify(path):
41 if path[0] != '/':
42 return os.path.join(cwd, path)
43 return path
44
09c82f9c
FT
45def unquoteurl(url):
46 buf = ""
47 i = 0
48 while i < len(url):
49 c = url[i]
50 i += 1
51 if c == '%':
370d235f 52 if len(url) >= i + 2:
09c82f9c
FT
53 c = 0
54 if '0' <= url[i] <= '9':
55 c |= (ord(url[i]) - ord('0')) << 4
56 elif 'a' <= url[i] <= 'f':
370d235f 57 c |= (ord(url[i]) - ord('a') + 10) << 4
09c82f9c 58 elif 'A' <= url[i] <= 'F':
370d235f 59 c |= (ord(url[i]) - ord('A') + 10) << 4
09c82f9c
FT
60 else:
61 raise ValueError("Illegal URL escape character")
62 if '0' <= url[i + 1] <= '9':
63 c |= ord(url[i + 1]) - ord('0')
64 elif 'a' <= url[i + 1] <= 'f':
370d235f 65 c |= ord(url[i + 1]) - ord('a') + 10
09c82f9c 66 elif 'A' <= url[i + 1] <= 'F':
370d235f 67 c |= ord(url[i + 1]) - ord('A') + 10
09c82f9c
FT
68 else:
69 raise ValueError("Illegal URL escape character")
70 buf += chr(c)
71 i += 2
72 else:
73 raise ValueError("Incomplete URL escape character")
74 else:
75 buf += c
76 return buf
c270f222
FT
77def dowsgi(req):
78 env = {}
79 env["wsgi.version"] = 1, 0
80 for key, val in req.headers:
81 env["HTTP_" + key.upper().replace("-", "_")] = val
82 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
83 env["GATEWAY_INTERFACE"] = "CGI/1.1"
84 env["SERVER_PROTOCOL"] = req.ver
85 env["REQUEST_METHOD"] = req.method
86 env["REQUEST_URI"] = req.url
09c82f9c
FT
87 try:
88 env["PATH_INFO"] = unquoteurl(req.rest)
89 except:
90 env["PATH_INFO"] = req.rest
c270f222
FT
91 name = req.url
92 p = name.find('?')
93 if p >= 0:
c270f222 94 env["QUERY_STRING"] = name[p + 1:]
8498ab28 95 name = name[:p]
c270f222
FT
96 else:
97 env["QUERY_STRING"] = ""
98 if name[-len(req.rest):] == req.rest:
99 name = name[:-len(req.rest)]
100 env["SCRIPT_NAME"] = name
101 if "Host" in req: env["SERVER_NAME"] = req["Host"]
102 if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
103 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
104 if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
105 if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"]
106 if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"]
70d942a7 107 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
c270f222
FT
108 if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
109 env["wsgi.input"] = req.sk
110 env["wsgi.errors"] = sys.stderr
111 env["wsgi.multithread"] = True
112 env["wsgi.multiprocess"] = False
113 env["wsgi.run_once"] = False
114
115 resp = []
116 respsent = []
117
699754de 118 def flushreq():
c270f222
FT
119 if not respsent:
120 if not resp:
121 raise Exception, "Trying to write data before starting response."
122 status, headers = resp
123 respsent[:] = [True]
124 req.sk.write("HTTP/1.1 %s\n" % status)
125 for nm, val in headers:
126 req.sk.write("%s: %s\n" % (nm, val))
127 req.sk.write("\n")
699754de
FT
128
129 def write(data):
130 if not data:
131 return
132 flushreq()
c270f222
FT
133 req.sk.write(data)
134 req.sk.flush()
135
136 def startreq(status, headers, exc_info = None):
137 if resp:
138 if exc_info: # Interesting, this...
139 try:
140 if respsent:
141 raise exc_info[0], exc_info[1], exc_info[2]
142 finally:
143 exc_info = None # CPython GC bug?
144 else:
145 raise Exception, "Can only start responding once."
146 resp[:] = status, headers
147 return write
148
149 respiter = handler(env, startreq)
150 try:
151 for data in respiter:
152 write(data)
699754de
FT
153 if resp:
154 flushreq()
c270f222
FT
155 finally:
156 if hasattr(respiter, "close"):
157 respiter.close()
158
159class reqthread(threading.Thread):
160 def __init__(self, req):
161 super(reqthread, self).__init__(name = "Request handler")
162 self.req = req.dup()
163
164 def run(self):
165 try:
166 dowsgi(self.req)
167 finally:
168 self.req.close()
169
170def handle(req):
171 reqthread(req).start()
172
4e7888f7 173ashd.util.serveloop(handle)