PageRenderTime 60ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/scrapy/xlib/tx/client.py

https://gitlab.com/oytunistrator/scrapy
Python | 1168 lines | 1121 code | 16 blank | 31 comment | 3 complexity | 2772ce6665bcec6ad58e8fa298aee28c MD5 | raw file
  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. try:
  10. from urlparse import urlunparse
  11. from urllib import splithost, splittype
  12. except ImportError:
  13. from urllib.parse import splithost, splittype
  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 zope.interface import implementer
  20. from twisted.python import log
  21. from twisted.python.failure import Failure
  22. from twisted.web import http
  23. from twisted.internet import defer, protocol, task, reactor
  24. from twisted.internet.interfaces import IProtocol
  25. from twisted.python import failure
  26. from twisted.python.components import proxyForInterface
  27. from twisted.web import error
  28. from twisted.web.http_headers import Headers
  29. from .endpoints import TCP4ClientEndpoint, SSL4ClientEndpoint
  30. from .iweb import IResponse, UNKNOWN_LENGTH, IBodyProducer
  31. class PartialDownloadError(error.Error):
  32. """
  33. Page was only partially downloaded, we got disconnected in middle.
  34. @ivar response: All of the response body which was downloaded.
  35. """
  36. class _URL(tuple):
  37. """
  38. A parsed URL.
  39. At some point this should be replaced with a better URL implementation.
  40. """
  41. def __new__(self, scheme, host, port, path):
  42. return tuple.__new__(_URL, (scheme, host, port, path))
  43. def __init__(self, scheme, host, port, path):
  44. self.scheme = scheme
  45. self.host = host
  46. self.port = port
  47. self.path = path
  48. def _parse(url, defaultPort=None):
  49. """
  50. Split the given URL into the scheme, host, port, and path.
  51. @type url: C{bytes}
  52. @param url: An URL to parse.
  53. @type defaultPort: C{int} or C{None}
  54. @param defaultPort: An alternate value to use as the port if the URL does
  55. not include one.
  56. @return: A four-tuple of the scheme, host, port, and path of the URL. All
  57. of these are C{bytes} instances except for port, which is an C{int}.
  58. """
  59. url = url.strip()
  60. parsed = http.urlparse(url)
  61. scheme = parsed[0]
  62. path = urlunparse((b'', b'') + parsed[2:])
  63. if defaultPort is None:
  64. if scheme == b'https':
  65. defaultPort = 443
  66. else:
  67. defaultPort = 80
  68. host, port = parsed[1], defaultPort
  69. if b':' in host:
  70. host, port = host.split(b':')
  71. try:
  72. port = int(port)
  73. except ValueError:
  74. port = defaultPort
  75. if path == b'':
  76. path = b'/'
  77. return _URL(scheme, host, port, path)
  78. def _makeGetterFactory(url, factoryFactory, contextFactory=None,
  79. *args, **kwargs):
  80. """
  81. Create and connect an HTTP page getting factory.
  82. Any additional positional or keyword arguments are used when calling
  83. C{factoryFactory}.
  84. @param factoryFactory: Factory factory that is called with C{url}, C{args}
  85. and C{kwargs} to produce the getter
  86. @param contextFactory: Context factory to use when creating a secure
  87. connection, defaulting to C{None}
  88. @return: The factory created by C{factoryFactory}
  89. """
  90. scheme, host, port, path = _parse(url)
  91. factory = factoryFactory(url, *args, **kwargs)
  92. if scheme == b'https':
  93. from twisted.internet import ssl
  94. if contextFactory is None:
  95. contextFactory = ssl.ClientContextFactory()
  96. reactor.connectSSL(host, port, factory, contextFactory)
  97. else:
  98. reactor.connectTCP(host, port, factory)
  99. return factory
  100. # The code which follows is based on the new HTTP client implementation. It
  101. # should be significantly better than anything above, though it is not yet
  102. # feature equivalent.
  103. from twisted.web.error import SchemeNotSupported
  104. from ._newclient import Request, Response, HTTP11ClientProtocol
  105. from ._newclient import ResponseDone, ResponseFailed
  106. from ._newclient import RequestNotSent, RequestTransmissionFailed
  107. from ._newclient import (
  108. ResponseNeverReceived, PotentialDataLoss, _WrapperException)
  109. try:
  110. from twisted.internet.ssl import ClientContextFactory
  111. except ImportError:
  112. class WebClientContextFactory(object):
  113. """
  114. A web context factory which doesn't work because the necessary SSL
  115. support is missing.
  116. """
  117. def getContext(self, hostname, port):
  118. raise NotImplementedError("SSL support unavailable")
  119. else:
  120. class WebClientContextFactory(ClientContextFactory):
  121. """
  122. A web context factory which ignores the hostname and port and does no
  123. certificate verification.
  124. """
  125. def getContext(self, hostname, port):
  126. return ClientContextFactory.getContext(self)
  127. class _WebToNormalContextFactory(object):
  128. """
  129. Adapt a web context factory to a normal context factory.
  130. @ivar _webContext: A web context factory which accepts a hostname and port
  131. number to its C{getContext} method.
  132. @ivar _hostname: The hostname which will be passed to
  133. C{_webContext.getContext}.
  134. @ivar _port: The port number which will be passed to
  135. C{_webContext.getContext}.
  136. """
  137. def __init__(self, webContext, hostname, port):
  138. self._webContext = webContext
  139. self._hostname = hostname
  140. self._port = port
  141. def getContext(self):
  142. """
  143. Called the wrapped web context factory's C{getContext} method with a
  144. hostname and port number and return the resulting context object.
  145. """
  146. return self._webContext.getContext(self._hostname, self._port)
  147. @implementer(IBodyProducer)
  148. class FileBodyProducer(object):
  149. """
  150. L{FileBodyProducer} produces bytes from an input file object incrementally
  151. and writes them to a consumer.
  152. Since file-like objects cannot be read from in an event-driven manner,
  153. L{FileBodyProducer} uses a L{Cooperator} instance to schedule reads from
  154. the file. This process is also paused and resumed based on notifications
  155. from the L{IConsumer} provider being written to.
  156. The file is closed after it has been read, or if the producer is stopped
  157. early.
  158. @ivar _inputFile: Any file-like object, bytes read from which will be
  159. written to a consumer.
  160. @ivar _cooperate: A method like L{Cooperator.cooperate} which is used to
  161. schedule all reads.
  162. @ivar _readSize: The number of bytes to read from C{_inputFile} at a time.
  163. """
  164. # Python 2.4 doesn't have these symbolic constants
  165. _SEEK_SET = getattr(os, 'SEEK_SET', 0)
  166. _SEEK_END = getattr(os, 'SEEK_END', 2)
  167. def __init__(self, inputFile, cooperator=task, readSize=2 ** 16):
  168. self._inputFile = inputFile
  169. self._cooperate = cooperator.cooperate
  170. self._readSize = readSize
  171. self.length = self._determineLength(inputFile)
  172. def _determineLength(self, fObj):
  173. """
  174. Determine how many bytes can be read out of C{fObj} (assuming it is not
  175. modified from this point on). If the determination cannot be made,
  176. return C{UNKNOWN_LENGTH}.
  177. """
  178. try:
  179. seek = fObj.seek
  180. tell = fObj.tell
  181. except AttributeError:
  182. return UNKNOWN_LENGTH
  183. originalPosition = tell()
  184. seek(0, self._SEEK_END)
  185. end = tell()
  186. seek(originalPosition, self._SEEK_SET)
  187. return end - originalPosition
  188. def stopProducing(self):
  189. """
  190. Permanently stop writing bytes from the file to the consumer by
  191. stopping the underlying L{CooperativeTask}.
  192. """
  193. self._inputFile.close()
  194. self._task.stop()
  195. def startProducing(self, consumer):
  196. """
  197. Start a cooperative task which will read bytes from the input file and
  198. write them to C{consumer}. Return a L{Deferred} which fires after all
  199. bytes have been written.
  200. @param consumer: Any L{IConsumer} provider
  201. """
  202. self._task = self._cooperate(self._writeloop(consumer))
  203. d = self._task.whenDone()
  204. def maybeStopped(reason):
  205. # IBodyProducer.startProducing's Deferred isn't support to fire if
  206. # stopProducing is called.
  207. reason.trap(task.TaskStopped)
  208. return defer.Deferred()
  209. d.addCallbacks(lambda ignored: None, maybeStopped)
  210. return d
  211. def _writeloop(self, consumer):
  212. """
  213. Return an iterator which reads one chunk of bytes from the input file
  214. and writes them to the consumer for each time it is iterated.
  215. """
  216. while True:
  217. bytes = self._inputFile.read(self._readSize)
  218. if not bytes:
  219. self._inputFile.close()
  220. break
  221. consumer.write(bytes)
  222. yield None
  223. def pauseProducing(self):
  224. """
  225. Temporarily suspend copying bytes from the input file to the consumer
  226. by pausing the L{CooperativeTask} which drives that activity.
  227. """
  228. self._task.pause()
  229. def resumeProducing(self):
  230. """
  231. Undo the effects of a previous C{pauseProducing} and resume copying
  232. bytes to the consumer by resuming the L{CooperativeTask} which drives
  233. the write activity.
  234. """
  235. self._task.resume()
  236. class _HTTP11ClientFactory(protocol.Factory):
  237. """
  238. A factory for L{HTTP11ClientProtocol}, used by L{HTTPConnectionPool}.
  239. @ivar _quiescentCallback: The quiescent callback to be passed to protocol
  240. instances, used to return them to the connection pool.
  241. @since: 11.1
  242. """
  243. def __init__(self, quiescentCallback):
  244. self._quiescentCallback = quiescentCallback
  245. def buildProtocol(self, addr):
  246. return HTTP11ClientProtocol(self._quiescentCallback)
  247. class _RetryingHTTP11ClientProtocol(object):
  248. """
  249. A wrapper for L{HTTP11ClientProtocol} that automatically retries requests.
  250. @ivar _clientProtocol: The underlying L{HTTP11ClientProtocol}.
  251. @ivar _newConnection: A callable that creates a new connection for a
  252. retry.
  253. """
  254. def __init__(self, clientProtocol, newConnection):
  255. self._clientProtocol = clientProtocol
  256. self._newConnection = newConnection
  257. def _shouldRetry(self, method, exception, bodyProducer):
  258. """
  259. Indicate whether request should be retried.
  260. Only returns C{True} if method is idempotent, no response was
  261. received, the reason for the failed request was not due to
  262. user-requested cancellation, and no body was sent. The latter
  263. requirement may be relaxed in the future, and PUT added to approved
  264. method list.
  265. """
  266. if method not in ("GET", "HEAD", "OPTIONS", "DELETE", "TRACE"):
  267. return False
  268. if not isinstance(exception, (RequestNotSent, RequestTransmissionFailed,
  269. ResponseNeverReceived)):
  270. return False
  271. if isinstance(exception, _WrapperException):
  272. for failure in exception.reasons:
  273. if failure.check(defer.CancelledError):
  274. return False
  275. if bodyProducer is not None:
  276. return False
  277. return True
  278. def request(self, request):
  279. """
  280. Do a request, and retry once (with a new connection) it it fails in
  281. a retryable manner.
  282. @param request: A L{Request} instance that will be requested using the
  283. wrapped protocol.
  284. """
  285. d = self._clientProtocol.request(request)
  286. def failed(reason):
  287. if self._shouldRetry(request.method, reason.value,
  288. request.bodyProducer):
  289. return self._newConnection().addCallback(
  290. lambda connection: connection.request(request))
  291. else:
  292. return reason
  293. d.addErrback(failed)
  294. return d
  295. class HTTPConnectionPool(object):
  296. """
  297. A pool of persistent HTTP connections.
  298. Features:
  299. - Cached connections will eventually time out.
  300. - Limits on maximum number of persistent connections.
  301. Connections are stored using keys, which should be chosen such that any
  302. connections stored under a given key can be used interchangeably.
  303. Failed requests done using previously cached connections will be retried
  304. once if they use an idempotent method (e.g. GET), in case the HTTP server
  305. timed them out.
  306. @ivar persistent: Boolean indicating whether connections should be
  307. persistent. Connections are persistent by default.
  308. @ivar maxPersistentPerHost: The maximum number of cached persistent
  309. connections for a C{host:port} destination.
  310. @type maxPersistentPerHost: C{int}
  311. @ivar cachedConnectionTimeout: Number of seconds a cached persistent
  312. connection will stay open before disconnecting.
  313. @ivar retryAutomatically: C{boolean} indicating whether idempotent
  314. requests should be retried once if no response was received.
  315. @ivar _factory: The factory used to connect to the proxy.
  316. @ivar _connections: Map (scheme, host, port) to lists of
  317. L{HTTP11ClientProtocol} instances.
  318. @ivar _timeouts: Map L{HTTP11ClientProtocol} instances to a
  319. C{IDelayedCall} instance of their timeout.
  320. @since: 12.1
  321. """
  322. _factory = _HTTP11ClientFactory
  323. maxPersistentPerHost = 2
  324. cachedConnectionTimeout = 240
  325. retryAutomatically = True
  326. def __init__(self, reactor, persistent=True):
  327. self._reactor = reactor
  328. self.persistent = persistent
  329. self._connections = {}
  330. self._timeouts = {}
  331. def getConnection(self, key, endpoint):
  332. """
  333. Supply a connection, newly created or retrieved from the pool, to be
  334. used for one HTTP request.
  335. The connection will remain out of the pool (not available to be
  336. returned from future calls to this method) until one HTTP request has
  337. been completed over it.
  338. Afterwards, if the connection is still open, it will automatically be
  339. added to the pool.
  340. @param key: A unique key identifying connections that can be used
  341. interchangeably.
  342. @param endpoint: An endpoint that can be used to open a new connection
  343. if no cached connection is available.
  344. @return: A C{Deferred} that will fire with a L{HTTP11ClientProtocol}
  345. (or a wrapper) that can be used to send a single HTTP request.
  346. """
  347. # Try to get cached version:
  348. connections = self._connections.get(key)
  349. while connections:
  350. connection = connections.pop(0)
  351. # Cancel timeout:
  352. self._timeouts[connection].cancel()
  353. del self._timeouts[connection]
  354. if connection.state == "QUIESCENT":
  355. if self.retryAutomatically:
  356. newConnection = lambda: self._newConnection(key, endpoint)
  357. connection = _RetryingHTTP11ClientProtocol(
  358. connection, newConnection)
  359. return defer.succeed(connection)
  360. return self._newConnection(key, endpoint)
  361. def _newConnection(self, key, endpoint):
  362. """
  363. Create a new connection.
  364. This implements the new connection code path for L{getConnection}.
  365. """
  366. def quiescentCallback(protocol):
  367. self._putConnection(key, protocol)
  368. factory = self._factory(quiescentCallback)
  369. return endpoint.connect(factory)
  370. def _removeConnection(self, key, connection):
  371. """
  372. Remove a connection from the cache and disconnect it.
  373. """
  374. connection.transport.loseConnection()
  375. self._connections[key].remove(connection)
  376. del self._timeouts[connection]
  377. def _putConnection(self, key, connection):
  378. """
  379. Return a persistent connection to the pool. This will be called by
  380. L{HTTP11ClientProtocol} when the connection becomes quiescent.
  381. """
  382. if connection.state != "QUIESCENT":
  383. # Log with traceback for debugging purposes:
  384. try:
  385. raise RuntimeError(
  386. "BUG: Non-quiescent protocol added to connection pool.")
  387. except:
  388. log.err()
  389. return
  390. connections = self._connections.setdefault(key, [])
  391. if len(connections) == self.maxPersistentPerHost:
  392. dropped = connections.pop(0)
  393. dropped.transport.loseConnection()
  394. self._timeouts[dropped].cancel()
  395. del self._timeouts[dropped]
  396. connections.append(connection)
  397. cid = self._reactor.callLater(self.cachedConnectionTimeout,
  398. self._removeConnection,
  399. key, connection)
  400. self._timeouts[connection] = cid
  401. def closeCachedConnections(self):
  402. """
  403. Close all persistent connections and remove them from the pool.
  404. @return: L{defer.Deferred} that fires when all connections have been
  405. closed.
  406. """
  407. results = []
  408. for protocols in self._connections.itervalues():
  409. for p in protocols:
  410. results.append(p.abort())
  411. self._connections = {}
  412. for dc in self._timeouts.values():
  413. dc.cancel()
  414. self._timeouts = {}
  415. return defer.gatherResults(results).addCallback(lambda ign: None)
  416. class _AgentBase(object):
  417. """
  418. Base class offering common facilities for L{Agent}-type classes.
  419. @ivar _reactor: The C{IReactorTime} implementation which will be used by
  420. the pool, and perhaps by subclasses as well.
  421. @ivar _pool: The L{HTTPConnectionPool} used to manage HTTP connections.
  422. """
  423. def __init__(self, reactor, pool):
  424. if pool is None:
  425. pool = HTTPConnectionPool(reactor, False)
  426. self._reactor = reactor
  427. self._pool = pool
  428. def _computeHostValue(self, scheme, host, port):
  429. """
  430. Compute the string to use for the value of the I{Host} header, based on
  431. the given scheme, host name, and port number.
  432. """
  433. if (scheme, port) in (('http', 80), ('https', 443)):
  434. return host
  435. return '%s:%d' % (host, port)
  436. def _requestWithEndpoint(self, key, endpoint, method, parsedURI,
  437. headers, bodyProducer, requestPath):
  438. """
  439. Issue a new request, given the endpoint and the path sent as part of
  440. the request.
  441. """
  442. # Create minimal headers, if necessary:
  443. if headers is None:
  444. headers = Headers()
  445. if not headers.hasHeader('host'):
  446. #headers = headers.copy() # not supported in twisted <= 11.1, and it doesn't affects us
  447. headers.addRawHeader(
  448. 'host', self._computeHostValue(parsedURI.scheme, parsedURI.host,
  449. parsedURI.port))
  450. d = self._pool.getConnection(key, endpoint)
  451. def cbConnected(proto):
  452. return proto.request(
  453. Request(method, requestPath, headers, bodyProducer,
  454. persistent=self._pool.persistent))
  455. d.addCallback(cbConnected)
  456. return d
  457. class Agent(_AgentBase):
  458. """
  459. L{Agent} is a very basic HTTP client. It supports I{HTTP} and I{HTTPS}
  460. scheme URIs (but performs no certificate checking by default).
  461. @param pool: A L{HTTPConnectionPool} instance, or C{None}, in which case a
  462. non-persistent L{HTTPConnectionPool} instance will be created.
  463. @ivar _contextFactory: A web context factory which will be used to create
  464. SSL context objects for any SSL connections the agent needs to make.
  465. @ivar _connectTimeout: If not C{None}, the timeout passed to C{connectTCP}
  466. or C{connectSSL} for specifying the connection timeout.
  467. @ivar _bindAddress: If not C{None}, the address passed to C{connectTCP} or
  468. C{connectSSL} for specifying the local address to bind to.
  469. @since: 9.0
  470. """
  471. def __init__(self, reactor, contextFactory=WebClientContextFactory(),
  472. connectTimeout=None, bindAddress=None,
  473. pool=None):
  474. _AgentBase.__init__(self, reactor, pool)
  475. self._contextFactory = contextFactory
  476. self._connectTimeout = connectTimeout
  477. self._bindAddress = bindAddress
  478. def _wrapContextFactory(self, host, port):
  479. """
  480. Create and return a normal context factory wrapped around
  481. C{self._contextFactory} in such a way that C{self._contextFactory} will
  482. have the host and port information passed to it.
  483. @param host: A C{str} giving the hostname which will be connected to in
  484. order to issue a request.
  485. @param port: An C{int} giving the port number the connection will be
  486. on.
  487. @return: A context factory suitable to be passed to
  488. C{reactor.connectSSL}.
  489. """
  490. return _WebToNormalContextFactory(self._contextFactory, host, port)
  491. def _getEndpoint(self, scheme, host, port):
  492. """
  493. Get an endpoint for the given host and port, using a transport
  494. selected based on scheme.
  495. @param scheme: A string like C{'http'} or C{'https'} (the only two
  496. supported values) to use to determine how to establish the
  497. connection.
  498. @param host: A C{str} giving the hostname which will be connected to in
  499. order to issue a request.
  500. @param port: An C{int} giving the port number the connection will be
  501. on.
  502. @return: An endpoint which can be used to connect to given address.
  503. """
  504. kwargs = {}
  505. if self._connectTimeout is not None:
  506. kwargs['timeout'] = self._connectTimeout
  507. kwargs['bindAddress'] = self._bindAddress
  508. if scheme == 'http':
  509. return TCP4ClientEndpoint(self._reactor, host, port, **kwargs)
  510. elif scheme == 'https':
  511. return SSL4ClientEndpoint(self._reactor, host, port,
  512. self._wrapContextFactory(host, port),
  513. **kwargs)
  514. else:
  515. raise SchemeNotSupported("Unsupported scheme: %r" % (scheme,))
  516. def request(self, method, uri, headers=None, bodyProducer=None):
  517. """
  518. Issue a new request.
  519. @param method: The request method to send.
  520. @type method: C{str}
  521. @param uri: The request URI send.
  522. @type uri: C{str}
  523. @param headers: The request headers to send. If no I{Host} header is
  524. included, one will be added based on the request URI.
  525. @type headers: L{Headers}
  526. @param bodyProducer: An object which will produce the request body or,
  527. if the request body is to be empty, L{None}.
  528. @type bodyProducer: L{IBodyProducer} provider
  529. @return: A L{Deferred} which fires with the result of the request (a
  530. L{twisted.web.iweb.IResponse} provider), or fails if there is a
  531. problem setting up a connection over which to issue the request.
  532. It may also fail with L{SchemeNotSupported} if the scheme of the
  533. given URI is not supported.
  534. @rtype: L{Deferred}
  535. """
  536. parsedURI = _parse(uri)
  537. try:
  538. endpoint = self._getEndpoint(parsedURI.scheme, parsedURI.host,
  539. parsedURI.port)
  540. except SchemeNotSupported:
  541. return defer.fail(Failure())
  542. key = (parsedURI.scheme, parsedURI.host, parsedURI.port)
  543. return self._requestWithEndpoint(key, endpoint, method, parsedURI,
  544. headers, bodyProducer, parsedURI.path)
  545. class ProxyAgent(_AgentBase):
  546. """
  547. An HTTP agent able to cross HTTP proxies.
  548. @ivar _proxyEndpoint: The endpoint used to connect to the proxy.
  549. @since: 11.1
  550. """
  551. def __init__(self, endpoint, reactor=None, pool=None):
  552. if reactor is None:
  553. from twisted.internet import reactor
  554. _AgentBase.__init__(self, reactor, pool)
  555. self._proxyEndpoint = endpoint
  556. def request(self, method, uri, headers=None, bodyProducer=None):
  557. """
  558. Issue a new request via the configured proxy.
  559. """
  560. # Cache *all* connections under the same key, since we are only
  561. # connecting to a single destination, the proxy:
  562. key = ("http-proxy", self._proxyEndpoint)
  563. # To support proxying HTTPS via CONNECT, we will use key
  564. # ("http-proxy-CONNECT", scheme, host, port), and an endpoint that
  565. # wraps _proxyEndpoint with an additional callback to do the CONNECT.
  566. return self._requestWithEndpoint(key, self._proxyEndpoint, method,
  567. _parse(uri), headers, bodyProducer,
  568. uri)
  569. class _FakeUrllib2Request(object):
  570. """
  571. A fake C{urllib2.Request} object for C{cookielib} to work with.
  572. @see: U{http://docs.python.org/library/urllib2.html#request-objects}
  573. @type uri: C{str}
  574. @ivar uri: Request URI.
  575. @type headers: L{twisted.web.http_headers.Headers}
  576. @ivar headers: Request headers.
  577. @type type: C{str}
  578. @ivar type: The scheme of the URI.
  579. @type host: C{str}
  580. @ivar host: The host[:port] of the URI.
  581. @since: 11.1
  582. """
  583. def __init__(self, uri):
  584. self.uri = uri
  585. self.headers = Headers()
  586. self.type, rest = splittype(self.uri)
  587. self.host, rest = splithost(rest)
  588. def has_header(self, header):
  589. return self.headers.hasHeader(header)
  590. def add_unredirected_header(self, name, value):
  591. self.headers.addRawHeader(name, value)
  592. def get_full_url(self):
  593. return self.uri
  594. def get_header(self, name, default=None):
  595. headers = self.headers.getRawHeaders(name, default)
  596. if headers is not None:
  597. return headers[0]
  598. return None
  599. def get_host(self):
  600. return self.host
  601. def get_type(self):
  602. return self.type
  603. def is_unverifiable(self):
  604. # In theory this shouldn't be hardcoded.
  605. return False
  606. class _FakeUrllib2Response(object):
  607. """
  608. A fake C{urllib2.Response} object for C{cookielib} to work with.
  609. @type response: C{twisted.web.iweb.IResponse}
  610. @ivar response: Underlying Twisted Web response.
  611. @since: 11.1
  612. """
  613. def __init__(self, response):
  614. self.response = response
  615. def info(self):
  616. class _Meta(object):
  617. def getheaders(zelf, name):
  618. return self.response.headers.getRawHeaders(name, [])
  619. return _Meta()
  620. class CookieAgent(object):
  621. """
  622. L{CookieAgent} extends the basic L{Agent} to add RFC-compliant
  623. handling of HTTP cookies. Cookies are written to and extracted
  624. from a C{cookielib.CookieJar} instance.
  625. The same cookie jar instance will be used for any requests through this
  626. agent, mutating it whenever a I{Set-Cookie} header appears in a response.
  627. @type _agent: L{twisted.web.client.Agent}
  628. @ivar _agent: Underlying Twisted Web agent to issue requests through.
  629. @type cookieJar: C{cookielib.CookieJar}
  630. @ivar cookieJar: Initialized cookie jar to read cookies from and store
  631. cookies to.
  632. @since: 11.1
  633. """
  634. def __init__(self, agent, cookieJar):
  635. self._agent = agent
  636. self.cookieJar = cookieJar
  637. def request(self, method, uri, headers=None, bodyProducer=None):
  638. """
  639. Issue a new request to the wrapped L{Agent}.
  640. Send a I{Cookie} header if a cookie for C{uri} is stored in
  641. L{CookieAgent.cookieJar}. Cookies are automatically extracted and
  642. stored from requests.
  643. If a C{'cookie'} header appears in C{headers} it will override the
  644. automatic cookie header obtained from the cookie jar.
  645. @see: L{Agent.request}
  646. """
  647. if headers is None:
  648. headers = Headers()
  649. lastRequest = _FakeUrllib2Request(uri)
  650. # Setting a cookie header explicitly will disable automatic request
  651. # cookies.
  652. if not headers.hasHeader('cookie'):
  653. self.cookieJar.add_cookie_header(lastRequest)
  654. cookieHeader = lastRequest.get_header('Cookie', None)
  655. if cookieHeader is not None:
  656. headers = headers.copy()
  657. headers.addRawHeader('cookie', cookieHeader)
  658. d = self._agent.request(method, uri, headers, bodyProducer)
  659. d.addCallback(self._extractCookies, lastRequest)
  660. return d
  661. def _extractCookies(self, response, request):
  662. """
  663. Extract response cookies and store them in the cookie jar.
  664. @type response: L{twisted.web.iweb.IResponse}
  665. @param response: Twisted Web response.
  666. @param request: A urllib2 compatible request object.
  667. """
  668. resp = _FakeUrllib2Response(response)
  669. self.cookieJar.extract_cookies(resp, request)
  670. return response
  671. class GzipDecoder(proxyForInterface(IResponse)):
  672. """
  673. A wrapper for a L{Response} instance which handles gzip'ed body.
  674. @ivar original: The original L{Response} object.
  675. @since: 11.1
  676. """
  677. def __init__(self, response):
  678. self.original = response
  679. self.length = UNKNOWN_LENGTH
  680. def deliverBody(self, protocol):
  681. """
  682. Override C{deliverBody} to wrap the given C{protocol} with
  683. L{_GzipProtocol}.
  684. """
  685. self.original.deliverBody(_GzipProtocol(protocol, self.original))
  686. class _GzipProtocol(proxyForInterface(IProtocol)):
  687. """
  688. A L{Protocol} implementation which wraps another one, transparently
  689. decompressing received data.
  690. @ivar _zlibDecompress: A zlib decompress object used to decompress the data
  691. stream.
  692. @ivar _response: A reference to the original response, in case of errors.
  693. @since: 11.1
  694. """
  695. def __init__(self, protocol, response):
  696. self.original = protocol
  697. self._response = response
  698. self._zlibDecompress = zlib.decompressobj(16 + zlib.MAX_WBITS)
  699. def dataReceived(self, data):
  700. """
  701. Decompress C{data} with the zlib decompressor, forwarding the raw data
  702. to the original protocol.
  703. """
  704. try:
  705. rawData = self._zlibDecompress.decompress(data)
  706. except zlib.error:
  707. raise ResponseFailed([failure.Failure()], self._response)
  708. if rawData:
  709. self.original.dataReceived(rawData)
  710. def connectionLost(self, reason):
  711. """
  712. Forward the connection lost event, flushing remaining data from the
  713. decompressor if any.
  714. """
  715. try:
  716. rawData = self._zlibDecompress.flush()
  717. except zlib.error:
  718. raise ResponseFailed([reason, failure.Failure()], self._response)
  719. if rawData:
  720. self.original.dataReceived(rawData)
  721. self.original.connectionLost(reason)
  722. class ContentDecoderAgent(object):
  723. """
  724. An L{Agent} wrapper to handle encoded content.
  725. It takes care of declaring the support for content in the
  726. I{Accept-Encoding} header, and automatically decompresses the received data
  727. if it's effectively using compression.
  728. @param decoders: A list or tuple of (name, decoder) objects. The name
  729. declares which decoding the decoder supports, and the decoder must
  730. return a response object when called/instantiated. For example,
  731. C{(('gzip', GzipDecoder))}. The order determines how the decoders are
  732. going to be advertized to the server.
  733. @since: 11.1
  734. """
  735. def __init__(self, agent, decoders):
  736. self._agent = agent
  737. self._decoders = dict(decoders)
  738. self._supported = ','.join([decoder[0] for decoder in decoders])
  739. def request(self, method, uri, headers=None, bodyProducer=None):
  740. """
  741. Send a client request which declares supporting compressed content.
  742. @see: L{Agent.request}.
  743. """
  744. if headers is None:
  745. headers = Headers()
  746. else:
  747. headers = headers.copy()
  748. headers.addRawHeader('accept-encoding', self._supported)
  749. deferred = self._agent.request(method, uri, headers, bodyProducer)
  750. return deferred.addCallback(self._handleResponse)
  751. def _handleResponse(self, response):
  752. """
  753. Check if the response is encoded, and wrap it to handle decompression.
  754. """
  755. contentEncodingHeaders = response.headers.getRawHeaders(
  756. 'content-encoding', [])
  757. contentEncodingHeaders = ','.join(contentEncodingHeaders).split(',')
  758. while contentEncodingHeaders:
  759. name = contentEncodingHeaders.pop().strip()
  760. decoder = self._decoders.get(name)
  761. if decoder is not None:
  762. response = decoder(response)
  763. else:
  764. # Add it back
  765. contentEncodingHeaders.append(name)
  766. break
  767. if contentEncodingHeaders:
  768. response.headers.setRawHeaders(
  769. 'content-encoding', [','.join(contentEncodingHeaders)])
  770. else:
  771. response.headers.removeHeader('content-encoding')
  772. return response
  773. class RedirectAgent(object):
  774. """
  775. An L{Agent} wrapper which handles HTTP redirects.
  776. The implementation is rather strict: 301 and 302 behaves like 307, not
  777. redirecting automatically on methods different from C{GET} and C{HEAD}.
  778. @param redirectLimit: The maximum number of times the agent is allowed to
  779. follow redirects before failing with a L{error.InfiniteRedirection}.
  780. @since: 11.1
  781. """
  782. def __init__(self, agent, redirectLimit=20):
  783. self._agent = agent
  784. self._redirectLimit = redirectLimit
  785. def request(self, method, uri, headers=None, bodyProducer=None):
  786. """
  787. Send a client request following HTTP redirects.
  788. @see: L{Agent.request}.
  789. """
  790. deferred = self._agent.request(method, uri, headers, bodyProducer)
  791. return deferred.addCallback(
  792. self._handleResponse, method, uri, headers, 0)
  793. def _handleRedirect(self, response, method, uri, headers, redirectCount):
  794. """
  795. Handle a redirect response, checking the number of redirects already
  796. followed, and extracting the location header fields.
  797. """
  798. if redirectCount >= self._redirectLimit:
  799. err = error.InfiniteRedirection(
  800. response.code,
  801. 'Infinite redirection detected',
  802. location=uri)
  803. raise ResponseFailed([failure.Failure(err)], response)
  804. locationHeaders = response.headers.getRawHeaders('location', [])
  805. if not locationHeaders:
  806. err = error.RedirectWithNoLocation(
  807. response.code, 'No location header field', uri)
  808. raise ResponseFailed([failure.Failure(err)], response)
  809. location = locationHeaders[0]
  810. deferred = self._agent.request(method, location, headers)
  811. return deferred.addCallback(
  812. self._handleResponse, method, uri, headers, redirectCount + 1)
  813. def _handleResponse(self, response, method, uri, headers, redirectCount):
  814. """
  815. Handle the response, making another request if it indicates a redirect.
  816. """
  817. if response.code in (http.MOVED_PERMANENTLY, http.FOUND,
  818. http.TEMPORARY_REDIRECT):
  819. if method not in ('GET', 'HEAD'):
  820. err = error.PageRedirect(response.code, location=uri)
  821. raise ResponseFailed([failure.Failure(err)], response)
  822. return self._handleRedirect(response, method, uri, headers,
  823. redirectCount)
  824. elif response.code == http.SEE_OTHER:
  825. return self._handleRedirect(response, 'GET', uri, headers,
  826. redirectCount)
  827. return response
  828. class _ReadBodyProtocol(protocol.Protocol):
  829. """
  830. Protocol that collects data sent to it.
  831. This is a helper for L{IResponse.deliverBody}, which collects the body and
  832. fires a deferred with it.
  833. @ivar deferred: See L{__init__}.
  834. @ivar status: See L{__init__}.
  835. @ivar message: See L{__init__}.
  836. @ivar dataBuffer: list of byte-strings received
  837. @type dataBuffer: L{list} of L{bytes}
  838. """
  839. def __init__(self, status, message, deferred):
  840. """
  841. @param status: Status of L{IResponse}
  842. @ivar status: L{int}
  843. @param message: Message of L{IResponse}
  844. @type message: L{bytes}
  845. @param deferred: deferred to fire when response is complete
  846. @type deferred: L{Deferred} firing with L{bytes}
  847. """
  848. self.deferred = deferred
  849. self.status = status
  850. self.message = message
  851. self.dataBuffer = []
  852. def dataReceived(self, data):
  853. """
  854. Accumulate some more bytes from the response.
  855. """
  856. self.dataBuffer.append(data)
  857. def connectionLost(self, reason):
  858. """
  859. Deliver the accumulated response bytes to the waiting L{Deferred}, if
  860. the response body has been completely received without error.
  861. """
  862. if reason.check(ResponseDone):
  863. self.deferred.callback(b''.join(self.dataBuffer))
  864. elif reason.check(PotentialDataLoss):
  865. self.deferred.errback(
  866. PartialDownloadError(self.status, self.message,
  867. b''.join(self.dataBuffer)))
  868. else:
  869. self.deferred.errback(reason)
  870. def readBody(response):
  871. """
  872. Get the body of an L{IResponse} and return it as a byte string.
  873. This is a helper function for clients that don't want to incrementally
  874. receive the body of an HTTP response.
  875. @param response: The HTTP response for which the body will be read.
  876. @type response: L{IResponse} provider
  877. @return: A L{Deferred} which will fire with the body of the response.
  878. """
  879. d = defer.Deferred()
  880. response.deliverBody(_ReadBodyProtocol(response.code, response.phrase, d))
  881. return d
  882. __all__ = [
  883. 'PartialDownloadError', 'HTTPPageGetter', 'HTTPPageDownloader',
  884. 'HTTPClientFactory', 'HTTPDownloader', 'getPage', 'downloadPage',
  885. 'ResponseDone', 'Response', 'ResponseFailed', 'Agent', 'CookieAgent',
  886. 'ProxyAgent', 'ContentDecoderAgent', 'GzipDecoder', 'RedirectAgent',
  887. 'HTTPConnectionPool', 'readBody']