forked from circuits/circuits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.py
522 lines (433 loc) · 16.9 KB
/
http.py
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# Module: http
# Date: 13th September 2007
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Hyper Text Transfer Protocol
This module implements the server side Hyper Text Transfer Protocol
or commonly known as HTTP.
"""
from io import BytesIO
try:
from urllib.parse import quote
from urllib.parse import urlparse, urlunparse
except ImportError:
from urllib import quote # NOQA
from urlparse import urlparse, urlunparse # NOQA
from circuits.six import text_type
from circuits.net.events import close, write
from circuits.net.utils import is_ssl_handshake
from circuits.core import handler, BaseComponent, Value
from . import wrappers
from .url import parse_url
from .exceptions import HTTPException
from .events import request, response, stream
from .parsers import HttpParser, BAD_FIRST_LINE
from .errors import httperror, notfound, redirect
from .exceptions import Redirect as RedirectException
from .constants import SERVER_VERSION, SERVER_PROTOCOL
MAX_HEADER_FRAGENTS = 20
HTTP_ENCODING = 'utf-8'
try:
unicode
except NameError:
unicode = str
class HTTP(BaseComponent):
"""HTTP Protocol Component
Implements the HTTP server protocol and parses and processes incoming
HTTP messages, creating and sending an appropriate response.
The component handles :class:`~circuits.net.sockets.Read` events
on its channel and collects the associated data until a complete
HTTP request has been received. It parses the request's content
and puts it in a :class:`~circuits.web.wrappers.Request` object and
creates a corresponding :class:`~circuits.web.wrappers.Response`
object. Then it emits a :class:`~circuits.web.events.Request`
event with these objects as arguments.
The component defines several handlers that send a response back to
the client.
"""
channel = "web"
def __init__(self, server, encoding=HTTP_ENCODING, channel=channel):
super(HTTP, self).__init__(channel=channel)
self._server = server
self._encoding = encoding
url = "{0:s}://{1:s}{2:s}".format(
(server.secure and "https") or "http",
server.host or "0.0.0.0",
":{0:d}".format(server.port or 80)
if server.port not in (80, 443)
else ""
)
self.uri = parse_url(url)
self._clients = {}
self._buffers = {}
@property
def version(self):
return SERVER_VERSION
@property
def protocol(self):
return SERVER_PROTOCOL
@property
def scheme(self):
if not hasattr(self, "_server"):
return
return "https" if self._server.secure else "http"
@property
def base(self):
if not hasattr(self, "uri"):
return
return self.uri.utf8().rstrip(b"/").decode(self._encoding)
@handler("stream") # noqa
def _on_stream(self, res, data):
sock = res.request.sock
if data is not None:
if isinstance(data, text_type):
data = data.encode(self._encoding)
if res.chunked:
buf = [
hex(len(data))[2:].encode(self._encoding),
b"\r\n",
data,
b"\r\n"
]
data = b"".join(buf)
self.fire(write(sock, data))
if res.body and not res.done:
try:
data = next(res.body)
while not data: # Skip over any null byte sequences
data = next(res.body)
except StopIteration:
data = None
self.fire(stream(res, data))
else:
if res.body:
res.body.close()
if res.chunked:
self.fire(write(sock, b"0\r\n\r\n"))
if res.close:
self.fire(close(sock))
if sock in self._clients:
del self._clients[sock]
res.done = True
@handler("response") # noqa
def _on_response(self, res):
"""``Response`` Event Handler
:param response: the ``Response`` object created when the
HTTP request was initially received.
:type response: :class:`~circuits.web.wrappers.Response`
This handler builds an HTTP response data stream from
the information contained in the *response* object and
sends it to the client (firing ``write`` events).
"""
# send HTTP response status line and headers
req = res.request
headers = res.headers
sock = req.sock
if req.method == "HEAD":
self.fire(write(sock, bytes(res)))
self.fire(write(sock, bytes(headers)))
elif res.stream and res.body:
try:
data = next(res.body)
except StopIteration:
data = None
self.fire(write(sock, bytes(res)))
self.fire(write(sock, bytes(headers)))
self.fire(stream(res, data))
else:
self.fire(write(sock, bytes(res)))
self.fire(write(sock, bytes(headers)))
if isinstance(res.body, bytes):
body = res.body
elif isinstance(res.body, text_type):
body = res.body.encode(self._encoding)
else:
parts = (
s
if isinstance(s, bytes) else s.encode(self._encoding)
for s in res.body if s is not None
)
body = b"".join(parts)
if body:
if res.chunked:
buf = [
hex(len(body))[2:].encode(self._encoding),
b"\r\n",
body,
b"\r\n"
]
body = b"".join(buf)
self.fire(write(sock, body))
if res.chunked:
self.fire(write(sock, b"0\r\n\r\n"))
if not res.stream:
if res.close:
self.fire(close(sock))
# Delete the request/response objects if present
if sock in self._clients:
del self._clients[sock]
res.done = True
@handler("disconnect")
def _on_disconnect(self, sock):
if sock in self._clients:
del self._clients[sock]
@handler("read") # noqa
def _on_read(self, sock, data):
"""Read Event Handler
Process any incoming data appending it to an internal buffer.
Split the buffer by the standard HTTP delimiter CRLF and create
Raw Event per line. Any unfinished lines of text, leave in the buffer.
"""
if sock in self._buffers:
parser = self._buffers[sock]
else:
self._buffers[sock] = parser = HttpParser(0, True)
# If we receive an SSL handshake at the start of a request
# and we're not a secure server, then immediately close the
# client connection since we can't respond to it anyway.
if is_ssl_handshake(data) and not self._server.secure:
if sock in self._buffers:
del self._buffers[sock]
if sock in self._clients:
del self._clients[sock]
return self.fire(close(sock))
_scheme = "https" if self._server.secure else "http"
parser.execute(data, len(data))
if not parser.is_headers_complete():
if parser.errno is not None:
if parser.errno == BAD_FIRST_LINE:
req = wrappers.Request(sock, server=self._server)
else:
req = wrappers.Request(
sock,
parser.get_method(),
parser.get_scheme() or _scheme,
parser.get_path(),
parser.get_version(),
parser.get_query_string(),
server=self._server
)
req.server = self._server
res = wrappers.Response(req, encoding=self._encoding)
del self._buffers[sock]
return self.fire(httperror(req, res, 400))
return
if sock in self._clients:
req, res = self._clients[sock]
else:
method = parser.get_method()
scheme = parser.get_scheme() or _scheme
path = parser.get_path()
version = parser.get_version()
query_string = parser.get_query_string()
req = wrappers.Request(
sock, method, scheme, path, version, query_string,
headers=parser.get_headers(), server=self._server
)
res = wrappers.Response(req, encoding=self._encoding)
self._clients[sock] = (req, res)
rp = req.protocol
sp = self.protocol
if rp[0] != sp[0]:
# the major HTTP version differs
return self.fire(httperror(req, res, 505))
res.protocol = "HTTP/{0:d}.{1:d}".format(*min(rp, sp))
res.close = not parser.should_keep_alive()
clen = int(req.headers.get("Content-Length", "0"))
if clen and not parser.is_message_complete():
return
if hasattr(sock, "getpeercert"):
peer_cert = sock.getpeercert()
if peer_cert:
e = request(req, res, peer_cert)
else:
e = request(req, res)
else:
e = request(req, res)
# Guard against unwanted request paths (SECURITY).
path = req.path
_path = req.uri._path
if (path.encode(self._encoding) != _path) and (
quote(path).encode(self._encoding) != _path):
return self.fire(
redirect(req, res, [req.uri.utf8()], 301)
)
req.body = BytesIO(parser.recv_body())
del self._buffers[sock]
self.fire(e)
@handler("httperror")
def _on_httperror(self, event, req, res, code, **kwargs):
"""Default HTTP Error Handler
Default Error Handler that by default just fires a ``Response``
event with the *response* as argument. The *response* is normally
modified by a :class:`~circuits.web.errors.HTTPError` instance
or a subclass thereof.
"""
res.body = str(event)
self.fire(response(res))
@handler("request_success") # noqa
def _on_request_success(self, e, value):
"""
Handler for the ``RequestSuccess`` event that is automatically
generated after all handlers for a
:class:`~circuits.web.events.Request` event have been invoked
successfully.
:param e: the successfully handled ``Request`` event (having
as attributes the associated
:class:`~circuits.web.wrappers.Request` and
:class:`~circuits.web.wrappers.Response` objects).
:param value: the value(s) returned by the invoked handler(s).
This handler converts the value(s) returned by the
(successfully invoked) handlers for the initial ``Request``
event to a body and assigns it to the ``Response`` object's
``body`` attribute. It then fires a
:class:`~circuits.web.events.Response` event with the
``Response`` object as argument.
"""
# We only want the non-recursive value at this point.
# If the value is an instance of Value we will set
# the .notify flag and be notified of changes to the value.
value = e.value.getValue(recursive=False)
if isinstance(value, Value) and not value.promise:
value = value.getValue(recursive=False)
req, res = e.args[:2]
if value is None:
self.fire(notfound(req, res))
elif isinstance(value, httperror):
res.body = str(value)
self.fire(response(res))
elif isinstance(value, wrappers.Response):
self.fire(response(value))
elif isinstance(value, Value):
if value.result and not value.errors:
res.body = value.value
self.fire(response(res))
elif value.errors:
error = value.value
etype, evalue, traceback = error
if isinstance(evalue, RedirectException):
self.fire(
redirect(req, res, evalue.urls, evalue.code)
)
elif isinstance(evalue, HTTPException):
if evalue.traceback:
self.fire(
httperror(
req, res, evalue.code,
description=evalue.description,
error=error
)
)
else:
self.fire(
httperror(
req, res, evalue.code,
description=evalue.description
)
)
else:
self.fire(httperror(req, res, error=error))
else:
# We want to be notified of changes to the value
value = e.value.getValue(recursive=False)
value.event = e
value.notify = True
elif isinstance(value, tuple):
etype, evalue, traceback = error = value
if isinstance(evalue, RedirectException):
self.fire(
redirect(req, res, evalue.urls, evalue.code)
)
elif isinstance(evalue, HTTPException):
if evalue.traceback:
self.fire(
httperror(
req, res, evalue.code,
description=evalue.description,
error=error
)
)
else:
self.fire(
httperror(
req, res, evalue.code,
description=evalue.description
)
)
else:
self.fire(httperror(req, res, error=error))
elif not isinstance(value, bool):
res.body = value
self.fire(response(res))
@handler("exception")
def _on_exception(self, *args, **kwargs):
if not len(args) == 3:
return
etype, evalue, etraceback = args
fevent = kwargs["fevent"]
if isinstance(fevent, response):
res = fevent.args[0]
req = res.request
elif isinstance(fevent.value.parent.event, request):
req, res = fevent.value.parent.event.args[:2]
elif len(fevent.args[2:]) == 4:
req, res = fevent.args[2:]
else:
return
if isinstance(evalue, HTTPException):
code = evalue.code
else:
code = None
self.fire(
httperror(
req, res, code=code, error=(etype, evalue, etraceback)
)
)
@handler("request_failure")
def _on_request_failure(self, erequest, error):
req, res = erequest.args
# Ignore filtered requests already handled (eg: HTTPException(s)).
if req.handled:
return
req.handled = True
etype, evalue, traceback = error
if isinstance(evalue, RedirectException):
self.fire(
redirect(req, res, evalue.urls, evalue.code)
)
elif isinstance(evalue, HTTPException):
self.fire(
httperror(
req, res, evalue.code,
description=evalue.description,
error=error
)
)
else:
self.fire(httperror(req, res, error=error))
@handler("response_failure")
def _on_response_failure(self, eresponse, error):
res = eresponse.args[0]
req = res.request
# Ignore failed "response" handlers (eg: Loggers or Tools)
if res.done:
return
res = wrappers.Response(req, self._encoding, 500)
self.fire(httperror(req, res, error=error))
@handler("request_complete")
def _on_request_complete(self, *args, **kwargs):
"""Dummy Event Handler for request events
- request_complete
"""
@handler("response_success", "response_complete")
def _on_response_feedback(self, *args, **kwargs):
"""Dummy Event Handler for response events
- response_success
- response_complete
"""
@handler("stream_success", "stream_failure", "stream_complete")
def _on_stream_feedback(self, *args, **kwargs):
"""Dummy Event Handler for stream events
- stream_success
- stream_failure
- stream_complete
"""