tls-client-python 1.16.0.1__py3-none-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
tls_client/context.py ADDED
@@ -0,0 +1,347 @@
1
+ """Browser-coherent request contexts (Sec-Fetch-*, Client Hints, Priority).
2
+
3
+ Real browsers derive a family of request headers from *how* the request was
4
+ initiated (a top-level navigation, an XHR, an <img> load, ...). Sending a
5
+ top-level-navigation ``Accept`` with an XHR ``Sec-Fetch-Mode`` — or omitting
6
+ the ``Sec-Fetch-*`` cluster entirely — is a strong automation tell.
7
+
8
+ This module lets callers describe the *context* of a request and derives the
9
+ coherent header set for it. Everything is opt-in: pass ``context=...`` to
10
+ ``Session.request`` / ``execute_request`` and the derived headers are merged
11
+ under the user's explicit headers (user values win).
12
+
13
+ Techniques mirror the behaviour captured in real Chrome / Firefox traffic
14
+ (same model as httpcloak's RequestContext and priority-urgency table):
15
+
16
+ - ``Sec-Fetch-Mode/Dest/Site`` per request context, ``Sec-Fetch-User: ?1``
17
+ only for user-triggered navigations;
18
+ - fetch-site computation from target URL vs referrer (registrable-domain
19
+ matching, simplified two-label heuristic);
20
+ - ``Priority: u=,i`` from the resource urgency table (Chrome semantics:
21
+ urgency 3 omits the ``u=`` component);
22
+ - ``Accept`` per destination and browser;
23
+ - ``Upgrade-Insecure-Requests: 1`` only on navigations.
24
+ """
25
+
26
+ from typing import Dict, Optional
27
+ from urllib.parse import urlsplit
28
+
29
+
30
+ class RequestContext:
31
+ """Describes how a request was initiated inside a browser page.
32
+
33
+ Attributes mirror the observable ``Sec-Fetch-*`` / ``Priority`` /
34
+ ``Accept`` header family.
35
+ """
36
+
37
+ __slots__ = (
38
+ "mode",
39
+ "dest",
40
+ "site",
41
+ "user_triggered",
42
+ "referrer",
43
+ "target_url",
44
+ "urgency",
45
+ "incremental",
46
+ )
47
+
48
+ def __init__(
49
+ self,
50
+ mode: str = "navigate",
51
+ dest: str = "document",
52
+ site: Optional[str] = None,
53
+ user_triggered: bool = False,
54
+ referrer: Optional[str] = None,
55
+ target_url: Optional[str] = None,
56
+ urgency: Optional[int] = None,
57
+ incremental: bool = False,
58
+ ) -> None:
59
+ self.mode = mode
60
+ self.dest = dest
61
+ self.site = site
62
+ self.user_triggered = user_triggered
63
+ self.referrer = referrer
64
+ self.target_url = target_url
65
+ self.urgency = urgency
66
+ self.incremental = incremental
67
+
68
+ # -- context constructors (mirror common page initiations) -------------
69
+
70
+ @classmethod
71
+ def navigation(cls, url: str, *, user_triggered: bool = True,
72
+ referrer: Optional[str] = None) -> "RequestContext":
73
+ """Top-level document navigation (address bar, link click)."""
74
+ return cls(mode="navigate", dest="document", user_triggered=user_triggered,
75
+ referrer=referrer, target_url=url)
76
+
77
+ @classmethod
78
+ def iframe(cls, url: str, *, referrer: Optional[str] = None) -> "RequestContext":
79
+ return cls(mode="navigate", dest="iframe", referrer=referrer, target_url=url)
80
+
81
+ @classmethod
82
+ def xhr(cls, url: str, *, referrer: Optional[str] = None) -> "RequestContext":
83
+ """fetch()/XHR — the default sub-resource data request."""
84
+ return cls(mode="cors", dest="empty", referrer=referrer, target_url=url)
85
+
86
+ @classmethod
87
+ def script(cls, url: str, *, referrer: Optional[str] = None) -> "RequestContext":
88
+ return cls(mode="no-cors", dest="script", referrer=referrer, target_url=url)
89
+
90
+ @classmethod
91
+ def style(cls, url: str, *, referrer: Optional[str] = None) -> "RequestContext":
92
+ return cls(mode="no-cors", dest="style", referrer=referrer, target_url=url)
93
+
94
+ @classmethod
95
+ def image(cls, url: str, *, referrer: Optional[str] = None) -> "RequestContext":
96
+ return cls(mode="no-cors", dest="image", referrer=referrer, target_url=url)
97
+
98
+ @classmethod
99
+ def font(cls, url: str, *, referrer: Optional[str] = None) -> "RequestContext":
100
+ return cls(mode="cors", dest="font", referrer=referrer, target_url=url)
101
+
102
+ @classmethod
103
+ def media(cls, url: str, *, referrer: Optional[str] = None) -> "RequestContext":
104
+ return cls(mode="no-cors", dest="video", referrer=referrer, target_url=url)
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Chrome's resource priority table (urgency, incremental) per destination —
109
+ # captured from real Chrome 147 traffic (same data as httpcloak's
110
+ # defaultPriorityTable). Urgency 3 is Chrome's internal default and is
111
+ # OMITTED from the header; 0-7 map to H2 stream weight 256-(73*u)/2.
112
+ # ---------------------------------------------------------------------------
113
+
114
+ _DEFAULT_URGENCY: Dict[str, int] = {
115
+ "audio": 3,
116
+ "document": 0,
117
+ "embed": 0,
118
+ "empty": 1,
119
+ "font": 1,
120
+ "iframe": 0,
121
+ "image": 2,
122
+ "manifest": 2,
123
+ "object": 0,
124
+ "script": 1,
125
+ "style": 0,
126
+ "track": 3,
127
+ "video": 3,
128
+ "worker": 4,
129
+ }
130
+
131
+ _DEFAULT_INCREMENTAL = frozenset((
132
+ "audio", "document", "embed", "empty", "iframe", "image",
133
+ "object", "track", "video", "worker",
134
+ ))
135
+
136
+ _CHROME_PRIORITY_DEFAULT_URGENCY = 3
137
+
138
+
139
+ def _registrable_domain(host: str) -> str:
140
+ """Simplified registrable-domain heuristic (two-label suffix).
141
+
142
+ Matches httpcloak's calculateFetchSite: good enough for the
143
+ same-site/cross-site distinction without a full PSL dependency.
144
+ """
145
+ labels = host.lower().split(".")
146
+ if len(labels) <= 2:
147
+ return ".".join(labels)
148
+ return ".".join(labels[-2:])
149
+
150
+
151
+ def compute_fetch_site(target_url: str, referrer: Optional[str]) -> str:
152
+ """Compute ``Sec-Fetch-Site`` for a request given its referrer.
153
+
154
+ ``none`` when there is no referrer (address-bar navigation),
155
+ ``same-origin`` / ``same-site`` / ``cross-site`` otherwise.
156
+ """
157
+ if not referrer:
158
+ return "none"
159
+ t_host = (urlsplit(target_url).hostname or "").lower()
160
+ r_host = (urlsplit(referrer).hostname or "").lower()
161
+ if not t_host or not r_host:
162
+ return "none"
163
+ if t_host == r_host:
164
+ return "same-origin"
165
+ if _registrable_domain(t_host) == _registrable_domain(r_host):
166
+ return "same-site"
167
+ return "cross-site"
168
+
169
+
170
+ def sec_fetch_headers(ctx: RequestContext) -> Dict[str, str]:
171
+ """Derive the ``Sec-Fetch-*`` cluster for *ctx*."""
172
+ headers = {
173
+ "sec-fetch-mode": ctx.mode,
174
+ "sec-fetch-dest": ctx.dest,
175
+ }
176
+ site = ctx.site
177
+ if site is None:
178
+ site = compute_fetch_site(ctx.target_url or "", ctx.referrer)
179
+ headers["sec-fetch-site"] = site
180
+ if ctx.mode == "navigate" and ctx.user_triggered:
181
+ headers["sec-fetch-user"] = "?1"
182
+ return headers
183
+
184
+
185
+ def priority_header(ctx: RequestContext) -> Optional[str]:
186
+ """Build the RFC 9218 ``Priority`` header value (Chrome emission rules).
187
+
188
+ Urgency defaults to the per-destination captured table; incremental
189
+ likewise. Urgency 3 is Chrome's internal default: it is omitted from
190
+ the header, so urgency-3 non-incremental requests carry no Priority
191
+ header at all, and urgency-3 incremental requests send just ``i``.
192
+ """
193
+ urgency = ctx.urgency
194
+ if urgency is None:
195
+ urgency = _DEFAULT_URGENCY.get(ctx.dest, _CHROME_PRIORITY_DEFAULT_URGENCY)
196
+ incremental = ctx.incremental
197
+ if not ctx.incremental and ctx.urgency is None:
198
+ incremental = ctx.dest in _DEFAULT_INCREMENTAL
199
+ is_default = urgency == _CHROME_PRIORITY_DEFAULT_URGENCY
200
+ if is_default and not incremental:
201
+ return None
202
+ if is_default and incremental:
203
+ return "i"
204
+ if incremental:
205
+ return "u=%d, i" % urgency
206
+ return "u=%d" % urgency
207
+
208
+
209
+ # ---------------------------------------------------------------------------
210
+ # Accept values per destination (Chrome / Firefox behaviour)
211
+ # ---------------------------------------------------------------------------
212
+
213
+ _CHROME_NAVIGATION_ACCEPT = (
214
+ "text/html,application/xhtml+xml,application/xml;q=0.9,"
215
+ "image/avif,image/webp,image/apng,*/*;q=0.8,"
216
+ "application/signed-exchange;v=b3;q=0.7"
217
+ )
218
+ _FIREFOX_NAVIGATION_ACCEPT = (
219
+ "text/html,application/xhtml+xml,application/xml;q=0.9,"
220
+ "image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8"
221
+ )
222
+ # Safari sends the same navigation Accept as Chrome but without the
223
+ # signed-exchange token, which is a Chromium-only feature.
224
+ _SAFARI_NAVIGATION_ACCEPT = (
225
+ "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
226
+ )
227
+ _CHROME_EMPTY_ACCEPT = "*/*"
228
+ _FIREFOX_EMPTY_ACCEPT = "*/*"
229
+ _IMAGE_ACCEPT = (
230
+ "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8"
231
+ )
232
+ _STYLE_ACCEPT = "text/css,*/*;q=0.1"
233
+ _SCRIPT_ACCEPT = (
234
+ "application/javascript, application/*-javascript+module, text/javascript, */*;q=0.5"
235
+ )
236
+
237
+
238
+ def _accept_for(ctx: RequestContext, browser: str) -> str:
239
+ """Navigation/XHR Accept header for *browser* ("" = unknown family).
240
+
241
+ An unknown family falls back to the Chromium value, which matches the
242
+ pre-existing behaviour for identifiers the engine does not recognise.
243
+ """
244
+ if ctx.dest == "document":
245
+ if browser == "firefox":
246
+ return _FIREFOX_NAVIGATION_ACCEPT
247
+ if browser == "safari":
248
+ return _SAFARI_NAVIGATION_ACCEPT
249
+ return _CHROME_NAVIGATION_ACCEPT
250
+ if ctx.dest == "image":
251
+ return _IMAGE_ACCEPT
252
+ if ctx.dest == "style":
253
+ return _STYLE_ACCEPT
254
+ if ctx.dest == "script":
255
+ return _SCRIPT_ACCEPT
256
+ return _FIREFOX_EMPTY_ACCEPT if browser == "firefox" else _CHROME_EMPTY_ACCEPT
257
+
258
+
259
+ def apply_context(
260
+ headers: Optional[Dict[str, str]],
261
+ ctx: RequestContext,
262
+ *,
263
+ browser: str = "chrome",
264
+ send_priority: bool = True,
265
+ user_keys: Optional[set] = None,
266
+ ) -> Dict[str, str]:
267
+ """Merge the context-derived headers into *headers*.
268
+
269
+ *user_keys* (casefolded header names) are the headers the caller set
270
+ explicitly on this request — they always win. Everything else that
271
+ the context owns is overridden or removed, because values inherited
272
+ from the profile's default header block (a navigation Accept, a
273
+ document ``Sec-Fetch-Mode``) would contradict this request's context.
274
+ """
275
+ merged = dict(headers) if headers else {}
276
+ user = user_keys or set()
277
+
278
+ def _folded_key(name: str) -> Optional[str]:
279
+ for key in merged:
280
+ if key.casefold() == name:
281
+ return key
282
+ return None
283
+
284
+ def _override(name: str, value: Optional[str]) -> None:
285
+ if value is None:
286
+ return
287
+ existing = _folded_key(name)
288
+ if existing is not None:
289
+ if existing.casefold() not in user:
290
+ merged[existing] = value
291
+ return
292
+ merged[name] = value
293
+
294
+ def _remove(name: str) -> None:
295
+ existing = _folded_key(name)
296
+ if existing is not None and existing.casefold() not in user:
297
+ del merged[existing]
298
+
299
+ for name, value in sec_fetch_headers(ctx).items():
300
+ _override(name, value)
301
+ if ctx.mode != "navigate" or not ctx.user_triggered:
302
+ _remove("sec-fetch-user")
303
+ _override("accept", _accept_for(ctx, browser))
304
+ if ctx.mode == "navigate":
305
+ _override("upgrade-insecure-requests", "1")
306
+ else:
307
+ _remove("upgrade-insecure-requests")
308
+ if send_priority:
309
+ _override("priority", priority_header(ctx))
310
+ return merged
311
+
312
+
313
+ def expand_client_hints(
314
+ sec_ch_ua: str,
315
+ *,
316
+ platform: str = '"Windows"',
317
+ platform_version: str = '"10.0.0"',
318
+ architecture: str = '"x86"',
319
+ bitness: str = '"64"',
320
+ model: str = '""',
321
+ mobile: str = "?0",
322
+ ua_full_version: Optional[str] = None,
323
+ ) -> Dict[str, str]:
324
+ """Expand the low-entropy client-hint trio into the full set.
325
+
326
+ The ``sec-ch-ua-full-version-list`` value is derived by
327
+ ``_client_hints.full_version_list``: every brand's major is expanded to
328
+ ``major.0.0.0`` (keeping the GREASE brand token verbatim), and when
329
+ *ua_full_version* is given the real browser brands (Chromium, Google
330
+ Chrome, Microsoft Edge, Brave, Opera) get that exact full version while
331
+ the GREASE brand keeps its own padded version — matching how Chrome
332
+ reports the header.
333
+ """
334
+ from tls_client._client_hints import full_version_list
335
+
336
+ return {
337
+ "sec-ch-ua": sec_ch_ua,
338
+ "sec-ch-ua-mobile": mobile,
339
+ "sec-ch-ua-platform": platform,
340
+ "sec-ch-ua-full-version-list": full_version_list(
341
+ sec_ch_ua, ua_full_version or ""
342
+ ),
343
+ "sec-ch-ua-platform-version": platform_version,
344
+ "sec-ch-ua-arch": architecture,
345
+ "sec-ch-ua-bitness": bitness,
346
+ "sec-ch-ua-model": model,
347
+ }
tls_client/cookies.py ADDED
@@ -0,0 +1,189 @@
1
+ """Dependency-free Requests-style cookie jar."""
2
+
3
+ from collections.abc import MutableMapping
4
+ from http.cookies import SimpleCookie
5
+ from urllib.parse import urlsplit
6
+
7
+
8
+ class CookieConflictError(RuntimeError):
9
+ pass
10
+
11
+
12
+ class RequestsCookieJar(MutableMapping):
13
+ def __init__(self):
14
+ self._cookies = {}
15
+
16
+ def set(self, name, value, **kwargs):
17
+ domain = kwargs.get("domain") or ""
18
+ path = kwargs.get("path") or "/"
19
+ key = (domain.lower(), path, str(name))
20
+ if value is None:
21
+ self._cookies.pop(key, None)
22
+ else:
23
+ self._cookies[key] = str(value)
24
+ return value
25
+
26
+ def set_cookie(self, cookie, *args, **kwargs):
27
+ return self.set(
28
+ cookie.name,
29
+ cookie.value,
30
+ domain=getattr(cookie, "domain", ""),
31
+ path=getattr(cookie, "path", "/"),
32
+ )
33
+
34
+ def get(self, name, default=None, domain=None, path=None):
35
+ matches = []
36
+ for (item_domain, item_path, item_name), value in self._cookies.items():
37
+ if item_name != name:
38
+ continue
39
+ if domain is not None and item_domain != domain.lower():
40
+ continue
41
+ if path is not None and item_path != path:
42
+ continue
43
+ matches.append(value)
44
+ if not matches:
45
+ return default
46
+ if len(set(matches)) > 1:
47
+ raise CookieConflictError("multiple cookies exist with name %r" % name)
48
+ return matches[0]
49
+
50
+ def get_dict(self, domain=None, path=None):
51
+ result = {}
52
+ for (item_domain, item_path, name), value in self._cookies.items():
53
+ if domain is not None and item_domain != domain.lower():
54
+ continue
55
+ if path is not None and item_path != path:
56
+ continue
57
+ result[name] = value
58
+ return result
59
+
60
+ def update(self, other=None, **kwargs):
61
+ if isinstance(other, RequestsCookieJar):
62
+ self._cookies.update(other._cookies)
63
+ elif other:
64
+ for name, value in dict(other).items():
65
+ self.set(name, value)
66
+ for name, value in kwargs.items():
67
+ self.set(name, value)
68
+
69
+ def copy(self):
70
+ jar = RequestsCookieJar()
71
+ jar._cookies.update(self._cookies)
72
+ return jar
73
+
74
+ def list_domains(self):
75
+ return sorted(set(key[0] for key in self._cookies))
76
+
77
+ def list_paths(self):
78
+ return sorted(set(key[1] for key in self._cookies))
79
+
80
+ def multiple_domains(self):
81
+ return len(set(key[0] for key in self._cookies)) > 1
82
+
83
+ def clear(self, domain=None, path=None, name=None):
84
+ if domain is None and path is None and name is None:
85
+ self._cookies.clear()
86
+ return
87
+ for key in list(self._cookies):
88
+ item_domain, item_path, item_name = key
89
+ if domain is not None and item_domain != domain.lower():
90
+ continue
91
+ if path is not None and item_path != path:
92
+ continue
93
+ if name is not None and item_name != name:
94
+ continue
95
+ del self._cookies[key]
96
+
97
+ def __getitem__(self, name):
98
+ value = self.get(name)
99
+ if value is None:
100
+ raise KeyError(name)
101
+ return value
102
+
103
+ def __setitem__(self, name, value):
104
+ self.set(name, value)
105
+
106
+ def __delitem__(self, name):
107
+ found = False
108
+ for key in list(self._cookies):
109
+ if key[2] == name:
110
+ del self._cookies[key]
111
+ found = True
112
+ if not found:
113
+ raise KeyError(name)
114
+
115
+ def __iter__(self):
116
+ seen = set()
117
+ for _, _, name in self._cookies:
118
+ if name not in seen:
119
+ seen.add(name)
120
+ yield name
121
+
122
+ def __len__(self):
123
+ return len(set(key[2] for key in self._cookies))
124
+
125
+ def __repr__(self):
126
+ return "<RequestsCookieJar %r>" % self.get_dict()
127
+
128
+
129
+ CookieJar = RequestsCookieJar
130
+
131
+
132
+ def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
133
+ jar = cookiejar or RequestsCookieJar()
134
+ for name, value in (cookie_dict or {}).items():
135
+ if overwrite or jar.get(name) is None:
136
+ jar.set(name, value)
137
+ return jar
138
+
139
+
140
+ def dict_from_cookiejar(jar):
141
+ return jar.get_dict() if hasattr(jar, "get_dict") else dict(jar)
142
+
143
+
144
+ def merge_cookies(cookiejar, cookies):
145
+ cookiejar.update(cookies or {})
146
+ return cookiejar
147
+
148
+
149
+ def cookie_header(jar, url):
150
+ parsed = urlsplit(url)
151
+ host = (parsed.hostname or "").lower()
152
+ path = parsed.path or "/"
153
+ pairs = []
154
+ for (domain, cookie_path, name), value in jar._cookies.items():
155
+ if domain:
156
+ bare_domain = domain.lstrip(".")
157
+ if host != bare_domain and not host.endswith("." + bare_domain):
158
+ continue
159
+ if not path.startswith(cookie_path):
160
+ continue
161
+ pairs.append("%s=%s" % (name, value))
162
+ return "; ".join(pairs)
163
+
164
+
165
+ def extract_cookies(headers, url):
166
+ parsed = urlsplit(url)
167
+ host = (parsed.hostname or "").lower()
168
+ jar = RequestsCookieJar()
169
+ values = []
170
+ for name, value in headers.items():
171
+ if str(name).lower() == "set-cookie":
172
+ values = value
173
+ break
174
+ if not isinstance(values, (list, tuple)):
175
+ values = [values]
176
+ for value in values:
177
+ parsed_cookie = SimpleCookie()
178
+ try:
179
+ parsed_cookie.load(value)
180
+ except Exception:
181
+ continue
182
+ for name, morsel in parsed_cookie.items():
183
+ jar.set(
184
+ name,
185
+ morsel.value,
186
+ domain=morsel["domain"] or host,
187
+ path=morsel["path"] or "/",
188
+ )
189
+ return jar
tls_client/ech.py ADDED
@@ -0,0 +1,50 @@
1
+ """ECH (Encrypted Client Hello) config resolution.
2
+
3
+ Resolves a hostname's ECHConfigList from DNS HTTPS records (RFC 9460) via
4
+ the binding's DoH-based resolver and converts it into the
5
+ ``ech_candidate_payloads`` form that ``custom_tls_client`` expects.
6
+
7
+ from tls_client import ech
8
+
9
+ payload = ech.resolve("tls.peet.ws")
10
+ session = Session(custom_tls_client={
11
+ "ja3_string": "...",
12
+ "ech_candidate_payloads": ech.to_candidate_payloads(payload),
13
+ })
14
+
15
+ Resolving on the Go side keeps the Python side free of DNS dependencies;
16
+ results are cached per host (1 h TTL, negative results 5 min). Re-resolve
17
+ after an ``illegal_parameter`` handshake failure — Cloudflare rotates ECH
18
+ keys periodically and the cached config may be stale. Not available in
19
+ the lite build (returns None).
20
+ """
21
+
22
+ from typing import List, Optional
23
+
24
+ import tls_client._core as _core
25
+
26
+
27
+ def resolve(host: str) -> Optional[bytes]:
28
+ """Return the raw ECHConfigList bytes advertised for *host*, or None.
29
+
30
+ Requires the ABI-2 native library (rebuild from current source).
31
+ """
32
+ _core._get_ffi()
33
+ _core._require_abi2()
34
+ raw = _core._lib.ResolveECHConfig(host.encode("utf-8"))
35
+ if not raw or raw == _core._ffi.NULL:
36
+ return None
37
+ return bytes.fromhex(_core._ffi.string(raw).decode("ascii"))
38
+
39
+
40
+ def to_candidate_payloads(ech_config_list: bytes) -> List[int]:
41
+ """Convert raw ECHConfigList bytes into ``ech_candidate_payloads``.
42
+
43
+ The Go engine consumes the ECHConfigList as big-endian 16-bit words.
44
+ """
45
+ if len(ech_config_list) % 2:
46
+ ech_config_list = ech_config_list + b"\x00"
47
+ return [
48
+ int.from_bytes(ech_config_list[i:i + 2], "big")
49
+ for i in range(0, len(ech_config_list), 2)
50
+ ]
@@ -0,0 +1,91 @@
1
+ """Requests-compatible exception hierarchy."""
2
+
3
+
4
+ class RequestException(IOError):
5
+ def __init__(self, *args, **kwargs):
6
+ self.response = kwargs.pop("response", None)
7
+ self.request = kwargs.pop("request", None)
8
+ if self.response is not None and self.request is None:
9
+ self.request = getattr(self.response, "request", None)
10
+ super(RequestException, self).__init__(*args)
11
+
12
+
13
+ class InvalidJSONError(RequestException):
14
+ pass
15
+
16
+
17
+ class JSONDecodeError(InvalidJSONError, ValueError):
18
+ pass
19
+
20
+
21
+ class HTTPError(RequestException):
22
+ pass
23
+
24
+
25
+ class ConnectionError(RequestException):
26
+ pass
27
+
28
+
29
+ class ProxyError(ConnectionError):
30
+ pass
31
+
32
+
33
+ class SSLError(ConnectionError):
34
+ pass
35
+
36
+
37
+ class Timeout(RequestException):
38
+ pass
39
+
40
+
41
+ class ConnectTimeout(ConnectionError, Timeout):
42
+ pass
43
+
44
+
45
+ class ReadTimeout(Timeout):
46
+ pass
47
+
48
+
49
+ class URLRequired(RequestException):
50
+ pass
51
+
52
+
53
+ class TooManyRedirects(RequestException):
54
+ pass
55
+
56
+
57
+ class MissingSchema(RequestException, ValueError):
58
+ pass
59
+
60
+
61
+ class InvalidSchema(RequestException, ValueError):
62
+ pass
63
+
64
+
65
+ class InvalidURL(RequestException, ValueError):
66
+ pass
67
+
68
+
69
+ class InvalidHeader(RequestException, ValueError):
70
+ pass
71
+
72
+
73
+ class StreamConsumedError(RequestException, TypeError):
74
+ pass
75
+
76
+
77
+ class RetryError(RequestException):
78
+ pass
79
+
80
+
81
+ class UnrewindableBodyError(RequestException):
82
+ pass
83
+
84
+
85
+ class FileModeWarning(DeprecationWarning):
86
+ pass
87
+
88
+
89
+ class RequestsDependencyWarning(Warning):
90
+ pass
91
+
tls_client/hooks.py ADDED
@@ -0,0 +1,30 @@
1
+ """Response hook helpers."""
2
+
3
+ HOOKS = ["response"]
4
+
5
+
6
+ def default_hooks():
7
+ return {"response": []}
8
+
9
+
10
+ def dispatch_hook(key, hooks, hook_data, **kwargs):
11
+ hooks = hooks or {}
12
+ selected = hooks.get(key, [])
13
+ if callable(selected):
14
+ selected = [selected]
15
+ for hook in selected:
16
+ result = hook(hook_data, **kwargs)
17
+ if result is not None:
18
+ hook_data = result
19
+ return hook_data
20
+
21
+
22
+ def merge_hooks(request_hooks, session_hooks):
23
+ result = default_hooks()
24
+ for source in (session_hooks or {}, request_hooks or {}):
25
+ for key, values in source.items():
26
+ if callable(values):
27
+ values = [values]
28
+ result.setdefault(key, []).extend(values or [])
29
+ return result
30
+