forked from twisted/twisted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
1789 lines (1425 loc) · 56.6 KB
/
client.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_webclient,twisted.web.test.test_agent -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
HTTP client.
"""
import collections
import os
import warnings
import zlib
from functools import wraps
from typing import Iterable
from urllib.parse import urldefrag, urljoin, urlunparse as _urlunparse
from zope.interface import implementer
from incremental import Version
from twisted.internet import defer, protocol, task
from twisted.internet.abstract import isIPv6Address
from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS
from twisted.internet.interfaces import IOpenSSLContextFactory, IProtocol
from twisted.logger import Logger
from twisted.python.compat import nativeString, networkString
from twisted.python.components import proxyForInterface
from twisted.python.deprecate import (
deprecatedModuleAttribute,
getDeprecationWarningString,
)
from twisted.python.failure import Failure
from twisted.web import error, http
from twisted.web._newclient import _ensureValidMethod, _ensureValidURI
from twisted.web.http_headers import Headers
from twisted.web.iweb import (
UNKNOWN_LENGTH,
IAgent,
IAgentEndpointFactory,
IBodyProducer,
IPolicyForHTTPS,
IResponse,
)
def urlunparse(parts):
result = _urlunparse(tuple(p.decode("charmap") for p in parts))
return result.encode("charmap")
class PartialDownloadError(error.Error):
"""
Page was only partially downloaded, we got disconnected in middle.
@ivar response: All of the response body which was downloaded.
"""
class URI:
"""
A URI object.
@see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21}
"""
def __init__(self, scheme, netloc, host, port, path, params, query, fragment):
"""
@type scheme: L{bytes}
@param scheme: URI scheme specifier.
@type netloc: L{bytes}
@param netloc: Network location component.
@type host: L{bytes}
@param host: Host name. For IPv6 address literals the brackets are
stripped.
@type port: L{int}
@param port: Port number.
@type path: L{bytes}
@param path: Hierarchical path.
@type params: L{bytes}
@param params: Parameters for last path segment.
@type query: L{bytes}
@param query: Query string.
@type fragment: L{bytes}
@param fragment: Fragment identifier.
"""
self.scheme = scheme
self.netloc = netloc
self.host = host.strip(b"[]")
self.port = port
self.path = path
self.params = params
self.query = query
self.fragment = fragment
@classmethod
def fromBytes(cls, uri, defaultPort=None):
"""
Parse the given URI into a L{URI}.
@type uri: C{bytes}
@param uri: URI to parse.
@type defaultPort: C{int} or L{None}
@param defaultPort: An alternate value to use as the port if the URI
does not include one.
@rtype: L{URI}
@return: Parsed URI instance.
"""
uri = uri.strip()
scheme, netloc, path, params, query, fragment = http.urlparse(uri)
if defaultPort is None:
if scheme == b"https":
defaultPort = 443
else:
defaultPort = 80
if b":" in netloc:
host, port = netloc.rsplit(b":", 1)
try:
port = int(port)
except ValueError:
host, port = netloc, defaultPort
else:
host, port = netloc, defaultPort
return cls(scheme, netloc, host, port, path, params, query, fragment)
def toBytes(self):
"""
Assemble the individual parts of the I{URI} into a fully formed I{URI}.
@rtype: C{bytes}
@return: A fully formed I{URI}.
"""
return urlunparse(
(
self.scheme,
self.netloc,
self.path,
self.params,
self.query,
self.fragment,
)
)
@property
def originForm(self):
"""
The absolute I{URI} path including I{URI} parameters, query string and
fragment identifier.
@see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21#section-5.3}
@return: The absolute path in original form.
@rtype: L{bytes}
"""
# The HTTP bis draft says the origin form should not include the
# fragment.
path = urlunparse((b"", b"", self.path, self.params, self.query, b""))
if path == b"":
path = b"/"
return path
def _urljoin(base, url):
"""
Construct a full ("absolute") URL by combining a "base URL" with another
URL. Informally, this uses components of the base URL, in particular the
addressing scheme, the network location and (part of) the path, to provide
missing components in the relative URL.
Additionally, the fragment identifier is preserved according to the HTTP
1.1 bis draft.
@type base: C{bytes}
@param base: Base URL.
@type url: C{bytes}
@param url: URL to combine with C{base}.
@return: An absolute URL resulting from the combination of C{base} and
C{url}.
@see: L{urllib.parse.urljoin()}
@see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2}
"""
base, baseFrag = urldefrag(base)
url, urlFrag = urldefrag(urljoin(base, url))
return urljoin(url, b"#" + (urlFrag or baseFrag))
def _makeGetterFactory(url, factoryFactory, contextFactory=None, *args, **kwargs):
"""
Create and connect an HTTP page getting factory.
Any additional positional or keyword arguments are used when calling
C{factoryFactory}.
@param factoryFactory: Factory factory that is called with C{url}, C{args}
and C{kwargs} to produce the getter
@param contextFactory: Context factory to use when creating a secure
connection, defaulting to L{None}
@return: The factory created by C{factoryFactory}
"""
uri = URI.fromBytes(_ensureValidURI(url.strip()))
factory = factoryFactory(url, *args, **kwargs)
from twisted.internet import reactor
if uri.scheme == b"https":
from twisted.internet import ssl
if contextFactory is None:
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(nativeString(uri.host), uri.port, factory, contextFactory)
else:
reactor.connectTCP(nativeString(uri.host), uri.port, factory)
return factory
# The code which follows is based on the new HTTP client implementation. It
# should be significantly better than anything above, though it is not yet
# feature equivalent.
from twisted.web._newclient import (
HTTP11ClientProtocol,
PotentialDataLoss,
Request,
RequestGenerationFailed,
RequestNotSent,
RequestTransmissionFailed,
Response,
ResponseDone,
ResponseFailed,
ResponseNeverReceived,
_WrapperException,
)
from twisted.web.error import SchemeNotSupported
try:
from OpenSSL import SSL
except ImportError:
SSL = None # type: ignore[assignment]
else:
from twisted.internet.ssl import (
CertificateOptions,
optionsForClientTLS,
platformTrust,
)
def _requireSSL(decoratee):
"""
The decorated method requires pyOpenSSL to be present, or it raises
L{NotImplementedError}.
@param decoratee: A function which requires pyOpenSSL.
@type decoratee: L{callable}
@return: A function which raises L{NotImplementedError} if pyOpenSSL is not
installed; otherwise, if it is installed, simply return C{decoratee}.
@rtype: L{callable}
"""
if SSL is None:
@wraps(decoratee)
def raiseNotImplemented(*a, **kw):
"""
pyOpenSSL is not available.
@param a: The positional arguments for C{decoratee}.
@param kw: The keyword arguments for C{decoratee}.
@raise NotImplementedError: Always.
"""
raise NotImplementedError("SSL support unavailable")
return raiseNotImplemented
return decoratee
class WebClientContextFactory:
"""
This class is deprecated. Please simply use L{Agent} as-is, or if you want
to customize something, use L{BrowserLikePolicyForHTTPS}.
A L{WebClientContextFactory} is an HTTPS policy which totally ignores the
hostname and port. It performs basic certificate verification, however the
lack of validation of service identity (e.g. hostname validation) means it
is still vulnerable to man-in-the-middle attacks. Don't use it any more.
"""
def _getCertificateOptions(self, hostname, port):
"""
Return a L{CertificateOptions}.
@param hostname: ignored
@param port: ignored
@return: A new CertificateOptions instance.
@rtype: L{CertificateOptions}
"""
return CertificateOptions(method=SSL.SSLv23_METHOD, trustRoot=platformTrust())
@_requireSSL
def getContext(self, hostname, port):
"""
Return an L{OpenSSL.SSL.Context}.
@param hostname: ignored
@param port: ignored
@return: A new SSL context.
@rtype: L{OpenSSL.SSL.Context}
"""
return self._getCertificateOptions(hostname, port).getContext()
@implementer(IPolicyForHTTPS)
class BrowserLikePolicyForHTTPS:
"""
SSL connection creator for web clients.
"""
def __init__(self, trustRoot=None):
self._trustRoot = trustRoot
@_requireSSL
def creatorForNetloc(self, hostname, port):
"""
Create a L{client connection creator
<twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} for a
given network location.
@param hostname: The hostname part of the URI.
@type hostname: L{bytes}
@param port: The port part of the URI.
@type port: L{int}
@return: a connection creator with appropriate verification
restrictions set
@rtype: L{client connection creator
<twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
"""
return optionsForClientTLS(hostname.decode("ascii"), trustRoot=self._trustRoot)
deprecatedModuleAttribute(
Version("Twisted", 14, 0, 0),
getDeprecationWarningString(
WebClientContextFactory,
Version("Twisted", 14, 0, 0),
replacement=BrowserLikePolicyForHTTPS,
).split("; ")[1],
WebClientContextFactory.__module__,
WebClientContextFactory.__name__,
)
@implementer(IPolicyForHTTPS)
class HostnameCachingHTTPSPolicy:
"""
IPolicyForHTTPS that wraps a L{IPolicyForHTTPS} and caches the created
L{IOpenSSLClientConnectionCreator}.
This policy will cache up to C{cacheSize}
L{client connection creators <twisted.internet.interfaces.
IOpenSSLClientConnectionCreator>} for reuse in subsequent requests to
the same hostname.
@ivar _policyForHTTPS: See C{policyforHTTPS} parameter of L{__init__}.
@ivar _cache: A cache associating hostnames to their
L{client connection creators <twisted.internet.interfaces.
IOpenSSLClientConnectionCreator>}.
@type _cache: L{collections.OrderedDict}
@ivar _cacheSize: See C{cacheSize} parameter of L{__init__}.
@since: Twisted 19.2.0
"""
def __init__(self, policyforHTTPS, cacheSize=20):
"""
@param policyforHTTPS: The IPolicyForHTTPS to wrap.
@type policyforHTTPS: L{IPolicyForHTTPS}
@param cacheSize: The maximum size of the hostname cache.
@type cacheSize: L{int}
"""
self._policyForHTTPS = policyforHTTPS
self._cache = collections.OrderedDict()
self._cacheSize = cacheSize
def creatorForNetloc(self, hostname, port):
"""
Create a L{client connection creator
<twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} for a
given network location and cache it for future use.
@param hostname: The hostname part of the URI.
@type hostname: L{bytes}
@param port: The port part of the URI.
@type port: L{int}
@return: a connection creator with appropriate verification
restrictions set
@rtype: L{client connection creator
<twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
"""
host = hostname.decode("ascii")
try:
creator = self._cache.pop(host)
except KeyError:
creator = self._policyForHTTPS.creatorForNetloc(hostname, port)
self._cache[host] = creator
if len(self._cache) > self._cacheSize:
self._cache.popitem(last=False)
return creator
@implementer(IOpenSSLContextFactory)
class _ContextFactoryWithContext:
"""
A L{_ContextFactoryWithContext} is like a
L{twisted.internet.ssl.ContextFactory} with a pre-created context.
@ivar _context: A Context.
@type _context: L{OpenSSL.SSL.Context}
"""
def __init__(self, context):
"""
Initialize a L{_ContextFactoryWithContext} with a context.
@param context: An SSL context.
@type context: L{OpenSSL.SSL.Context}
"""
self._context = context
def getContext(self):
"""
Return the context created by
L{_DeprecatedToCurrentPolicyForHTTPS._webContextFactory}.
@return: A context.
@rtype: L{OpenSSL.SSL.Context}
"""
return self._context
@implementer(IPolicyForHTTPS)
class _DeprecatedToCurrentPolicyForHTTPS:
"""
Adapt a web context factory to a normal context factory.
@ivar _webContextFactory: An object providing a getContext method with
C{hostname} and C{port} arguments.
@type _webContextFactory: L{WebClientContextFactory} (or object with a
similar C{getContext} method).
"""
def __init__(self, webContextFactory):
"""
Wrap a web context factory in an L{IPolicyForHTTPS}.
@param webContextFactory: An object providing a getContext method with
C{hostname} and C{port} arguments.
@type webContextFactory: L{WebClientContextFactory} (or object with a
similar C{getContext} method).
"""
self._webContextFactory = webContextFactory
def creatorForNetloc(self, hostname, port):
"""
Called the wrapped web context factory's C{getContext} method with a
hostname and port number and return the resulting context object.
@param hostname: The hostname part of the URI.
@type hostname: L{bytes}
@param port: The port part of the URI.
@type port: L{int}
@return: A context factory.
@rtype: L{IOpenSSLContextFactory}
"""
context = self._webContextFactory.getContext(hostname, port)
return _ContextFactoryWithContext(context)
@implementer(IBodyProducer)
class FileBodyProducer:
"""
L{FileBodyProducer} produces bytes from an input file object incrementally
and writes them to a consumer.
Since file-like objects cannot be read from in an event-driven manner,
L{FileBodyProducer} uses a L{Cooperator} instance to schedule reads from
the file. This process is also paused and resumed based on notifications
from the L{IConsumer} provider being written to.
The file is closed after it has been read, or if the producer is stopped
early.
@ivar _inputFile: Any file-like object, bytes read from which will be
written to a consumer.
@ivar _cooperate: A method like L{Cooperator.cooperate} which is used to
schedule all reads.
@ivar _readSize: The number of bytes to read from C{_inputFile} at a time.
"""
def __init__(self, inputFile, cooperator=task, readSize=2 ** 16):
self._inputFile = inputFile
self._cooperate = cooperator.cooperate
self._readSize = readSize
self.length = self._determineLength(inputFile)
def _determineLength(self, fObj):
"""
Determine how many bytes can be read out of C{fObj} (assuming it is not
modified from this point on). If the determination cannot be made,
return C{UNKNOWN_LENGTH}.
"""
try:
seek = fObj.seek
tell = fObj.tell
except AttributeError:
return UNKNOWN_LENGTH
originalPosition = tell()
seek(0, os.SEEK_END)
end = tell()
seek(originalPosition, os.SEEK_SET)
return end - originalPosition
def stopProducing(self):
"""
Permanently stop writing bytes from the file to the consumer by
stopping the underlying L{CooperativeTask}.
"""
self._inputFile.close()
try:
self._task.stop()
except task.TaskFinished:
pass
def startProducing(self, consumer):
"""
Start a cooperative task which will read bytes from the input file and
write them to C{consumer}. Return a L{Deferred} which fires after all
bytes have been written. If this L{Deferred} is cancelled before it is
fired, stop reading and writing bytes.
@param consumer: Any L{IConsumer} provider
"""
self._task = self._cooperate(self._writeloop(consumer))
d = self._task.whenDone()
def maybeStopped(reason):
if reason.check(defer.CancelledError):
self.stopProducing()
elif reason.check(task.TaskStopped):
pass
else:
return reason
# IBodyProducer.startProducing's Deferred isn't supposed to fire if
# stopProducing is called.
return defer.Deferred()
d.addCallbacks(lambda ignored: None, maybeStopped)
return d
def _writeloop(self, consumer):
"""
Return an iterator which reads one chunk of bytes from the input file
and writes them to the consumer for each time it is iterated.
"""
while True:
bytes = self._inputFile.read(self._readSize)
if not bytes:
self._inputFile.close()
break
consumer.write(bytes)
yield None
def pauseProducing(self):
"""
Temporarily suspend copying bytes from the input file to the consumer
by pausing the L{CooperativeTask} which drives that activity.
"""
self._task.pause()
def resumeProducing(self):
"""
Undo the effects of a previous C{pauseProducing} and resume copying
bytes to the consumer by resuming the L{CooperativeTask} which drives
the write activity.
"""
self._task.resume()
class _HTTP11ClientFactory(protocol.Factory):
"""
A factory for L{HTTP11ClientProtocol}, used by L{HTTPConnectionPool}.
@ivar _quiescentCallback: The quiescent callback to be passed to protocol
instances, used to return them to the connection pool.
@ivar _metadata: Metadata about the low-level connection details,
used to make the repr more useful.
@since: 11.1
"""
def __init__(self, quiescentCallback, metadata):
self._quiescentCallback = quiescentCallback
self._metadata = metadata
def __repr__(self) -> str:
return "_HTTP11ClientFactory({}, {})".format(
self._quiescentCallback, self._metadata
)
def buildProtocol(self, addr):
return HTTP11ClientProtocol(self._quiescentCallback)
class _RetryingHTTP11ClientProtocol:
"""
A wrapper for L{HTTP11ClientProtocol} that automatically retries requests.
@ivar _clientProtocol: The underlying L{HTTP11ClientProtocol}.
@ivar _newConnection: A callable that creates a new connection for a
retry.
"""
def __init__(self, clientProtocol, newConnection):
self._clientProtocol = clientProtocol
self._newConnection = newConnection
def _shouldRetry(self, method, exception, bodyProducer):
"""
Indicate whether request should be retried.
Only returns C{True} if method is idempotent, no response was
received, the reason for the failed request was not due to
user-requested cancellation, and no body was sent. The latter
requirement may be relaxed in the future, and PUT added to approved
method list.
@param method: The method of the request.
@type method: L{bytes}
"""
if method not in (b"GET", b"HEAD", b"OPTIONS", b"DELETE", b"TRACE"):
return False
if not isinstance(
exception,
(RequestNotSent, RequestTransmissionFailed, ResponseNeverReceived),
):
return False
if isinstance(exception, _WrapperException):
for aFailure in exception.reasons:
if aFailure.check(defer.CancelledError):
return False
if bodyProducer is not None:
return False
return True
def request(self, request):
"""
Do a request, and retry once (with a new connection) if it fails in
a retryable manner.
@param request: A L{Request} instance that will be requested using the
wrapped protocol.
"""
d = self._clientProtocol.request(request)
def failed(reason):
if self._shouldRetry(request.method, reason.value, request.bodyProducer):
return self._newConnection().addCallback(
lambda connection: connection.request(request)
)
else:
return reason
d.addErrback(failed)
return d
class HTTPConnectionPool:
"""
A pool of persistent HTTP connections.
Features:
- Cached connections will eventually time out.
- Limits on maximum number of persistent connections.
Connections are stored using keys, which should be chosen such that any
connections stored under a given key can be used interchangeably.
Failed requests done using previously cached connections will be retried
once if they use an idempotent method (e.g. GET), in case the HTTP server
timed them out.
@ivar persistent: Boolean indicating whether connections should be
persistent. Connections are persistent by default.
@ivar maxPersistentPerHost: The maximum number of cached persistent
connections for a C{host:port} destination.
@type maxPersistentPerHost: C{int}
@ivar cachedConnectionTimeout: Number of seconds a cached persistent
connection will stay open before disconnecting.
@ivar retryAutomatically: C{boolean} indicating whether idempotent
requests should be retried once if no response was received.
@ivar _factory: The factory used to connect to the proxy.
@ivar _connections: Map (scheme, host, port) to lists of
L{HTTP11ClientProtocol} instances.
@ivar _timeouts: Map L{HTTP11ClientProtocol} instances to a
C{IDelayedCall} instance of their timeout.
@since: 12.1
"""
_factory = _HTTP11ClientFactory
maxPersistentPerHost = 2
cachedConnectionTimeout = 240
retryAutomatically = True
_log = Logger()
def __init__(self, reactor, persistent=True):
self._reactor = reactor
self.persistent = persistent
self._connections = {}
self._timeouts = {}
def getConnection(self, key, endpoint):
"""
Supply a connection, newly created or retrieved from the pool, to be
used for one HTTP request.
The connection will remain out of the pool (not available to be
returned from future calls to this method) until one HTTP request has
been completed over it.
Afterwards, if the connection is still open, it will automatically be
added to the pool.
@param key: A unique key identifying connections that can be used
interchangeably.
@param endpoint: An endpoint that can be used to open a new connection
if no cached connection is available.
@return: A C{Deferred} that will fire with a L{HTTP11ClientProtocol}
(or a wrapper) that can be used to send a single HTTP request.
"""
# Try to get cached version:
connections = self._connections.get(key)
while connections:
connection = connections.pop(0)
# Cancel timeout:
self._timeouts[connection].cancel()
del self._timeouts[connection]
if connection.state == "QUIESCENT":
if self.retryAutomatically:
newConnection = lambda: self._newConnection(key, endpoint)
connection = _RetryingHTTP11ClientProtocol(
connection, newConnection
)
return defer.succeed(connection)
return self._newConnection(key, endpoint)
def _newConnection(self, key, endpoint):
"""
Create a new connection.
This implements the new connection code path for L{getConnection}.
"""
def quiescentCallback(protocol):
self._putConnection(key, protocol)
factory = self._factory(quiescentCallback, repr(endpoint))
return endpoint.connect(factory)
def _removeConnection(self, key, connection):
"""
Remove a connection from the cache and disconnect it.
"""
connection.transport.loseConnection()
self._connections[key].remove(connection)
del self._timeouts[connection]
def _putConnection(self, key, connection):
"""
Return a persistent connection to the pool. This will be called by
L{HTTP11ClientProtocol} when the connection becomes quiescent.
"""
if connection.state != "QUIESCENT":
# Log with traceback for debugging purposes:
try:
raise RuntimeError(
"BUG: Non-quiescent protocol added to connection pool."
)
except BaseException:
self._log.failure(
"BUG: Non-quiescent protocol added to connection pool."
)
return
connections = self._connections.setdefault(key, [])
if len(connections) == self.maxPersistentPerHost:
dropped = connections.pop(0)
dropped.transport.loseConnection()
self._timeouts[dropped].cancel()
del self._timeouts[dropped]
connections.append(connection)
cid = self._reactor.callLater(
self.cachedConnectionTimeout, self._removeConnection, key, connection
)
self._timeouts[connection] = cid
def closeCachedConnections(self):
"""
Close all persistent connections and remove them from the pool.
@return: L{defer.Deferred} that fires when all connections have been
closed.
"""
results = []
for protocols in self._connections.values():
for p in protocols:
results.append(p.abort())
self._connections = {}
for dc in self._timeouts.values():
dc.cancel()
self._timeouts = {}
return defer.gatherResults(results).addCallback(lambda ign: None)
class _AgentBase:
"""
Base class offering common facilities for L{Agent}-type classes.
@ivar _reactor: The C{IReactorTime} implementation which will be used by
the pool, and perhaps by subclasses as well.
@ivar _pool: The L{HTTPConnectionPool} used to manage HTTP connections.
"""
def __init__(self, reactor, pool):
if pool is None:
pool = HTTPConnectionPool(reactor, False)
self._reactor = reactor
self._pool = pool
def _computeHostValue(self, scheme, host, port):
"""
Compute the string to use for the value of the I{Host} header, based on
the given scheme, host name, and port number.
"""
if isIPv6Address(nativeString(host)):
host = b"[" + host + b"]"
if (scheme, port) in ((b"http", 80), (b"https", 443)):
return host
return b"%b:%d" % (host, port)
def _requestWithEndpoint(
self, key, endpoint, method, parsedURI, headers, bodyProducer, requestPath
):
"""
Issue a new request, given the endpoint and the path sent as part of
the request.
"""
if not isinstance(method, bytes):
raise TypeError(f"method={method!r} is {type(method)}, but must be bytes")
method = _ensureValidMethod(method)
# Create minimal headers, if necessary:
if headers is None:
headers = Headers()
if not headers.hasHeader(b"host"):
headers = headers.copy()
headers.addRawHeader(
b"host",
self._computeHostValue(
parsedURI.scheme, parsedURI.host, parsedURI.port
),
)
d = self._pool.getConnection(key, endpoint)
def cbConnected(proto):
return proto.request(
Request._construct(
method,
requestPath,
headers,
bodyProducer,
persistent=self._pool.persistent,
parsedURI=parsedURI,
)
)
d.addCallback(cbConnected)
return d
@implementer(IAgentEndpointFactory)
class _StandardEndpointFactory:
"""
Standard HTTP endpoint destinations - TCP for HTTP, TCP+TLS for HTTPS.
@ivar _policyForHTTPS: A web context factory which will be used to create
SSL context objects for any SSL connections the agent needs to make.
@ivar _connectTimeout: If not L{None}, the timeout passed to
L{HostnameEndpoint} for specifying the connection timeout.
@ivar _bindAddress: If not L{None}, the address passed to
L{HostnameEndpoint} for specifying the local address to bind to.
"""
def __init__(self, reactor, contextFactory, connectTimeout, bindAddress):
"""
@param reactor: A provider to use to create endpoints.
@type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
types.
@param contextFactory: A factory for TLS contexts, to control the
verification parameters of OpenSSL.
@type contextFactory: L{IPolicyForHTTPS}.
@param connectTimeout: The amount of time that this L{Agent} will wait
for the peer to accept a connection.
@type connectTimeout: L{float} or L{None}
@param bindAddress: The local address for client sockets to bind to.
@type bindAddress: L{bytes} or L{None}
"""
self._reactor = reactor
self._policyForHTTPS = contextFactory
self._connectTimeout = connectTimeout
self._bindAddress = bindAddress
def endpointForURI(self, uri):
"""
Connect directly over TCP for C{b'http'} scheme, and TLS for
C{b'https'}.
@param uri: L{URI} to connect to.
@return: Endpoint to connect to.
@rtype: L{IStreamClientEndpoint}
"""
kwargs = {}
if self._connectTimeout is not None:
kwargs["timeout"] = self._connectTimeout
kwargs["bindAddress"] = self._bindAddress
try:
host = nativeString(uri.host)
except UnicodeDecodeError:
raise ValueError(
(
"The host of the provided URI ({uri.host!r}) "
"contains non-ASCII octets, it should be ASCII "
"decodable."
).format(uri=uri)
)
endpoint = HostnameEndpoint(self._reactor, host, uri.port, **kwargs)
if uri.scheme == b"http":