common.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. from __future__ import annotations
  2. import abc
  3. import copy
  4. import enum
  5. import functools
  6. import io
  7. import typing
  8. import urllib.parse
  9. import urllib.request
  10. import urllib.response
  11. from collections.abc import Iterable, Mapping
  12. from email.message import Message
  13. from http import HTTPStatus
  14. from ._helper import make_ssl_context, wrap_request_errors
  15. from .exceptions import (
  16. NoSupportingHandlers,
  17. RequestError,
  18. TransportError,
  19. UnsupportedRequest,
  20. )
  21. from ..compat.types import NoneType
  22. from ..cookies import YoutubeDLCookieJar
  23. from ..utils import (
  24. bug_reports_message,
  25. classproperty,
  26. deprecation_warning,
  27. error_to_str,
  28. update_url_query,
  29. )
  30. from ..utils.networking import HTTPHeaderDict, normalize_url
  31. def register_preference(*handlers: type[RequestHandler]):
  32. assert all(issubclass(handler, RequestHandler) for handler in handlers)
  33. def outer(preference: Preference):
  34. @functools.wraps(preference)
  35. def inner(handler, *args, **kwargs):
  36. if not handlers or isinstance(handler, handlers):
  37. return preference(handler, *args, **kwargs)
  38. return 0
  39. _RH_PREFERENCES.add(inner)
  40. return inner
  41. return outer
  42. class RequestDirector:
  43. """RequestDirector class
  44. Helper class that, when given a request, forward it to a RequestHandler that supports it.
  45. Preference functions in the form of func(handler, request) -> int
  46. can be registered into the `preferences` set. These are used to sort handlers
  47. in order of preference.
  48. @param logger: Logger instance.
  49. @param verbose: Print debug request information to stdout.
  50. """
  51. def __init__(self, logger, verbose=False):
  52. self.handlers: dict[str, RequestHandler] = {}
  53. self.preferences: set[Preference] = set()
  54. self.logger = logger # TODO(Grub4k): default logger
  55. self.verbose = verbose
  56. def close(self):
  57. for handler in self.handlers.values():
  58. handler.close()
  59. def add_handler(self, handler: RequestHandler):
  60. """Add a handler. If a handler of the same RH_KEY exists, it will overwrite it"""
  61. assert isinstance(handler, RequestHandler), 'handler must be a RequestHandler'
  62. self.handlers[handler.RH_KEY] = handler
  63. def _get_handlers(self, request: Request) -> list[RequestHandler]:
  64. """Sorts handlers by preference, given a request"""
  65. preferences = {
  66. rh: sum(pref(rh, request) for pref in self.preferences)
  67. for rh in self.handlers.values()
  68. }
  69. self._print_verbose('Handler preferences for this request: %s' % ', '.join(
  70. f'{rh.RH_NAME}={pref}' for rh, pref in preferences.items()))
  71. return sorted(self.handlers.values(), key=preferences.get, reverse=True)
  72. def _print_verbose(self, msg):
  73. if self.verbose:
  74. self.logger.stdout(f'director: {msg}')
  75. def send(self, request: Request) -> Response:
  76. """
  77. Passes a request onto a suitable RequestHandler
  78. """
  79. if not self.handlers:
  80. raise RequestError('No request handlers configured')
  81. assert isinstance(request, Request)
  82. unexpected_errors = []
  83. unsupported_errors = []
  84. for handler in self._get_handlers(request):
  85. self._print_verbose(f'Checking if "{handler.RH_NAME}" supports this request.')
  86. try:
  87. handler.validate(request)
  88. except UnsupportedRequest as e:
  89. self._print_verbose(
  90. f'"{handler.RH_NAME}" cannot handle this request (reason: {error_to_str(e)})')
  91. unsupported_errors.append(e)
  92. continue
  93. self._print_verbose(f'Sending request via "{handler.RH_NAME}"')
  94. try:
  95. response = handler.send(request)
  96. except RequestError:
  97. raise
  98. except Exception as e:
  99. self.logger.error(
  100. f'[{handler.RH_NAME}] Unexpected error: {error_to_str(e)}{bug_reports_message()}',
  101. is_error=False)
  102. unexpected_errors.append(e)
  103. continue
  104. assert isinstance(response, Response)
  105. return response
  106. raise NoSupportingHandlers(unsupported_errors, unexpected_errors)
  107. _REQUEST_HANDLERS = {}
  108. def register_rh(handler):
  109. """Register a RequestHandler class"""
  110. assert issubclass(handler, RequestHandler), f'{handler} must be a subclass of RequestHandler'
  111. assert handler.RH_KEY not in _REQUEST_HANDLERS, f'RequestHandler {handler.RH_KEY} already registered'
  112. _REQUEST_HANDLERS[handler.RH_KEY] = handler
  113. return handler
  114. class Features(enum.Enum):
  115. ALL_PROXY = enum.auto()
  116. NO_PROXY = enum.auto()
  117. class RequestHandler(abc.ABC):
  118. """Request Handler class
  119. Request handlers are class that, given a Request,
  120. process the request from start to finish and return a Response.
  121. Concrete subclasses need to redefine the _send(request) method,
  122. which handles the underlying request logic and returns a Response.
  123. RH_NAME class variable may contain a display name for the RequestHandler.
  124. By default, this is generated from the class name.
  125. The concrete request handler MUST have "RH" as the suffix in the class name.
  126. All exceptions raised by a RequestHandler should be an instance of RequestError.
  127. Any other exception raised will be treated as a handler issue.
  128. If a Request is not supported by the handler, an UnsupportedRequest
  129. should be raised with a reason.
  130. By default, some checks are done on the request in _validate() based on the following class variables:
  131. - `_SUPPORTED_URL_SCHEMES`: a tuple of supported url schemes.
  132. Any Request with an url scheme not in this list will raise an UnsupportedRequest.
  133. - `_SUPPORTED_PROXY_SCHEMES`: a tuple of support proxy url schemes. Any Request that contains
  134. a proxy url with an url scheme not in this list will raise an UnsupportedRequest.
  135. - `_SUPPORTED_FEATURES`: a tuple of supported features, as defined in Features enum.
  136. The above may be set to None to disable the checks.
  137. Parameters:
  138. @param logger: logger instance
  139. @param headers: HTTP Headers to include when sending requests.
  140. @param cookiejar: Cookiejar to use for requests.
  141. @param timeout: Socket timeout to use when sending requests.
  142. @param proxies: Proxies to use for sending requests.
  143. @param source_address: Client-side IP address to bind to for requests.
  144. @param verbose: Print debug request and traffic information to stdout.
  145. @param prefer_system_certs: Whether to prefer system certificates over other means (e.g. certifi).
  146. @param client_cert: SSL client certificate configuration.
  147. dict with {client_certificate, client_certificate_key, client_certificate_password}
  148. @param verify: Verify SSL certificates
  149. @param legacy_ssl_support: Enable legacy SSL options such as legacy server connect and older cipher support.
  150. Some configuration options may be available for individual Requests too. In this case,
  151. either the Request configuration option takes precedence or they are merged.
  152. Requests may have additional optional parameters defined as extensions.
  153. RequestHandler subclasses may choose to support custom extensions.
  154. If an extension is supported, subclasses should extend _check_extensions(extensions)
  155. to pop and validate the extension.
  156. - Extensions left in `extensions` are treated as unsupported and UnsupportedRequest will be raised.
  157. The following extensions are defined for RequestHandler:
  158. - `cookiejar`: Cookiejar to use for this request.
  159. - `timeout`: socket timeout to use for this request.
  160. To enable these, add extensions.pop('<extension>', None) to _check_extensions
  161. Apart from the url protocol, proxies dict may contain the following keys:
  162. - `all`: proxy to use for all protocols. Used as a fallback if no proxy is set for a specific protocol.
  163. - `no`: comma seperated list of hostnames (optionally with port) to not use a proxy for.
  164. Note: a RequestHandler may not support these, as defined in `_SUPPORTED_FEATURES`.
  165. """
  166. _SUPPORTED_URL_SCHEMES = ()
  167. _SUPPORTED_PROXY_SCHEMES = ()
  168. _SUPPORTED_FEATURES = ()
  169. def __init__(
  170. self, *,
  171. logger, # TODO(Grub4k): default logger
  172. headers: HTTPHeaderDict = None,
  173. cookiejar: YoutubeDLCookieJar = None,
  174. timeout: float | int | None = None,
  175. proxies: dict = None,
  176. source_address: str = None,
  177. verbose: bool = False,
  178. prefer_system_certs: bool = False,
  179. client_cert: dict[str, str | None] = None,
  180. verify: bool = True,
  181. legacy_ssl_support: bool = False,
  182. **_,
  183. ):
  184. self._logger = logger
  185. self.headers = headers or {}
  186. self.cookiejar = cookiejar if cookiejar is not None else YoutubeDLCookieJar()
  187. self.timeout = float(timeout or 20)
  188. self.proxies = proxies or {}
  189. self.source_address = source_address
  190. self.verbose = verbose
  191. self.prefer_system_certs = prefer_system_certs
  192. self._client_cert = client_cert or {}
  193. self.verify = verify
  194. self.legacy_ssl_support = legacy_ssl_support
  195. super().__init__()
  196. def _make_sslcontext(self):
  197. return make_ssl_context(
  198. verify=self.verify,
  199. legacy_support=self.legacy_ssl_support,
  200. use_certifi=not self.prefer_system_certs,
  201. **self._client_cert,
  202. )
  203. def _merge_headers(self, request_headers):
  204. return HTTPHeaderDict(self.headers, request_headers)
  205. def _check_url_scheme(self, request: Request):
  206. scheme = urllib.parse.urlparse(request.url).scheme.lower()
  207. if self._SUPPORTED_URL_SCHEMES is not None and scheme not in self._SUPPORTED_URL_SCHEMES:
  208. raise UnsupportedRequest(f'Unsupported url scheme: "{scheme}"')
  209. return scheme # for further processing
  210. def _check_proxies(self, proxies):
  211. for proxy_key, proxy_url in proxies.items():
  212. if proxy_url is None:
  213. continue
  214. if proxy_key == 'no':
  215. if self._SUPPORTED_FEATURES is not None and Features.NO_PROXY not in self._SUPPORTED_FEATURES:
  216. raise UnsupportedRequest('"no" proxy is not supported')
  217. continue
  218. if (
  219. proxy_key == 'all'
  220. and self._SUPPORTED_FEATURES is not None
  221. and Features.ALL_PROXY not in self._SUPPORTED_FEATURES
  222. ):
  223. raise UnsupportedRequest('"all" proxy is not supported')
  224. # Unlikely this handler will use this proxy, so ignore.
  225. # This is to allow a case where a proxy may be set for a protocol
  226. # for one handler in which such protocol (and proxy) is not supported by another handler.
  227. if self._SUPPORTED_URL_SCHEMES is not None and proxy_key not in (*self._SUPPORTED_URL_SCHEMES, 'all'):
  228. continue
  229. if self._SUPPORTED_PROXY_SCHEMES is None:
  230. # Skip proxy scheme checks
  231. continue
  232. try:
  233. if urllib.request._parse_proxy(proxy_url)[0] is None:
  234. # Scheme-less proxies are not supported
  235. raise UnsupportedRequest(f'Proxy "{proxy_url}" missing scheme')
  236. except ValueError as e:
  237. # parse_proxy may raise on some invalid proxy urls such as "/a/b/c"
  238. raise UnsupportedRequest(f'Invalid proxy url "{proxy_url}": {e}')
  239. scheme = urllib.parse.urlparse(proxy_url).scheme.lower()
  240. if scheme not in self._SUPPORTED_PROXY_SCHEMES:
  241. raise UnsupportedRequest(f'Unsupported proxy type: "{scheme}"')
  242. def _check_extensions(self, extensions):
  243. """Check extensions for unsupported extensions. Subclasses should extend this."""
  244. assert isinstance(extensions.get('cookiejar'), (YoutubeDLCookieJar, NoneType))
  245. assert isinstance(extensions.get('timeout'), (float, int, NoneType))
  246. def _validate(self, request):
  247. self._check_url_scheme(request)
  248. self._check_proxies(request.proxies or self.proxies)
  249. extensions = request.extensions.copy()
  250. self._check_extensions(extensions)
  251. if extensions:
  252. # TODO: add support for optional extensions
  253. raise UnsupportedRequest(f'Unsupported extensions: {", ".join(extensions.keys())}')
  254. @wrap_request_errors
  255. def validate(self, request: Request):
  256. if not isinstance(request, Request):
  257. raise TypeError('Expected an instance of Request')
  258. self._validate(request)
  259. @wrap_request_errors
  260. def send(self, request: Request) -> Response:
  261. if not isinstance(request, Request):
  262. raise TypeError('Expected an instance of Request')
  263. return self._send(request)
  264. @abc.abstractmethod
  265. def _send(self, request: Request):
  266. """Handle a request from start to finish. Redefine in subclasses."""
  267. pass
  268. def close(self):
  269. pass
  270. @classproperty
  271. def RH_NAME(cls):
  272. return cls.__name__[:-2]
  273. @classproperty
  274. def RH_KEY(cls):
  275. assert cls.__name__.endswith('RH'), 'RequestHandler class names must end with "RH"'
  276. return cls.__name__[:-2]
  277. def __enter__(self):
  278. return self
  279. def __exit__(self, *args):
  280. self.close()
  281. class Request:
  282. """
  283. Represents a request to be made.
  284. Partially backwards-compatible with urllib.request.Request.
  285. @param url: url to send. Will be sanitized.
  286. @param data: payload data to send. Must be bytes, iterable of bytes, a file-like object or None
  287. @param headers: headers to send.
  288. @param proxies: proxy dict mapping of proto:proxy to use for the request and any redirects.
  289. @param query: URL query parameters to update the url with.
  290. @param method: HTTP method to use. If no method specified, will use POST if payload data is present else GET
  291. @param extensions: Dictionary of Request extensions to add, as supported by handlers.
  292. """
  293. def __init__(
  294. self,
  295. url: str,
  296. data: RequestData = None,
  297. headers: typing.Mapping = None,
  298. proxies: dict = None,
  299. query: dict = None,
  300. method: str = None,
  301. extensions: dict = None
  302. ):
  303. self._headers = HTTPHeaderDict()
  304. self._data = None
  305. if query:
  306. url = update_url_query(url, query)
  307. self.url = url
  308. self.method = method
  309. if headers:
  310. self.headers = headers
  311. self.data = data # note: must be done after setting headers
  312. self.proxies = proxies or {}
  313. self.extensions = extensions or {}
  314. @property
  315. def url(self):
  316. return self._url
  317. @url.setter
  318. def url(self, url):
  319. if not isinstance(url, str):
  320. raise TypeError('url must be a string')
  321. elif url.startswith('//'):
  322. url = 'http:' + url
  323. self._url = normalize_url(url)
  324. @property
  325. def method(self):
  326. return self._method or ('POST' if self.data is not None else 'GET')
  327. @method.setter
  328. def method(self, method):
  329. if method is None:
  330. self._method = None
  331. elif isinstance(method, str):
  332. self._method = method.upper()
  333. else:
  334. raise TypeError('method must be a string')
  335. @property
  336. def data(self):
  337. return self._data
  338. @data.setter
  339. def data(self, data: RequestData):
  340. # Try catch some common mistakes
  341. if data is not None and (
  342. not isinstance(data, (bytes, io.IOBase, Iterable)) or isinstance(data, (str, Mapping))
  343. ):
  344. raise TypeError('data must be bytes, iterable of bytes, or a file-like object')
  345. if data == self._data and self._data is None:
  346. self.headers.pop('Content-Length', None)
  347. # https://docs.python.org/3/library/urllib.request.html#urllib.request.Request.data
  348. if data != self._data:
  349. if self._data is not None:
  350. self.headers.pop('Content-Length', None)
  351. self._data = data
  352. if self._data is None:
  353. self.headers.pop('Content-Type', None)
  354. if 'Content-Type' not in self.headers and self._data is not None:
  355. self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
  356. @property
  357. def headers(self) -> HTTPHeaderDict:
  358. return self._headers
  359. @headers.setter
  360. def headers(self, new_headers: Mapping):
  361. """Replaces headers of the request. If not a CaseInsensitiveDict, it will be converted to one."""
  362. if isinstance(new_headers, HTTPHeaderDict):
  363. self._headers = new_headers
  364. elif isinstance(new_headers, Mapping):
  365. self._headers = HTTPHeaderDict(new_headers)
  366. else:
  367. raise TypeError('headers must be a mapping')
  368. def update(self, url=None, data=None, headers=None, query=None):
  369. self.data = data if data is not None else self.data
  370. self.headers.update(headers or {})
  371. self.url = update_url_query(url or self.url, query or {})
  372. def copy(self):
  373. return self.__class__(
  374. url=self.url,
  375. headers=copy.deepcopy(self.headers),
  376. proxies=copy.deepcopy(self.proxies),
  377. data=self._data,
  378. extensions=copy.copy(self.extensions),
  379. method=self._method,
  380. )
  381. HEADRequest = functools.partial(Request, method='HEAD')
  382. PUTRequest = functools.partial(Request, method='PUT')
  383. class Response(io.IOBase):
  384. """
  385. Base class for HTTP response adapters.
  386. By default, it provides a basic wrapper for a file-like response object.
  387. Interface partially backwards-compatible with addinfourl and http.client.HTTPResponse.
  388. @param fp: Original, file-like, response.
  389. @param url: URL that this is a response of.
  390. @param headers: response headers.
  391. @param status: Response HTTP status code. Default is 200 OK.
  392. @param reason: HTTP status reason. Will use built-in reasons based on status code if not provided.
  393. """
  394. def __init__(
  395. self,
  396. fp: typing.IO,
  397. url: str,
  398. headers: Mapping[str, str],
  399. status: int = 200,
  400. reason: str = None):
  401. self.fp = fp
  402. self.headers = Message()
  403. for name, value in headers.items():
  404. self.headers.add_header(name, value)
  405. self.status = status
  406. self.url = url
  407. try:
  408. self.reason = reason or HTTPStatus(status).phrase
  409. except ValueError:
  410. self.reason = None
  411. def readable(self):
  412. return self.fp.readable()
  413. def read(self, amt: int = None) -> bytes:
  414. # Expected errors raised here should be of type RequestError or subclasses.
  415. # Subclasses should redefine this method with more precise error handling.
  416. try:
  417. return self.fp.read(amt)
  418. except Exception as e:
  419. raise TransportError(cause=e) from e
  420. def close(self):
  421. self.fp.close()
  422. return super().close()
  423. def get_header(self, name, default=None):
  424. """Get header for name.
  425. If there are multiple matching headers, return all seperated by comma."""
  426. headers = self.headers.get_all(name)
  427. if not headers:
  428. return default
  429. if name.title() == 'Set-Cookie':
  430. # Special case, only get the first one
  431. # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.3-4.1
  432. return headers[0]
  433. return ', '.join(headers)
  434. # The following methods are for compatability reasons and are deprecated
  435. @property
  436. def code(self):
  437. deprecation_warning('Response.code is deprecated, use Response.status', stacklevel=2)
  438. return self.status
  439. def getcode(self):
  440. deprecation_warning('Response.getcode() is deprecated, use Response.status', stacklevel=2)
  441. return self.status
  442. def geturl(self):
  443. deprecation_warning('Response.geturl() is deprecated, use Response.url', stacklevel=2)
  444. return self.url
  445. def info(self):
  446. deprecation_warning('Response.info() is deprecated, use Response.headers', stacklevel=2)
  447. return self.headers
  448. def getheader(self, name, default=None):
  449. deprecation_warning('Response.getheader() is deprecated, use Response.get_header', stacklevel=2)
  450. return self.get_header(name, default)
  451. if typing.TYPE_CHECKING:
  452. RequestData = bytes | Iterable[bytes] | typing.IO | None
  453. Preference = typing.Callable[[RequestHandler, Request], int]
  454. _RH_PREFERENCES: set[Preference] = set()