Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

336 linhas
9.7 KiB

  1. from __future__ import annotations
  2. import socket
  3. import typing
  4. import warnings
  5. from email.errors import MessageDefect
  6. from http.client import IncompleteRead as httplib_IncompleteRead
  7. if typing.TYPE_CHECKING:
  8. from .connection import HTTPConnection
  9. from .connectionpool import ConnectionPool
  10. from .response import HTTPResponse
  11. from .util.retry import Retry
  12. # Base Exceptions
  13. class HTTPError(Exception):
  14. """Base exception used by this module."""
  15. class HTTPWarning(Warning):
  16. """Base warning used by this module."""
  17. _TYPE_REDUCE_RESULT = tuple[typing.Callable[..., object], tuple[object, ...]]
  18. class PoolError(HTTPError):
  19. """Base exception for errors caused within a pool."""
  20. def __init__(self, pool: ConnectionPool, message: str) -> None:
  21. self.pool = pool
  22. self._message = message
  23. super().__init__(f"{pool}: {message}")
  24. def __reduce__(self) -> _TYPE_REDUCE_RESULT:
  25. # For pickling purposes.
  26. return self.__class__, (None, self._message)
  27. class RequestError(PoolError):
  28. """Base exception for PoolErrors that have associated URLs."""
  29. def __init__(self, pool: ConnectionPool, url: str, message: str) -> None:
  30. self.url = url
  31. super().__init__(pool, message)
  32. def __reduce__(self) -> _TYPE_REDUCE_RESULT:
  33. # For pickling purposes.
  34. return self.__class__, (None, self.url, self._message)
  35. class SSLError(HTTPError):
  36. """Raised when SSL certificate fails in an HTTPS connection."""
  37. class ProxyError(HTTPError):
  38. """Raised when the connection to a proxy fails."""
  39. # The original error is also available as __cause__.
  40. original_error: Exception
  41. def __init__(self, message: str, error: Exception) -> None:
  42. super().__init__(message, error)
  43. self.original_error = error
  44. class DecodeError(HTTPError):
  45. """Raised when automatic decoding based on Content-Type fails."""
  46. class ProtocolError(HTTPError):
  47. """Raised when something unexpected happens mid-request/response."""
  48. #: Renamed to ProtocolError but aliased for backwards compatibility.
  49. ConnectionError = ProtocolError
  50. # Leaf Exceptions
  51. class MaxRetryError(RequestError):
  52. """Raised when the maximum number of retries is exceeded.
  53. :param pool: The connection pool
  54. :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`
  55. :param str url: The requested Url
  56. :param reason: The underlying error
  57. :type reason: :class:`Exception`
  58. """
  59. def __init__(
  60. self, pool: ConnectionPool, url: str, reason: Exception | None = None
  61. ) -> None:
  62. self.reason = reason
  63. message = f"Max retries exceeded with url: {url} (Caused by {reason!r})"
  64. super().__init__(pool, url, message)
  65. def __reduce__(self) -> _TYPE_REDUCE_RESULT:
  66. # For pickling purposes.
  67. return self.__class__, (None, self.url, self.reason)
  68. class HostChangedError(RequestError):
  69. """Raised when an existing pool gets a request for a foreign host."""
  70. def __init__(
  71. self, pool: ConnectionPool, url: str, retries: Retry | int = 3
  72. ) -> None:
  73. message = f"Tried to open a foreign host with url: {url}"
  74. super().__init__(pool, url, message)
  75. self.retries = retries
  76. class TimeoutStateError(HTTPError):
  77. """Raised when passing an invalid state to a timeout"""
  78. class TimeoutError(HTTPError):
  79. """Raised when a socket timeout error occurs.
  80. Catching this error will catch both :exc:`ReadTimeoutErrors
  81. <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.
  82. """
  83. class ReadTimeoutError(TimeoutError, RequestError):
  84. """Raised when a socket timeout occurs while receiving data from a server"""
  85. # This timeout error does not have a URL attached and needs to inherit from the
  86. # base HTTPError
  87. class ConnectTimeoutError(TimeoutError):
  88. """Raised when a socket timeout occurs while connecting to a server"""
  89. class NewConnectionError(ConnectTimeoutError, HTTPError):
  90. """Raised when we fail to establish a new connection. Usually ECONNREFUSED."""
  91. def __init__(self, conn: HTTPConnection, message: str) -> None:
  92. self.conn = conn
  93. self._message = message
  94. super().__init__(f"{conn}: {message}")
  95. def __reduce__(self) -> _TYPE_REDUCE_RESULT:
  96. # For pickling purposes.
  97. return self.__class__, (None, self._message)
  98. @property
  99. def pool(self) -> HTTPConnection:
  100. warnings.warn(
  101. "The 'pool' property is deprecated and will be removed "
  102. "in urllib3 v2.1.0. Use 'conn' instead.",
  103. DeprecationWarning,
  104. stacklevel=2,
  105. )
  106. return self.conn
  107. class NameResolutionError(NewConnectionError):
  108. """Raised when host name resolution fails."""
  109. def __init__(self, host: str, conn: HTTPConnection, reason: socket.gaierror):
  110. message = f"Failed to resolve '{host}' ({reason})"
  111. self._host = host
  112. self._reason = reason
  113. super().__init__(conn, message)
  114. def __reduce__(self) -> _TYPE_REDUCE_RESULT:
  115. # For pickling purposes.
  116. return self.__class__, (self._host, None, self._reason)
  117. class EmptyPoolError(PoolError):
  118. """Raised when a pool runs out of connections and no more are allowed."""
  119. class FullPoolError(PoolError):
  120. """Raised when we try to add a connection to a full pool in blocking mode."""
  121. class ClosedPoolError(PoolError):
  122. """Raised when a request enters a pool after the pool has been closed."""
  123. class LocationValueError(ValueError, HTTPError):
  124. """Raised when there is something wrong with a given URL input."""
  125. class LocationParseError(LocationValueError):
  126. """Raised when get_host or similar fails to parse the URL input."""
  127. def __init__(self, location: str) -> None:
  128. message = f"Failed to parse: {location}"
  129. super().__init__(message)
  130. self.location = location
  131. class URLSchemeUnknown(LocationValueError):
  132. """Raised when a URL input has an unsupported scheme."""
  133. def __init__(self, scheme: str):
  134. message = f"Not supported URL scheme {scheme}"
  135. super().__init__(message)
  136. self.scheme = scheme
  137. class ResponseError(HTTPError):
  138. """Used as a container for an error reason supplied in a MaxRetryError."""
  139. GENERIC_ERROR = "too many error responses"
  140. SPECIFIC_ERROR = "too many {status_code} error responses"
  141. class SecurityWarning(HTTPWarning):
  142. """Warned when performing security reducing actions"""
  143. class InsecureRequestWarning(SecurityWarning):
  144. """Warned when making an unverified HTTPS request."""
  145. class NotOpenSSLWarning(SecurityWarning):
  146. """Warned when using unsupported SSL library"""
  147. class SystemTimeWarning(SecurityWarning):
  148. """Warned when system time is suspected to be wrong"""
  149. class InsecurePlatformWarning(SecurityWarning):
  150. """Warned when certain TLS/SSL configuration is not available on a platform."""
  151. class DependencyWarning(HTTPWarning):
  152. """
  153. Warned when an attempt is made to import a module with missing optional
  154. dependencies.
  155. """
  156. class ResponseNotChunked(ProtocolError, ValueError):
  157. """Response needs to be chunked in order to read it as chunks."""
  158. class BodyNotHttplibCompatible(HTTPError):
  159. """
  160. Body should be :class:`http.client.HTTPResponse` like
  161. (have an fp attribute which returns raw chunks) for read_chunked().
  162. """
  163. class IncompleteRead(HTTPError, httplib_IncompleteRead):
  164. """
  165. Response length doesn't match expected Content-Length
  166. Subclass of :class:`http.client.IncompleteRead` to allow int value
  167. for ``partial`` to avoid creating large objects on streamed reads.
  168. """
  169. partial: int # type: ignore[assignment]
  170. expected: int
  171. def __init__(self, partial: int, expected: int) -> None:
  172. self.partial = partial
  173. self.expected = expected
  174. def __repr__(self) -> str:
  175. return "IncompleteRead(%i bytes read, %i more expected)" % (
  176. self.partial,
  177. self.expected,
  178. )
  179. class InvalidChunkLength(HTTPError, httplib_IncompleteRead):
  180. """Invalid chunk length in a chunked response."""
  181. def __init__(self, response: HTTPResponse, length: bytes) -> None:
  182. self.partial: int = response.tell() # type: ignore[assignment]
  183. self.expected: int | None = response.length_remaining
  184. self.response = response
  185. self.length = length
  186. def __repr__(self) -> str:
  187. return "InvalidChunkLength(got length %r, %i bytes read)" % (
  188. self.length,
  189. self.partial,
  190. )
  191. class InvalidHeader(HTTPError):
  192. """The header provided was somehow invalid."""
  193. class ProxySchemeUnknown(AssertionError, URLSchemeUnknown):
  194. """ProxyManager does not support the supplied scheme"""
  195. # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.
  196. def __init__(self, scheme: str | None) -> None:
  197. # 'localhost' is here because our URL parser parses
  198. # localhost:8080 -> scheme=localhost, remove if we fix this.
  199. if scheme == "localhost":
  200. scheme = None
  201. if scheme is None:
  202. message = "Proxy URL had no scheme, should start with http:// or https://"
  203. else:
  204. message = f"Proxy URL had unsupported scheme {scheme}, should use http:// or https://"
  205. super().__init__(message)
  206. class ProxySchemeUnsupported(ValueError):
  207. """Fetching HTTPS resources through HTTPS proxies is unsupported"""
  208. class HeaderParsingError(HTTPError):
  209. """Raised by assert_header_parsing, but we convert it to a log.warning statement."""
  210. def __init__(
  211. self, defects: list[MessageDefect], unparsed_data: bytes | str | None
  212. ) -> None:
  213. message = f"{defects or 'Unknown'}, unparsed data: {unparsed_data!r}"
  214. super().__init__(message)
  215. class UnrewindableBodyError(HTTPError):
  216. """urllib3 encountered an error when trying to rewind a body"""