3 import sys, os, getopt, threading, logging, time
4 import ashd.proto, ashd.util, ashd.perf
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")
39 handlermod = __import__(args[0], fromlist = ["dummy"])
40 except ImportError, exc:
41 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
43 if not modwsgi_compat:
44 if not hasattr(handlermod, "wmain"):
45 sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
47 handler = handlermod.wmain(*args[1:])
49 if not hasattr(handlermod, "application"):
50 sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
52 handler = handlermod.application
54 class closed(IOError):
56 super(closed, self).__init__("The client has closed the connection.")
61 return os.path.join(cwd, path)
73 if '0' <= url[i] <= '9':
74 c |= (ord(url[i]) - ord('0')) << 4
75 elif 'a' <= url[i] <= 'f':
76 c |= (ord(url[i]) - ord('a') + 10) << 4
77 elif 'A' <= url[i] <= 'F':
78 c |= (ord(url[i]) - ord('A') + 10) << 4
80 raise ValueError("Illegal URL escape character")
81 if '0' <= url[i + 1] <= '9':
82 c |= ord(url[i + 1]) - ord('0')
83 elif 'a' <= url[i + 1] <= 'f':
84 c |= ord(url[i + 1]) - ord('a') + 10
85 elif 'A' <= url[i + 1] <= 'F':
86 c |= ord(url[i + 1]) - ord('A') + 10
88 raise ValueError("Illegal URL escape character")
92 raise ValueError("Incomplete URL escape character")
99 env["wsgi.version"] = 1, 0
100 for key, val in req.headers:
101 env["HTTP_" + key.upper().replace("-", "_")] = val
102 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
103 env["GATEWAY_INTERFACE"] = "CGI/1.1"
104 env["SERVER_PROTOCOL"] = req.ver
105 env["REQUEST_METHOD"] = req.method
106 env["REQUEST_URI"] = req.url
110 env["QUERY_STRING"] = name[p + 1:]
113 env["QUERY_STRING"] = ""
114 if name[-len(req.rest):] == req.rest:
115 # This is the same hack used in call*cgi.
116 name = name[:-len(req.rest)]
118 pi = unquoteurl(req.rest)
122 # This seems to be normal CGI behavior, but see callcgi.c for
126 env["SCRIPT_NAME"] = name
127 env["PATH_INFO"] = pi
128 if "Host" in req: env["SERVER_NAME"] = req["Host"]
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"]
132 if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"]
133 if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"]
134 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
135 if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
136 env["wsgi.input"] = req.sk
137 env["wsgi.errors"] = sys.stderr
138 env["wsgi.multithread"] = True
139 env["wsgi.multiprocess"] = False
140 env["wsgi.run_once"] = False
148 raise Exception, "Trying to write data before starting response."
149 status, headers = resp
152 req.sk.write("HTTP/1.1 %s\n" % status)
153 for nm, val in headers:
154 req.sk.write("%s: %s\n" % (nm, val))
169 def startreq(status, headers, exc_info = None):
171 if exc_info: # Interesting, this...
174 raise exc_info[0], exc_info[1], exc_info[2]
176 exc_info = None # CPython GC bug?
178 raise Exception, "Can only start responding once."
179 resp[:] = status, headers
182 reqevent = ashd.perf.request(env)
183 exc = (None, None, None)
185 respiter = handler(env, startreq)
188 for data in respiter:
195 if hasattr(respiter, "close"):
198 reqevent.response(resp)
203 reqevent.__exit__(*exc)
205 flightlock = threading.Condition()
208 class reqthread(threading.Thread):
209 def __init__(self, req):
210 super(reqthread, self).__init__(name = "Request handler")
220 while inflight >= reqlimit:
222 if time.time() - start > 10:
240 reqthread(req).start()
242 ashd.util.serveloop(handle)