client.py 72 KB

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