/
http.py
3335 lines (2732 loc) · 110 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
# -*- test-case-name: twisted.web.test.test_http -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
HyperText Transfer Protocol implementation.
This is the basic server-side protocol implementation used by the Twisted
Web server. It can parse HTTP 1.0 requests and supports many HTTP 1.1
features as well. Additionally, some functionality implemented here is
also useful for HTTP clients (such as the chunked encoding parser).
@var CACHED: A marker value to be returned from cache-related request methods
to indicate to the caller that a cached response will be usable and no
response body should be generated.
@var FOUND: An HTTP response code indicating a temporary redirect.
@var NOT_MODIFIED: An HTTP response code indicating that a requested
pre-condition (for example, the condition represented by an
I{If-Modified-Since} header is present in the request) has succeeded. This
indicates a response body cached by the client can be used.
@var PRECONDITION_FAILED: An HTTP response code indicating that a requested
pre-condition (for example, the condition represented by an I{If-None-Match}
header is present in the request) has failed. This should typically
indicate that the server has not taken the requested action.
@var maxChunkSizeLineLength: Maximum allowable length of the CRLF-terminated
line that indicates the size of a chunk and the extensions associated with
it, as in the HTTP 1.1 chunked I{Transfer-Encoding} (RFC 7230 section 4.1).
This limits how much data may be buffered when decoding the line.
"""
from __future__ import annotations
__all__ = [
"SWITCHING",
"OK",
"CREATED",
"ACCEPTED",
"NON_AUTHORITATIVE_INFORMATION",
"NO_CONTENT",
"RESET_CONTENT",
"PARTIAL_CONTENT",
"MULTI_STATUS",
"MULTIPLE_CHOICE",
"MOVED_PERMANENTLY",
"FOUND",
"SEE_OTHER",
"NOT_MODIFIED",
"USE_PROXY",
"TEMPORARY_REDIRECT",
"PERMANENT_REDIRECT",
"BAD_REQUEST",
"UNAUTHORIZED",
"PAYMENT_REQUIRED",
"FORBIDDEN",
"NOT_FOUND",
"NOT_ALLOWED",
"NOT_ACCEPTABLE",
"PROXY_AUTH_REQUIRED",
"REQUEST_TIMEOUT",
"CONFLICT",
"GONE",
"LENGTH_REQUIRED",
"PRECONDITION_FAILED",
"REQUEST_ENTITY_TOO_LARGE",
"REQUEST_URI_TOO_LONG",
"UNSUPPORTED_MEDIA_TYPE",
"REQUESTED_RANGE_NOT_SATISFIABLE",
"EXPECTATION_FAILED",
"IM_A_TEAPOT",
"INTERNAL_SERVER_ERROR",
"NOT_IMPLEMENTED",
"BAD_GATEWAY",
"SERVICE_UNAVAILABLE",
"GATEWAY_TIMEOUT",
"HTTP_VERSION_NOT_SUPPORTED",
"INSUFFICIENT_STORAGE_SPACE",
"NOT_EXTENDED",
"RESPONSES",
"CACHED",
"urlparse",
"parse_qs",
"datetimeToString",
"datetimeToLogString",
"timegm",
"stringToDatetime",
"toChunk",
"fromChunk",
"parseContentRange",
"StringTransport",
"HTTPClient",
"NO_BODY_CODES",
"Request",
"PotentialDataLoss",
"HTTPChannel",
"HTTPFactory",
]
import base64
import binascii
import calendar
import math
import os
import re
import tempfile
import time
import warnings
from email import message_from_bytes
from email.message import EmailMessage, Message
from io import BytesIO
from typing import AnyStr, Callable, Dict, List, Optional, Tuple
from urllib.parse import (
ParseResultBytes,
unquote_to_bytes as unquote,
urlparse as _urlparse,
)
from zope.interface import Attribute, Interface, implementer, provider
from incremental import Version
from twisted.internet import address, interfaces, protocol
from twisted.internet._producer_helpers import _PullToPush
from twisted.internet.defer import Deferred
from twisted.internet.interfaces import IProtocol
from twisted.logger import Logger
from twisted.protocols import basic, policies
from twisted.python import log
from twisted.python.compat import nativeString, networkString
from twisted.python.components import proxyForInterface
from twisted.python.deprecate import deprecated
from twisted.python.failure import Failure
from twisted.web._responses import (
ACCEPTED,
BAD_GATEWAY,
BAD_REQUEST,
CONFLICT,
CREATED,
EXPECTATION_FAILED,
FORBIDDEN,
FOUND,
GATEWAY_TIMEOUT,
GONE,
HTTP_VERSION_NOT_SUPPORTED,
IM_A_TEAPOT,
INSUFFICIENT_STORAGE_SPACE,
INTERNAL_SERVER_ERROR,
LENGTH_REQUIRED,
MOVED_PERMANENTLY,
MULTI_STATUS,
MULTIPLE_CHOICE,
NO_CONTENT,
NON_AUTHORITATIVE_INFORMATION,
NOT_ACCEPTABLE,
NOT_ALLOWED,
NOT_EXTENDED,
NOT_FOUND,
NOT_IMPLEMENTED,
NOT_MODIFIED,
OK,
PARTIAL_CONTENT,
PAYMENT_REQUIRED,
PERMANENT_REDIRECT,
PRECONDITION_FAILED,
PROXY_AUTH_REQUIRED,
REQUEST_ENTITY_TOO_LARGE,
REQUEST_TIMEOUT,
REQUEST_URI_TOO_LONG,
REQUESTED_RANGE_NOT_SATISFIABLE,
RESET_CONTENT,
RESPONSES,
SEE_OTHER,
SERVICE_UNAVAILABLE,
SWITCHING,
TEMPORARY_REDIRECT,
UNAUTHORIZED,
UNSUPPORTED_MEDIA_TYPE,
USE_PROXY,
)
from twisted.web.http_headers import Headers, _sanitizeLinearWhitespace
from twisted.web.iweb import IAccessLogFormatter, INonQueuedRequestFactory, IRequest
try:
from twisted.web._http2 import H2Connection
H2_ENABLED = True
except ImportError:
H2_ENABLED = False
# A common request timeout -- 1 minute. This is roughly what nginx uses, and
# so it seems to be a good choice for us too.
_REQUEST_TIMEOUT = 1 * 60
protocol_version = "HTTP/1.1"
CACHED = """Magic constant returned by http.Request methods to set cache
validation headers when the request is conditional and the value fails
the condition."""
# backwards compatibility
responses = RESPONSES
# datetime parsing and formatting
weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
monthname = [
None,
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
weekdayname_lower = [name.lower() for name in weekdayname]
monthname_lower = [name and name.lower() for name in monthname]
def _parseContentType(line: bytes) -> bytes:
"""
Parse the Content-Type header.
"""
msg = EmailMessage()
msg["content-type"] = line.decode("charmap")
key = msg.get_content_type()
encodedKey = key.encode("charmap")
return encodedKey
class _MultiPartParseException(Exception):
"""
Failed to parse the multipart/form-data payload.
"""
def _getMultiPartArgs(content: bytes, ctype: bytes) -> dict[bytes, list[bytes]]:
"""
Parse the content of a multipart/form-data request.
"""
result = {}
multiPartHeaders = b"MIME-Version: 1.0\r\n" + b"Content-Type: " + ctype + b"\r\n"
msg = message_from_bytes(multiPartHeaders + content)
if not msg.is_multipart():
raise _MultiPartParseException("Not a multipart.")
part: Message
# "per Python docs, a list of Message objects when is_multipart() is True,
# or a string when is_multipart() is False"
for part in msg.get_payload(): # type:ignore[assignment]
name: str | None = part.get_param(
"name", header="content-disposition"
) # type:ignore[assignment]
if not name:
continue
payload: bytes = part.get_payload(decode=True) # type:ignore[assignment]
result[name.encode("utf8")] = [payload]
return result
def urlparse(url):
"""
Parse an URL into six components.
This is similar to C{urlparse.urlparse}, but rejects C{str} input
and always produces C{bytes} output.
@type url: C{bytes}
@raise TypeError: The given url was a C{str} string instead of a
C{bytes}.
@return: The scheme, net location, path, params, query string, and fragment
of the URL - all as C{bytes}.
@rtype: C{ParseResultBytes}
"""
if isinstance(url, str):
raise TypeError("url must be bytes, not unicode")
scheme, netloc, path, params, query, fragment = _urlparse(url)
if isinstance(scheme, str):
scheme = scheme.encode("ascii")
netloc = netloc.encode("ascii")
path = path.encode("ascii")
query = query.encode("ascii")
fragment = fragment.encode("ascii")
return ParseResultBytes(scheme, netloc, path, params, query, fragment)
def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
"""
Like C{cgi.parse_qs}, but with support for parsing byte strings on Python 3.
This was created to help with Python 2 to Python 3 migration.
Consider using L{urllib.parse.parse_qs}.
@type qs: C{bytes}
"""
d = {}
items = [s2 for s1 in qs.split(b"&") for s2 in s1.split(b";")]
for item in items:
try:
k, v = item.split(b"=", 1)
except ValueError:
if strict_parsing:
raise
continue
if v or keep_blank_values:
k = unquote(k.replace(b"+", b" "))
v = unquote(v.replace(b"+", b" "))
if k in d:
d[k].append(v)
else:
d[k] = [v]
return d
def datetimeToString(msSinceEpoch=None):
"""
Convert seconds since epoch to HTTP datetime string.
@rtype: C{bytes}
"""
if msSinceEpoch == None:
msSinceEpoch = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(msSinceEpoch)
s = networkString(
"%s, %02d %3s %4d %02d:%02d:%02d GMT"
% (weekdayname[wd], day, monthname[month], year, hh, mm, ss)
)
return s
def datetimeToLogString(msSinceEpoch=None):
"""
Convert seconds since epoch to log datetime string.
@rtype: C{str}
"""
if msSinceEpoch == None:
msSinceEpoch = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(msSinceEpoch)
s = "[%02d/%3s/%4d:%02d:%02d:%02d +0000]" % (
day,
monthname[month],
year,
hh,
mm,
ss,
)
return s
def timegm(year, month, day, hour, minute, second):
"""
Convert time tuple in GMT to seconds since epoch, GMT
"""
EPOCH = 1970
if year < EPOCH:
raise ValueError("Years prior to %d not supported" % (EPOCH,))
assert 1 <= month <= 12
days = 365 * (year - EPOCH) + calendar.leapdays(EPOCH, year)
for i in range(1, month):
days = days + calendar.mdays[i]
if month > 2 and calendar.isleap(year):
days = days + 1
days = days + day - 1
hours = days * 24 + hour
minutes = hours * 60 + minute
seconds = minutes * 60 + second
return seconds
def stringToDatetime(dateString):
"""
Convert an HTTP date string (one of three formats) to seconds since epoch.
@type dateString: C{bytes}
"""
parts = nativeString(dateString).split()
if not parts[0][0:3].lower() in weekdayname_lower:
# Weekday is stupid. Might have been omitted.
try:
return stringToDatetime(b"Sun, " + dateString)
except ValueError:
# Guess not.
pass
partlen = len(parts)
if (partlen == 5 or partlen == 6) and parts[1].isdigit():
# 1st date format: Sun, 06 Nov 1994 08:49:37 GMT
# (Note: "GMT" is literal, not a variable timezone)
# (also handles without "GMT")
# This is the normal format
day = parts[1]
month = parts[2]
year = parts[3]
time = parts[4]
elif (partlen == 3 or partlen == 4) and parts[1].find("-") != -1:
# 2nd date format: Sunday, 06-Nov-94 08:49:37 GMT
# (Note: "GMT" is literal, not a variable timezone)
# (also handles without without "GMT")
# Two digit year, yucko.
day, month, year = parts[1].split("-")
time = parts[2]
year = int(year)
if year < 69:
year = year + 2000
elif year < 100:
year = year + 1900
elif len(parts) == 5:
# 3rd date format: Sun Nov 6 08:49:37 1994
# ANSI C asctime() format.
day = parts[2]
month = parts[1]
year = parts[4]
time = parts[3]
else:
raise ValueError("Unknown datetime format %r" % dateString)
day = int(day)
month = int(monthname_lower.index(month.lower()))
year = int(year)
hour, min, sec = map(int, time.split(":"))
return int(timegm(year, month, day, hour, min, sec))
def toChunk(data):
"""
Convert string to a chunk.
@type data: C{bytes}
@returns: a tuple of C{bytes} representing the chunked encoding of data
"""
return (networkString(f"{len(data):x}"), b"\r\n", data, b"\r\n")
def _ishexdigits(b: bytes) -> bool:
"""
Is the string case-insensitively hexidecimal?
It must be composed of one or more characters in the ranges a-f, A-F
and 0-9.
"""
for c in b:
if c not in b"0123456789abcdefABCDEF":
return False
return b != b""
def _hexint(b: bytes) -> int:
"""
Decode a hexadecimal integer.
Unlike L{int(b, 16)}, this raises L{ValueError} when the integer has
a prefix like C{b'0x'}, C{b'+'}, or C{b'-'}, which is desirable when
parsing network protocols.
"""
if not _ishexdigits(b):
raise ValueError(b)
return int(b, 16)
def fromChunk(data: bytes) -> Tuple[bytes, bytes]:
"""
Convert chunk to string.
Note that this function is not specification compliant: it doesn't handle
chunk extensions.
@type data: C{bytes}
@return: tuple of (result, remaining) - both C{bytes}.
@raise ValueError: If the given data is not a correctly formatted chunked
byte string.
"""
prefix, rest = data.split(b"\r\n", 1)
length = _hexint(prefix)
if length < 0:
raise ValueError("Chunk length must be >= 0, not %d" % (length,))
if rest[length : length + 2] != b"\r\n":
raise ValueError("chunk must end with CRLF")
return rest[:length], rest[length + 2 :]
def parseContentRange(header):
"""
Parse a content-range header into (start, end, realLength).
realLength might be None if real length is not known ('*').
"""
kind, other = header.strip().split()
if kind.lower() != "bytes":
raise ValueError("a range of type %r is not supported")
startend, realLength = other.split("/")
start, end = map(int, startend.split("-"))
if realLength == "*":
realLength = None
else:
realLength = int(realLength)
return (start, end, realLength)
class _IDeprecatedHTTPChannelToRequestInterface(Interface):
"""
The interface L{HTTPChannel} expects of L{Request}.
"""
requestHeaders = Attribute(
"A L{http_headers.Headers} instance giving all received HTTP request "
"headers."
)
responseHeaders = Attribute(
"A L{http_headers.Headers} instance holding all HTTP response "
"headers to be sent."
)
def connectionLost(reason):
"""
The underlying connection has been lost.
@param reason: A failure instance indicating the reason why
the connection was lost.
@type reason: L{twisted.python.failure.Failure}
"""
def gotLength(length):
"""
Called when L{HTTPChannel} has determined the length, if any,
of the incoming request's body.
@param length: The length of the request's body.
@type length: L{int} if the request declares its body's length
and L{None} if it does not.
"""
def handleContentChunk(data):
"""
Deliver a received chunk of body data to the request. Note
this does not imply chunked transfer encoding.
@param data: The received chunk.
@type data: L{bytes}
"""
def parseCookies():
"""
Parse the request's cookies out of received headers.
"""
def requestReceived(command, path, version):
"""
Called when the entire request, including its body, has been
received.
@param command: The request's HTTP command.
@type command: L{bytes}
@param path: The request's path. Note: this is actually what
RFC7320 calls the URI.
@type path: L{bytes}
@param version: The request's HTTP version.
@type version: L{bytes}
"""
def __eq__(other: object) -> bool:
"""
Determines if two requests are the same object.
@param other: Another object whose identity will be compared
to this instance's.
@return: L{True} when the two are the same object and L{False}
when not.
"""
def __ne__(other: object) -> bool:
"""
Determines if two requests are not the same object.
@param other: Another object whose identity will be compared
to this instance's.
@return: L{True} when the two are not the same object and
L{False} when they are.
"""
def __hash__():
"""
Generate a hash value for the request.
@return: The request's hash value.
@rtype: L{int}
"""
class StringTransport:
"""
I am a BytesIO wrapper that conforms for the transport API. I support
the `writeSequence' method.
"""
def __init__(self):
self.s = BytesIO()
def writeSequence(self, seq):
self.s.write(b"".join(seq))
def __getattr__(self, attr):
return getattr(self.__dict__["s"], attr)
class HTTPClient(basic.LineReceiver):
"""
A client for HTTP 1.0.
Notes:
You probably want to send a 'Host' header with the name of the site you're
connecting to, in order to not break name based virtual hosting.
@ivar length: The length of the request body in bytes.
@type length: C{int}
@ivar firstLine: Are we waiting for the first header line?
@type firstLine: C{bool}
@ivar __buffer: The buffer that stores the response to the HTTP request.
@type __buffer: A C{BytesIO} object.
@ivar _header: Part or all of an HTTP request header.
@type _header: C{bytes}
"""
length = None
firstLine = True
__buffer = None
_header = b""
def sendCommand(self, command, path):
self.transport.writeSequence([command, b" ", path, b" HTTP/1.0\r\n"])
def sendHeader(self, name, value):
if not isinstance(value, bytes):
# XXX Deprecate this case
value = networkString(str(value))
santizedName = _sanitizeLinearWhitespace(name)
santizedValue = _sanitizeLinearWhitespace(value)
self.transport.writeSequence([santizedName, b": ", santizedValue, b"\r\n"])
def endHeaders(self):
self.transport.write(b"\r\n")
def extractHeader(self, header):
"""
Given a complete HTTP header, extract the field name and value and
process the header.
@param header: a complete HTTP request header of the form
'field-name: value'.
@type header: C{bytes}
"""
key, val = header.split(b":", 1)
val = val.lstrip()
self.handleHeader(key, val)
if key.lower() == b"content-length":
self.length = int(val)
def lineReceived(self, line):
"""
Parse the status line and headers for an HTTP request.
@param line: Part of an HTTP request header. Request bodies are parsed
in L{HTTPClient.rawDataReceived}.
@type line: C{bytes}
"""
if self.firstLine:
self.firstLine = False
l = line.split(None, 2)
version = l[0]
status = l[1]
try:
message = l[2]
except IndexError:
# sometimes there is no message
message = b""
self.handleStatus(version, status, message)
return
if not line:
if self._header != b"":
# Only extract headers if there are any
self.extractHeader(self._header)
self.__buffer = BytesIO()
self.handleEndHeaders()
self.setRawMode()
return
if line.startswith(b"\t") or line.startswith(b" "):
# This line is part of a multiline header. According to RFC 822, in
# "unfolding" multiline headers you do not strip the leading
# whitespace on the continuing line.
self._header = self._header + line
elif self._header:
# This line starts a new header, so process the previous one.
self.extractHeader(self._header)
self._header = line
else: # First header
self._header = line
def connectionLost(self, reason):
self.handleResponseEnd()
def handleResponseEnd(self):
"""
The response has been completely received.
This callback may be invoked more than once per request.
"""
if self.__buffer is not None:
b = self.__buffer.getvalue()
self.__buffer = None
self.handleResponse(b)
def handleResponsePart(self, data):
self.__buffer.write(data)
def connectionMade(self):
pass
def handleStatus(self, version, status, message):
"""
Called when the status-line is received.
@param version: e.g. 'HTTP/1.0'
@param status: e.g. '200'
@type status: C{bytes}
@param message: e.g. 'OK'
"""
def handleHeader(self, key, val):
"""
Called every time a header is received.
"""
def handleEndHeaders(self):
"""
Called when all headers have been received.
"""
def rawDataReceived(self, data):
if self.length is not None:
data, rest = data[: self.length], data[self.length :]
self.length -= len(data)
else:
rest = b""
self.handleResponsePart(data)
if self.length == 0:
self.handleResponseEnd()
self.setLineMode(rest)
# response codes that must have empty bodies
NO_BODY_CODES = (204, 304)
# Sentinel object that detects people explicitly passing `queued` to Request.
_QUEUED_SENTINEL = object()
def _getContentFile(length):
"""
Get a writeable file-like object to which request content can be written.
"""
if length is not None and length < 100000:
return BytesIO()
return tempfile.TemporaryFile()
_hostHeaderExpression = re.compile(rb"^\[?(?P<host>.*?)\]?(:\d+)?$")
@implementer(interfaces.IConsumer, _IDeprecatedHTTPChannelToRequestInterface)
class Request:
"""
A HTTP request.
Subclasses should override the process() method to determine how
the request will be processed.
@ivar method: The HTTP method that was used, e.g. C{b'GET'}.
@type method: L{bytes}
@ivar uri: The full encoded URI which was requested (including query
arguments), e.g. C{b'/a/b%20/c?q=v'}.
@type uri: L{bytes}
@ivar path: The encoded path of the request URI (not including query
arguments), e.g. C{b'/a/b%20/c'}.
@type path: L{bytes}
@ivar args: A mapping of decoded query argument names as L{bytes} to
corresponding query argument values as L{list}s of L{bytes}.
For example, for a URI with C{foo=bar&foo=baz&quux=spam}
as its query part C{args} will be C{{b'foo': [b'bar', b'baz'],
b'quux': [b'spam']}}.
@type args: L{dict} of L{bytes} to L{list} of L{bytes}
@ivar content: A file-like object giving the request body. This may be
a file on disk, an L{io.BytesIO}, or some other type. The
implementation is free to decide on a per-request basis.
@type content: L{typing.BinaryIO}
@ivar cookies: The cookies that will be sent in the response.
@type cookies: L{list} of L{bytes}
@type requestHeaders: L{http_headers.Headers}
@ivar requestHeaders: All received HTTP request headers.
@type responseHeaders: L{http_headers.Headers}
@ivar responseHeaders: All HTTP response headers to be sent.
@ivar notifications: A L{list} of L{Deferred}s which are waiting for
notification that the response to this request has been finished
(successfully or with an error). Don't use this attribute directly,
instead use the L{Request.notifyFinish} method.
@ivar _disconnected: A flag which is C{False} until the connection over
which this request was received is closed and which is C{True} after
that.
@type _disconnected: L{bool}
@ivar _log: A logger instance for request related messages.
@type _log: L{twisted.logger.Logger}
"""
producer = None
finished = 0
code = OK
code_message = RESPONSES[OK]
method = b"(no method yet)"
clientproto = b"(no clientproto yet)"
uri = b"(no uri yet)"
startedWriting = 0
chunked = 0
sentLength = 0 # content-length of response, or total bytes sent via chunking
etag = None
lastModified = None
args = None
path = None
content = None
_forceSSL = 0
_disconnected = False
_log = Logger()
def __init__(self, channel: HTTPChannel, queued: object = _QUEUED_SENTINEL) -> None:
"""
@param channel: the channel we're connected to.
@param queued: (deprecated) are we in the request queue, or can we
start writing to the transport?
"""
self.notifications: List[Deferred[None]] = []
self.channel = channel
# Cache the client and server information, we'll need this
# later to be serialized and sent with the request so CGIs
# will work remotely
self.client = self.channel.getPeer()
self.host = self.channel.getHost()
self.requestHeaders: Headers = Headers()
self.received_cookies: Dict[bytes, bytes] = {}
self.responseHeaders: Headers = Headers()
self.cookies: List[bytes] = [] # outgoing cookies
self.transport = self.channel.transport
if queued is _QUEUED_SENTINEL:
queued = False
self.queued = queued
def _cleanup(self):
"""
Called when have finished responding and are no longer queued.
"""
if self.producer:
self._log.failure(
"",
Failure(RuntimeError(f"Producer was not unregistered for {self.uri}")),
)
self.unregisterProducer()
self.channel.requestDone(self)
del self.channel
if self.content is not None:
try:
self.content.close()
except OSError:
# win32 suckiness, no idea why it does this
pass
del self.content
for d in self.notifications:
d.callback(None)
self.notifications = []
# methods for channel - end users should not use these
@deprecated(Version("Twisted", 16, 3, 0))
def noLongerQueued(self):
"""
Notify the object that it is no longer queued.
We start writing whatever data we have to the transport, etc.
This method is not intended for users.
In 16.3 this method was changed to become a no-op, as L{Request}
objects are now never queued.
"""
pass
def gotLength(self, length):
"""
Called when HTTP channel got length of content in this request.
This method is not intended for users.
@param length: The length of the request body, as indicated by the
request headers. L{None} if the request headers do not indicate a
length.
"""
self.content = _getContentFile(length)
def parseCookies(self):
"""
Parse cookie headers.
This method is not intended for users.
"""
cookieheaders = self.requestHeaders.getRawHeaders(b"cookie")
if cookieheaders is None:
return
for cookietxt in cookieheaders:
if cookietxt:
for cook in cookietxt.split(b";"):
cook = cook.lstrip()
try:
k, v = cook.split(b"=", 1)
self.received_cookies[k] = v
except ValueError:
pass
def handleContentChunk(self, data):
"""
Write a chunk of data.
This method is not intended for users.
"""
self.content.write(data)
def requestReceived(self, command, path, version):
"""
Called by channel when all data has been received.
This method is not intended for users.
@type command: C{bytes}
@param command: The HTTP verb of this request. This has the case
supplied by the client (eg, it maybe "get" rather than "GET").
@type path: C{bytes}
@param path: The URI of this request.
@type version: C{bytes}
@param version: The HTTP version of this request.
"""
clength = self.content.tell()
self.content.seek(0, 0)
self.args = {}
self.method, self.uri = command, path
self.clientproto = version
x = self.uri.split(b"?", 1)
if len(x) == 1:
self.path = self.uri
else:
self.path, argstring = x