Updated changelog.
[ashd.git] / python / ashd-wsgi
1 #!/usr/bin/python
2
3 import sys, os, getopt, threading
4 import ashd.proto, ashd.util
5
6 def usage(out):
7     out.write("usage: ashd-wsgi [-hA] [-p MODPATH] HANDLER-MODULE [ARGS...]\n")
8
9 modwsgi_compat = False
10 opts, args = getopt.getopt(sys.argv[1:], "+hAp:")
11 for 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
19 if len(args) < 1:
20     usage(sys.stderr)
21     sys.exit(1)
22
23 try:
24     handlermod = __import__(args[0], fromlist = ["dummy"])
25 except ImportError, exc:
26     sys.stderr.write("ashd-wsgi: handler %s not found: %s\n" % (args[0], exc.message))
27     sys.exit(1)
28 if 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)
32     handler = handlermod.wmain(*args[1:])
33 else:
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
39 cwd = os.getcwd()
40 def absolutify(path):
41     if path[0] != '/':
42         return os.path.join(cwd, path)
43     return path
44
45 def unquoteurl(url):
46     buf = ""
47     i = 0
48     while i < len(url):
49         c = url[i]
50         i += 1
51         if c == '%':
52             if len(url) >= i + 2:
53                 c = 0
54                 if '0' <= url[i] <= '9':
55                     c |= (ord(url[i]) - ord('0')) << 4
56                 elif 'a' <= url[i] <= 'f':
57                     c |= (ord(url[i]) - ord('a') + 10) << 4
58                 elif 'A' <= url[i] <= 'F':
59                     c |= (ord(url[i]) - ord('A') + 10) << 4
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':
65                     c |= ord(url[i + 1]) - ord('a') + 10
66                 elif 'A' <= url[i + 1] <= 'F':
67                     c |= ord(url[i + 1]) - ord('A') + 10
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
77 def 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
87     try:
88         env["PATH_INFO"] = unquoteurl(req.rest)
89     except:
90         env["PATH_INFO"] = req.rest
91     name = req.url
92     p = name.find('?')
93     if p >= 0:
94         env["QUERY_STRING"] = name[p + 1:]
95         name = name[:p]
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"]
107     if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
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
118     def flushreq():
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")
128
129     def write(data):
130         if not data:
131             return
132         flushreq()
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)
153         if resp:
154             flushreq()
155     finally:
156         if hasattr(respiter, "close"):
157             respiter.close()
158
159 class 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     
170 def handle(req):
171     reqthread(req).start()
172
173 ashd.util.serveloop(handle)