1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
|
__all__ = []
import asyncore
import socket
import sys
try:
import cStringIO as StringIO
except ImportError:
import StringIO
class SCGIConnection(asyncore.dispatcher):
"""SCGI connection class used by L{SCGIServer}."""
# connection states
NEW = 0*4 | 1 # connection established, waiting for request
HEADER = 1*4 | 1 # the request length was received, waiting for the rest
BODY = 2*4 | 1 # the request header was received, waiting for the body
REQ = 3*4 | 2 # request received, sending response
def __init__(self, server, connection, addr, maxrequestsize=65536,
maxpostsize=8<<20, blocksize=4096):
asyncore.dispatcher.__init__(self, connection)
self.server = server # WSGISCGIServer instance
self.addr = addr # scgi client address
self.maxrequestsize = maxrequestsize
self.maxpostsize = maxpostsize
self.blocksize = blocksize
self.state = SCGIConnection.NEW # internal state
self.environ = {} # environment passed to wsgi app
self.reqlen = -1 # request length used in two different meanings
self.inbuff = "" # input buffer
self.outbuff = "" # output buffer
self.wsgihandler = None # wsgi application iterator
self.outheaders = () # headers to be sent
# () -> unset, (..,..) -> set, True -> sent
self.body = StringIO.StringIO() # request body
def _wsgi_headers(self):
return {"wsgi.version": (1, 0),
"wsgi.input": self.body,
"wsgi.errors": self.server.error,
"wsgi.url_scheme": "http",
"wsgi.multithread": False,
"wsgi.multiprocess": False,
"wsgi.run_once": False}
def _try_send_headers(self):
if self.outheaders != True:
assert not self.outbuff
status, headers = self.outheaders
headdata = "".join(map("%s: %s\r\n".__mod__, headers))
self.outbuff = "Status: %s\r\n%s\r\n" % (status, headdata)
self.outheaders = True
def _wsgi_write(self, data):
assert self.state >= SCGIConnection.REQ
assert isinstance(data, str)
if data:
self._try_send_headers()
self.outbuff += data
def readable(self):
"""C{asyncore} interface"""
return self.state & 1 == 1
def writable(self):
"""C{asyncore} interface"""
return self.state & 2 == 2
def handle_read(self):
"""C{asyncore} interface"""
data = self.recv(self.blocksize)
self.inbuff += data
if self.state == SCGIConnection.NEW:
if ':' in self.inbuff:
reqlen, self.inbuff = self.inbuff.split(':', 1)
if not reqlen.isdigit():
self.close()
return # invalid request format
reqlen = long(reqlen)
if reqlen > self.maxrequestsize:
self.close()
return # request too long
self.reqlen = reqlen
self.state = SCGIConnection.HEADER
elif len(self.inbuff) > self.maxrequestsize:
self.close()
return # request too long
if self.state == SCGIConnection.HEADER:
buff = self.inbuff[:self.reqlen]
remainder = self.inbuff[self.reqlen:]
while buff.count('\0') >= 2:
key, value, buff = buff.split('\0', 2)
self.environ[key] = value
self.reqlen -= len(key) + len(value) + 2
self.inbuff = buff + remainder
if self.reqlen == 0:
if self.inbuff.startswith(','):
self.inbuff = self.inbuff[1:]
if not self.environ.get("CONTENT_LENGTH", "bad").isdigit():
self.close()
return
self.reqlen = long(self.environ["CONTENT_LENGTH"])
if self.reqlen > self.maxpostsize:
self.close()
return
self.state = SCGIConnection.BODY
else:
self.close()
return # protocol violation
if self.state == SCGIConnection.BODY:
if len(self.inbuff) >= self.reqlen:
self.body.write(self.inbuff[:self.reqlen])
self.body.seek(0)
self.inbuff = ""
self.reqlen = 0
self.environ.update(self._wsgi_headers())
if self.environ.get("HTTPS", "no").lower() in ('yes', 'y', '1'):
self.environ["wsgi.url_scheme"] = "https"
if "HTTP_CONTENT_TYPE" in self.environ:
self.environ["CONTENT_TYPE"] = \
self.environ.pop("HTTP_CONTENT_TYPE")
if "HTTP_CONTENT_LENGTH" in self.environ:
del self.environ["HTTP_CONTENT_LENGTH"] # TODO: better way?
self.wsgihandler = iter(self.server.wsgiapp(
self.environ, self.start_response))
self.state = SCGIConnection.REQ
else:
self.body.write(self.inbuff)
self.reqlen -= len(self.inbuff)
self.inbuff = ""
def start_response(self, status, headers, exc_info=None):
assert isinstance(status, str)
assert isinstance(headers, list)
if exc_info:
if self.outheaders == True:
try:
raise exc_info[0], exc_info[1], exc_info[2]
finally:
exc_info = None
assert self.outheaders != True # unsent
self.outheaders = (status, headers)
return self._wsgi_write
def handle_write(self):
"""C{asyncore} interface"""
assert self.state >= SCGIConnection.REQ
if len(self.outbuff) < self.blocksize:
self._try_send_headers()
for data in self.wsgihandler:
assert isinstance(data, str)
if data:
self.outbuff += data
if len(self.outbuff) >= self.blocksize:
break
if len(self.outbuff) == 0:
if hasattr(self.wsgihandler, "close"):
self.wsgihandler.close()
self.close()
return
try:
sentbytes = self.send(self.outbuff[:self.blocksize])
except socket.error:
if hasattr(self.wsgihandler, "close"):
self.wsgihandler.close()
self.close()
return
self.outbuff = self.outbuff[sentbytes:]
def handle_close(self):
"""C{asyncore} interface"""
self.close()
__all__.append("SCGIServer")
class SCGIServer(asyncore.dispatcher):
"""SCGI Server for WSGI applications. It does not use multiple processes or
multiple threads."""
def __init__(self, wsgiapp, port, interface="localhost", error=sys.stderr,
maxrequestsize=None, maxpostsize=None, blocksize=None):
"""
@param wsgiapp: is the wsgi application to be run.
@type port: int
@param port: is an int representing the TCP port number to be used.
@type interface: str
@param interface: is a string specifying the network interface to bind
which defaults to C{"localhost"} making the server inaccessible
over network.
@param error: is a file-like object being passed as C{wsgi.error} in the
environ parameter defaulting to stderr.
@type maxrequestsize: int
@param maxrequestsize: limit the size of request blocks in scgi
connections. Connections are dropped when this limit is hit.
@type maxpostsize: int
@param maxpostsize: limit the size of post bodies that may be processed
by this instance. Connections are dropped when this limit is
hit.
@type blocksize: int
@param blocksize: is amount of data to read or write from or to the
network at once
"""
asyncore.dispatcher.__init__(self)
self.wsgiapp = wsgiapp
self.error = error
self.conf = {}
if maxrequestsize is not None:
self.conf["maxrequestsize"] = maxrequestsize
if maxpostsize is not None:
self.conf["maxpostsize"] = maxpostsize
if blocksize is not None:
self.conf["blocksize"] = blocksize
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((interface, port))
self.listen(5)
def handle_accept(self):
"""asyncore interface"""
ret = self.accept()
if ret is not None:
conn, addr = ret
SCGIConnection(self, conn, addr, **self.conf)
def run(self):
"""Runs the server. It will not return and you can invoke
C{asyncore.loop()} instead achieving the same effect."""
asyncore.loop()
|