forked from twisted/twisted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_newclient.py
1728 lines (1434 loc) · 62.3 KB
/
_newclient.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_newclient -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
An U{HTTP 1.1<http://www.w3.org/Protocols/rfc2616/rfc2616.html>} client.
The way to use the functionality provided by this module is to:
- Connect a L{HTTP11ClientProtocol} to an HTTP server
- Create a L{Request} with the appropriate data
- Pass the request to L{HTTP11ClientProtocol.request}
- The returned Deferred will fire with a L{Response} object
- Create a L{IProtocol} provider which can handle the response body
- Connect it to the response with L{Response.deliverBody}
- When the protocol's C{connectionLost} method is called, the response is
complete. See L{Response.deliverBody} for details.
Various other classes in this module support this usage:
- HTTPParser is the basic HTTP parser. It can handle the parts of HTTP which
are symmetric between requests and responses.
- HTTPClientParser extends HTTPParser to handle response-specific parts of
HTTP. One instance is created for each request to parse the corresponding
response.
"""
import re
from zope.interface import implementer
from twisted.internet.defer import (
CancelledError,
Deferred,
fail,
maybeDeferred,
succeed,
)
from twisted.internet.error import ConnectionDone
from twisted.internet.interfaces import IConsumer, IPushProducer
from twisted.internet.protocol import Protocol
from twisted.logger import Logger
from twisted.protocols.basic import LineReceiver
from twisted.python.compat import networkString
from twisted.python.components import proxyForInterface
from twisted.python.failure import Failure
from twisted.python.reflect import fullyQualifiedName
from twisted.web.http import (
NO_CONTENT,
NOT_MODIFIED,
PotentialDataLoss,
_ChunkedTransferDecoder,
_DataLoss,
_IdentityTransferDecoder,
)
from twisted.web.http_headers import Headers
from twisted.web.iweb import UNKNOWN_LENGTH, IClientRequest, IResponse
# States HTTPParser can be in
STATUS = "STATUS"
HEADER = "HEADER"
BODY = "BODY"
DONE = "DONE"
_moduleLog = Logger()
class BadHeaders(Exception):
"""
Headers passed to L{Request} were in some way invalid.
"""
class ExcessWrite(Exception):
"""
The body L{IBodyProducer} for a request tried to write data after
indicating it had finished writing data.
"""
class ParseError(Exception):
"""
Some received data could not be parsed.
@ivar data: The string which could not be parsed.
"""
def __init__(self, reason, data):
Exception.__init__(self, reason, data)
self.data = data
class BadResponseVersion(ParseError):
"""
The version string in a status line was unparsable.
"""
class _WrapperException(Exception):
"""
L{_WrapperException} is the base exception type for exceptions which
include one or more other exceptions as the low-level causes.
@ivar reasons: A L{list} of one or more L{Failure} instances encountered
during an HTTP request. See subclass documentation for more details.
"""
def __init__(self, reasons):
Exception.__init__(self, reasons)
self.reasons = reasons
class RequestGenerationFailed(_WrapperException):
"""
There was an error while creating the bytes which make up a request.
@ivar reasons: A C{list} of one or more L{Failure} instances giving the
reasons the request generation was considered to have failed.
"""
class RequestTransmissionFailed(_WrapperException):
"""
There was an error while sending the bytes which make up a request.
@ivar reasons: A C{list} of one or more L{Failure} instances giving the
reasons the request transmission was considered to have failed.
"""
class ConnectionAborted(Exception):
"""
The connection was explicitly aborted by application code.
"""
class WrongBodyLength(Exception):
"""
An L{IBodyProducer} declared the number of bytes it was going to
produce (via its C{length} attribute) and then produced a different number
of bytes.
"""
class ResponseDone(Exception):
"""
L{ResponseDone} may be passed to L{IProtocol.connectionLost} on the
protocol passed to L{Response.deliverBody} and indicates that the entire
response has been delivered.
"""
class ResponseFailed(_WrapperException):
"""
L{ResponseFailed} indicates that all of the response to a request was not
received for some reason.
@ivar reasons: A C{list} of one or more L{Failure} instances giving the
reasons the response was considered to have failed.
@ivar response: If specified, the L{Response} received from the server (and
in particular the status code and the headers).
"""
def __init__(self, reasons, response=None):
_WrapperException.__init__(self, reasons)
self.response = response
class ResponseNeverReceived(ResponseFailed):
"""
A L{ResponseFailed} that knows no response bytes at all have been received.
"""
class RequestNotSent(Exception):
"""
L{RequestNotSent} indicates that an attempt was made to issue a request but
for reasons unrelated to the details of the request itself, the request
could not be sent. For example, this may indicate that an attempt was made
to send a request using a protocol which is no longer connected to a
server.
"""
def _callAppFunction(function):
"""
Call C{function}. If it raises an exception, log it with a minimal
description of the source.
@return: L{None}
"""
try:
function()
except BaseException:
_moduleLog.failure(
"Unexpected exception from {name}", name=fullyQualifiedName(function)
)
class HTTPParser(LineReceiver):
"""
L{HTTPParser} handles the parsing side of HTTP processing. With a suitable
subclass, it can parse either the client side or the server side of the
connection.
@ivar headers: All of the non-connection control message headers yet
received.
@ivar state: State indicator for the response parsing state machine. One
of C{STATUS}, C{HEADER}, C{BODY}, C{DONE}.
@ivar _partialHeader: L{None} or a C{list} of the lines of a multiline
header while that header is being received.
"""
# NOTE: According to HTTP spec, we're supposed to eat the
# 'Proxy-Authenticate' and 'Proxy-Authorization' headers also, but that
# doesn't sound like a good idea to me, because it makes it impossible to
# have a non-authenticating transparent proxy in front of an authenticating
# proxy. An authenticating proxy can eat them itself. -jknight
#
# Further, quoting
# http://homepages.tesco.net/J.deBoynePollard/FGA/web-proxy-connection-header.html
# regarding the 'Proxy-Connection' header:
#
# The Proxy-Connection: header is a mistake in how some web browsers
# use HTTP. Its name is the result of a false analogy. It is not a
# standard part of the protocol. There is a different standard
# protocol mechanism for doing what it does. And its existence
# imposes a requirement upon HTTP servers such that no proxy HTTP
# server can be standards-conforming in practice.
#
# -exarkun
# Some servers (like http://news.ycombinator.com/) return status lines and
# HTTP headers delimited by \n instead of \r\n.
delimiter = b"\n"
CONNECTION_CONTROL_HEADERS = {
b"content-length",
b"connection",
b"keep-alive",
b"te",
b"trailers",
b"transfer-encoding",
b"upgrade",
b"proxy-connection",
}
def connectionMade(self):
self.headers = Headers()
self.connHeaders = Headers()
self.state = STATUS
self._partialHeader = None
def switchToBodyMode(self, decoder):
"""
Switch to body parsing mode - interpret any more bytes delivered as
part of the message body and deliver them to the given decoder.
"""
if self.state == BODY:
raise RuntimeError("already in body mode")
self.bodyDecoder = decoder
self.state = BODY
self.setRawMode()
def lineReceived(self, line):
"""
Handle one line from a response.
"""
# Handle the normal CR LF case.
if line[-1:] == b"\r":
line = line[:-1]
if self.state == STATUS:
self.statusReceived(line)
self.state = HEADER
elif self.state == HEADER:
if not line or line[0] not in b" \t":
if self._partialHeader is not None:
header = b"".join(self._partialHeader)
name, value = header.split(b":", 1)
value = value.strip()
self.headerReceived(name, value)
if not line:
# Empty line means the header section is over.
self.allHeadersReceived()
else:
# Line not beginning with LWS is another header.
self._partialHeader = [line]
else:
# A line beginning with LWS is a continuation of a header
# begun on a previous line.
self._partialHeader.append(line)
def rawDataReceived(self, data):
"""
Pass data from the message body to the body decoder object.
"""
self.bodyDecoder.dataReceived(data)
def isConnectionControlHeader(self, name):
"""
Return C{True} if the given lower-cased name is the name of a
connection control header (rather than an entity header).
According to RFC 2616, section 14.10, the tokens in the Connection
header are probably relevant here. However, I am not sure what the
practical consequences of either implementing or ignoring that are.
So I leave it unimplemented for the time being.
"""
return name in self.CONNECTION_CONTROL_HEADERS
def statusReceived(self, status):
"""
Callback invoked whenever the first line of a new message is received.
Override this.
@param status: The first line of an HTTP request or response message
without trailing I{CR LF}.
@type status: C{bytes}
"""
def headerReceived(self, name, value):
"""
Store the given header in C{self.headers}.
"""
name = name.lower()
if self.isConnectionControlHeader(name):
headers = self.connHeaders
else:
headers = self.headers
headers.addRawHeader(name, value)
def allHeadersReceived(self):
"""
Callback invoked after the last header is passed to C{headerReceived}.
Override this to change to the C{BODY} or C{DONE} state.
"""
self.switchToBodyMode(None)
class HTTPClientParser(HTTPParser):
"""
An HTTP parser which only handles HTTP responses.
@ivar request: The request with which the expected response is associated.
@type request: L{Request}
@ivar NO_BODY_CODES: A C{set} of response codes which B{MUST NOT} have a
body.
@ivar finisher: A callable to invoke when this response is fully parsed.
@ivar _responseDeferred: A L{Deferred} which will be called back with the
response when all headers in the response have been received.
Thereafter, L{None}.
@ivar _everReceivedData: C{True} if any bytes have been received.
"""
NO_BODY_CODES = {NO_CONTENT, NOT_MODIFIED}
_transferDecoders = {
b"chunked": _ChunkedTransferDecoder,
}
bodyDecoder = None
_log = Logger()
def __init__(self, request, finisher):
self.request = request
self.finisher = finisher
self._responseDeferred = Deferred()
self._everReceivedData = False
def dataReceived(self, data):
"""
Override so that we know if any response has been received.
"""
self._everReceivedData = True
HTTPParser.dataReceived(self, data)
def parseVersion(self, strversion):
"""
Parse version strings of the form Protocol '/' Major '.' Minor. E.g.
b'HTTP/1.1'. Returns (protocol, major, minor). Will raise ValueError
on bad syntax.
"""
try:
proto, strnumber = strversion.split(b"/")
major, minor = strnumber.split(b".")
major, minor = int(major), int(minor)
except ValueError as e:
raise BadResponseVersion(str(e), strversion)
if major < 0 or minor < 0:
raise BadResponseVersion("version may not be negative", strversion)
return (proto, major, minor)
def statusReceived(self, status):
"""
Parse the status line into its components and create a response object
to keep track of this response's state.
"""
parts = status.split(b" ", 2)
if len(parts) == 2:
# Some broken servers omit the required `phrase` portion of
# `status-line`. One such server identified as
# "cloudflare-nginx". Others fail to identify themselves
# entirely. Fill in an empty phrase for such cases.
version, codeBytes = parts
phrase = b""
elif len(parts) == 3:
version, codeBytes, phrase = parts
else:
raise ParseError("wrong number of parts", status)
try:
statusCode = int(codeBytes)
except ValueError:
raise ParseError("non-integer status code", status)
self.response = Response._construct(
self.parseVersion(version),
statusCode,
phrase,
self.headers,
self.transport,
self.request,
)
def _finished(self, rest):
"""
Called to indicate that an entire response has been received. No more
bytes will be interpreted by this L{HTTPClientParser}. Extra bytes are
passed up and the state of this L{HTTPClientParser} is set to I{DONE}.
@param rest: A C{bytes} giving any extra bytes delivered to this
L{HTTPClientParser} which are not part of the response being
parsed.
"""
self.state = DONE
self.finisher(rest)
def isConnectionControlHeader(self, name):
"""
Content-Length in the response to a HEAD request is an entity header,
not a connection control header.
"""
if self.request.method == b"HEAD" and name == b"content-length":
return False
return HTTPParser.isConnectionControlHeader(self, name)
def allHeadersReceived(self):
"""
Figure out how long the response body is going to be by examining
headers and stuff.
"""
if 100 <= self.response.code < 200:
# RFC 7231 Section 6.2 says that if we receive a 1XX status code
# and aren't expecting it, we MAY ignore it. That's what we're
# going to do. We reset the parser here, but we leave
# _everReceivedData in its True state because we have, in fact,
# received data.
self._log.info(
"Ignoring unexpected {code} response", code=self.response.code
)
self.connectionMade()
del self.response
return
if self.response.code in self.NO_BODY_CODES or self.request.method == b"HEAD":
self.response.length = 0
# The order of the next two lines might be of interest when adding
# support for pipelining.
self._finished(self.clearLineBuffer())
self.response._bodyDataFinished()
else:
transferEncodingHeaders = self.connHeaders.getRawHeaders(
b"transfer-encoding"
)
if transferEncodingHeaders:
# This could be a KeyError. However, that would mean we do not
# know how to decode the response body, so failing the request
# is as good a behavior as any. Perhaps someday we will want
# to normalize/document/test this specifically, but failing
# seems fine to me for now.
transferDecoder = self._transferDecoders[
transferEncodingHeaders[0].lower()
]
# If anyone ever invents a transfer encoding other than
# chunked (yea right), and that transfer encoding can predict
# the length of the response body, it might be sensible to
# allow the transfer decoder to set the response object's
# length attribute.
else:
contentLengthHeaders = self.connHeaders.getRawHeaders(b"content-length")
if contentLengthHeaders is None:
contentLength = None
elif len(contentLengthHeaders) == 1:
contentLength = int(contentLengthHeaders[0])
self.response.length = contentLength
else:
# "HTTP Message Splitting" or "HTTP Response Smuggling"
# potentially happening. Or it's just a buggy server.
raise ValueError(
"Too many Content-Length headers; " "response is invalid"
)
if contentLength == 0:
self._finished(self.clearLineBuffer())
transferDecoder = None
else:
transferDecoder = lambda x, y: _IdentityTransferDecoder(
contentLength, x, y
)
if transferDecoder is None:
self.response._bodyDataFinished()
else:
# Make sure as little data as possible from the response body
# gets delivered to the response object until the response
# object actually indicates it is ready to handle bytes
# (probably because an application gave it a way to interpret
# them).
self.transport.pauseProducing()
self.switchToBodyMode(
transferDecoder(self.response._bodyDataReceived, self._finished)
)
# This must be last. If it were first, then application code might
# change some state (for example, registering a protocol to receive the
# response body). Then the pauseProducing above would be wrong since
# the response is ready for bytes and nothing else would ever resume
# the transport.
self._responseDeferred.callback(self.response)
del self._responseDeferred
def connectionLost(self, reason):
if self.bodyDecoder is not None:
try:
try:
self.bodyDecoder.noMoreData()
except PotentialDataLoss:
self.response._bodyDataFinished(Failure())
except _DataLoss:
self.response._bodyDataFinished(
Failure(ResponseFailed([reason, Failure()], self.response))
)
else:
self.response._bodyDataFinished()
except BaseException:
# Handle exceptions from both the except suites and the else
# suite. Those functions really shouldn't raise exceptions,
# but maybe there's some buggy application code somewhere
# making things difficult.
self._log.failure("")
elif self.state != DONE:
if self._everReceivedData:
exceptionClass = ResponseFailed
else:
exceptionClass = ResponseNeverReceived
self._responseDeferred.errback(Failure(exceptionClass([reason])))
del self._responseDeferred
_VALID_METHOD = re.compile(
br"\A[%s]+\Z"
% (
bytes().join(
(
b"!",
b"#",
b"$",
b"%",
b"&",
b"'",
b"*",
b"+",
b"-",
b".",
b"^",
b"_",
b"`",
b"|",
b"~",
b"\x30-\x39",
b"\x41-\x5a",
b"\x61-\x7A",
),
),
),
)
def _ensureValidMethod(method):
"""
An HTTP method is an HTTP token, which consists of any visible
ASCII character that is not a delimiter (i.e. one of
C{"(),/:;<=>?@[\\]{}}.)
@param method: the method to check
@type method: L{bytes}
@return: the method if it is valid
@rtype: L{bytes}
@raise ValueError: if the method is not valid
@see: U{https://tools.ietf.org/html/rfc7230#section-3.1.1},
U{https://tools.ietf.org/html/rfc7230#section-3.2.6},
U{https://tools.ietf.org/html/rfc5234#appendix-B.1}
"""
if _VALID_METHOD.match(method):
return method
raise ValueError(f"Invalid method {method!r}")
_VALID_URI = re.compile(br"\A[\x21-\x7e]+\Z")
def _ensureValidURI(uri):
"""
A valid URI cannot contain control characters (i.e., characters
between 0-32, inclusive and 127) or non-ASCII characters (i.e.,
characters with values between 128-255, inclusive).
@param uri: the URI to check
@type uri: L{bytes}
@return: the URI if it is valid
@rtype: L{bytes}
@raise ValueError: if the URI is not valid
@see: U{https://tools.ietf.org/html/rfc3986#section-3.3},
U{https://tools.ietf.org/html/rfc3986#appendix-A},
U{https://tools.ietf.org/html/rfc5234#appendix-B.1}
"""
if _VALID_URI.match(uri):
return uri
raise ValueError(f"Invalid URI {uri!r}")
@implementer(IClientRequest)
class Request:
"""
A L{Request} instance describes an HTTP request to be sent to an HTTP
server.
@ivar method: See L{__init__}.
@ivar uri: See L{__init__}.
@ivar headers: See L{__init__}.
@ivar bodyProducer: See L{__init__}.
@ivar persistent: See L{__init__}.
@ivar _parsedURI: Parsed I{URI} for the request, or L{None}.
@type _parsedURI: L{twisted.web.client.URI} or L{None}
"""
_log = Logger()
def __init__(self, method, uri, headers, bodyProducer, persistent=False):
"""
@param method: The HTTP method for this request, ex: b'GET', b'HEAD',
b'POST', etc.
@type method: L{bytes}
@param uri: The relative URI of the resource to request. For example,
C{b'/foo/bar?baz=quux'}.
@type uri: L{bytes}
@param headers: Headers to be sent to the server. It is important to
note that this object does not create any implicit headers. So it
is up to the HTTP Client to add required headers such as 'Host'.
@type headers: L{twisted.web.http_headers.Headers}
@param bodyProducer: L{None} or an L{IBodyProducer} provider which
produces the content body to send to the remote HTTP server.
@param persistent: Set to C{True} when you use HTTP persistent
connection, defaults to C{False}.
@type persistent: L{bool}
"""
self.method = _ensureValidMethod(method)
self.uri = _ensureValidURI(uri)
self.headers = headers
self.bodyProducer = bodyProducer
self.persistent = persistent
self._parsedURI = None
@classmethod
def _construct(
cls, method, uri, headers, bodyProducer, persistent=False, parsedURI=None
):
"""
Private constructor.
@param method: See L{__init__}.
@param uri: See L{__init__}.
@param headers: See L{__init__}.
@param bodyProducer: See L{__init__}.
@param persistent: See L{__init__}.
@param parsedURI: See L{Request._parsedURI}.
@return: L{Request} instance.
"""
request = cls(method, uri, headers, bodyProducer, persistent)
request._parsedURI = parsedURI
return request
@property
def absoluteURI(self):
"""
The absolute URI of the request as C{bytes}, or L{None} if the
absolute URI cannot be determined.
"""
return getattr(self._parsedURI, "toBytes", lambda: None)()
def _writeHeaders(self, transport, TEorCL):
hosts = self.headers.getRawHeaders(b"host", ())
if len(hosts) != 1:
raise BadHeaders("Exactly one Host header required")
# In the future, having the protocol version be a parameter to this
# method would probably be good. It would be nice if this method
# weren't limited to issuing HTTP/1.1 requests.
requestLines = []
requestLines.append(
b" ".join(
[
_ensureValidMethod(self.method),
_ensureValidURI(self.uri),
b"HTTP/1.1\r\n",
]
),
)
if not self.persistent:
requestLines.append(b"Connection: close\r\n")
if TEorCL is not None:
requestLines.append(TEorCL)
for name, values in self.headers.getAllRawHeaders():
requestLines.extend([name + b": " + v + b"\r\n" for v in values])
requestLines.append(b"\r\n")
transport.writeSequence(requestLines)
def _writeToBodyProducerChunked(self, transport):
"""
Write this request to the given transport using chunked
transfer-encoding to frame the body.
@param transport: See L{writeTo}.
@return: See L{writeTo}.
"""
self._writeHeaders(transport, b"Transfer-Encoding: chunked\r\n")
encoder = ChunkedEncoder(transport)
encoder.registerProducer(self.bodyProducer, True)
d = self.bodyProducer.startProducing(encoder)
def cbProduced(ignored):
encoder.unregisterProducer()
def ebProduced(err):
encoder._allowNoMoreWrites()
# Don't call the encoder's unregisterProducer because it will write
# a zero-length chunk. This would indicate to the server that the
# request body is complete. There was an error, though, so we
# don't want to do that.
transport.unregisterProducer()
return err
d.addCallbacks(cbProduced, ebProduced)
return d
def _writeToBodyProducerContentLength(self, transport):
"""
Write this request to the given transport using content-length to frame
the body.
@param transport: See L{writeTo}.
@return: See L{writeTo}.
"""
self._writeHeaders(
transport,
networkString("Content-Length: %d\r\n" % (self.bodyProducer.length,)),
)
# This Deferred is used to signal an error in the data written to the
# encoder below. It can only errback and it will only do so before too
# many bytes have been written to the encoder and before the producer
# Deferred fires.
finishedConsuming = Deferred()
# This makes sure the producer writes the correct number of bytes for
# the request body.
encoder = LengthEnforcingConsumer(
self.bodyProducer, transport, finishedConsuming
)
transport.registerProducer(self.bodyProducer, True)
finishedProducing = self.bodyProducer.startProducing(encoder)
def combine(consuming, producing):
# This Deferred is returned and will be fired when the first of
# consuming or producing fires. If it's cancelled, forward that
# cancellation to the producer.
def cancelConsuming(ign):
finishedProducing.cancel()
ultimate = Deferred(cancelConsuming)
# Keep track of what has happened so far. This initially
# contains None, then an integer uniquely identifying what
# sequence of events happened. See the callbacks and errbacks
# defined below for the meaning of each value.
state = [None]
def ebConsuming(err):
if state == [None]:
# The consuming Deferred failed first. This means the
# overall writeTo Deferred is going to errback now. The
# producing Deferred should not fire later (because the
# consumer should have called stopProducing on the
# producer), but if it does, a callback will be ignored
# and an errback will be logged.
state[0] = 1
ultimate.errback(err)
else:
# The consuming Deferred errbacked after the producing
# Deferred fired. This really shouldn't ever happen.
# If it does, I goofed. Log the error anyway, just so
# there's a chance someone might notice and complain.
self._log.failure(
"Buggy state machine in {request}/[{state}]: "
"ebConsuming called",
failure=err,
request=repr(self),
state=state[0],
)
def cbProducing(result):
if state == [None]:
# The producing Deferred succeeded first. Nothing will
# ever happen to the consuming Deferred. Tell the
# encoder we're done so it can check what the producer
# wrote and make sure it was right.
state[0] = 2
try:
encoder._noMoreWritesExpected()
except BaseException:
# Fail the overall writeTo Deferred - something the
# producer did was wrong.
ultimate.errback()
else:
# Success - succeed the overall writeTo Deferred.
ultimate.callback(None)
# Otherwise, the consuming Deferred already errbacked. The
# producing Deferred wasn't supposed to fire, but it did
# anyway. It's buggy, but there's not really anything to be
# done about it. Just ignore this result.
def ebProducing(err):
if state == [None]:
# The producing Deferred failed first. This means the
# overall writeTo Deferred is going to errback now.
# Tell the encoder that we're done so it knows to reject
# further writes from the producer (which should not
# happen, but the producer may be buggy).
state[0] = 3
encoder._allowNoMoreWrites()
ultimate.errback(err)
else:
# The producing Deferred failed after the consuming
# Deferred failed. It shouldn't have, so it's buggy.
# Log the exception in case anyone who can fix the code
# is watching.
self._log.failure("Producer is buggy", failure=err)
consuming.addErrback(ebConsuming)
producing.addCallbacks(cbProducing, ebProducing)
return ultimate
d = combine(finishedConsuming, finishedProducing)
def f(passthrough):
# Regardless of what happens with the overall Deferred, once it
# fires, the producer registered way up above the definition of
# combine should be unregistered.
transport.unregisterProducer()
return passthrough
d.addBoth(f)
return d
def _writeToEmptyBodyContentLength(self, transport):
"""
Write this request to the given transport using content-length to frame
the (empty) body.
@param transport: See L{writeTo}.
@return: See L{writeTo}.
"""
self._writeHeaders(transport, b"Content-Length: 0\r\n")
return succeed(None)
def writeTo(self, transport):
"""
Format this L{Request} as an HTTP/1.1 request and write it to the given
transport. If bodyProducer is not None, it will be associated with an
L{IConsumer}.
@param transport: The transport to which to write.
@type transport: L{twisted.internet.interfaces.ITransport} provider
@return: A L{Deferred} which fires with L{None} when the request has
been completely written to the transport or with a L{Failure} if
there is any problem generating the request bytes.
"""
if self.bodyProducer is None:
# If the method semantics anticipate a body, include a
# Content-Length even if it is 0.
# https://tools.ietf.org/html/rfc7230#section-3.3.2
if self.method in (b"PUT", b"POST"):
self._writeToEmptyBodyContentLength(transport)
else:
self._writeHeaders(transport, None)
elif self.bodyProducer.length is UNKNOWN_LENGTH:
return self._writeToBodyProducerChunked(transport)
else:
return self._writeToBodyProducerContentLength(transport)
def stopWriting(self):
"""
Stop writing this request to the transport. This can only be called
after C{writeTo} and before the L{Deferred} returned by C{writeTo}
fires. It should cancel any asynchronous task started by C{writeTo}.
The L{Deferred} returned by C{writeTo} need not be fired if this method
is called.
"""
# If bodyProducer is None, then the Deferred returned by writeTo has
# fired already and this method cannot be called.
_callAppFunction(self.bodyProducer.stopProducing)
class LengthEnforcingConsumer:
"""
An L{IConsumer} proxy which enforces an exact length requirement on the
total data written to it.
@ivar _length: The number of bytes remaining to be written.
@ivar _producer: The L{IBodyProducer} which is writing to this
consumer.
@ivar _consumer: The consumer to which at most C{_length} bytes will be
forwarded.
@ivar _finished: A L{Deferred} which will be fired with a L{Failure} if too
many bytes are written to this consumer.
"""
def __init__(self, producer, consumer, finished):
self._length = producer.length
self._producer = producer
self._consumer = consumer
self._finished = finished
def _allowNoMoreWrites(self):
"""
Indicate that no additional writes are allowed. Attempts to write
after calling this method will be met with an exception.
"""
self._finished = None
def write(self, bytes):
"""
Write C{bytes} to the underlying consumer unless
C{_noMoreWritesExpected} has been called or there are/have been too
many bytes.
"""
if self._finished is None:
# No writes are supposed to happen any more. Try to convince the
# calling code to stop calling this method by calling its
# stopProducing method and then throwing an exception at it. This
# exception isn't documented as part of the API because you're
# never supposed to expect it: only buggy code will ever receive
# it.
self._producer.stopProducing()
raise ExcessWrite()
if len(bytes) <= self._length:
self._length -= len(bytes)
self._consumer.write(bytes)
else: