3 import sys, os, getopt, threading, time
4 import ashd.proto, ashd.util
7 out.write("usage: ashd-wsgi [-hA] [-p MODPATH] [-l REQLIMIT] HANDLER-MODULE [ARGS...]\n")
10 modwsgi_compat = False
11 opts, args = getopt.getopt(sys.argv[1:], "+hAp:l:")
27 handlermod = __import__(args[0], fromlist = ["dummy"])
28 except ImportError, exc:
29 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
31 if not modwsgi_compat:
32 if not hasattr(handlermod, "wmain"):
33 sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
35 handler = handlermod.wmain(*args[1:])
37 if not hasattr(handlermod, "application"):
38 sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
40 handler = handlermod.application
42 class closed(IOError):
44 super(closed, self).__init__("The client has closed the connection.")
49 return os.path.join(cwd, path)
61 if '0' <= url[i] <= '9':
62 c |= (ord(url[i]) - ord('0')) << 4
63 elif 'a' <= url[i] <= 'f':
64 c |= (ord(url[i]) - ord('a') + 10) << 4
65 elif 'A' <= url[i] <= 'F':
66 c |= (ord(url[i]) - ord('A') + 10) << 4
68 raise ValueError("Illegal URL escape character")
69 if '0' <= url[i + 1] <= '9':
70 c |= ord(url[i + 1]) - ord('0')
71 elif 'a' <= url[i + 1] <= 'f':
72 c |= ord(url[i + 1]) - ord('a') + 10
73 elif 'A' <= url[i + 1] <= 'F':
74 c |= ord(url[i + 1]) - ord('A') + 10
76 raise ValueError("Illegal URL escape character")
80 raise ValueError("Incomplete URL escape character")
87 env["wsgi.version"] = 1, 0
88 for key, val in req.headers:
89 env["HTTP_" + key.upper().replace("-", "_")] = val
90 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
91 env["GATEWAY_INTERFACE"] = "CGI/1.1"
92 env["SERVER_PROTOCOL"] = req.ver
93 env["REQUEST_METHOD"] = req.method
94 env["REQUEST_URI"] = req.url
98 env["QUERY_STRING"] = name[p + 1:]
101 env["QUERY_STRING"] = ""
102 if name[-len(req.rest):] == req.rest:
103 # This is the same hack used in call*cgi.
104 name = name[:-len(req.rest)]
106 pi = unquoteurl(req.rest)
110 # This seems to be normal CGI behavior, but see callcgi.c for
114 env["SCRIPT_NAME"] = name
115 env["PATH_INFO"] = pi
116 if "Host" in req: env["SERVER_NAME"] = req["Host"]
117 if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
118 if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
119 if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
120 if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"]
121 if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"]
122 if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
123 if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
124 env["wsgi.input"] = req.sk
125 env["wsgi.errors"] = sys.stderr
126 env["wsgi.multithread"] = True
127 env["wsgi.multiprocess"] = False
128 env["wsgi.run_once"] = False
136 raise Exception, "Trying to write data before starting response."
137 status, headers = resp
140 req.sk.write("HTTP/1.1 %s\n" % status)
141 for nm, val in headers:
142 req.sk.write("%s: %s\n" % (nm, val))
157 def startreq(status, headers, exc_info = None):
159 if exc_info: # Interesting, this...
162 raise exc_info[0], exc_info[1], exc_info[2]
164 exc_info = None # CPython GC bug?
166 raise Exception, "Can only start responding once."
167 resp[:] = status, headers
170 respiter = handler(env, startreq)
173 for data in respiter:
180 if hasattr(respiter, "close"):
183 flightlock = threading.Condition()
186 class reqthread(threading.Thread):
187 def __init__(self, req):
188 super(reqthread, self).__init__(name = "Request handler")
198 while inflight >= reqlimit:
200 if time.time() - start > 10:
218 reqthread(req).start()
220 ashd.util.serveloop(handle)