client.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336
  1. # -*- test-case-name: twisted.web.test.test_webclient,twisted.web.test.test_agent -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. HTTP client.
  6. """
  7. from __future__ import division, absolute_import
  8. import os
  9. import collections
  10. import warnings
  11. try:
  12. from urlparse import urlunparse, urljoin, urldefrag
  13. except ImportError:
  14. from urllib.parse import urljoin, urldefrag
  15. from urllib.parse import urlunparse as _urlunparse
  16. def urlunparse(parts):
  17. result = _urlunparse(tuple([p.decode("charmap") for p in parts]))
  18. return result.encode("charmap")
  19. import zlib
  20. from functools import wraps
  21. from zope.interface import implementer
  22. from twisted.python.compat import _PY3, networkString
  23. from twisted.python.compat import nativeString, intToBytes, unicode, itervalues
  24. from twisted.python.deprecate import deprecatedModuleAttribute, deprecated
  25. from twisted.python.failure import Failure
  26. from incremental import Version
  27. from twisted.web.iweb import IPolicyForHTTPS, IAgentEndpointFactory
  28. from twisted.python.deprecate import getDeprecationWarningString
  29. from twisted.web import http
  30. from twisted.internet import defer, protocol, task, reactor
  31. from twisted.internet.abstract import isIPv6Address
  32. from twisted.internet.interfaces import IProtocol, IOpenSSLContextFactory
  33. from twisted.internet.endpoints import HostnameEndpoint, wrapClientTLS
  34. from twisted.python.util import InsensitiveDict
  35. from twisted.python.components import proxyForInterface
  36. from twisted.web import error
  37. from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse
  38. from twisted.web.http_headers import Headers
  39. from twisted.logger import Logger
  40. from twisted.web._newclient import _ensureValidURI, _ensureValidMethod
  41. class PartialDownloadError(error.Error):
  42. """
  43. Page was only partially downloaded, we got disconnected in middle.
  44. @ivar response: All of the response body which was downloaded.
  45. """
  46. class HTTPPageGetter(http.HTTPClient):
  47. """
  48. Gets a resource via HTTP, then quits.
  49. Typically used with L{HTTPClientFactory}. Note that this class does not, by
  50. itself, do anything with the response. If you want to download a resource
  51. into a file, use L{HTTPPageDownloader} instead.
  52. @ivar _completelyDone: A boolean indicating whether any further requests are
  53. necessary after this one completes in order to provide a result to
  54. C{self.factory.deferred}. If it is C{False}, then a redirect is going
  55. to be followed. Otherwise, this protocol's connection is the last one
  56. before firing the result Deferred. This is used to make sure the result
  57. Deferred is only fired after the connection is cleaned up.
  58. """
  59. quietLoss = 0
  60. followRedirect = True
  61. failed = 0
  62. _completelyDone = True
  63. _specialHeaders = set(
  64. (b'host', b'user-agent', b'cookie', b'content-length'),
  65. )
  66. def connectionMade(self):
  67. method = _ensureValidMethod(getattr(self.factory, 'method', b'GET'))
  68. self.sendCommand(method, _ensureValidURI(self.factory.path))
  69. if self.factory.scheme == b'http' and self.factory.port != 80:
  70. host = self.factory.host + b':' + intToBytes(self.factory.port)
  71. elif self.factory.scheme == b'https' and self.factory.port != 443:
  72. host = self.factory.host + b':' + intToBytes(self.factory.port)
  73. else:
  74. host = self.factory.host
  75. self.sendHeader(b'Host', self.factory.headers.get(b"host", host))
  76. self.sendHeader(b'User-Agent', self.factory.agent)
  77. data = getattr(self.factory, 'postdata', None)
  78. if data is not None:
  79. self.sendHeader(b"Content-Length", intToBytes(len(data)))
  80. cookieData = []
  81. for (key, value) in self.factory.headers.items():
  82. if key.lower() not in self._specialHeaders:
  83. # we calculated it on our own
  84. self.sendHeader(key, value)
  85. if key.lower() == b'cookie':
  86. cookieData.append(value)
  87. for cookie, cookval in self.factory.cookies.items():
  88. cookieData.append(cookie + b'=' + cookval)
  89. if cookieData:
  90. self.sendHeader(b'Cookie', b'; '.join(cookieData))
  91. self.endHeaders()
  92. self.headers = {}
  93. if data is not None:
  94. self.transport.write(data)
  95. def handleHeader(self, key, value):
  96. """
  97. Called every time a header is received. Stores the header information
  98. as key-value pairs in the C{headers} attribute.
  99. @type key: C{str}
  100. @param key: An HTTP header field name.
  101. @type value: C{str}
  102. @param value: An HTTP header field value.
  103. """
  104. key = key.lower()
  105. l = self.headers.setdefault(key, [])
  106. l.append(value)
  107. def handleStatus(self, version, status, message):
  108. """
  109. Handle the HTTP status line.
  110. @param version: The HTTP version.
  111. @type version: L{bytes}
  112. @param status: The HTTP status code, an integer represented as a
  113. bytestring.
  114. @type status: L{bytes}
  115. @param message: The HTTP status message.
  116. @type message: L{bytes}
  117. """
  118. self.version, self.status, self.message = version, status, message
  119. self.factory.gotStatus(version, status, message)
  120. def handleEndHeaders(self):
  121. self.factory.gotHeaders(self.headers)
  122. m = getattr(self, 'handleStatus_' + nativeString(self.status),
  123. self.handleStatusDefault)
  124. m()
  125. def handleStatus_200(self):
  126. pass
  127. handleStatus_201 = lambda self: self.handleStatus_200()
  128. handleStatus_202 = lambda self: self.handleStatus_200()
  129. def handleStatusDefault(self):
  130. self.failed = 1
  131. def handleStatus_301(self):
  132. l = self.headers.get(b'location')
  133. if not l:
  134. self.handleStatusDefault()
  135. return
  136. url = l[0]
  137. if self.followRedirect:
  138. self.factory._redirectCount += 1
  139. if self.factory._redirectCount >= self.factory.redirectLimit:
  140. err = error.InfiniteRedirection(
  141. self.status,
  142. b'Infinite redirection detected',
  143. location=url)
  144. self.factory.noPage(Failure(err))
  145. self.quietLoss = True
  146. self.transport.loseConnection()
  147. return
  148. self._completelyDone = False
  149. self.factory.setURL(url)
  150. if self.factory.scheme == b'https':
  151. from twisted.internet import ssl
  152. contextFactory = ssl.ClientContextFactory()
  153. reactor.connectSSL(nativeString(self.factory.host),
  154. self.factory.port,
  155. self.factory, contextFactory)
  156. else:
  157. reactor.connectTCP(nativeString(self.factory.host),
  158. self.factory.port,
  159. self.factory)
  160. else:
  161. self.handleStatusDefault()
  162. self.factory.noPage(
  163. Failure(
  164. error.PageRedirect(
  165. self.status, self.message, location = url)))
  166. self.quietLoss = True
  167. self.transport.loseConnection()
  168. def handleStatus_302(self):
  169. if self.afterFoundGet:
  170. self.handleStatus_303()
  171. else:
  172. self.handleStatus_301()
  173. def handleStatus_303(self):
  174. self.factory.method = b'GET'
  175. self.handleStatus_301()
  176. def connectionLost(self, reason):
  177. """
  178. When the connection used to issue the HTTP request is closed, notify the
  179. factory if we have not already, so it can produce a result.
  180. """
  181. if not self.quietLoss:
  182. http.HTTPClient.connectionLost(self, reason)
  183. self.factory.noPage(reason)
  184. if self._completelyDone:
  185. # Only if we think we're completely done do we tell the factory that
  186. # we're "disconnected". This way when we're following redirects,
  187. # only the last protocol used will fire the _disconnectedDeferred.
  188. self.factory._disconnectedDeferred.callback(None)
  189. def handleResponse(self, response):
  190. if self.quietLoss:
  191. return
  192. if self.failed:
  193. self.factory.noPage(
  194. Failure(
  195. error.Error(
  196. self.status, self.message, response)))
  197. if self.factory.method == b'HEAD':
  198. # Callback with empty string, since there is never a response
  199. # body for HEAD requests.
  200. self.factory.page(b'')
  201. elif self.length != None and self.length != 0:
  202. self.factory.noPage(Failure(
  203. PartialDownloadError(self.status, self.message, response)))
  204. else:
  205. self.factory.page(response)
  206. # server might be stupid and not close connection. admittedly
  207. # the fact we do only one request per connection is also
  208. # stupid...
  209. self.transport.loseConnection()
  210. def timeout(self):
  211. self.quietLoss = True
  212. self.transport.abortConnection()
  213. self.factory.noPage(defer.TimeoutError("Getting %s took longer than %s seconds." % (self.factory.url, self.factory.timeout)))
  214. class HTTPPageDownloader(HTTPPageGetter):
  215. transmittingPage = 0
  216. def handleStatus_200(self, partialContent=0):
  217. HTTPPageGetter.handleStatus_200(self)
  218. self.transmittingPage = 1
  219. self.factory.pageStart(partialContent)
  220. def handleStatus_206(self):
  221. self.handleStatus_200(partialContent=1)
  222. def handleResponsePart(self, data):
  223. if self.transmittingPage:
  224. self.factory.pagePart(data)
  225. def handleResponseEnd(self):
  226. if self.length:
  227. self.transmittingPage = 0
  228. self.factory.noPage(
  229. Failure(
  230. PartialDownloadError(self.status)))
  231. if self.transmittingPage:
  232. self.factory.pageEnd()
  233. self.transmittingPage = 0
  234. if self.failed:
  235. self.factory.noPage(
  236. Failure(
  237. error.Error(
  238. self.status, self.message, None)))
  239. self.transport.loseConnection()
  240. class HTTPClientFactory(protocol.ClientFactory):
  241. """Download a given URL.
  242. @type deferred: Deferred
  243. @ivar deferred: A Deferred that will fire when the content has
  244. been retrieved. Once this is fired, the ivars `status', `version',
  245. and `message' will be set.
  246. @type status: bytes
  247. @ivar status: The status of the response.
  248. @type version: bytes
  249. @ivar version: The version of the response.
  250. @type message: bytes
  251. @ivar message: The text message returned with the status.
  252. @type response_headers: dict
  253. @ivar response_headers: The headers that were specified in the
  254. response from the server.
  255. @type method: bytes
  256. @ivar method: The HTTP method to use in the request. This should be one of
  257. OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, or CONNECT (case
  258. matters). Other values may be specified if the server being contacted
  259. supports them.
  260. @type redirectLimit: int
  261. @ivar redirectLimit: The maximum number of HTTP redirects that can occur
  262. before it is assumed that the redirection is endless.
  263. @type afterFoundGet: C{bool}
  264. @ivar afterFoundGet: Deviate from the HTTP 1.1 RFC by handling redirects
  265. the same way as most web browsers; if the request method is POST and a
  266. 302 status is encountered, the redirect is followed with a GET method
  267. @type _redirectCount: int
  268. @ivar _redirectCount: The current number of HTTP redirects encountered.
  269. @ivar _disconnectedDeferred: A L{Deferred} which only fires after the last
  270. connection associated with the request (redirects may cause multiple
  271. connections to be required) has closed. The result Deferred will only
  272. fire after this Deferred, so that callers can be assured that there are
  273. no more event sources in the reactor once they get the result.
  274. """
  275. protocol = HTTPPageGetter
  276. url = None
  277. scheme = None
  278. host = b''
  279. port = None
  280. path = None
  281. def __init__(self, url, method=b'GET', postdata=None, headers=None,
  282. agent=b"Twisted PageGetter", timeout=0, cookies=None,
  283. followRedirect=True, redirectLimit=20,
  284. afterFoundGet=False):
  285. self.followRedirect = followRedirect
  286. self.redirectLimit = redirectLimit
  287. self._redirectCount = 0
  288. self.timeout = timeout
  289. self.agent = agent
  290. self.afterFoundGet = afterFoundGet
  291. if cookies is None:
  292. cookies = {}
  293. self.cookies = cookies
  294. if headers is not None:
  295. self.headers = InsensitiveDict(headers)
  296. else:
  297. self.headers = InsensitiveDict()
  298. if postdata is not None:
  299. self.headers.setdefault(b'Content-Length',
  300. intToBytes(len(postdata)))
  301. # just in case a broken http/1.1 decides to keep connection alive
  302. self.headers.setdefault(b"connection", b"close")
  303. self.postdata = postdata
  304. self.method = _ensureValidMethod(method)
  305. self.setURL(url)
  306. self.waiting = 1
  307. self._disconnectedDeferred = defer.Deferred()
  308. self.deferred = defer.Deferred()
  309. # Make sure the first callback on the result Deferred pauses the
  310. # callback chain until the request connection is closed.
  311. self.deferred.addBoth(self._waitForDisconnect)
  312. self.response_headers = None
  313. def _waitForDisconnect(self, passthrough):
  314. """
  315. Chain onto the _disconnectedDeferred, preserving C{passthrough}, so that
  316. the result is only available after the associated connection has been
  317. closed.
  318. """
  319. self._disconnectedDeferred.addCallback(lambda ignored: passthrough)
  320. return self._disconnectedDeferred
  321. def __repr__(self):
  322. return "<%s: %s>" % (self.__class__.__name__, self.url)
  323. def setURL(self, url):
  324. _ensureValidURI(url.strip())
  325. self.url = url
  326. uri = URI.fromBytes(url)
  327. if uri.scheme and uri.host:
  328. self.scheme = uri.scheme
  329. self.host = uri.host
  330. self.port = uri.port
  331. self.path = uri.originForm
  332. def buildProtocol(self, addr):
  333. p = protocol.ClientFactory.buildProtocol(self, addr)
  334. p.followRedirect = self.followRedirect
  335. p.afterFoundGet = self.afterFoundGet
  336. if self.timeout:
  337. timeoutCall = reactor.callLater(self.timeout, p.timeout)
  338. self.deferred.addBoth(self._cancelTimeout, timeoutCall)
  339. return p
  340. def _cancelTimeout(self, result, timeoutCall):
  341. if timeoutCall.active():
  342. timeoutCall.cancel()
  343. return result
  344. def gotHeaders(self, headers):
  345. """
  346. Parse the response HTTP headers.
  347. @param headers: The response HTTP headers.
  348. @type headers: L{dict}
  349. """
  350. self.response_headers = headers
  351. if b'set-cookie' in headers:
  352. for cookie in headers[b'set-cookie']:
  353. if b'=' in cookie:
  354. cookparts = cookie.split(b';')
  355. cook = cookparts[0]
  356. cook.lstrip()
  357. k, v = cook.split(b'=', 1)
  358. self.cookies[k.lstrip()] = v.lstrip()
  359. def gotStatus(self, version, status, message):
  360. """
  361. Set the status of the request on us.
  362. @param version: The HTTP version.
  363. @type version: L{bytes}
  364. @param status: The HTTP status code, an integer represented as a
  365. bytestring.
  366. @type status: L{bytes}
  367. @param message: The HTTP status message.
  368. @type message: L{bytes}
  369. """
  370. self.version, self.status, self.message = version, status, message
  371. def page(self, page):
  372. if self.waiting:
  373. self.waiting = 0
  374. self.deferred.callback(page)
  375. def noPage(self, reason):
  376. if self.waiting:
  377. self.waiting = 0
  378. self.deferred.errback(reason)
  379. def clientConnectionFailed(self, _, reason):
  380. """
  381. When a connection attempt fails, the request cannot be issued. If no
  382. result has yet been provided to the result Deferred, provide the
  383. connection failure reason as an error result.
  384. """
  385. if self.waiting:
  386. self.waiting = 0
  387. # If the connection attempt failed, there is nothing more to
  388. # disconnect, so just fire that Deferred now.
  389. self._disconnectedDeferred.callback(None)
  390. self.deferred.errback(reason)
  391. class HTTPDownloader(HTTPClientFactory):
  392. """
  393. Download to a file.
  394. """
  395. protocol = HTTPPageDownloader
  396. value = None
  397. _log = Logger()
  398. def __init__(self, url, fileOrName,
  399. method=b'GET', postdata=None, headers=None,
  400. agent=b"Twisted client", supportPartial=False,
  401. timeout=0, cookies=None, followRedirect=True,
  402. redirectLimit=20, afterFoundGet=False):
  403. self.requestedPartial = 0
  404. if isinstance(fileOrName, (str, unicode)):
  405. self.fileName = fileOrName
  406. self.file = None
  407. if supportPartial and os.path.exists(self.fileName):
  408. fileLength = os.path.getsize(self.fileName)
  409. if fileLength:
  410. self.requestedPartial = fileLength
  411. if headers == None:
  412. headers = {}
  413. headers[b"range"] = b"bytes=" + intToBytes(fileLength) + b"-"
  414. else:
  415. self.file = fileOrName
  416. HTTPClientFactory.__init__(
  417. self, url, method=method, postdata=postdata, headers=headers,
  418. agent=agent, timeout=timeout, cookies=cookies,
  419. followRedirect=followRedirect, redirectLimit=redirectLimit,
  420. afterFoundGet=afterFoundGet)
  421. def gotHeaders(self, headers):
  422. HTTPClientFactory.gotHeaders(self, headers)
  423. if self.requestedPartial:
  424. contentRange = headers.get(b"content-range", None)
  425. if not contentRange:
  426. # server doesn't support partial requests, oh well
  427. self.requestedPartial = 0
  428. return
  429. start, end, realLength = http.parseContentRange(contentRange[0])
  430. if start != self.requestedPartial:
  431. # server is acting weirdly
  432. self.requestedPartial = 0
  433. def openFile(self, partialContent):
  434. if partialContent:
  435. file = open(self.fileName, 'rb+')
  436. file.seek(0, 2)
  437. else:
  438. file = open(self.fileName, 'wb')
  439. return file
  440. def pageStart(self, partialContent):
  441. """Called on page download start.
  442. @param partialContent: tells us if the download is partial download we requested.
  443. """
  444. if partialContent and not self.requestedPartial:
  445. raise ValueError("we shouldn't get partial content response if we didn't want it!")
  446. if self.waiting:
  447. try:
  448. if not self.file:
  449. self.file = self.openFile(partialContent)
  450. except IOError:
  451. #raise
  452. self.deferred.errback(Failure())
  453. def pagePart(self, data):
  454. if not self.file:
  455. return
  456. try:
  457. self.file.write(data)
  458. except IOError:
  459. #raise
  460. self.file = None
  461. self.deferred.errback(Failure())
  462. def noPage(self, reason):
  463. """
  464. Close the storage file and errback the waiting L{Deferred} with the
  465. given reason.
  466. """
  467. if self.waiting:
  468. self.waiting = 0
  469. if self.file:
  470. try:
  471. self.file.close()
  472. except:
  473. self._log.failure("Error closing HTTPDownloader file")
  474. self.deferred.errback(reason)
  475. def pageEnd(self):
  476. self.waiting = 0
  477. if not self.file:
  478. return
  479. try:
  480. self.file.close()
  481. except IOError:
  482. self.deferred.errback(Failure())
  483. return
  484. self.deferred.callback(self.value)
  485. class URI(object):
  486. """
  487. A URI object.
  488. @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21}
  489. """
  490. def __init__(self, scheme, netloc, host, port, path, params, query,
  491. fragment):
  492. """
  493. @type scheme: L{bytes}
  494. @param scheme: URI scheme specifier.
  495. @type netloc: L{bytes}
  496. @param netloc: Network location component.
  497. @type host: L{bytes}
  498. @param host: Host name. For IPv6 address literals the brackets are
  499. stripped.
  500. @type port: L{int}
  501. @param port: Port number.
  502. @type path: L{bytes}
  503. @param path: Hierarchical path.
  504. @type params: L{bytes}
  505. @param params: Parameters for last path segment.
  506. @type query: L{bytes}
  507. @param query: Query string.
  508. @type fragment: L{bytes}
  509. @param fragment: Fragment identifier.
  510. """
  511. self.scheme = scheme
  512. self.netloc = netloc
  513. self.host = host.strip(b'[]')
  514. self.port = port
  515. self.path = path
  516. self.params = params
  517. self.query = query
  518. self.fragment = fragment
  519. @classmethod
  520. def fromBytes(cls, uri, defaultPort=None):
  521. """
  522. Parse the given URI into a L{URI}.
  523. @type uri: C{bytes}
  524. @param uri: URI to parse.
  525. @type defaultPort: C{int} or L{None}
  526. @param defaultPort: An alternate value to use as the port if the URI
  527. does not include one.
  528. @rtype: L{URI}
  529. @return: Parsed URI instance.
  530. """
  531. uri = uri.strip()
  532. scheme, netloc, path, params, query, fragment = http.urlparse(uri)
  533. if defaultPort is None:
  534. if scheme == b'https':
  535. defaultPort = 443
  536. else:
  537. defaultPort = 80
  538. if b':' in netloc:
  539. host, port = netloc.rsplit(b':', 1)
  540. try:
  541. port = int(port)
  542. except ValueError:
  543. host, port = netloc, defaultPort
  544. else:
  545. host, port = netloc, defaultPort
  546. return cls(scheme, netloc, host, port, path, params, query, fragment)
  547. def toBytes(self):
  548. """
  549. Assemble the individual parts of the I{URI} into a fully formed I{URI}.
  550. @rtype: C{bytes}
  551. @return: A fully formed I{URI}.
  552. """
  553. return urlunparse(
  554. (self.scheme, self.netloc, self.path, self.params, self.query,
  555. self.fragment))
  556. @property
  557. def originForm(self):
  558. """
  559. The absolute I{URI} path including I{URI} parameters, query string and
  560. fragment identifier.
  561. @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p1-messaging-21#section-5.3}
  562. @return: The absolute path in original form.
  563. @rtype: L{bytes}
  564. """
  565. # The HTTP bis draft says the origin form should not include the
  566. # fragment.
  567. path = urlunparse(
  568. (b'', b'', self.path, self.params, self.query, b''))
  569. if path == b'':
  570. path = b'/'
  571. return path
  572. def _urljoin(base, url):
  573. """
  574. Construct a full ("absolute") URL by combining a "base URL" with another
  575. URL. Informally, this uses components of the base URL, in particular the
  576. addressing scheme, the network location and (part of) the path, to provide
  577. missing components in the relative URL.
  578. Additionally, the fragment identifier is preserved according to the HTTP
  579. 1.1 bis draft.
  580. @type base: C{bytes}
  581. @param base: Base URL.
  582. @type url: C{bytes}
  583. @param url: URL to combine with C{base}.
  584. @return: An absolute URL resulting from the combination of C{base} and
  585. C{url}.
  586. @see: L{urlparse.urljoin}
  587. @see: U{https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-22#section-7.1.2}
  588. """
  589. base, baseFrag = urldefrag(base)
  590. url, urlFrag = urldefrag(urljoin(base, url))
  591. return urljoin(url, b'#' + (urlFrag or baseFrag))
  592. def _makeGetterFactory(url, factoryFactory, contextFactory=None,
  593. *args, **kwargs):
  594. """
  595. Create and connect an HTTP page getting factory.
  596. Any additional positional or keyword arguments are used when calling
  597. C{factoryFactory}.
  598. @param factoryFactory: Factory factory that is called with C{url}, C{args}
  599. and C{kwargs} to produce the getter
  600. @param contextFactory: Context factory to use when creating a secure
  601. connection, defaulting to L{None}
  602. @return: The factory created by C{factoryFactory}
  603. """
  604. uri = URI.fromBytes(_ensureValidURI(url.strip()))
  605. factory = factoryFactory(url, *args, **kwargs)
  606. if uri.scheme == b'https':
  607. from twisted.internet import ssl
  608. if contextFactory is None:
  609. contextFactory = ssl.ClientContextFactory()
  610. reactor.connectSSL(
  611. nativeString(uri.host), uri.port, factory, contextFactory)
  612. else:
  613. reactor.connectTCP(nativeString(uri.host), uri.port, factory)
  614. return factory
  615. _GETPAGE_REPLACEMENT_TEXT = "https://pypi.org/project/treq/ or twisted.web.client.Agent"
  616. def _deprecateGetPageClasses():
  617. """
  618. Mark the protocols and factories associated with L{getPage} and
  619. L{downloadPage} as deprecated.
  620. """
  621. for klass in [
  622. HTTPPageGetter, HTTPPageDownloader,
  623. HTTPClientFactory, HTTPDownloader
  624. ]:
  625. deprecatedModuleAttribute(
  626. Version("Twisted", 16, 7, 0),
  627. getDeprecationWarningString(
  628. klass,
  629. Version("Twisted", 16, 7, 0),
  630. replacement=_GETPAGE_REPLACEMENT_TEXT)
  631. .split("; ")[1],
  632. klass.__module__,
  633. klass.__name__)
  634. _deprecateGetPageClasses()
  635. @deprecated(Version("Twisted", 16, 7, 0),
  636. _GETPAGE_REPLACEMENT_TEXT)
  637. def getPage(url, contextFactory=None, *args, **kwargs):
  638. """
  639. Download a web page as a string.
  640. Download a page. Return a deferred, which will callback with a
  641. page (as a string) or errback with a description of the error.
  642. See L{HTTPClientFactory} to see what extra arguments can be passed.
  643. """
  644. return _makeGetterFactory(
  645. url,
  646. HTTPClientFactory,
  647. contextFactory=contextFactory,
  648. *args, **kwargs).deferred
  649. @deprecated(Version("Twisted", 16, 7, 0),
  650. _GETPAGE_REPLACEMENT_TEXT)
  651. def downloadPage(url, file, contextFactory=None, *args, **kwargs):
  652. """
  653. Download a web page to a file.
  654. @param file: path to file on filesystem, or file-like object.
  655. See HTTPDownloader to see what extra args can be passed.
  656. """
  657. factoryFactory = lambda url, *a, **kw: HTTPDownloader(url, file, *a, **kw)
  658. return _makeGetterFactory(
  659. url,
  660. factoryFactory,
  661. contextFactory=contextFactory,
  662. *args, **kwargs).deferred
  663. # The code which follows is based on the new HTTP client implementation. It
  664. # should be significantly better than anything above, though it is not yet
  665. # feature equivalent.
  666. from twisted.web.error import SchemeNotSupported
  667. from twisted.web._newclient import (
  668. HTTP11ClientProtocol,
  669. PotentialDataLoss,
  670. Request,
  671. RequestGenerationFailed,
  672. RequestNotSent,
  673. RequestTransmissionFailed,
  674. Response,
  675. ResponseDone,
  676. ResponseFailed,
  677. ResponseNeverReceived,
  678. _WrapperException,
  679. )
  680. try:
  681. from OpenSSL import SSL
  682. except ImportError:
  683. SSL = None
  684. else:
  685. from twisted.internet.ssl import (CertificateOptions,
  686. platformTrust,
  687. optionsForClientTLS)
  688. def _requireSSL(decoratee):
  689. """
  690. The decorated method requires pyOpenSSL to be present, or it raises
  691. L{NotImplementedError}.
  692. @param decoratee: A function which requires pyOpenSSL.
  693. @type decoratee: L{callable}
  694. @return: A function which raises L{NotImplementedError} if pyOpenSSL is not
  695. installed; otherwise, if it is installed, simply return C{decoratee}.
  696. @rtype: L{callable}
  697. """
  698. if SSL is None:
  699. @wraps(decoratee)
  700. def raiseNotImplemented(*a, **kw):
  701. """
  702. pyOpenSSL is not available.
  703. @param a: The positional arguments for C{decoratee}.
  704. @param kw: The keyword arguments for C{decoratee}.
  705. @raise NotImplementedError: Always.
  706. """
  707. raise NotImplementedError("SSL support unavailable")
  708. return raiseNotImplemented
  709. return decoratee
  710. class WebClientContextFactory(object):
  711. """
  712. This class is deprecated. Please simply use L{Agent} as-is, or if you want
  713. to customize something, use L{BrowserLikePolicyForHTTPS}.
  714. A L{WebClientContextFactory} is an HTTPS policy which totally ignores the
  715. hostname and port. It performs basic certificate verification, however the
  716. lack of validation of service identity (e.g. hostname validation) means it
  717. is still vulnerable to man-in-the-middle attacks. Don't use it any more.
  718. """
  719. def _getCertificateOptions(self, hostname, port):
  720. """
  721. Return a L{CertificateOptions}.
  722. @param hostname: ignored
  723. @param port: ignored
  724. @return: A new CertificateOptions instance.
  725. @rtype: L{CertificateOptions}
  726. """
  727. return CertificateOptions(
  728. method=SSL.SSLv23_METHOD,
  729. trustRoot=platformTrust()
  730. )
  731. @_requireSSL
  732. def getContext(self, hostname, port):
  733. """
  734. Return an L{OpenSSL.SSL.Context}.
  735. @param hostname: ignored
  736. @param port: ignored
  737. @return: A new SSL context.
  738. @rtype: L{OpenSSL.SSL.Context}
  739. """
  740. return self._getCertificateOptions(hostname, port).getContext()
  741. @implementer(IPolicyForHTTPS)
  742. class BrowserLikePolicyForHTTPS(object):
  743. """
  744. SSL connection creator for web clients.
  745. """
  746. def __init__(self, trustRoot=None):
  747. self._trustRoot = trustRoot
  748. @_requireSSL
  749. def creatorForNetloc(self, hostname, port):
  750. """
  751. Create a L{client connection creator
  752. <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} for a
  753. given network location.
  754. @param tls: The TLS protocol to create a connection for.
  755. @type tls: L{twisted.protocols.tls.TLSMemoryBIOProtocol}
  756. @param hostname: The hostname part of the URI.
  757. @type hostname: L{bytes}
  758. @param port: The port part of the URI.
  759. @type port: L{int}
  760. @return: a connection creator with appropriate verification
  761. restrictions set
  762. @rtype: L{client connection creator
  763. <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
  764. """
  765. return optionsForClientTLS(hostname.decode("ascii"),
  766. trustRoot=self._trustRoot)
  767. deprecatedModuleAttribute(Version("Twisted", 14, 0, 0),
  768. getDeprecationWarningString(
  769. WebClientContextFactory,
  770. Version("Twisted", 14, 0, 0),
  771. replacement=BrowserLikePolicyForHTTPS)
  772. .split("; ")[1],
  773. WebClientContextFactory.__module__,
  774. WebClientContextFactory.__name__)
  775. @implementer(IPolicyForHTTPS)
  776. class HostnameCachingHTTPSPolicy(object):
  777. """
  778. IPolicyForHTTPS that wraps a L{IPolicyForHTTPS} and caches the created
  779. L{IOpenSSLClientConnectionCreator}.
  780. This policy will cache up to C{cacheSize}
  781. L{client connection creators <twisted.internet.interfaces.
  782. IOpenSSLClientConnectionCreator>} for reuse in subsequent requests to
  783. the same hostname.
  784. @ivar _policyForHTTPS: See C{policyforHTTPS} parameter of L{__init__}.
  785. @ivar _cache: A cache associating hostnames to their
  786. L{client connection creators <twisted.internet.interfaces.
  787. IOpenSSLClientConnectionCreator>}.
  788. @type _cache: L{collections.OrderedDict}
  789. @ivar _cacheSize: See C{cacheSize} parameter of L{__init__}.
  790. @since: Twisted 19.2.0
  791. """
  792. def __init__(self, policyforHTTPS, cacheSize=20):
  793. """
  794. @param policyforHTTPS: The IPolicyForHTTPS to wrap.
  795. @type policyforHTTPS: L{IPolicyForHTTPS}
  796. @param cacheSize: The maximum size of the hostname cache.
  797. @type cacheSize: L{int}
  798. """
  799. self._policyForHTTPS = policyforHTTPS
  800. self._cache = collections.OrderedDict()
  801. self._cacheSize = cacheSize
  802. def creatorForNetloc(self, hostname, port):
  803. """
  804. Create a L{client connection creator
  805. <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>} for a
  806. given network location and cache it for future use.
  807. @param hostname: The hostname part of the URI.
  808. @type hostname: L{bytes}
  809. @param port: The port part of the URI.
  810. @type port: L{int}
  811. @return: a connection creator with appropriate verification
  812. restrictions set
  813. @rtype: L{client connection creator
  814. <twisted.internet.interfaces.IOpenSSLClientConnectionCreator>}
  815. """
  816. host = hostname.decode("ascii")
  817. try:
  818. creator = self._cache.pop(host)
  819. except KeyError:
  820. creator = self._policyForHTTPS.creatorForNetloc(hostname, port)
  821. self._cache[host] = creator
  822. if len(self._cache) > self._cacheSize:
  823. self._cache.popitem(last=False)
  824. return creator
  825. @implementer(IOpenSSLContextFactory)
  826. class _ContextFactoryWithContext(object):
  827. """
  828. A L{_ContextFactoryWithContext} is like a
  829. L{twisted.internet.ssl.ContextFactory} with a pre-created context.
  830. @ivar _context: A Context.
  831. @type _context: L{OpenSSL.SSL.Context}
  832. """
  833. def __init__(self, context):
  834. """
  835. Initialize a L{_ContextFactoryWithContext} with a context.
  836. @param context: An SSL context.
  837. @type context: L{OpenSSL.SSL.Context}
  838. """
  839. self._context = context
  840. def getContext(self):
  841. """
  842. Return the context created by
  843. L{_DeprecatedToCurrentPolicyForHTTPS._webContextFactory}.
  844. @return: A context.
  845. @rtype context: L{OpenSSL.SSL.Context}
  846. """
  847. return self._context
  848. @implementer(IPolicyForHTTPS)
  849. class _DeprecatedToCurrentPolicyForHTTPS(object):
  850. """
  851. Adapt a web context factory to a normal context factory.
  852. @ivar _webContextFactory: An object providing a getContext method with
  853. C{hostname} and C{port} arguments.
  854. @type _webContextFactory: L{WebClientContextFactory} (or object with a
  855. similar C{getContext} method).
  856. """
  857. def __init__(self, webContextFactory):
  858. """
  859. Wrap a web context factory in an L{IPolicyForHTTPS}.
  860. @param webContextFactory: An object providing a getContext method with
  861. C{hostname} and C{port} arguments.
  862. @type webContextFactory: L{WebClientContextFactory} (or object with a
  863. similar C{getContext} method).
  864. """
  865. self._webContextFactory = webContextFactory
  866. def creatorForNetloc(self, hostname, port):
  867. """
  868. Called the wrapped web context factory's C{getContext} method with a
  869. hostname and port number and return the resulting context object.
  870. @param hostname: The hostname part of the URI.
  871. @type hostname: L{bytes}
  872. @param port: The port part of the URI.
  873. @type port: L{int}
  874. @return: A context factory.
  875. @rtype: L{IOpenSSLContextFactory}
  876. """
  877. context = self._webContextFactory.getContext(hostname, port)
  878. return _ContextFactoryWithContext(context)
  879. @implementer(IBodyProducer)
  880. class FileBodyProducer(object):
  881. """
  882. L{FileBodyProducer} produces bytes from an input file object incrementally
  883. and writes them to a consumer.
  884. Since file-like objects cannot be read from in an event-driven manner,
  885. L{FileBodyProducer} uses a L{Cooperator} instance to schedule reads from
  886. the file. This process is also paused and resumed based on notifications
  887. from the L{IConsumer} provider being written to.
  888. The file is closed after it has been read, or if the producer is stopped
  889. early.
  890. @ivar _inputFile: Any file-like object, bytes read from which will be
  891. written to a consumer.
  892. @ivar _cooperate: A method like L{Cooperator.cooperate} which is used to
  893. schedule all reads.
  894. @ivar _readSize: The number of bytes to read from C{_inputFile} at a time.
  895. """
  896. def __init__(self, inputFile, cooperator=task, readSize=2 ** 16):
  897. self._inputFile = inputFile
  898. self._cooperate = cooperator.cooperate
  899. self._readSize = readSize
  900. self.length = self._determineLength(inputFile)
  901. def _determineLength(self, fObj):
  902. """
  903. Determine how many bytes can be read out of C{fObj} (assuming it is not
  904. modified from this point on). If the determination cannot be made,
  905. return C{UNKNOWN_LENGTH}.
  906. """
  907. try:
  908. seek = fObj.seek
  909. tell = fObj.tell
  910. except AttributeError:
  911. return UNKNOWN_LENGTH
  912. originalPosition = tell()
  913. seek(0, os.SEEK_END)
  914. end = tell()
  915. seek(originalPosition, os.SEEK_SET)
  916. return end - originalPosition
  917. def stopProducing(self):
  918. """
  919. Permanently stop writing bytes from the file to the consumer by
  920. stopping the underlying L{CooperativeTask}.
  921. """
  922. self._inputFile.close()
  923. self._task.stop()
  924. def startProducing(self, consumer):
  925. """
  926. Start a cooperative task which will read bytes from the input file and
  927. write them to C{consumer}. Return a L{Deferred} which fires after all
  928. bytes have been written. If this L{Deferred} is cancelled before it is
  929. fired, stop reading and writing bytes.
  930. @param consumer: Any L{IConsumer} provider
  931. """
  932. self._task = self._cooperate(self._writeloop(consumer))
  933. d = self._task.whenDone()
  934. def maybeStopped(reason):
  935. if reason.check(defer.CancelledError):
  936. self.stopProducing()
  937. elif reason.check(task.TaskStopped):
  938. pass
  939. else:
  940. return reason
  941. # IBodyProducer.startProducing's Deferred isn't supposed to fire if
  942. # stopProducing is called.
  943. return defer.Deferred()
  944. d.addCallbacks(lambda ignored: None, maybeStopped)
  945. return d
  946. def _writeloop(self, consumer):
  947. """
  948. Return an iterator which reads one chunk of bytes from the input file
  949. and writes them to the consumer for each time it is iterated.
  950. """
  951. while True:
  952. bytes = self._inputFile.read(self._readSize)
  953. if not bytes:
  954. self._inputFile.close()
  955. break
  956. consumer.write(bytes)
  957. yield None
  958. def pauseProducing(self):
  959. """
  960. Temporarily suspend copying bytes from the input file to the consumer
  961. by pausing the L{CooperativeTask} which drives that activity.
  962. """
  963. self._task.pause()
  964. def resumeProducing(self):
  965. """
  966. Undo the effects of a previous C{pauseProducing} and resume copying
  967. bytes to the consumer by resuming the L{CooperativeTask} which drives
  968. the write activity.
  969. """
  970. self._task.resume()
  971. class _HTTP11ClientFactory(protocol.Factory):
  972. """
  973. A factory for L{HTTP11ClientProtocol}, used by L{HTTPConnectionPool}.
  974. @ivar _quiescentCallback: The quiescent callback to be passed to protocol
  975. instances, used to return them to the connection pool.
  976. @ivar _metadata: Metadata about the low-level connection details,
  977. used to make the repr more useful.
  978. @since: 11.1
  979. """
  980. def __init__(self, quiescentCallback, metadata):
  981. self._quiescentCallback = quiescentCallback
  982. self._metadata = metadata
  983. def __repr__(self):
  984. return '_HTTP11ClientFactory({}, {})'.format(
  985. self._quiescentCallback,
  986. self._metadata)
  987. def buildProtocol(self, addr):
  988. return HTTP11ClientProtocol(self._quiescentCallback)
  989. class _RetryingHTTP11ClientProtocol(object):
  990. """
  991. A wrapper for L{HTTP11ClientProtocol} that automatically retries requests.
  992. @ivar _clientProtocol: The underlying L{HTTP11ClientProtocol}.
  993. @ivar _newConnection: A callable that creates a new connection for a
  994. retry.
  995. """
  996. def __init__(self, clientProtocol, newConnection):
  997. self._clientProtocol = clientProtocol
  998. self._newConnection = newConnection
  999. def _shouldRetry(self, method, exception, bodyProducer):
  1000. """
  1001. Indicate whether request should be retried.
  1002. Only returns C{True} if method is idempotent, no response was
  1003. received, the reason for the failed request was not due to
  1004. user-requested cancellation, and no body was sent. The latter
  1005. requirement may be relaxed in the future, and PUT added to approved
  1006. method list.
  1007. @param method: The method of the request.
  1008. @type method: L{bytes}
  1009. """
  1010. if method not in (b"GET", b"HEAD", b"OPTIONS", b"DELETE", b"TRACE"):
  1011. return False
  1012. if not isinstance(exception, (RequestNotSent,
  1013. RequestTransmissionFailed,
  1014. ResponseNeverReceived)):
  1015. return False
  1016. if isinstance(exception, _WrapperException):
  1017. for aFailure in exception.reasons:
  1018. if aFailure.check(defer.CancelledError):
  1019. return False
  1020. if bodyProducer is not None:
  1021. return False
  1022. return True
  1023. def request(self, request):
  1024. """
  1025. Do a request, and retry once (with a new connection) if it fails in
  1026. a retryable manner.
  1027. @param request: A L{Request} instance that will be requested using the
  1028. wrapped protocol.
  1029. """
  1030. d = self._clientProtocol.request(request)
  1031. def failed(reason):
  1032. if self._shouldRetry(request.method, reason.value,
  1033. request.bodyProducer):
  1034. return self._newConnection().addCallback(
  1035. lambda connection: connection.request(request))
  1036. else:
  1037. return reason
  1038. d.addErrback(failed)
  1039. return d
  1040. class HTTPConnectionPool(object):
  1041. """
  1042. A pool of persistent HTTP connections.
  1043. Features:
  1044. - Cached connections will eventually time out.
  1045. - Limits on maximum number of persistent connections.
  1046. Connections are stored using keys, which should be chosen such that any
  1047. connections stored under a given key can be used interchangeably.
  1048. Failed requests done using previously cached connections will be retried
  1049. once if they use an idempotent method (e.g. GET), in case the HTTP server
  1050. timed them out.
  1051. @ivar persistent: Boolean indicating whether connections should be
  1052. persistent. Connections are persistent by default.
  1053. @ivar maxPersistentPerHost: The maximum number of cached persistent
  1054. connections for a C{host:port} destination.
  1055. @type maxPersistentPerHost: C{int}
  1056. @ivar cachedConnectionTimeout: Number of seconds a cached persistent
  1057. connection will stay open before disconnecting.
  1058. @ivar retryAutomatically: C{boolean} indicating whether idempotent
  1059. requests should be retried once if no response was received.
  1060. @ivar _factory: The factory used to connect to the proxy.
  1061. @ivar _connections: Map (scheme, host, port) to lists of
  1062. L{HTTP11ClientProtocol} instances.
  1063. @ivar _timeouts: Map L{HTTP11ClientProtocol} instances to a
  1064. C{IDelayedCall} instance of their timeout.
  1065. @since: 12.1
  1066. """
  1067. _factory = _HTTP11ClientFactory
  1068. maxPersistentPerHost = 2
  1069. cachedConnectionTimeout = 240
  1070. retryAutomatically = True
  1071. _log = Logger()
  1072. def __init__(self, reactor, persistent=True):
  1073. self._reactor = reactor
  1074. self.persistent = persistent
  1075. self._connections = {}
  1076. self._timeouts = {}
  1077. def getConnection(self, key, endpoint):
  1078. """
  1079. Supply a connection, newly created or retrieved from the pool, to be
  1080. used for one HTTP request.
  1081. The connection will remain out of the pool (not available to be
  1082. returned from future calls to this method) until one HTTP request has
  1083. been completed over it.
  1084. Afterwards, if the connection is still open, it will automatically be
  1085. added to the pool.
  1086. @param key: A unique key identifying connections that can be used
  1087. interchangeably.
  1088. @param endpoint: An endpoint that can be used to open a new connection
  1089. if no cached connection is available.
  1090. @return: A C{Deferred} that will fire with a L{HTTP11ClientProtocol}
  1091. (or a wrapper) that can be used to send a single HTTP request.
  1092. """
  1093. # Try to get cached version:
  1094. connections = self._connections.get(key)
  1095. while connections:
  1096. connection = connections.pop(0)
  1097. # Cancel timeout:
  1098. self._timeouts[connection].cancel()
  1099. del self._timeouts[connection]
  1100. if connection.state == "QUIESCENT":
  1101. if self.retryAutomatically:
  1102. newConnection = lambda: self._newConnection(key, endpoint)
  1103. connection = _RetryingHTTP11ClientProtocol(
  1104. connection, newConnection)
  1105. return defer.succeed(connection)
  1106. return self._newConnection(key, endpoint)
  1107. def _newConnection(self, key, endpoint):
  1108. """
  1109. Create a new connection.
  1110. This implements the new connection code path for L{getConnection}.
  1111. """
  1112. def quiescentCallback(protocol):
  1113. self._putConnection(key, protocol)
  1114. factory = self._factory(quiescentCallback, repr(endpoint))
  1115. return endpoint.connect(factory)
  1116. def _removeConnection(self, key, connection):
  1117. """
  1118. Remove a connection from the cache and disconnect it.
  1119. """
  1120. connection.transport.loseConnection()
  1121. self._connections[key].remove(connection)
  1122. del self._timeouts[connection]
  1123. def _putConnection(self, key, connection):
  1124. """
  1125. Return a persistent connection to the pool. This will be called by
  1126. L{HTTP11ClientProtocol} when the connection becomes quiescent.
  1127. """
  1128. if connection.state != "QUIESCENT":
  1129. # Log with traceback for debugging purposes:
  1130. try:
  1131. raise RuntimeError(
  1132. "BUG: Non-quiescent protocol added to connection pool.")
  1133. except:
  1134. self._log.failure(
  1135. "BUG: Non-quiescent protocol added to connection pool.")
  1136. return
  1137. connections = self._connections.setdefault(key, [])
  1138. if len(connections) == self.maxPersistentPerHost:
  1139. dropped = connections.pop(0)
  1140. dropped.transport.loseConnection()
  1141. self._timeouts[dropped].cancel()
  1142. del self._timeouts[dropped]
  1143. connections.append(connection)
  1144. cid = self._reactor.callLater(self.cachedConnectionTimeout,
  1145. self._removeConnection,
  1146. key, connection)
  1147. self._timeouts[connection] = cid
  1148. def closeCachedConnections(self):
  1149. """
  1150. Close all persistent connections and remove them from the pool.
  1151. @return: L{defer.Deferred} that fires when all connections have been
  1152. closed.
  1153. """
  1154. results = []
  1155. for protocols in itervalues(self._connections):
  1156. for p in protocols:
  1157. results.append(p.abort())
  1158. self._connections = {}
  1159. for dc in itervalues(self._timeouts):
  1160. dc.cancel()
  1161. self._timeouts = {}
  1162. return defer.gatherResults(results).addCallback(lambda ign: None)
  1163. class _AgentBase(object):
  1164. """
  1165. Base class offering common facilities for L{Agent}-type classes.
  1166. @ivar _reactor: The C{IReactorTime} implementation which will be used by
  1167. the pool, and perhaps by subclasses as well.
  1168. @ivar _pool: The L{HTTPConnectionPool} used to manage HTTP connections.
  1169. """
  1170. def __init__(self, reactor, pool):
  1171. if pool is None:
  1172. pool = HTTPConnectionPool(reactor, False)
  1173. self._reactor = reactor
  1174. self._pool = pool
  1175. def _computeHostValue(self, scheme, host, port):
  1176. """
  1177. Compute the string to use for the value of the I{Host} header, based on
  1178. the given scheme, host name, and port number.
  1179. """
  1180. if (isIPv6Address(nativeString(host))):
  1181. host = b'[' + host + b']'
  1182. if (scheme, port) in ((b'http', 80), (b'https', 443)):
  1183. return host
  1184. return host + b":" + intToBytes(port)
  1185. def _requestWithEndpoint(self, key, endpoint, method, parsedURI,
  1186. headers, bodyProducer, requestPath):
  1187. """
  1188. Issue a new request, given the endpoint and the path sent as part of
  1189. the request.
  1190. """
  1191. if not isinstance(method, bytes):
  1192. raise TypeError('method={!r} is {}, but must be bytes'.format(
  1193. method, type(method)))
  1194. method = _ensureValidMethod(method)
  1195. # Create minimal headers, if necessary:
  1196. if headers is None:
  1197. headers = Headers()
  1198. if not headers.hasHeader(b'host'):
  1199. headers = headers.copy()
  1200. headers.addRawHeader(
  1201. b'host', self._computeHostValue(parsedURI.scheme,
  1202. parsedURI.host,
  1203. parsedURI.port))
  1204. d = self._pool.getConnection(key, endpoint)
  1205. def cbConnected(proto):
  1206. return proto.request(
  1207. Request._construct(method, requestPath, headers, bodyProducer,
  1208. persistent=self._pool.persistent,
  1209. parsedURI=parsedURI))
  1210. d.addCallback(cbConnected)
  1211. return d
  1212. @implementer(IAgentEndpointFactory)
  1213. class _StandardEndpointFactory(object):
  1214. """
  1215. Standard HTTP endpoint destinations - TCP for HTTP, TCP+TLS for HTTPS.
  1216. @ivar _policyForHTTPS: A web context factory which will be used to create
  1217. SSL context objects for any SSL connections the agent needs to make.
  1218. @ivar _connectTimeout: If not L{None}, the timeout passed to
  1219. L{HostnameEndpoint} for specifying the connection timeout.
  1220. @ivar _bindAddress: If not L{None}, the address passed to
  1221. L{HostnameEndpoint} for specifying the local address to bind to.
  1222. """
  1223. def __init__(self, reactor, contextFactory, connectTimeout, bindAddress):
  1224. """
  1225. @param reactor: A provider to use to create endpoints.
  1226. @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
  1227. types.
  1228. @param contextFactory: A factory for TLS contexts, to control the
  1229. verification parameters of OpenSSL.
  1230. @type contextFactory: L{IPolicyForHTTPS}.
  1231. @param connectTimeout: The amount of time that this L{Agent} will wait
  1232. for the peer to accept a connection.
  1233. @type connectTimeout: L{float} or L{None}
  1234. @param bindAddress: The local address for client sockets to bind to.
  1235. @type bindAddress: L{bytes} or L{None}
  1236. """
  1237. self._reactor = reactor
  1238. self._policyForHTTPS = contextFactory
  1239. self._connectTimeout = connectTimeout
  1240. self._bindAddress = bindAddress
  1241. def endpointForURI(self, uri):
  1242. """
  1243. Connect directly over TCP for C{b'http'} scheme, and TLS for
  1244. C{b'https'}.
  1245. @param uri: L{URI} to connect to.
  1246. @return: Endpoint to connect to.
  1247. @rtype: L{IStreamClientEndpoint}
  1248. """
  1249. kwargs = {}
  1250. if self._connectTimeout is not None:
  1251. kwargs['timeout'] = self._connectTimeout
  1252. kwargs['bindAddress'] = self._bindAddress
  1253. try:
  1254. host = nativeString(uri.host)
  1255. except UnicodeDecodeError:
  1256. raise ValueError(("The host of the provided URI ({uri.host!r}) "
  1257. "contains non-ASCII octets, it should be ASCII "
  1258. "decodable.").format(uri=uri))
  1259. endpoint = HostnameEndpoint(self._reactor, host, uri.port, **kwargs)
  1260. if uri.scheme == b'http':
  1261. return endpoint
  1262. elif uri.scheme == b'https':
  1263. connectionCreator = self._policyForHTTPS.creatorForNetloc(uri.host,
  1264. uri.port)
  1265. return wrapClientTLS(connectionCreator, endpoint)
  1266. else:
  1267. raise SchemeNotSupported("Unsupported scheme: %r" % (uri.scheme,))
  1268. @implementer(IAgent)
  1269. class Agent(_AgentBase):
  1270. """
  1271. L{Agent} is a very basic HTTP client. It supports I{HTTP} and I{HTTPS}
  1272. scheme URIs.
  1273. @ivar _pool: An L{HTTPConnectionPool} instance.
  1274. @ivar _endpointFactory: The L{IAgentEndpointFactory} which will
  1275. be used to create endpoints for outgoing connections.
  1276. @since: 9.0
  1277. """
  1278. def __init__(self, reactor,
  1279. contextFactory=BrowserLikePolicyForHTTPS(),
  1280. connectTimeout=None, bindAddress=None,
  1281. pool=None):
  1282. """
  1283. Create an L{Agent}.
  1284. @param reactor: A reactor for this L{Agent} to place outgoing
  1285. connections.
  1286. @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
  1287. types.
  1288. @param contextFactory: A factory for TLS contexts, to control the
  1289. verification parameters of OpenSSL. The default is to use a
  1290. L{BrowserLikePolicyForHTTPS}, so unless you have special
  1291. requirements you can leave this as-is.
  1292. @type contextFactory: L{IPolicyForHTTPS}.
  1293. @param connectTimeout: The amount of time that this L{Agent} will wait
  1294. for the peer to accept a connection.
  1295. @type connectTimeout: L{float}
  1296. @param bindAddress: The local address for client sockets to bind to.
  1297. @type bindAddress: L{bytes}
  1298. @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which
  1299. case a non-persistent L{HTTPConnectionPool} instance will be
  1300. created.
  1301. @type pool: L{HTTPConnectionPool}
  1302. """
  1303. if not IPolicyForHTTPS.providedBy(contextFactory):
  1304. warnings.warn(
  1305. repr(contextFactory) +
  1306. " was passed as the HTTPS policy for an Agent, but it does "
  1307. "not provide IPolicyForHTTPS. Since Twisted 14.0, you must "
  1308. "pass a provider of IPolicyForHTTPS.",
  1309. stacklevel=2, category=DeprecationWarning
  1310. )
  1311. contextFactory = _DeprecatedToCurrentPolicyForHTTPS(contextFactory)
  1312. endpointFactory = _StandardEndpointFactory(
  1313. reactor, contextFactory, connectTimeout, bindAddress)
  1314. self._init(reactor, endpointFactory, pool)
  1315. @classmethod
  1316. def usingEndpointFactory(cls, reactor, endpointFactory, pool=None):
  1317. """
  1318. Create a new L{Agent} that will use the endpoint factory to figure
  1319. out how to connect to the server.
  1320. @param reactor: A reactor for this L{Agent} to place outgoing
  1321. connections.
  1322. @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
  1323. types.
  1324. @param endpointFactory: Used to construct endpoints which the
  1325. HTTP client will connect with.
  1326. @type endpointFactory: an L{IAgentEndpointFactory} provider.
  1327. @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which
  1328. case a non-persistent L{HTTPConnectionPool} instance will be
  1329. created.
  1330. @type pool: L{HTTPConnectionPool}
  1331. @return: A new L{Agent}.
  1332. """
  1333. agent = cls.__new__(cls)
  1334. agent._init(reactor, endpointFactory, pool)
  1335. return agent
  1336. def _init(self, reactor, endpointFactory, pool):
  1337. """
  1338. Initialize a new L{Agent}.
  1339. @param reactor: A reactor for this L{Agent} to place outgoing
  1340. connections.
  1341. @type reactor: see L{HostnameEndpoint.__init__} for acceptable reactor
  1342. types.
  1343. @param endpointFactory: Used to construct endpoints which the
  1344. HTTP client will connect with.
  1345. @type endpointFactory: an L{IAgentEndpointFactory} provider.
  1346. @param pool: An L{HTTPConnectionPool} instance, or L{None}, in which
  1347. case a non-persistent L{HTTPConnectionPool} instance will be
  1348. created.
  1349. @type pool: L{HTTPConnectionPool}
  1350. @return: A new L{Agent}.
  1351. """
  1352. _AgentBase.__init__(self, reactor, pool)
  1353. self._endpointFactory = endpointFactory
  1354. def _getEndpoint(self, uri):
  1355. """
  1356. Get an endpoint for the given URI, using C{self._endpointFactory}.
  1357. @param uri: The URI of the request.
  1358. @type uri: L{URI}
  1359. @return: An endpoint which can be used to connect to given address.
  1360. """
  1361. return self._endpointFactory.endpointForURI(uri)
  1362. def request(self, method, uri, headers=None, bodyProducer=None):
  1363. """
  1364. Issue a request to the server indicated by the given C{uri}.
  1365. An existing connection from the connection pool may be used or a new
  1366. one may be created.
  1367. I{HTTP} and I{HTTPS} schemes are supported in C{uri}.
  1368. @see: L{twisted.web.iweb.IAgent.request}
  1369. """
  1370. uri = _ensureValidURI(uri.strip())
  1371. parsedURI = URI.fromBytes(uri)
  1372. try:
  1373. endpoint = self._getEndpoint(parsedURI)
  1374. except SchemeNotSupported:
  1375. return defer.fail(Failure())
  1376. key = (parsedURI.scheme, parsedURI.host, parsedURI.port)
  1377. return self._requestWithEndpoint(key, endpoint, method, parsedURI,
  1378. headers, bodyProducer,
  1379. parsedURI.originForm)
  1380. @implementer(IAgent)
  1381. class ProxyAgent(_AgentBase):
  1382. """
  1383. An HTTP agent able to cross HTTP proxies.
  1384. @ivar _proxyEndpoint: The endpoint used to connect to the proxy.
  1385. @since: 11.1
  1386. """
  1387. def __init__(self, endpoint, reactor=None, pool=None):
  1388. if reactor is None:
  1389. from twisted.internet import reactor
  1390. _AgentBase.__init__(self, reactor, pool)
  1391. self._proxyEndpoint = endpoint
  1392. def request(self, method, uri, headers=None, bodyProducer=None):
  1393. """
  1394. Issue a new request via the configured proxy.
  1395. """
  1396. uri = _ensureValidURI(uri.strip())
  1397. # Cache *all* connections under the same key, since we are only
  1398. # connecting to a single destination, the proxy:
  1399. key = ("http-proxy", self._proxyEndpoint)
  1400. # To support proxying HTTPS via CONNECT, we will use key
  1401. # ("http-proxy-CONNECT", scheme, host, port), and an endpoint that
  1402. # wraps _proxyEndpoint with an additional callback to do the CONNECT.
  1403. return self._requestWithEndpoint(key, self._proxyEndpoint, method,
  1404. URI.fromBytes(uri), headers,
  1405. bodyProducer, uri)
  1406. class _FakeUrllib2Request(object):
  1407. """
  1408. A fake C{urllib2.Request} object for C{cookielib} to work with.
  1409. @see: U{http://docs.python.org/library/urllib2.html#request-objects}
  1410. @type uri: native L{str}
  1411. @ivar uri: Request URI.
  1412. @type headers: L{twisted.web.http_headers.Headers}
  1413. @ivar headers: Request headers.
  1414. @type type: native L{str}
  1415. @ivar type: The scheme of the URI.
  1416. @type host: native L{str}
  1417. @ivar host: The host[:port] of the URI.
  1418. @since: 11.1
  1419. """
  1420. def __init__(self, uri):
  1421. """
  1422. Create a fake Urllib2 request.
  1423. @param uri: Request URI.
  1424. @type uri: L{bytes}
  1425. """
  1426. self.uri = nativeString(uri)
  1427. self.headers = Headers()
  1428. _uri = URI.fromBytes(uri)
  1429. self.type = nativeString(_uri.scheme)
  1430. self.host = nativeString(_uri.host)
  1431. if (_uri.scheme, _uri.port) not in ((b'http', 80), (b'https', 443)):
  1432. # If it's not a schema on the regular port, add the port.
  1433. self.host += ":" + str(_uri.port)
  1434. if _PY3:
  1435. self.origin_req_host = nativeString(_uri.host)
  1436. self.unverifiable = lambda _: False
  1437. def has_header(self, header):
  1438. return self.headers.hasHeader(networkString(header))
  1439. def add_unredirected_header(self, name, value):
  1440. self.headers.addRawHeader(networkString(name), networkString(value))
  1441. def get_full_url(self):
  1442. return self.uri
  1443. def get_header(self, name, default=None):
  1444. headers = self.headers.getRawHeaders(networkString(name), default)
  1445. if headers is not None:
  1446. headers = [nativeString(x) for x in headers]
  1447. return headers[0]
  1448. return None
  1449. def get_host(self):
  1450. return self.host
  1451. def get_type(self):
  1452. return self.type
  1453. def is_unverifiable(self):
  1454. # In theory this shouldn't be hardcoded.
  1455. return False
  1456. class _FakeUrllib2Response(object):
  1457. """
  1458. A fake C{urllib2.Response} object for C{cookielib} to work with.
  1459. @type response: C{twisted.web.iweb.IResponse}
  1460. @ivar response: Underlying Twisted Web response.
  1461. @since: 11.1
  1462. """
  1463. def __init__(self, response):
  1464. self.response = response
  1465. def info(self):
  1466. class _Meta(object):
  1467. def getheaders(zelf, name):
  1468. # PY2
  1469. headers = self.response.headers.getRawHeaders(name, [])
  1470. return headers
  1471. def get_all(zelf, name, default):
  1472. # PY3
  1473. headers = self.response.headers.getRawHeaders(
  1474. networkString(name), default)
  1475. h = [nativeString(x) for x in headers]
  1476. return h
  1477. return _Meta()
  1478. @implementer(IAgent)
  1479. class CookieAgent(object):
  1480. """
  1481. L{CookieAgent} extends the basic L{Agent} to add RFC-compliant
  1482. handling of HTTP cookies. Cookies are written to and extracted
  1483. from a C{cookielib.CookieJar} instance.
  1484. The same cookie jar instance will be used for any requests through this
  1485. agent, mutating it whenever a I{Set-Cookie} header appears in a response.
  1486. @type _agent: L{twisted.web.client.Agent}
  1487. @ivar _agent: Underlying Twisted Web agent to issue requests through.
  1488. @type cookieJar: C{cookielib.CookieJar}
  1489. @ivar cookieJar: Initialized cookie jar to read cookies from and store
  1490. cookies to.
  1491. @since: 11.1
  1492. """
  1493. def __init__(self, agent, cookieJar):
  1494. self._agent = agent
  1495. self.cookieJar = cookieJar
  1496. def request(self, method, uri, headers=None, bodyProducer=None):
  1497. """
  1498. Issue a new request to the wrapped L{Agent}.
  1499. Send a I{Cookie} header if a cookie for C{uri} is stored in
  1500. L{CookieAgent.cookieJar}. Cookies are automatically extracted and
  1501. stored from requests.
  1502. If a C{'cookie'} header appears in C{headers} it will override the
  1503. automatic cookie header obtained from the cookie jar.
  1504. @see: L{Agent.request}
  1505. """
  1506. if headers is None:
  1507. headers = Headers()
  1508. lastRequest = _FakeUrllib2Request(uri)
  1509. # Setting a cookie header explicitly will disable automatic request
  1510. # cookies.
  1511. if not headers.hasHeader(b'cookie'):
  1512. self.cookieJar.add_cookie_header(lastRequest)
  1513. cookieHeader = lastRequest.get_header('Cookie', None)
  1514. if cookieHeader is not None:
  1515. headers = headers.copy()
  1516. headers.addRawHeader(b'cookie', networkString(cookieHeader))
  1517. d = self._agent.request(method, uri, headers, bodyProducer)
  1518. d.addCallback(self._extractCookies, lastRequest)
  1519. return d
  1520. def _extractCookies(self, response, request):
  1521. """
  1522. Extract response cookies and store them in the cookie jar.
  1523. @type response: L{twisted.web.iweb.IResponse}
  1524. @param response: Twisted Web response.
  1525. @param request: A urllib2 compatible request object.
  1526. """
  1527. resp = _FakeUrllib2Response(response)
  1528. self.cookieJar.extract_cookies(resp, request)
  1529. return response
  1530. class GzipDecoder(proxyForInterface(IResponse)):
  1531. """
  1532. A wrapper for a L{Response} instance which handles gzip'ed body.
  1533. @ivar original: The original L{Response} object.
  1534. @since: 11.1
  1535. """
  1536. def __init__(self, response):
  1537. self.original = response
  1538. self.length = UNKNOWN_LENGTH
  1539. def deliverBody(self, protocol):
  1540. """
  1541. Override C{deliverBody} to wrap the given C{protocol} with
  1542. L{_GzipProtocol}.
  1543. """
  1544. self.original.deliverBody(_GzipProtocol(protocol, self.original))
  1545. class _GzipProtocol(proxyForInterface(IProtocol)):
  1546. """
  1547. A L{Protocol} implementation which wraps another one, transparently
  1548. decompressing received data.
  1549. @ivar _zlibDecompress: A zlib decompress object used to decompress the data
  1550. stream.
  1551. @ivar _response: A reference to the original response, in case of errors.
  1552. @since: 11.1
  1553. """
  1554. def __init__(self, protocol, response):
  1555. self.original = protocol
  1556. self._response = response
  1557. self._zlibDecompress = zlib.decompressobj(16 + zlib.MAX_WBITS)
  1558. def dataReceived(self, data):
  1559. """
  1560. Decompress C{data} with the zlib decompressor, forwarding the raw data
  1561. to the original protocol.
  1562. """
  1563. try:
  1564. rawData = self._zlibDecompress.decompress(data)
  1565. except zlib.error:
  1566. raise ResponseFailed([Failure()], self._response)
  1567. if rawData:
  1568. self.original.dataReceived(rawData)
  1569. def connectionLost(self, reason):
  1570. """
  1571. Forward the connection lost event, flushing remaining data from the
  1572. decompressor if any.
  1573. """
  1574. try:
  1575. rawData = self._zlibDecompress.flush()
  1576. except zlib.error:
  1577. raise ResponseFailed([reason, Failure()], self._response)
  1578. if rawData:
  1579. self.original.dataReceived(rawData)
  1580. self.original.connectionLost(reason)
  1581. @implementer(IAgent)
  1582. class ContentDecoderAgent(object):
  1583. """
  1584. An L{Agent} wrapper to handle encoded content.
  1585. It takes care of declaring the support for content in the
  1586. I{Accept-Encoding} header, and automatically decompresses the received data
  1587. if it's effectively using compression.
  1588. @param decoders: A list or tuple of (name, decoder) objects. The name
  1589. declares which decoding the decoder supports, and the decoder must
  1590. return a response object when called/instantiated. For example,
  1591. C{(('gzip', GzipDecoder))}. The order determines how the decoders are
  1592. going to be advertized to the server.
  1593. @since: 11.1
  1594. """
  1595. def __init__(self, agent, decoders):
  1596. self._agent = agent
  1597. self._decoders = dict(decoders)
  1598. self._supported = b','.join([decoder[0] for decoder in decoders])
  1599. def request(self, method, uri, headers=None, bodyProducer=None):
  1600. """
  1601. Send a client request which declares supporting compressed content.
  1602. @see: L{Agent.request}.
  1603. """
  1604. if headers is None:
  1605. headers = Headers()
  1606. else:
  1607. headers = headers.copy()
  1608. headers.addRawHeader(b'accept-encoding', self._supported)
  1609. deferred = self._agent.request(method, uri, headers, bodyProducer)
  1610. return deferred.addCallback(self._handleResponse)
  1611. def _handleResponse(self, response):
  1612. """
  1613. Check if the response is encoded, and wrap it to handle decompression.
  1614. """
  1615. contentEncodingHeaders = response.headers.getRawHeaders(
  1616. b'content-encoding', [])
  1617. contentEncodingHeaders = b','.join(contentEncodingHeaders).split(b',')
  1618. while contentEncodingHeaders:
  1619. name = contentEncodingHeaders.pop().strip()
  1620. decoder = self._decoders.get(name)
  1621. if decoder is not None:
  1622. response = decoder(response)
  1623. else:
  1624. # Add it back
  1625. contentEncodingHeaders.append(name)
  1626. break
  1627. if contentEncodingHeaders:
  1628. response.headers.setRawHeaders(
  1629. b'content-encoding', [b','.join(contentEncodingHeaders)])
  1630. else:
  1631. response.headers.removeHeader(b'content-encoding')
  1632. return response
  1633. @implementer(IAgent)
  1634. class RedirectAgent(object):
  1635. """
  1636. An L{Agent} wrapper which handles HTTP redirects.
  1637. The implementation is rather strict: 301 and 302 behaves like 307, not
  1638. redirecting automatically on methods different from I{GET} and I{HEAD}.
  1639. See L{BrowserLikeRedirectAgent} for a redirecting Agent that behaves more
  1640. like a web browser.
  1641. @param redirectLimit: The maximum number of times the agent is allowed to
  1642. follow redirects before failing with a L{error.InfiniteRedirection}.
  1643. @cvar _redirectResponses: A L{list} of HTTP status codes to be redirected
  1644. for I{GET} and I{HEAD} methods.
  1645. @cvar _seeOtherResponses: A L{list} of HTTP status codes to be redirected
  1646. for any method and the method altered to I{GET}.
  1647. @since: 11.1
  1648. """
  1649. _redirectResponses = [http.MOVED_PERMANENTLY, http.FOUND,
  1650. http.TEMPORARY_REDIRECT]
  1651. _seeOtherResponses = [http.SEE_OTHER]
  1652. def __init__(self, agent, redirectLimit=20):
  1653. self._agent = agent
  1654. self._redirectLimit = redirectLimit
  1655. def request(self, method, uri, headers=None, bodyProducer=None):
  1656. """
  1657. Send a client request following HTTP redirects.
  1658. @see: L{Agent.request}.
  1659. """
  1660. deferred = self._agent.request(method, uri, headers, bodyProducer)
  1661. return deferred.addCallback(
  1662. self._handleResponse, method, uri, headers, 0)
  1663. def _resolveLocation(self, requestURI, location):
  1664. """
  1665. Resolve the redirect location against the request I{URI}.
  1666. @type requestURI: C{bytes}
  1667. @param requestURI: The request I{URI}.
  1668. @type location: C{bytes}
  1669. @param location: The redirect location.
  1670. @rtype: C{bytes}
  1671. @return: Final resolved I{URI}.
  1672. """
  1673. return _urljoin(requestURI, location)
  1674. def _handleRedirect(self, response, method, uri, headers, redirectCount):
  1675. """
  1676. Handle a redirect response, checking the number of redirects already
  1677. followed, and extracting the location header fields.
  1678. """
  1679. if redirectCount >= self._redirectLimit:
  1680. err = error.InfiniteRedirection(
  1681. response.code,
  1682. b'Infinite redirection detected',
  1683. location=uri)
  1684. raise ResponseFailed([Failure(err)], response)
  1685. locationHeaders = response.headers.getRawHeaders(b'location', [])
  1686. if not locationHeaders:
  1687. err = error.RedirectWithNoLocation(
  1688. response.code, b'No location header field', uri)
  1689. raise ResponseFailed([Failure(err)], response)
  1690. location = self._resolveLocation(uri, locationHeaders[0])
  1691. deferred = self._agent.request(method, location, headers)
  1692. def _chainResponse(newResponse):
  1693. newResponse.setPreviousResponse(response)
  1694. return newResponse
  1695. deferred.addCallback(_chainResponse)
  1696. return deferred.addCallback(
  1697. self._handleResponse, method, uri, headers, redirectCount + 1)
  1698. def _handleResponse(self, response, method, uri, headers, redirectCount):
  1699. """
  1700. Handle the response, making another request if it indicates a redirect.
  1701. """
  1702. if response.code in self._redirectResponses:
  1703. if method not in (b'GET', b'HEAD'):
  1704. err = error.PageRedirect(response.code, location=uri)
  1705. raise ResponseFailed([Failure(err)], response)
  1706. return self._handleRedirect(response, method, uri, headers,
  1707. redirectCount)
  1708. elif response.code in self._seeOtherResponses:
  1709. return self._handleRedirect(response, b'GET', uri, headers,
  1710. redirectCount)
  1711. return response
  1712. class BrowserLikeRedirectAgent(RedirectAgent):
  1713. """
  1714. An L{Agent} wrapper which handles HTTP redirects in the same fashion as web
  1715. browsers.
  1716. Unlike L{RedirectAgent}, the implementation is more relaxed: 301 and 302
  1717. behave like 303, redirecting automatically on any method and altering the
  1718. redirect request to a I{GET}.
  1719. @see: L{RedirectAgent}
  1720. @since: 13.1
  1721. """
  1722. _redirectResponses = [http.TEMPORARY_REDIRECT]
  1723. _seeOtherResponses = [http.MOVED_PERMANENTLY, http.FOUND, http.SEE_OTHER]
  1724. class _ReadBodyProtocol(protocol.Protocol):
  1725. """
  1726. Protocol that collects data sent to it.
  1727. This is a helper for L{IResponse.deliverBody}, which collects the body and
  1728. fires a deferred with it.
  1729. @ivar deferred: See L{__init__}.
  1730. @ivar status: See L{__init__}.
  1731. @ivar message: See L{__init__}.
  1732. @ivar dataBuffer: list of byte-strings received
  1733. @type dataBuffer: L{list} of L{bytes}
  1734. """
  1735. def __init__(self, status, message, deferred):
  1736. """
  1737. @param status: Status of L{IResponse}
  1738. @ivar status: L{int}
  1739. @param message: Message of L{IResponse}
  1740. @type message: L{bytes}
  1741. @param deferred: deferred to fire when response is complete
  1742. @type deferred: L{Deferred} firing with L{bytes}
  1743. """
  1744. self.deferred = deferred
  1745. self.status = status
  1746. self.message = message
  1747. self.dataBuffer = []
  1748. def dataReceived(self, data):
  1749. """
  1750. Accumulate some more bytes from the response.
  1751. """
  1752. self.dataBuffer.append(data)
  1753. def connectionLost(self, reason):
  1754. """
  1755. Deliver the accumulated response bytes to the waiting L{Deferred}, if
  1756. the response body has been completely received without error.
  1757. """
  1758. if reason.check(ResponseDone):
  1759. self.deferred.callback(b''.join(self.dataBuffer))
  1760. elif reason.check(PotentialDataLoss):
  1761. self.deferred.errback(
  1762. PartialDownloadError(self.status, self.message,
  1763. b''.join(self.dataBuffer)))
  1764. else:
  1765. self.deferred.errback(reason)
  1766. def readBody(response):
  1767. """
  1768. Get the body of an L{IResponse} and return it as a byte string.
  1769. This is a helper function for clients that don't want to incrementally
  1770. receive the body of an HTTP response.
  1771. @param response: The HTTP response for which the body will be read.
  1772. @type response: L{IResponse} provider
  1773. @return: A L{Deferred} which will fire with the body of the response.
  1774. Cancelling it will close the connection to the server immediately.
  1775. """
  1776. def cancel(deferred):
  1777. """
  1778. Cancel a L{readBody} call, close the connection to the HTTP server
  1779. immediately, if it is still open.
  1780. @param deferred: The cancelled L{defer.Deferred}.
  1781. """
  1782. abort = getAbort()
  1783. if abort is not None:
  1784. abort()
  1785. d = defer.Deferred(cancel)
  1786. protocol = _ReadBodyProtocol(response.code, response.phrase, d)
  1787. def getAbort():
  1788. return getattr(protocol.transport, 'abortConnection', None)
  1789. response.deliverBody(protocol)
  1790. if protocol.transport is not None and getAbort() is None:
  1791. warnings.warn(
  1792. 'Using readBody with a transport that does not have an '
  1793. 'abortConnection method',
  1794. category=DeprecationWarning,
  1795. stacklevel=2)
  1796. return d
  1797. __all__ = [
  1798. 'Agent',
  1799. 'BrowserLikePolicyForHTTPS',
  1800. 'BrowserLikeRedirectAgent',
  1801. 'ContentDecoderAgent',
  1802. 'CookieAgent',
  1803. 'downloadPage',
  1804. 'getPage',
  1805. 'GzipDecoder',
  1806. 'HTTPClientFactory',
  1807. 'HTTPConnectionPool',
  1808. 'HTTPDownloader',
  1809. 'HTTPPageDownloader',
  1810. 'HTTPPageGetter',
  1811. 'PartialDownloadError',
  1812. 'ProxyAgent',
  1813. 'readBody',
  1814. 'RedirectAgent',
  1815. 'RequestGenerationFailed',
  1816. 'RequestTransmissionFailed',
  1817. 'Response',
  1818. 'ResponseDone',
  1819. 'ResponseFailed',
  1820. 'ResponseNeverReceived',
  1821. 'URI',
  1822. ]