3 import sys, os, getopt, threading, logging, time
4 import ashd.proto, ashd.util, ashd.perf, ashd.serve
11 out.write("usage: ashd-wsgi [-hAL] [-m PDM-SPEC] [-p MODPATH] [-l REQLIMIT] HANDLER-MODULE [ARGS...]\n")
14 modwsgi_compat = False
16 opts, args = getopt.getopt(sys.argv[1:], "+hAp:l:m:")
36 logging.basicConfig(format="ashd-wsgi(%(name)s): %(levelname)s: %(message)s")
37 log = logging.getLogger("ashd-wsgi")
40 handlermod = __import__(args[0], fromlist = ["dummy"])
41 except ImportError, exc:
42 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
44 if not modwsgi_compat:
45 if not hasattr(handlermod, "wmain"):
46 sys.stderr.write("ashd-wsgi: 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-wsgi: handler %s has no `application' object\n" % args[0])
53 handler = handlermod.application
58 return os.path.join(cwd, path)
70 if '0' <= url[i] <= '9':
71 c |= (ord(url[i]) - ord('0')) << 4
72 elif 'a' <= url[i] <= 'f':
73 c |= (ord(url[i]) - ord('a') + 10) << 4
74 elif 'A' <= url[i] <= 'F':
75 c |= (ord(url[i]) - ord('A') + 10) << 4
77 raise ValueError("Illegal URL escape character")
78 if '0' <= url[i + 1] <= '9':
79 c |= ord(url[i + 1]) - ord('0')
80 elif 'a' <= url[i + 1] <= 'f':
81 c |= ord(url[i + 1]) - ord('a') + 10
82 elif 'A' <= url[i + 1] <= 'F':
83 c |= ord(url[i + 1]) - ord('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("-", "_")] = val
99 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
100 env["GATEWAY_INTERFACE"] = "CGI/1.1"
101 env["SERVER_PROTOCOL"] = req.ver
102 env["REQUEST_METHOD"] = req.method
103 env["REQUEST_URI"] = req.url
107 env["QUERY_STRING"] = name[p + 1:]
110 env["QUERY_STRING"] = ""
111 if name[-len(req.rest):] == req.rest:
112 # This is the same hack used in call*cgi.
113 name = name[:-len(req.rest)]
115 pi = unquoteurl(req.rest)
119 # This seems to be normal CGI behavior, but see callcgi.c for
123 env["SCRIPT_NAME"] = name
124 env["PATH_INFO"] = pi
125 if "Host" in req: env["SERVER_NAME"] = req["Host"]
126 if "X-Ash-Server-Address" in req: env["SERVER_ADDR"] = req["X-Ash-Server-Address"]
127 if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
128 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
129 if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
130 if "X-Ash-Port" in req: env["REMOTE_PORT"] = req["X-Ash-Port"]
131 if "Content-Type" in req:
132 env["CONTENT_TYPE"] = req["Content-Type"]
133 # The CGI specification does not strictly require this, but
134 # many actualy programs and libraries seem to.
135 del env["HTTP_CONTENT_TYPE"]
136 if "Content-Length" in req:
137 env["CONTENT_LENGTH"] = req["Content-Length"]
138 del env["HTTP_CONTENT_LENGTH"]
139 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
140 if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
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()
153 class reqthread(ashd.serve.wsgithread):
154 def __init__(self, req):
155 super(reqthread, self).__init__()
158 def handlewsgi(self):
159 return handler(self.env, self.startreq)
161 def writehead(self, status, headers):
163 self.req.sk.write("HTTP/1.1 %s\n" % status)
164 for nm, val in headers:
165 self.req.sk.write("%s: %s\n" % (nm, val))
166 self.req.sk.write("\n")
168 raise ashd.serve.closed()
170 def writedata(self, data):
172 self.req.sk.write(data)
175 raise ashd.serve.closed()
178 self.env = mkenv(self.req)
179 reqevent = ashd.perf.request(self.env)
180 exc = (None, None, None)
182 super(reqthread, self).handle()
184 reqevent.response([self.status, self.headers])
189 reqevent.__exit__(*exc)
193 guard(super(reqthread, self).run)
198 reqthread(req).start()
200 ashd.util.serveloop(handle)