forked from twisted/twisted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
2201 lines (1712 loc) · 71.9 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.
"""
from __future__ import division, absolute_import
import os
import warnings
try:
from urlparse import urlunparse, urljoin, urldefrag
except ImportError:
from urllib.parse import urljoin, urldefrag
from urllib.parse import urlunparse as _urlunparse
def urlunparse(parts):
result = _urlunparse(tuple([p.decode("charmap") for p in parts]))
return result.encode("charmap")
import zlib
from functools import wraps
from zope.interface import implementer
from twisted.python import log
from twisted.python.compat import _PY3, networkString
from twisted.python.compat import nativeString, intToBytes, unicode, itervalues
from twisted.python.deprecate import deprecatedModuleAttribute, deprecated
from twisted.python.failure import Failure
from incremental import Version
from twisted.web.iweb import IPolicyForHTTPS, IAgentEndpointFactory
from twisted.python.deprecate import getDeprecationWarningString
from twisted.web import http
from twisted.internet import defer, protocol, task, reactor
from twisted.internet.abstract import isIPv6Address
from twisted.internet.interfaces import IProtocol, IOpenSSLContextFactory
from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS
from twisted.python.util import InsensitiveDict
from twisted.python.components import proxyForInterface
from twisted.web import error
from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse
from twisted.web.http_headers import Headers
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 HTTPPageGetter(http.HTTPClient):
"""
Gets a resource via HTTP, then quits.
Typically used with L{HTTPClientFactory}. Note that this class does not, by
itself, do anything with the response. If you want to download a resource
into a file, use L{HTTPPageDownloader} instead.
@ivar _completelyDone: A boolean indicating whether any further requests are
necessary after this one completes in order to provide a result to
C{self.factory.deferred}. If it is C{False}, then a redirect is going
to be followed. Otherwise, this protocol's connection is the last one
before firing the result Deferred. This is used to make sure the result
Deferred is only fired after the connection is cleaned up.
"""
quietLoss = 0
followRedirect = True
failed = 0
_completelyDone = True
_specialHeaders = set((b'host', b'user-agent', b'cookie', b'content-length'))
def connectionMade(self):
method = getattr(self.factory, 'method', b'GET')
self.sendCommand(method, self.factory.path)
if self.factory.scheme == b'http' and self.factory.port != 80:
host = self.factory.host + b':' + intToBytes(self.factory.port)
elif self.factory.scheme == b'https' and self.factory.port != 443:
host = self.factory.host + b':' + intToBytes(self.factory.port)
else:
host = self.factory.host
self.sendHeader(b'Host', self.factory.headers.get(b"host", host))
self.sendHeader(b'User-Agent', self.factory.agent)
data = getattr(self.factory, 'postdata', None)
if data is not None:
self.sendHeader(b"Content-Length", intToBytes(len(data)))
cookieData = []
for (key, value) in self.factory.headers.items():
if key.lower() not in self._specialHeaders:
# we calculated it on our own
self.sendHeader(key, value)
if key.lower() == b'cookie':
cookieData.append(value)
for cookie, cookval in self.factory.cookies.items():
cookieData.append(cookie + b'=' + cookval)
if cookieData:
self.sendHeader(b'Cookie', b'; '.join(cookieData))
self.endHeaders()
self.headers = {}
if data is not None:
self.transport.write(data)
def handleHeader(self, key, value):
"""
Called every time a header is received. Stores the header information
as key-value pairs in the C{headers} attribute.
@type key: C{str}
@param key: An HTTP header field name.
@type value: C{str}
@param value: An HTTP header field value.
"""
key = key.lower()
l = self.headers.setdefault(key, [])
l.append(value)
def handleStatus(self, version, status, message):
"""
Handle the HTTP status line.
@param version: The HTTP version.
@type version: L{bytes}
@param status: The HTTP status code, an integer represented as a
bytestring.
@type status: L{bytes}
@param message: The HTTP status message.
@type message: L{bytes}
"""
self.version, self.status, self.message = version, status, message
self.factory.gotStatus(version, status, message)
def handleEndHeaders(self):
self.factory.gotHeaders(self.headers)
m = getattr(self, 'handleStatus_' + nativeString(self.status),
self.handleStatusDefault)
m()
def handleStatus_200(self):
pass
handleStatus_201 = lambda self: self.handleStatus_200()
handleStatus_202 = lambda self: self.handleStatus_200()
def handleStatusDefault(self):
self.failed = 1
def handleStatus_301(self):
l = self.headers.get(b'location')
if not l:
self.handleStatusDefault()
return
url = l[0]
if self.followRedirect:
self.factory._redirectCount += 1
if self.factory._redirectCount >= self.factory.redirectLimit:
err = error.InfiniteRedirection(
self.status,
b'Infinite redirection detected',
location=url)
self.factory.noPage(Failure(err))
self.quietLoss = True
self.transport.loseConnection()
return
self._completelyDone = False
self.factory.setURL(url)
if self.factory.scheme == b'https':
from twisted.internet import ssl
contextFactory = ssl.ClientContextFactory()
reactor.connectSSL(nativeString(self.factory.host),
self.factory.port,
self.factory, contextFactory)
else:
reactor.connectTCP(nativeString(self.factory.host),
self.factory.port,
self.factory)
else:
self.handleStatusDefault()
self.factory.noPage(
Failure(
error.PageRedirect(
self.status, self.message, location = url)))
self.quietLoss = True
self.transport.loseConnection()
def handleStatus_302(self):
if self.afterFoundGet:
self.handleStatus_303()
else:
self.handleStatus_301()
def handleStatus_303(self):
self.factory.method = b'GET'
self.handleStatus_301()
def connectionLost(self, reason):
"""
When the connection used to issue the HTTP request is closed, notify the
factory if we have not already, so it can produce a result.
"""
if not self.quietLoss:
http.HTTPClient.connectionLost(self, reason)
self.factory.noPage(reason)
if self._completelyDone:
# Only if we think we're completely done do we tell the factory that
# we're "disconnected". This way when we're following redirects,
# only the last protocol used will fire the _disconnectedDeferred.
self.factory._disconnectedDeferred.callback(None)
def handleResponse(self, response):
if self.quietLoss:
return
if self.failed:
self.factory.noPage(
Failure(
error.Error(
self.status, self.message, response)))
if self.factory.method == b'HEAD':
# Callback with empty string, since there is never a response
# body for HEAD requests.
self.factory.page(b'')
elif self.length != None and self.length != 0:
self.factory.noPage(Failure(
PartialDownloadError(self.status, self.message, response)))
else:
self.factory.page(response)
# server might be stupid and not close connection. admittedly
# the fact we do only one request per connection is also
# stupid...
self.transport.loseConnection()
def timeout(self):
self.quietLoss = True
self.transport.abortConnection()
self.factory.noPage(defer.TimeoutError("Getting %s took longer than %s seconds." % (self.factory.url, self.factory.timeout)))
class HTTPPageDownloader(HTTPPageGetter):
transmittingPage = 0
def handleStatus_200(self, partialContent=0):
HTTPPageGetter.handleStatus_200(self)
self.transmittingPage = 1
self.factory.pageStart(partialContent)
def handleStatus_206(self):
self.handleStatus_200(partialContent=1)
def handleResponsePart(self, data):
if self.transmittingPage:
self.factory.pagePart(data)
def handleResponseEnd(self):
if self.length:
self.transmittingPage = 0
self.factory.noPage(
Failure(
PartialDownloadError(self.status)))
if self.transmittingPage:
self.factory.pageEnd()
self.transmittingPage = 0
if self.failed:
self.factory.noPage(
Failure(
error.Error(
self.status, self.message, None)))
self.transport.loseConnection()
class HTTPClientFactory(protocol.ClientFactory):
"""Download a given URL.
@type deferred: Deferred
@ivar deferred: A Deferred that will fire when the content has
been retrieved. Once this is fired, the ivars `status', `version',
and `message' will be set.
@type status: bytes
@ivar status: The status of the response.
@type version: bytes
@ivar version: The version of the response.
@type message: bytes
@ivar message: The text message returned with the status.
@type response_headers: dict
@ivar response_headers: The headers that were specified in the
response from the server.
@type method: bytes
@ivar method: The HTTP method to use in the request. This should be one of
OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, or CONNECT (case
matters). Other values may be specified if the server being contacted
supports them.
@type redirectLimit: int
@ivar redirectLimit: The maximum number of HTTP redirects that can occur
before it is assumed that the redirection is endless.
@type afterFoundGet: C{bool}
@ivar afterFoundGet: Deviate from the HTTP 1.1 RFC by handling redirects
the same way as most web browsers; if the request method is POST and a
302 status is encountered, the redirect is followed with a GET method
@type _redirectCount: int
@ivar _redirectCount: The current number of HTTP redirects encountered.
@ivar _disconnectedDeferred: A L{Deferred} which only fires after the last
connection associated with the request (redirects may cause multiple
connections to be required) has closed. The result Deferred will only
fire after this Deferred, so that callers can be assured that there are
no more event sources in the reactor once they get the result.
"""
protocol = HTTPPageGetter
url = None
scheme = None
host = b''
port = None
path = None
def __init__(self, url, method=b'GET', postdata=None, headers=None,
agent=b"Twisted PageGetter", timeout=0, cookies=None,
followRedirect=True, redirectLimit=20,
afterFoundGet=False):
self.followRedirect = followRedirect
self.redirectLimit = redirectLimit
self._redirectCount = 0
self.timeout = timeout
self.agent = agent
self.afterFoundGet = afterFoundGet
if cookies is None:
cookies = {}
self.cookies = cookies
if headers is not None:
self.headers = InsensitiveDict(headers)
else:
self.headers = InsensitiveDict()
if postdata is not None:
self.headers.setdefault(b'Content-Length',
intToBytes(len(postdata)))
# just in case a broken http/1.1 decides to keep connection alive
self.headers.setdefault(b"connection", b"close")
self.postdata = postdata
self.method = method
self.setURL(url)
self.waiting = 1
self._disconnectedDeferred = defer.Deferred()
self.deferred = defer.Deferred()
# Make sure the first callback on the result Deferred pauses the
# callback chain until the request connection is closed.
self.deferred.addBoth(self._waitForDisconnect)
self.response_headers = None
def _waitForDisconnect(self, passthrough):
"""
Chain onto the _disconnectedDeferred, preserving C{passthrough}, so that
the result is only available after the associated connection has been
closed.
"""
self._disconnectedDeferred.addCallback(lambda ignored: passthrough)
return self._disconnectedDeferred
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.url)
def setURL(self, url):
self.url = url
uri = URI.fromBytes(url)
if uri.scheme and uri.host:
self.scheme = uri.scheme
self.host = uri.host
self.port = uri.port
self.path = uri.originForm
def buildProtocol(self, addr):
p = protocol.ClientFactory.buildProtocol(self, addr)
p.followRedirect = self.followRedirect
p.afterFoundGet = self.afterFoundGet
if self.timeout:
timeoutCall = reactor.callLater(self.timeout, p.timeout)
self.deferred.addBoth(self._cancelTimeout, timeoutCall)
return p
def _cancelTimeout(self, result, timeoutCall):
if timeoutCall.active():
timeoutCall.cancel()
return result
def gotHeaders(self, headers):
self.response_headers = headers
if b'set-cookie' in headers:
for cookie in headers[b'set-cookie']:
cookparts = cookie.split(b';')
cook = cookparts[0]
cook.lstrip()
k, v = cook.split(b'=', 1)
self.cookies[k.lstrip()] = v.lstrip()
def gotStatus(self, version, status, message):
"""
Set the status of the request on us.
@param version: The HTTP version.
@type version: L{bytes}
@param status: The HTTP status code, an integer represented as a
bytestring.
@type status: L{bytes}
@param message: The HTTP status message.
@type message: L{bytes}
"""
self.version, self.status, self.message = version, status, message
def page(self, page):
if self.waiting:
self.waiting = 0
self.deferred.callback(page)
def noPage(self, reason):
if self.waiting:
self.waiting = 0
self.deferred.errback(reason)
def clientConnectionFailed(self, _, reason):
"""
When a connection attempt fails, the request cannot be issued. If no
result has yet been provided to the result Deferred, provide the
connection failure reason as an error result.
"""
if self.waiting:
self.waiting = 0
# If the connection attempt failed, there is nothing more to
# disconnect, so just fire that Deferred now.
self._disconnectedDeferred.callback(None)
self.deferred.errback(reason)
class HTTPDownloader(HTTPClientFactory):
"""
Download to a file.
"""
protocol = HTTPPageDownloader
value = None
def __init__(self, url, fileOrName,
method=b'GET', postdata=None, headers=None,
agent=b"Twisted client", supportPartial=False,
timeout=0, cookies=None, followRedirect=True,
redirectLimit=20, afterFoundGet=False):
self.requestedPartial = 0
if isinstance(fileOrName, (str, unicode)):
self.fileName = fileOrName
self.file = None
if supportPartial and os.path.exists(self.fileName):
fileLength = os.path.getsize(self.fileName)
if fileLength:
self.requestedPartial = fileLength
if headers == None:
headers = {}
headers[b"range"] = b"bytes=" + intToBytes(fileLength) + b"-"
else:
self.file = fileOrName
HTTPClientFactory.__init__(
self, url, method=method, postdata=postdata, headers=headers,
agent=agent, timeout=timeout, cookies=cookies,
followRedirect=followRedirect, redirectLimit=redirectLimit,
afterFoundGet=afterFoundGet)
def gotHeaders(self, headers):
HTTPClientFactory.gotHeaders(self, headers)
if self.requestedPartial:
contentRange = headers.get(b"content-range", None)
if not contentRange:
# server doesn't support partial requests, oh well
self.requestedPartial = 0
return
start, end, realLength = http.parseContentRange(contentRange[0])
if start != self.requestedPartial:
# server is acting weirdly
self.requestedPartial = 0
def openFile(self, partialContent):
if partialContent:
file = open(self.fileName, 'rb+')
file.seek(0, 2)
else:
file = open(self.fileName, 'wb')
return file
def pageStart(self, partialContent):
"""Called on page download start.
@param partialContent: tells us if the download is partial download we requested.
"""
if partialContent and not self.requestedPartial:
raise ValueError("we shouldn't get partial content response if we didn't want it!")
if self.waiting:
try:
if not self.file:
self.file = self.openFile(partialContent)
except IOError:
#raise
self.deferred.errback(Failure())
def pagePart(self, data):
if not self.file:
return
try:
self.file.write(data)
except IOError:
#raise
self.file = None
self.deferred.errback(Failure())
def noPage(self, reason):
"""
Close the storage file and errback the waiting L{Deferred} with the
given reason.
"""
if self.waiting:
self.waiting = 0
if self.file:
try:
self.file.close()
except:
log.err(None, "Error closing HTTPDownloader file")
self.deferred.errback(reason)
def pageEnd(self):
self.waiting = 0
if not self.file:
return
try:
self.file.close()
except IOError:
self.deferred.errback(Failure())
return
self.deferred.callback(self.value)
class URI(object):
"""
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{urlparse.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(url)
factory = factoryFactory(url, *args, **kwargs)
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
_GETPAGE_REPLACEMENT_TEXT = "https://pypi.org/project/treq/ or twisted.web.client.Agent"
def _deprecateGetPageClasses():
"""
Mark the protocols and factories associated with L{getPage} and
L{downloadPage} as deprecated.
"""
for klass in [
HTTPPageGetter, HTTPPageDownloader,
HTTPClientFactory, HTTPDownloader
]:
deprecatedModuleAttribute(
Version("Twisted", 16, 7, 0),
getDeprecationWarningString(
klass,
Version("Twisted", 16, 7, 0),
replacement=_GETPAGE_REPLACEMENT_TEXT)
.split("; ")[1],
klass.__module__,
klass.__name__)
_deprecateGetPageClasses()
@deprecated(Version("Twisted", 16, 7, 0),
_GETPAGE_REPLACEMENT_TEXT)
def getPage(url, contextFactory=None, *args, **kwargs):
"""
Download a web page as a string.
Download a page. Return a deferred, which will callback with a
page (as a string) or errback with a description of the error.
See L{HTTPClientFactory} to see what extra arguments can be passed.
"""
return _makeGetterFactory(
url,
HTTPClientFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
@deprecated(Version("Twisted", 16, 7, 0),
_GETPAGE_REPLACEMENT_TEXT)
def downloadPage(url, file, contextFactory=None, *args, **kwargs):
"""
Download a web page to a file.
@param file: path to file on filesystem, or file-like object.
See HTTPDownloader to see what extra args can be passed.
"""
factoryFactory = lambda url, *a, **kw: HTTPDownloader(url, file, *a, **kw)
return _makeGetterFactory(
url,
factoryFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
# 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.error import SchemeNotSupported
from twisted.web._newclient import Request, Response, HTTP11ClientProtocol
from twisted.web._newclient import ResponseDone, ResponseFailed
from twisted.web._newclient import RequestNotSent, RequestTransmissionFailed
from twisted.web._newclient import (
ResponseNeverReceived, PotentialDataLoss, _WrapperException)
try:
from OpenSSL import SSL
except ImportError:
SSL = None
else:
from twisted.internet.ssl import (CertificateOptions,
platformTrust,
optionsForClientTLS)
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(object):
"""
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(object):
"""
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 tls: The TLS protocol to create a connection for.
@type tls: L{twisted.protocols.tls.TLSMemoryBIOProtocol}
@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(IOpenSSLContextFactory)
class _ContextFactoryWithContext(object):
"""
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 context: L{OpenSSL.SSL.Context}
"""
return self._context
@implementer(IPolicyForHTTPS)
class _DeprecatedToCurrentPolicyForHTTPS(object):
"""
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