doc: Include the header use of htextauth.
[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 class closed(IOError):
40     def __init__(self):
41         super(closed, self).__init__("The client has closed the connection.")
42
43 cwd = os.getcwd()
44 def absolutify(path):
45     if path[0] != '/':
46         return os.path.join(cwd, path)
47     return path
48
49 def unquoteurl(url):
50     buf = ""
51     i = 0
52     while i < len(url):
53         c = url[i]
54         i += 1
55         if c == '%':
56             if len(url) >= i + 2:
57                 c = 0
58                 if '0' <= url[i] <= '9':
59                     c |= (ord(url[i]) - ord('0')) << 4
60                 elif 'a' <= url[i] <= 'f':
61                     c |= (ord(url[i]) - ord('a') + 10) << 4
62                 elif 'A' <= url[i] <= 'F':
63                     c |= (ord(url[i]) - ord('A') + 10) << 4
64                 else:
65                     raise ValueError("Illegal URL escape character")
66                 if '0' <= url[i + 1] <= '9':
67                     c |= ord(url[i + 1]) - ord('0')
68                 elif 'a' <= url[i + 1] <= 'f':
69                     c |= ord(url[i + 1]) - ord('a') + 10
70                 elif 'A' <= url[i + 1] <= 'F':
71                     c |= ord(url[i + 1]) - ord('A') + 10
72                 else:
73                     raise ValueError("Illegal URL escape character")
74                 buf += chr(c)
75                 i += 2
76             else:
77                 raise ValueError("Incomplete URL escape character")
78         else:
79             buf += c
80     return buf
81
82 def dowsgi(req):
83     env = {}
84     env["wsgi.version"] = 1, 0
85     for key, val in req.headers:
86         env["HTTP_" + key.upper().replace("-", "_")] = val
87     env["SERVER_SOFTWARE"] = "ashd-wsgi/1"
88     env["GATEWAY_INTERFACE"] = "CGI/1.1"
89     env["SERVER_PROTOCOL"] = req.ver
90     env["REQUEST_METHOD"] = req.method
91     env["REQUEST_URI"] = req.url
92     try:
93         env["PATH_INFO"] = unquoteurl(req.rest)
94     except:
95         env["PATH_INFO"] = req.rest
96     name = req.url
97     p = name.find('?')
98     if p >= 0:
99         env["QUERY_STRING"] = name[p + 1:]
100         name = name[:p]
101     else:
102         env["QUERY_STRING"] = ""
103     if name[-len(req.rest):] == req.rest:
104         name = name[:-len(req.rest)]
105     env["SCRIPT_NAME"] = name
106     if "Host" in req: env["SERVER_NAME"] = req["Host"]
107     if "X-Ash-Server-Port" in req: env["SERVER_PORT"] = req["X-Ash-Server-Port"]
108     if "X-Ash-Protocol" in req and req["X-Ash-Protocol"] == "https": env["HTTPS"] = "on"
109     if "X-Ash-Address" in req: env["REMOTE_ADDR"] = req["X-Ash-Address"]
110     if "Content-Type" in req: env["CONTENT_TYPE"] = req["Content-Type"]
111     if "Content-Length" in req: env["CONTENT_LENGTH"] = req["Content-Length"]
112     if "X-Ash-File" in req: env["SCRIPT_FILENAME"] = absolutify(req["X-Ash-File"])
113     if "X-Ash-Protocol" in req: env["wsgi.url_scheme"] = req["X-Ash-Protocol"]
114     env["wsgi.input"] = req.sk
115     env["wsgi.errors"] = sys.stderr
116     env["wsgi.multithread"] = True
117     env["wsgi.multiprocess"] = False
118     env["wsgi.run_once"] = False
119
120     resp = []
121     respsent = []
122
123     def flushreq():
124         if not respsent:
125             if not resp:
126                 raise Exception, "Trying to write data before starting response."
127             status, headers = resp
128             respsent[:] = [True]
129             try:
130                 req.sk.write("HTTP/1.1 %s\n" % status)
131                 for nm, val in headers:
132                     req.sk.write("%s: %s\n" % (nm, val))
133                 req.sk.write("\n")
134             except IOError:
135                 raise closed()
136
137     def write(data):
138         if not data:
139             return
140         flushreq()
141         try:
142             req.sk.write(data)
143             req.sk.flush()
144         except IOError:
145             raise closed()
146
147     def startreq(status, headers, exc_info = None):
148         if resp:
149             if exc_info:                # Interesting, this...
150                 try:
151                     if respsent:
152                         raise exc_info[0], exc_info[1], exc_info[2]
153                 finally:
154                     exc_info = None     # CPython GC bug?
155             else:
156                 raise Exception, "Can only start responding once."
157         resp[:] = status, headers
158         return write
159
160     respiter = handler(env, startreq)
161     try:
162         try:
163             for data in respiter:
164                 write(data)
165             if resp:
166                 flushreq()
167         except closed:
168             pass
169     finally:
170         if hasattr(respiter, "close"):
171             respiter.close()
172
173 class reqthread(threading.Thread):
174     def __init__(self, req):
175         super(reqthread, self).__init__(name = "Request handler")
176         self.req = req.dup()
177     
178     def run(self):
179         try:
180             dowsgi(self.req)
181         finally:
182             self.req.close()
183     
184 def handle(req):
185     reqthread(req).start()
186
187 ashd.util.serveloop(handle)