3 import sys, os, getopt, socket, logging, time
4 import ashd.util, ashd.serve
11 out.write("usage: ashd-wsgi [-hAL] [-m PDM-SPEC] [-p MODPATH] [-t REQUEST-HANDLER[:PAR[=VAL](,PAR[=VAL])...]] HANDLER-MODULE [ARGS...]\n")
14 modwsgi_compat = False
16 opts, args = getopt.getopt(sys.argv[1:], "+hALp:t:l:m:")
28 hspec = "free", {"max": a, "abort": "10"}
30 hspec = ashd.serve.parsehspec(a)
38 logging.basicConfig(format="ashd-wsgi(%(name)s): %(levelname)s: %(message)s")
39 log = logging.getLogger("ashd-wsgi")
42 handlermod = __import__(args[0], fromlist = ["dummy"])
43 except ImportError, exc:
44 sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
46 if not modwsgi_compat:
47 if not hasattr(handlermod, "wmain"):
48 sys.stderr.write("ashd-wsgi: handler %s has no `wmain' function\n" % args[0])
50 handler = handlermod.wmain(*args[1:])
52 if not hasattr(handlermod, "application"):
53 sys.stderr.write("ashd-wsgi: handler %s has no `application' object\n" % args[0])
55 handler = handlermod.application
60 return os.path.join(cwd, path)
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
79 raise ValueError("Illegal URL escape character")
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
87 raise ValueError("Illegal URL escape character")
91 raise ValueError("Incomplete URL escape character")
98 env["wsgi.version"] = 1, 0
99 for key, val in req.headers:
100 env["HTTP_" + key.upper().replace("-", "_")] = val
101 env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
102 env["GATEWAY_INTERFACE"] = "CGI/1.1"
103 env["SERVER_PROTOCOL"] = req.ver
104 env["REQUEST_METHOD"] = req.method
105 env["REQUEST_URI"] = req.url
109 env["QUERY_STRING"] = name[p + 1:]
112 env["QUERY_STRING"] = ""
113 if name[-len(req.rest):] == req.rest:
114 # This is the same hack used in call*cgi.
115 name = name[:-len(req.rest)]
117 pi = unquoteurl(req.rest)
121 # This seems to be normal CGI behavior, but see callcgi.c for
125 env["SCRIPT_NAME"] = name
126 env["PATH_INFO"] = pi
127 if "Host" in req: env["SERVER_NAME"] = req["Host"]
128 if "X-Ash-Server-Address" in req: env["SERVER_ADDR"] = req["X-Ash-Server-Address"]
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 "X-Ash-Port" in req: env["REMOTE_PORT"] = req["X-Ash-Port"]
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"]
140 del env["HTTP_CONTENT_LENGTH"]
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"]
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
150 class request(ashd.serve.wsgirequest):
151 def __init__(self, bkreq, **kw):
152 super(request, self).__init__(**kw)
153 self.bkreq = bkreq.dup()
156 return mkenv(self.bkreq)
158 def handlewsgi(self, env, startreq):
159 return handler(env, startreq)
162 return self.bkreq.bsk.fileno()
164 def writehead(self, status, headers):
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))
173 ret = self.bkreq.bsk.send(self.buffer, socket.MSG_DONTWAIT)
174 self.buffer[:ret] = ""
176 raise ashd.serve.closed()
182 reqhandler.handle(request(bkreq=req, handler=reqhandler))
184 if hspec[0] not in ashd.serve.names:
185 sys.stderr.write("ashd-wsgi: no such request handler: %s\n" % hspec[0])
187 hclass = ashd.serve.names[hspec[0]]
189 hargs = hclass.parseargs(**hspec[1])
190 except ValueError as exc:
191 sys.stderr.write("ashd-wsgi: %s\n" % exc)
194 reqhandler = hclass(**hargs)
196 ashd.util.serveloop(handle)