/
http.py
1502 lines (1309 loc) · 51.8 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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Hive Netius System
# Copyright (c) 2008-2018 Hive Solutions Lda.
#
# This file is part of Hive Netius System.
#
# Hive Netius System is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by the Apache
# Foundation, either version 2.0 of the License, or (at your option) any
# later version.
#
# Hive Netius System is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Apache License for more details.
#
# You should have received a copy of the Apache License along with
# Hive Netius System. If not, see <http://www.apache.org/licenses/>.
__author__ = "João Magalhães <joamag@hive.pt>"
""" The author(s) of the module """
__version__ = "1.0.0"
""" The version of the module """
__revision__ = "$LastChangedRevision$"
""" The revision number of the module """
__date__ = "$LastChangedDate$"
""" The last change date of the module """
__copyright__ = "Copyright (c) 2008-2018 Hive Solutions Lda."
""" The copyright for the module """
__license__ = "Apache License, Version 2.0"
""" The license for the module """
import time
import zlib
import base64
import tempfile
import netius.common
from netius.common import PLAIN_ENCODING, CHUNKED_ENCODING,\
GZIP_ENCODING, DEFLATE_ENCODING
Z_PARTIAL_FLUSH = 1
""" The zlib constant value representing the partial flush
of the current zlib stream, this value has to be defined
locally as it is not defines under the zlib module """
class HTTPProtocol(netius.StreamProtocol):
"""
Implementation of the HTTP protocol to be used by a client
of the HTTP implementation to send requests and receive
responses.
"""
BASE_HEADERS = {
"user-agent" : netius.IDENTIFIER
}
""" The map containing the complete set of headers
that are meant to be applied to all the requests """
def __init__(
self,
method,
url,
params = None,
headers = None,
data = None,
version = "HTTP/1.1",
encoding = PLAIN_ENCODING,
encodings = "gzip, deflate",
safe = False,
request = False,
asynchronous = True,
timeout = None,
use_file = False,
callback = None,
on_init = None,
on_open = None,
on_close = None,
on_headers = None,
on_data = None,
on_result = None,
*args,
**kwargs
):
netius.StreamProtocol.__init__(self, *args, **kwargs)
self.parser = None
self.set(
method,
url,
params = params,
headers = headers,
data = data,
version = version,
encoding = encoding,
encodings = encodings,
safe = safe,
request = request,
asynchronous = asynchronous,
timeout = timeout,
use_file = use_file,
callback = callback,
on_init = on_init,
on_open = on_open,
on_close = on_close,
on_headers = on_headers,
on_data = on_data,
on_result = on_result
)
@classmethod
def key_g(cls, url):
parsed = netius.legacy.urlparse(url)
ssl = parsed.scheme == "https"
host = parsed.hostname
port = parsed.port or (443 if ssl else 80)
return (host, port, ssl)
@classmethod
def decode_gzip(cls, data):
if not data: return data
return zlib.decompress(data, zlib.MAX_WBITS | 16)
@classmethod
def decode_deflate(cls, data):
if not data: return data
try: return zlib.decompress(data)
except: return zlib.decompress(data, -zlib.MAX_WBITS)
@classmethod
def decode_zlib_file(
cls,
input,
output,
buffer_size = 16384,
wbits = zlib.MAX_WBITS | 16
):
decompressor = zlib.decompressobj(wbits)
while True:
data = input.read(buffer_size)
if not data: break
raw_data = decompressor.decompress(data)
output.write(raw_data)
raw_data = decompressor.flush()
output.write(raw_data)
return output
@classmethod
def decode_gzip_file(
cls,
input,
output,
buffer_size = 16384,
wbits = zlib.MAX_WBITS | 16
):
return cls.decode_zlib_file(
input,
output,
buffer_size = buffer_size,
wbits = wbits
)
@classmethod
def decode_deflate_file(
cls,
input,
output,
buffer_size = 16384,
wbits = -zlib.MAX_WBITS
):
return cls.decode_zlib_file(
input,
output,
buffer_size = buffer_size,
wbits = wbits
)
@classmethod
def set_request(cls, parser, buffer, request = None):
if request == None: request = dict()
headers = parser.get_headers()
data = b"".join(buffer)
encoding = headers.get("Content-Encoding", None)
decoder = getattr(cls, "decode_%s" % encoding) if encoding else None
if decoder and data: data = decoder(data)
request["code"] = parser.code
request["status"] = parser.status
request["headers"] = headers
request["data"] = data
return request
@classmethod
def set_request_file(
cls,
parser,
input,
request = None,
output = None,
buffer_size = 16384
):
# verifies if a request object has been passes to the current
# method and if that's not the case creates a new one (as a map)
if request == None: request = dict()
# retrieves the complete set of headers and tries discover the
# encoding of it and the associated decoder (if any)
headers = parser.get_headers()
encoding = headers.get("Content-Encoding", None)
decoder = getattr(cls, "decode_%s_file" % encoding) if encoding else None
# in case there's a decoder and an input (file) then runs the decoding
# process setting the data as the resulting (decoded object)
if decoder and input:
if output == None: output = tempfile.NamedTemporaryFile(mode = "w+b")
input.seek(0)
try:
data = decoder(
input,
output,
buffer_size = buffer_size
)
finally:
input.close()
# otherwise it's a simplified process (no decoding required) and the
# data may be set directly as the input file
else:
data = input
# seeks the data object to the initial position so that it
# is set as ready to be read from a third party
data.seek(0)
# updates the structure of the request object/map so that it
# contains a series of information on the request, including
# the file contents (stored in a temporary file)
request["code"] = parser.code
request["status"] = parser.status
request["headers"] = headers
request["data"] = data
# returns the request object that has just been populated
# to the caller method so that it may be used to read the contents
return request
@classmethod
def set_error(cls, error, message = None, request = None, force = False):
if request == None: request = dict()
if "error" in request and not force: return
request["error"] = error
request["message"] = message
return request
def open_c(self, *args, **kwargs):
netius.StreamProtocol.open_c(self, *args, **kwargs)
# creates a new HTTP parser instance and set the correct event
# handlers so that the data parsing is properly handled
self.parser = netius.common.HTTPParser(self, type = netius.common.RESPONSE)
self.parser.bind("on_data", self._on_data)
self.parser.bind("on_partial", self.on_partial)
self.parser.bind("on_headers", self.on_headers)
self.parser.bind("on_chunk", self.on_chunk)
def close_c(self, *args, **kwargs):
netius.StreamProtocol.close_c(self, *args, **kwargs)
if self.parser: self.parser.destroy()
if self.parsed: self.parsed = None
if self.gzip: self._close_gzip(safe = True)
if self.gzip_c: self.gzip_c = None
def info_dict(self, full = False):
info = netius.StreamProtocol.info_dict(self, full = full)
info.update(
version = self.version,
method = self.method,
encoding = self.encodings,
url = self.url,
parsed = self.parsed,
host = self.host,
port = self.port,
path = self.path,
headers = self.headers
)
if full: info.update(
parser = self.parser.info_dict()
)
return info
def connection_made(self, transport):
netius.StreamProtocol.connection_made(self, transport)
# performs the run request operation that should trigger
# the process of sending the request to the server
self.run_request()
def loop_set(self, loop):
netius.StreamProtocol.loop_set(self, loop)
self.set_dynamic()
def flush(self, force = False, callback = None):
if self.current == DEFLATE_ENCODING:
self._flush_gzip(force = force, callback = callback)
elif self.current == GZIP_ENCODING:
self._flush_gzip(force = force, callback = callback)
elif self.current == CHUNKED_ENCODING:
self._flush_chunked(force = force, callback = callback)
elif self.current == PLAIN_ENCODING:
self._flush_plain(force = force, callback = callback)
self.current = self.encoding
def send_base(
self,
data,
stream = None,
final = True,
delay = True,
force = False,
callback = None
):
data = netius.legacy.bytes(data) if data else data
if self.current == PLAIN_ENCODING:
return self.send_plain(
data,
stream = stream,
final = final,
delay = delay,
force = force,
callback = callback
)
elif self.current == CHUNKED_ENCODING:
return self.send_chunked(
data,
stream = stream,
final = final,
delay = delay,
force = force,
callback = callback
)
elif self.current == GZIP_ENCODING:
return self.send_gzip(
data,
stream = stream,
final = final,
delay = delay,
force = force,
callback = callback
)
elif self.current == DEFLATE_ENCODING:
return self.send_gzip(
data,
stream = stream,
final = final,
delay = delay,
force = force,
callback = callback
)
def send_plain(
self,
data,
stream = None,
final = True,
delay = True,
force = False,
callback = None
):
return self.send(
data,
delay = delay,
force = force,
callback = callback
)
def send_chunked(
self,
data,
stream = None,
final = True,
delay = True,
force = False,
callback = None
):
# in case there's no valid data to be sent uses the plain
# send method to send the empty string and returns immediately
# to the caller method, to avoid any problems
if not data: return self.send_plain(
data,
stream = stream,
final = final,
delay = delay,
force = force,
callback = callback
)
# creates the new list that is going to be used to store
# the various parts of the chunk and then calculates the
# size (in bytes) of the data that is going to be sent
buffer = []
size = len(data)
# creates the various parts of the chunk with the size
# of the data that is going to be sent and then adds
# each of the parts to the chunk buffer list
buffer.append(netius.legacy.bytes("%x\r\n" % size))
buffer.append(data)
buffer.append(netius.legacy.bytes("\r\n"))
# joins the buffer containing the chunk parts and then
# sends it to the connection using the plain method
buffer_s = b"".join(buffer)
return self.send_plain(
buffer_s,
stream = stream,
final = final,
delay = delay,
force = force,
callback = callback
)
def send_gzip(
self,
data,
stream = None,
final = True,
delay = True,
force = False,
callback = None,
level = 6
):
# verifies if the provided data buffer is valid and in
# in case it's not propagates the sending to the upper
# layer (chunked sending) for proper processing
if not data: return self.send_chunked(
data,
stream = stream,
final = final,
delay = delay,
force = force,
callback = callback
)
# "calculates" if the current sending of gzip data is
# the first one by verifying if the gzip object is set
is_first = self.gzip == None
# in case this is the first sending a new compress object
# is created with the requested compress level, notice that
# the special deflate case is handled differently
if is_first:
is_deflate = self.is_deflate()
wbits = -zlib.MAX_WBITS if is_deflate else zlib.MAX_WBITS | 16
self.gzip = zlib.compressobj(level, zlib.DEFLATED, wbits)
# compresses the provided data string and removes the
# initial data contents of the compressed data because
# they are not part of the gzip specification, notice
# that in case the resulting of the compress operation
# is not valid a sync flush operation is performed
data_c = self.gzip.compress(data)
if not data_c: data_c = self.gzip.flush(Z_PARTIAL_FLUSH)
# sends the compressed data to the client endpoint setting
# the correct callback values as requested
return self.send_chunked(
data_c,
stream = stream,
final = final,
delay = delay,
force = force,
callback = callback
)
def set(
self,
method,
url,
params = None,
headers = None,
data = None,
version = "HTTP/1.1",
encoding = PLAIN_ENCODING,
encodings = "gzip, deflate",
safe = False,
request = False,
asynchronous = True,
timeout = None,
use_file = False,
callback = None,
on_init = None,
on_open = None,
on_close = None,
on_headers = None,
on_data = None,
on_result = None,
):
cls = self.__class__
self.method = method.upper()
self.url = url
self.params = params or {}
self.headers = headers or {}
self.data = data
self.version = version
self.encoding = encoding
self.current = encoding
self.encodings = encodings
self.safe = safe
self.asynchronous = asynchronous
self.timeout = timeout or 60
self.use_file = use_file
self.parsed = False
self.request = None
self.ssl = False
self.host = None
self.port = None
self.path = None
self.gzip = None
self.gzip_c = None
# in case the provided data is a unicode string it's converted into
# a raw set of bytes using the default encoding
if netius.legacy.is_unicode(self.data):
self.data = netius.legacy.bytes(data)
# in case the data currently set is a plain byte stream wraps it
# around an iterator to provide compatibility with generators
if netius.legacy.is_bytes(self.data):
self.data = iter((len(self.data), self.data))
# in case the provided data responds to the typical file-like
# object interface, then it's wrapped around a generator to
# provided compatibility with the generators based interface
if hasattr(self.data, "tell"):
self.data = netius.common.file_iterator(self.data)
# computes the unique re-usage key for the current protocol taking
# into account its own state
self.key = cls.key_g(self.url)
# runs the unbind all operation to make sure that no handlers is
# currently registered for operations
self.unbind_all()
# in case there's an HTTP parser already set for the protocol runs
# the reset operation so that its state is guaranteed to be clean
if self.parser: self.parser.clear()
# tries to determine if the protocol response should be request
# wrapped, meaning that a map based object is going to be populated
# with the contents of the HTTP request/response
wrap_request = request or (not asynchronous and not on_data and not callback)
wrap_request = wrap_request or on_result
# in case the wrap request flag is set (conditions for request usage
# are met) the protocol is called to run the wrapping operation
if wrap_request:
_request, on_close, on_data, callback = self.wrap_request(
use_file = use_file,
callback = callback,
on_close = on_close,
on_data = on_data,
on_result = on_result
)
# registers for the proper event handlers according to the
# provided parameters, note that these are considered to be
# the lower level infra-structure of the event handling
if on_init: self.bind("loop_set", on_init)
if on_open: self.bind("open", on_open)
if on_close: self.bind("close", on_close)
if on_headers: self.bind("headers", on_headers)
if on_data: self.bind("partial", on_data)
if callback: self.bind("message", callback)
# sets the static part of the protocol internal (no loop is required)
# so that the required initials fields are properly populated
self.set_static()
# returns the current instance with the proper modified state
# according to the current changes
return self
def set_all(self):
self.set_static()
self.set_dynamic()
def set_static(self):
# creates the message that is going to be used in the logging of
# the current method request for debugging purposes, this may be
# useful for a full record traceability of the request
message = "%s %s %s" % (self.method, self.url, self.version)
self.debug(message)
# stores the initial version of the url in a fallback variable so
# that it may latter be used for the storage of that information
# in the associated connection (used in callbacks)
self.base = self.url
# encodes the provided parameters into the query string and then
# adds these parameters to the end of the provided url, these
# values are commonly named get parameters
query = netius.legacy.urlencode(self.params)
if query: self.url = self.url + "?" + query
# parses the provided url and retrieves the various parts of the
# url that are going to be used in the creation of the connection
# takes into account some default values in case their are not part
# of the provided url (eg: port and the scheme)
self.parsed = netius.legacy.urlparse(self.url)
self.ssl = self.parsed.scheme == "https"
self.host = self.parsed.hostname
self.port = self.parsed.port or (443 if self.ssl else 80)
self.path = self.parsed.path or "/"
self.username = self.parsed.username
self.password = self.parsed.password
# in case both the username and the password values are defined the
# authorization header must be created and added to the default set
# of headers that are going to be included in the request
if self.username and self.password:
payload = "%s:%s" % (self.username, self.password)
payload = netius.legacy.bytes(payload)
authorization = base64.b64encode(payload)
authorization = netius.legacy.str(authorization)
self.headers["authorization"] = "Basic %s" % authorization
# sets the complete set of information under the protocol instance so
# that it may be latter used to send the request through the transport
self.set_headers(self.headers)
def set_dynamic(self):
cls = self.__class__
# creates the function that is going to be used to validate
# the on connect timeout so that whenever the timeout for
# the connection operation is exceeded an error is set int
# the connection and the connection is properly closed
def connect_timeout():
if self.is_open(): return
self.request and cls.set_error(
"timeout",
message = "Timeout on connect",
request = self.request
)
self.close()
# schedules a delay operation to run the timeout handler for
# both connect operation (this is considered the initial
# triggers for the such verifiers)
self.delay(connect_timeout, timeout = self.timeout)
def run_request(self):
# retrieves the reference to the top level class to be used
# for class level operations
cls = self.__class__
# saves the current request instance locally to be used latter
# for request verification (integrity check)
request = self.request
# creates a function that is going to be used to validate
# the receive operation of the connection (receive timeout)
def receive_timeout():
# runs the initial verification operations that will
# try to validate if the requirements for proper request
# validations are defined, if any of them is not the control
# full is returned immediately avoiding re-schedule of handler
if not self.request: return
if not self.is_open(): return
if self.request["code"]: return
if not id(request) == id(self.request): return
# retrieves the current time and the time of the last data
# receive operation and using that calculates the delta
current = time.time()
last = self.request.get("last", 0)
delta = current - last
# retrieves the amount of bytes that have been received so
# far during the request handling this is going to be used
# for logging purposes on the error information to be printed
received = self.request.get("received", 0)
# determines if the protocol is considered valid, either
# the connection is not "yet" connected, the time between
# receive operations is valid or there's data still pending
# to be sent to the server side, and if that's the case delays
# the timeout verification according to the timeout value
if not self.is_open() or delta < self.timeout or\
not self.transport().get_write_buffer_size() == 0:
self.delay(receive_timeout, timeout = self.timeout)
return
# tries to determine the proper message that is going to be
# set in the request error, this value should take into account
# the current development mode flag value
if self.is_devel(): message = "Timeout on receive (received %d bytes)" % received
else: message = "Timeout on receive"
# sets the error information in the request so that the
# request handler is properly "notified" about the error
cls.set_error(
"timeout",
message = message,
request = self.request
)
# closes the protocol (it's no longer considered valid)
# and then verifies the various auto closing values
self.close()
# sends the request effectively triggering a chain of event
# that should end with the complete receiving of the response
self.send_request(callback = lambda c: self.delay(
receive_timeout, timeout = self.timeout
))
def send_request(self, callback = None):
method = self.method
path = self.path
version = self.version
headers = self.headers
data = self.data
parsed = self.parsed
safe = self.safe
if parsed.query: path += "?" + parsed.query
headers = dict(headers)
self._apply_base(headers)
self._apply_dynamic(headers)
self._apply_connection(headers)
if safe: self._headers_normalize(headers)
buffer = []
buffer.append("%s %s %s\r\n" % (method, path, version))
for key, value in netius.legacy.iteritems(headers):
key = netius.common.header_up(key)
if not isinstance(value, list): value = (value,)
for _value in value:
_value = netius.legacy.ascii(_value)
buffer.append("%s: %s\r\n" % (key, _value))
buffer.append("\r\n")
buffer_data = "".join(buffer)
if data: count = self.send_plain(buffer_data, force = True)
else: count = self.send_plain(buffer_data, force = True, callback = callback)
if not data: return count
def send_part(transport = None):
try:
_data = next(data)
except StopIteration:
if hasattr(data, "close"): data.close()
callback and callback(transport)
return
self.send_base(_data, force = True, callback = send_part)
send_part()
return count
def wrap_request(
self,
use_file = False,
callback = None,
on_close = None,
on_data = None,
on_result = None
):
"""
Wraps the current set of operations for the protocol so that
a request object is going to be created and properly populated
according to the multiple protocol events.
This method should focus on wrapping the provided callback handlers
with ones that change the request object state.
:type use_file: bool
:param use_file: If a filesystem based approach should be used
for the storing of the request information.
:type callback: Function
:param callback: Callback function to be called when the message
response has been completely received.
:type on_close: Function
:param on_close: Callback function to be called when the underlying
protocol is closed.
:type on_data: Function
:param on_data: Function to be called whenever some data is received
from the client side, notice that this data may be encoded (eg: gzip).
:type on_result: Function
:param on_result: Callback function to be called on the final result
with the resulting request object.
:rtype: Tuple
:return: The tuple containing both the request dictionary object that
is going to store the information for the request in the current protocol
and the multiple changed callback methods.
"""
# retrieves the reference to the parent class object
# going to be used for class wide operations
cls = self.__class__
# saves the references to the previous callback method so that
# they can be used from the current request based approach
_on_close = on_close
_on_data = on_data
_callback = callback
# creates both the buffer list and the request structure so that
# they may be used for the correct construction of the request
# structure that is going to be send in the callback, then sets
# the identifier (memory address) of the request in the connection
buffer = tempfile.NamedTemporaryFile(mode = "w+b") if use_file else []
self.request = dict(code = None, data = None)
def on_close(protocol):
if _on_close: _on_close(protocol)
protocol._request = None
if self.request["code"]: return
cls.set_error(
"closed",
message = "Connection closed",
request = self.request
)
def on_data(protocol, parser, data):
if _on_data: _on_data(protocol, parser, data)
if use_file: buffer.write(data)
else: buffer.append(data)
received = self.request.get("received", 0)
self.request["received"] = received + len(data)
self.request["last"] = time.time()
def callback(protocol, parser, message):
if _callback: _callback(protocol, parser, message)
if use_file: cls.set_request_file(parser, buffer, request = self.request)
else: cls.set_request(parser, buffer, request = self.request)
if on_result: on_result(protocol, parser, self.request)
# returns the request object that is going to be properly
# populated over the life-cycle of the protocol
return self.request, on_close, on_data, callback
def set_headers(self, headers, normalize = True):
self.headers = headers
if normalize: self.normalize_headers()
def normalize_headers(self):
for key, value in netius.legacy.items(self.headers):
del self.headers[key]
key = netius.common.header_down(key)
self.headers[key] = value
def parse(self, data):
return self.parser.parse(data)
def raw_data(self, data):
"""
Tries to obtain the raw version of the provided data, taking
into account the possible content encoding present for compression
or any other kind of operation.
:type data: String
:param data: The data to be converted back to its original
raw value (probably through decompression).
:rtype: String
:return: The final raw value for the provided data.
"""
encoding = self.parser.headers.get("content-encoding", None)
if not encoding: return data
if not self.gzip_c:
is_deflate = encoding == "deflate"
wbits = zlib.MAX_WBITS if is_deflate else zlib.MAX_WBITS | 16
self.gzip_c = zlib.decompressobj(wbits)
return self.gzip_c.decompress(data)
def is_plain(self):
return self.current == PLAIN_ENCODING
def is_chunked(self):
return self.current > PLAIN_ENCODING
def is_gzip(self):
return self.current == GZIP_ENCODING
def is_deflate(self):
return self.current == DEFLATE_ENCODING
def is_compressed(self):
return self.current > CHUNKED_ENCODING
def is_uncompressed(self):
return not self.is_compressed()
def is_flushed(self):
return self.current > PLAIN_ENCODING
def is_measurable(self, strict = True):
if self.is_compressed(): return False
if strict and self.is_chunked(): return False
return True
def on_data(self, data):
netius.StreamProtocol.on_data(self, data)
self.parser.parse(data)
def _on_data(self):
message = self.parser.get_message()
self.trigger("message", self, self.parser, message)
self.parser.clear()
self.gzip_c = None
def on_partial(self, data):
self.trigger("partial", self, self.parser, data)
def on_headers(self):
self.trigger("headers", self, self.parser)
def on_chunk(self, range):
self.trigger("chunk", self, self.parser, range)
def _flush_plain(self, force = False, callback = None):
if not callback: return
self.send_plain(b"", force = force, callback = callback)
def _flush_chunked(self, force = False, callback = None):
self.send_plain(b"0\r\n\r\n", force = force, callback = callback)
def _flush_gzip(self, force = False, callback = None):
# in case the gzip structure has not been initialized
# (no data sent) no need to run the flushing of the
# gzip data, so only the chunked part is flushed
if not self.gzip:
self._flush_chunked(force = force, callback = callback)
return
# flushes the internal zlib buffers to be able to retrieve
# the data pending to be sent to the client and then sends
# it using the chunked encoding strategy
data_c = self.gzip.flush(zlib.Z_FINISH)
self.send_chunked(data_c, force = force, final = False)
# resets the gzip values to the original ones so that new
# requests will starts the information from the beginning
self.gzip = None
# runs the flush operation for the underlying chunked encoding
# layer so that the client is correctly notified about the
# end of the current request (normal operation)
self._flush_chunked(force = force, callback = callback)
def _close_gzip(self, safe = True):
# in case the gzip object is not defined returns the control
# to the caller method immediately (nothing to be done)
if not self.gzip: return
try:
# runs the flush operation for the the final finish stage
# (note that an exception may be raised) and then unsets
# the gzip object (meaning no more interaction)
self.gzip.flush(zlib.Z_FINISH)
self.gzip = None
except:
# in case the safe flag is not set re-raises the exception
# to the caller stack (as expected by the callers)
if not safe: raise
def _apply_base(self, headers, replace = False):
cls = self.__class__
for key, value in netius.legacy.iteritems(cls.BASE_HEADERS):
if not replace and key in headers: continue
headers[key] = value
def _apply_dynamic(self, headers):
host = self.host
port = self.port
data = self.data
is_plain = self.is_plain()
# determines the proper strategy for data payload length, taking into
# account if there's a payload and if it exists if it's a byte stream
# or instead an iterator/generator
if not data: length = 0
elif netius.legacy.is_bytes(data): length = len(data)
else: length = next(data)