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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
|
import string, urlparse, binascii
import odict, utils
class HttpError(Exception):
def __init__(self, code, message):
super(HttpError, self).__init__(message)
self.code = code
class HttpErrorConnClosed(HttpError):
pass
def _is_valid_port(port):
if not 0 <= port <= 65535:
return False
return True
def _is_valid_host(host):
try:
host.decode("idna")
except ValueError:
return False
if "\0" in host:
return None
return True
def parse_url(url):
"""
Returns a (scheme, host, port, path) tuple, or None on error.
Checks that:
port is an integer 0-65535
host is a valid IDNA-encoded hostname with no null-bytes
path is valid ASCII
"""
try:
scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
except ValueError:
return None
if not scheme:
return None
if ':' in netloc:
host, port = string.rsplit(netloc, ':', maxsplit=1)
try:
port = int(port)
except ValueError:
return None
else:
host = netloc
if scheme == "https":
port = 443
else:
port = 80
path = urlparse.urlunparse(('', '', path, params, query, fragment))
if not path.startswith("/"):
path = "/" + path
if not _is_valid_host(host):
return None
if not utils.isascii(path):
return None
if not _is_valid_port(port):
return None
return scheme, host, port, path
def read_headers(fp):
"""
Read a set of headers from a file pointer. Stop once a blank line is
reached. Return a ODictCaseless object, or None if headers are invalid.
"""
ret = []
name = ''
while 1:
line = fp.readline()
if not line or line == '\r\n' or line == '\n':
break
if line[0] in ' \t':
if not ret:
return None
# continued header
ret[-1][1] = ret[-1][1] + '\r\n ' + line.strip()
else:
i = line.find(':')
# We're being liberal in what we accept, here.
if i > 0:
name = line[:i]
value = line[i+1:].strip()
ret.append([name, value])
else:
return None
return odict.ODictCaseless(ret)
def read_chunked(fp, headers, limit, is_request):
"""
Read a chunked HTTP body.
May raise HttpError.
"""
# FIXME: Should check if chunked is the final encoding in the headers
# http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-16#section-3.3 3.3 2.
content = ""
total = 0
code = 400 if is_request else 502
while 1:
line = fp.readline(128)
if line == "":
raise HttpErrorConnClosed(code, "Connection closed prematurely")
if line != '\r\n' and line != '\n':
try:
length = int(line, 16)
except ValueError:
# FIXME: Not strictly correct - this could be from the server, in which
# case we should send a 502.
raise HttpError(code, "Invalid chunked encoding length: %s"%line)
if not length:
break
total += length
if limit is not None and total > limit:
msg = "HTTP Body too large."\
" Limit is %s, chunked content length was at least %s"%(limit, total)
raise HttpError(code, msg)
content += fp.read(length)
line = fp.readline(5)
if line != '\r\n':
raise HttpError(code, "Malformed chunked body")
while 1:
line = fp.readline()
if line == "":
raise HttpErrorConnClosed(code, "Connection closed prematurely")
if line == '\r\n' or line == '\n':
break
return content
def read_next_chunk(fp, headers, is_request):
"""
Read next piece of a chunked HTTP body. Returns next piece of
content as a string or None if we hit the end.
"""
# TODO: see and understand the FIXME in read_chunked and
# see if we need to apply here?
content = ""
code = 400 if is_request else 502
line = fp.readline(128)
if line == "":
raise HttpErrorConnClosed(code, "Connection closed prematurely")
try:
length = int(line, 16)
except ValueError:
# TODO: see note in this part of read_chunked()
raise HttpError(code, "Invalid chunked encoding length: %s"%line)
if length > 0:
content += fp.read(length)
print "read content: '%s'" % content
line = fp.readline(5)
if line == '':
raise HttpErrorConnClosed(code, "Connection closed prematurely")
if line != '\r\n':
raise HttpError(code, "Malformed chunked body: '%s' (len=%d)" % (line, length))
if content == "":
content = None # normalize zero length to None, meaning end of chunked stream
return content # return this chunk
def write_chunk(fp, content):
"""
Write a chunk with chunked encoding format, returns True
if there should be more chunks or False if you passed
None, meaning this was the last chunk.
"""
if content == None or content == "":
fp.write("0\r\n\r\n")
return False
fp.write("%x\r\n" % len(content))
fp.write(content)
fp.write("\r\n")
return True
def get_header_tokens(headers, key):
"""
Retrieve all tokens for a header key. A number of different headers
follow a pattern where each header line can containe comma-separated
tokens, and headers can be set multiple times.
"""
toks = []
for i in headers[key]:
for j in i.split(","):
toks.append(j.strip())
return toks
def has_chunked_encoding(headers):
return "chunked" in [i.lower() for i in get_header_tokens(headers, "transfer-encoding")]
def parse_http_protocol(s):
"""
Parse an HTTP protocol declaration. Returns a (major, minor) tuple, or
None.
"""
if not s.startswith("HTTP/"):
return None
_, version = s.split('/', 1)
if "." not in version:
return None
major, minor = version.split('.', 1)
try:
major = int(major)
minor = int(minor)
except ValueError:
return None
return major, minor
def parse_http_basic_auth(s):
words = s.split()
if len(words) != 2:
return None
scheme = words[0]
try:
user = binascii.a2b_base64(words[1])
except binascii.Error:
return None
parts = user.split(':')
if len(parts) != 2:
return None
return scheme, parts[0], parts[1]
def assemble_http_basic_auth(scheme, username, password):
v = binascii.b2a_base64(username + ":" + password)
return scheme + " " + v
def parse_init(line):
try:
method, url, protocol = string.split(line)
except ValueError:
return None
httpversion = parse_http_protocol(protocol)
if not httpversion:
return None
if not utils.isascii(method):
return None
return method, url, httpversion
def parse_init_connect(line):
"""
Returns (host, port, httpversion) if line is a valid CONNECT line.
http://tools.ietf.org/html/draft-luotonen-web-proxy-tunneling-01 section 3.1
"""
v = parse_init(line)
if not v:
return None
method, url, httpversion = v
if method.upper() != 'CONNECT':
return None
try:
host, port = url.split(":")
except ValueError:
return None
try:
port = int(port)
except ValueError:
return None
if not _is_valid_port(port):
return None
if not _is_valid_host(host):
return None
return host, port, httpversion
def parse_init_proxy(line):
v = parse_init(line)
if not v:
return None
method, url, httpversion = v
parts = parse_url(url)
if not parts:
return None
scheme, host, port, path = parts
return method, scheme, host, port, path, httpversion
def parse_init_http(line):
"""
Returns (method, url, httpversion)
"""
v = parse_init(line)
if not v:
return None
method, url, httpversion = v
if not utils.isascii(url):
return None
if not (url.startswith("/") or url == "*"):
return None
return method, url, httpversion
def connection_close(httpversion, headers):
"""
Checks the message to see if the client connection should be closed according to RFC 2616 Section 8.1
"""
# At first, check if we have an explicit Connection header.
if "connection" in headers:
toks = get_header_tokens(headers, "connection")
if "close" in toks:
return True
elif "keep-alive" in toks:
return False
# If we don't have a Connection header, HTTP 1.1 connections are assumed to be persistent
if httpversion == (1, 1):
return False
return True
def parse_response_line(line):
parts = line.strip().split(" ", 2)
if len(parts) == 2: # handle missing message gracefully
parts.append("")
if len(parts) != 3:
return None
proto, code, msg = parts
try:
code = int(code)
except ValueError:
return None
return (proto, code, msg)
def read_response(rfile, method, body_size_limit, include_body=True):
"""
Return an (httpversion, code, msg, headers, content) tuple.
"""
line = rfile.readline()
if line == "\r\n" or line == "\n": # Possible leftover from previous message
line = rfile.readline()
if not line:
raise HttpErrorConnClosed(502, "Server disconnect.")
parts = parse_response_line(line)
if not parts:
raise HttpError(502, "Invalid server response: %s"%repr(line))
proto, code, msg = parts
httpversion = parse_http_protocol(proto)
if httpversion is None:
raise HttpError(502, "Invalid HTTP version in line: %s"%repr(proto))
headers = read_headers(rfile)
if headers is None:
raise HttpError(502, "Invalid headers.")
# Parse response body according to http://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-16#section-3.3
if method in ["HEAD", "CONNECT"] or (code in [204, 304]) or 100 <= code <= 199:
content = ""
elif include_body:
content = read_http_body(rfile, headers, body_size_limit, False)
else:
content = None # if include_body==False then a None content means the body should be read separately
return httpversion, code, msg, headers, content
def read_http_body(rfile, headers, limit, is_request):
"""
Read an HTTP message body:
rfile: A file descriptor to read from
headers: An ODictCaseless object
limit: Size limit.
is_request: True if the body to read belongs to a request, False otherwise
"""
if has_chunked_encoding(headers):
content = read_chunked(rfile, headers, limit, is_request)
elif "content-length" in headers:
try:
l = int(headers["content-length"][0])
if l < 0:
raise ValueError()
except ValueError:
raise HttpError(400 if is_request else 502, "Invalid content-length header: %s"%headers["content-length"])
if limit is not None and l > limit:
raise HttpError(400 if is_request else 509, "HTTP Body too large. Limit is %s, content-length was %s"%(limit, l))
content = rfile.read(l)
elif is_request:
content = ""
else:
content = rfile.read(limit if limit else -1)
not_done = rfile.read(1)
if not_done:
raise HttpError(400 if is_request else 509, "HTTP Body too large. Limit is %s," % limit)
return content
def expected_http_body_size(headers, is_request):
"""
Returns length of body expected or -1 if not
known and we should just read until end of
stream.
"""
if "content-length" in headers:
try:
l = int(headers["content-length"][0])
if l < 0:
raise ValueError()
return l
except ValueError:
raise HttpError(400 if is_request else 502, "Invalid content-length header: %s"%headers["content-length"])
elif is_request:
return 0
return -1
|