tls-client-python 1.15.0.2__py3-none-macosx_11_0_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/_core.py ADDED
@@ -0,0 +1,3063 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ tls_client._core – Low‑level CFFI binding for the Go tls-client engine.
4
+
5
+ Architecture
6
+ ────────────
7
+ • Go shared library compiled with `-buildmode=c-shared` exports four
8
+ symbols: ExecuteRequest, RequestAsync, FreeResponse, ClearClientPool.
9
+ • Sync path: ExecuteRequest blocks until completion, returns CResponseResult*.
10
+ Python wraps it with `raw_res = ffi.gc(raw_res, lib.FreeResponse)` for
11
+ automatic cleanup.
12
+ • Async path: RequestAsync deep-copies all C data into Go heap, dispatches a
13
+ goroutine, and returns immediately. The goroutine executes the HTTP request
14
+ and calls a CFFI callback with (request_id, CResponseResult*). Python
15
+ unpacks the response in the callback, calls FreeResponse, and resolves an
16
+ asyncio.Future via `loop.call_soon_threadsafe()`. No thread pool — Python's
17
+ event loop is never blocked.
18
+ • Response body is read via `ffi.buffer(res.body, res.body_len)[:]` for
19
+ a single zero-copy-style memory view → Python bytes conversion.
20
+ • All temporary C allocations are anchored in a `keep_alive` list for the
21
+ duration of the call, preventing premature GC and dangling pointers.
22
+
23
+ Classes
24
+ ───────
25
+ • Session – synchronous client. Supports `with` context manager.
26
+ • AsyncSession – asynchronous client using Go goroutines + CFFI callbacks.
27
+ Compatible with uvloop / winloop for maximum event-loop performance.
28
+ """
29
+
30
+ import asyncio
31
+ import ctypes
32
+ import os
33
+ import platform
34
+ import sys
35
+ import threading
36
+ from pathlib import Path
37
+ from typing import Any, Dict, List, Literal, Optional
38
+ import hashlib
39
+
40
+ from tls_client._default_headers import DEFAULT_HEADERS
41
+
42
+ try:
43
+ from typing import Literal, TypedDict
44
+ except ImportError:
45
+ from typing_extensions import Literal, TypedDict # Python 3.6–3.7
46
+
47
+ from typing_extensions import TypeAlias # Python <3.10
48
+
49
+
50
+ # ---------------------------------------------------------------------------
51
+ # Supported TLS client identifiers — literal type for IDE autocompletion
52
+ # ---------------------------------------------------------------------------
53
+
54
+ ClientIdentifiers: TypeAlias = Literal[
55
+ # ── Chrome ──
56
+ "chrome_103", "chrome_104", "chrome_105", "chrome_106",
57
+ "chrome_107", "chrome_108", "chrome_109", "chrome_110",
58
+ "chrome_111", "chrome_112",
59
+ "chrome_116_PSK", "chrome_116_PSK_PQ",
60
+ "chrome_117", "chrome_120", "chrome_124",
61
+ "chrome_130_PSK",
62
+ "chrome_131", "chrome_131_PSK",
63
+ "chrome_133", "chrome_133_PSK",
64
+ "chrome_144", "chrome_144_PSK",
65
+ "chrome_146", "chrome_146_PSK",
66
+ # ── Brave ──
67
+ "brave_146", "brave_146_PSK",
68
+ # ── Safari ──
69
+ "safari_15_6_1", "safari_16_0",
70
+ "safari_ipad_15_6",
71
+ "safari_ios_15_5", "safari_ios_15_6", "safari_ios_16_0",
72
+ "safari_ios_17_0",
73
+ "safari_ios_18_0", "safari_ios_18_5",
74
+ "safari_ios_26_0",
75
+ # ── Firefox ──
76
+ "firefox_102", "firefox_104", "firefox_105", "firefox_106",
77
+ "firefox_108", "firefox_110",
78
+ "firefox_117", "firefox_120", "firefox_123",
79
+ "firefox_132", "firefox_133", "firefox_135",
80
+ "firefox_146_PSK",
81
+ "firefox_147", "firefox_147_PSK",
82
+ "firefox_148",
83
+ # ── Opera ──
84
+ "opera_89", "opera_90", "opera_91",
85
+ # ── Zalando ──
86
+ "zalando_android_mobile", "zalando_ios_mobile",
87
+ # ── Nike ──
88
+ "nike_ios_mobile", "nike_android_mobile",
89
+ # ── Cloudflare ──
90
+ "cloudscraper",
91
+ # ── MMS ──
92
+ "mms_ios", "mms_ios_1", "mms_ios_2", "mms_ios_3",
93
+ # ── Mesh ──
94
+ "mesh_ios", "mesh_ios_1", "mesh_ios_2",
95
+ "mesh_android", "mesh_android_1", "mesh_android_2",
96
+ # ── Confirmed ──
97
+ "confirmed_ios", "confirmed_android",
98
+ # ── OkHttp ──
99
+ "okhttp4_android_7", "okhttp4_android_8", "okhttp4_android_9",
100
+ "okhttp4_android_10", "okhttp4_android_11",
101
+ "okhttp4_android_12", "okhttp4_android_13",
102
+ ]
103
+
104
+
105
+ # ---------------------------------------------------------------------------
106
+ # 强类型请求对象 ─ 提供 IDE 自动补全
107
+ # Strongly-typed request object — provides IDE autocompletion
108
+ # ---------------------------------------------------------------------------
109
+
110
+ class Request(TypedDict, total=False):
111
+ """强类型请求对象,提供 IDE 自动补全。
112
+
113
+ Strongly-typed request object for IDE autocompletion.
114
+ """
115
+
116
+ method: str
117
+ """HTTP 方法,如 ``"GET"``、``"POST"``。在 :meth:`Session.typed_request` 中必填。
118
+
119
+ HTTP method, e.g. ``"GET"``, ``"POST"``. Required in :meth:`Session.typed_request`.
120
+ """
121
+ url: str
122
+ """请求 URL。在 :meth:`Session.typed_request` 中必填。
123
+
124
+ Request URL. Required in :meth:`Session.typed_request`.
125
+ """
126
+ headers: Optional[Dict[str, str]]
127
+ """请求头字典。
128
+
129
+ Request headers dict.
130
+ """
131
+ header_order: Optional[List[str]]
132
+ """请求头发送顺序列表。
133
+
134
+ Header send-order list.
135
+ """
136
+ body: Optional[bytes]
137
+ """请求体原始字节串。
138
+
139
+ Request body as raw bytes.
140
+ """
141
+ client_identifier: Optional[str]
142
+ """TLS 指纹标识。
143
+
144
+ TLS fingerprint identifier.
145
+ """
146
+ timeout: Optional[int]
147
+ """超时时间(秒)。
148
+
149
+ Timeout in seconds.
150
+ """
151
+ timeout_milliseconds: Optional[int]
152
+ """超时时间(毫秒)。
153
+
154
+ Timeout in milliseconds.
155
+ """
156
+ follow_redirects: Optional[bool]
157
+ """是否跟随重定向。
158
+
159
+ Whether to follow redirects.
160
+ """
161
+ verify: Optional[bool]
162
+ """是否验证 TLS 证书。
163
+
164
+ Whether to verify the TLS certificate.
165
+ """
166
+ force_http1: Optional[bool]
167
+ """是否强制 HTTP/1.1。
168
+
169
+ Whether to force HTTP/1.1.
170
+ """
171
+ random_tls_extension_order: Optional[bool]
172
+ """是否随机 TLS 扩展顺序。
173
+
174
+ Whether to randomise TLS extension order.
175
+ """
176
+ with_protocol_racing: Optional[bool]
177
+ """是否启用协议竞速。
178
+
179
+ Whether to enable protocol racing.
180
+ """
181
+ server_name_overwrite: Optional[str]
182
+ """SNI 主机名覆盖。
183
+
184
+ SNI hostname override.
185
+ """
186
+ request_host_override: Optional[str]
187
+ """Host 请求头覆盖。
188
+
189
+ Host header override.
190
+ """
191
+ proxy: Optional[str]
192
+ """代理 URL。
193
+
194
+ Proxy URL.
195
+ """
196
+ local_address: Optional[str]
197
+ """本地绑定地址。
198
+
199
+ Local bind address.
200
+ """
201
+ pseudo_header_order: Optional[List[str]]
202
+ """HTTP/2 伪头顺序。
203
+
204
+ HTTP/2 pseudo-header order.
205
+ """
206
+ h3_pseudo_header_order: Optional[List[str]]
207
+ """HTTP/3 伪头顺序。
208
+
209
+ HTTP/3 pseudo-header order.
210
+ """
211
+ max_idle_connections: Optional[int]
212
+ """全局最大空闲连接数。
213
+
214
+ Global max idle connections.
215
+ """
216
+ max_idle_connections_per_host: Optional[int]
217
+ """每 Host 最大空闲连接数。
218
+
219
+ Max idle connections per host.
220
+ """
221
+ max_connections_per_host: Optional[int]
222
+ """每 Host 最大总连接数。
223
+
224
+ Max total connections per host.
225
+ """
226
+ disable_keep_alives: Optional[bool]
227
+ """是否禁用 Keep-Alive。
228
+
229
+ Whether to disable Keep-Alive.
230
+ """
231
+ disable_compression: Optional[bool]
232
+ """是否禁用响应解压。
233
+
234
+ Whether to disable decompression.
235
+ """
236
+ idle_conn_timeout_seconds: Optional[int]
237
+ """空闲连接超时(秒)。
238
+
239
+ Idle connection timeout (seconds).
240
+ """
241
+ max_response_header_bytes: Optional[int]
242
+ """响应头最大字节数。
243
+
244
+ Max response header bytes.
245
+ """
246
+ write_buffer_size: Optional[int]
247
+ """写缓冲区大小。
248
+
249
+ Write buffer size.
250
+ """
251
+ read_buffer_size: Optional[int]
252
+ """读缓冲区大小。
253
+
254
+ Read buffer size.
255
+ """
256
+ allow_empty_cookies: Optional[bool]
257
+ """是否允许空 Cookie。
258
+
259
+ Whether to allow empty cookies.
260
+ """
261
+ without_cookie_jar: Optional[bool]
262
+ """是否禁用 Cookie Jar。
263
+
264
+ Whether to disable Cookie Jar.
265
+ """
266
+ disable_http3: Optional[bool]
267
+ """是否禁用 HTTP/3。
268
+
269
+ Whether to disable HTTP/3.
270
+ """
271
+ disable_ipv4: Optional[bool]
272
+ """是否禁用 IPv4。
273
+
274
+ Whether to disable IPv4.
275
+ """
276
+ disable_ipv6: Optional[bool]
277
+ """是否禁用 IPv6。
278
+
279
+ Whether to disable IPv6.
280
+ """
281
+ catch_panics: Optional[bool]
282
+ """是否捕获 Go panic。
283
+
284
+ Whether to catch Go panics.
285
+ """
286
+ with_debug: Optional[bool]
287
+ """是否启用调试日志。
288
+
289
+ Whether to enable debug logging.
290
+ """
291
+ default_headers: Optional[Dict[str, str]]
292
+ """默认请求头字典,每次请求自动附加。
293
+
294
+ Default headers dict, automatically added to every request.
295
+ """
296
+ connect_headers: Optional[Dict[str, str]]
297
+ """代理 CONNECT 隧道请求头字典。
298
+
299
+ Proxy CONNECT tunnel headers dict.
300
+ """
301
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]]
302
+ """SSL 证书固定字典,格式为 ``{host: [pin1, pin2, ...]}``。
303
+
304
+ SSL certificate pinning dict, format ``{host: [pin1, pin2, ...]}``.
305
+ """
306
+ with_default_bad_pin_handler: Optional[bool]
307
+ """是否在证书固定失败时调用默认 Bad-Pin 处理器。
308
+
309
+ Whether to invoke the default bad-pin handler on pin mismatch.
310
+ """
311
+ request_cookies: Optional[Dict[str, str]]
312
+ """预置 Cookie 字典,在发送请求前注入到 Cookie Jar。
313
+
314
+ Pre-populated cookie dict, injected into the Cookie Jar before sending.
315
+ """
316
+ custom_tls_client: Optional[Dict[str, Any]]
317
+ """完全自定义的 TLS 客户端配置字典。
318
+
319
+ Fully custom TLS client configuration dict.
320
+
321
+ 包含 JA3 字符串、密码套件、ECH、ALPN、HTTP/2/3 设置等 26 个字段。
322
+ 设置后将忽略 ``client_identifier``。
323
+
324
+ Contains JA3 string, cipher suites, ECH, ALPN, HTTP/2/3 settings, etc.
325
+ (26 fields). When set, ``client_identifier`` is ignored.
326
+ """
327
+ client_certificates: Optional[List[Dict[str, bytes]]]
328
+ """客户端证书列表,用于 mTLS 双向认证。
329
+
330
+ 每个元素为 ``{'cert_pem': bytes, 'key_pem': bytes}``。
331
+
332
+ Client certificate list for mTLS mutual authentication.
333
+
334
+ Each element is ``{'cert_pem': bytes, 'key_pem': bytes}``.
335
+ """
336
+
337
+
338
+ # ---------------------------------------------------------------------------
339
+ # Response – requests‑style response object
340
+ # ---------------------------------------------------------------------------
341
+
342
+ class Response:
343
+ """HTTP 响应对象,兼容 requests 库风格。
344
+
345
+ A requests‑compatible HTTP response object.
346
+
347
+ Attributes
348
+ ----------
349
+ status_code : int
350
+ HTTP 状态码 / HTTP status code.
351
+ headers : dict
352
+ 响应头字典 / Response headers.
353
+ content : bytes
354
+ 原始响应体字节串 / Raw response body as bytes.
355
+ text : str
356
+ 已解码的响应体文本 / Decoded response body text.
357
+ encoding : str
358
+ 检测到的字符编码 / Detected charset encoding.
359
+ url : str or None
360
+ 最终请求 URL(重定向后)/ Final URL after redirects.
361
+ cookies : dict
362
+ 响应 Cookie 字典 / Response cookies dict.
363
+ used_protocol : str or None
364
+ 实际使用的 HTTP 协议版本 / HTTP protocol version used.
365
+ """
366
+
367
+ __slots__ = (
368
+ "_status_code",
369
+ "_headers",
370
+ "_content",
371
+ "_text",
372
+ "_encoding",
373
+ "_url",
374
+ "_cookies",
375
+ "_used_protocol",
376
+ )
377
+
378
+ def __init__(
379
+ self,
380
+ status_code: int,
381
+ headers: Dict[str, List[str]],
382
+ content: bytes,
383
+ text: str,
384
+ encoding: str,
385
+ url: Optional[str] = None,
386
+ cookies: Optional[Dict[str, str]] = None,
387
+ used_protocol: Optional[str] = None,
388
+ ) -> None:
389
+ self._status_code = status_code
390
+ self._headers = headers
391
+ self._content = content
392
+ self._text = text
393
+ self._encoding = encoding
394
+ self._url = url
395
+ self._cookies = cookies or {}
396
+ self._used_protocol = used_protocol
397
+
398
+ # -- read‑only properties ----------------------------------------------
399
+
400
+ @property
401
+ def status_code(self) -> int:
402
+ """HTTP 状态码 / HTTP status code."""
403
+ return self._status_code
404
+
405
+ @property
406
+ def headers(self) -> Dict[str, List[str]]:
407
+ """响应头字典 / Response headers."""
408
+ return self._headers
409
+
410
+ @property
411
+ def content(self) -> bytes:
412
+ """原始响应体字节串 / Raw bytes body."""
413
+ return self._content
414
+
415
+ @property
416
+ def text(self) -> str:
417
+ """已解码的响应体文本 / Decoded text body."""
418
+ return self._text
419
+
420
+ @property
421
+ def encoding(self) -> str:
422
+ """文本编码 / Text encoding."""
423
+ return self._encoding
424
+
425
+ @property
426
+ def url(self) -> Optional[str]:
427
+ """最终请求 URL(重定向后)/ Final URL after redirects."""
428
+ return self._url
429
+
430
+ @property
431
+ def cookies(self) -> Dict[str, str]:
432
+ """响应 Cookie 字典 / Response cookies dict."""
433
+ return self._cookies
434
+
435
+ @property
436
+ def used_protocol(self) -> Optional[str]:
437
+ """使用的 HTTP 协议版本 / HTTP protocol version (e.g. ``"HTTP/2.0"``)."""
438
+ return self._used_protocol
439
+
440
+ @property
441
+ def ok(self) -> bool:
442
+ """状态码 < 400 时为 ``True``。 / ``True`` if status_code < 400."""
443
+ return self._status_code < 400
444
+
445
+ @property
446
+ def reason(self) -> str:
447
+ """HTTP 状态文本 / HTTP reason phrase."""
448
+ from http.client import responses
449
+ return responses.get(self._status_code, "Unknown")
450
+
451
+ # -- public methods ----------------------------------------------------
452
+
453
+ def json(self, **kwargs: Any) -> Any:
454
+ """解析 JSON 响应体。 / Parse response body as JSON.
455
+
456
+ Parameters are forwarded to :func:`json.loads`.
457
+ """
458
+ import json
459
+ return json.loads(self._text, **kwargs)
460
+
461
+ def raise_for_status(self) -> None:
462
+ """若状态码 ≥ 400,抛出 :exc:`RuntimeError`。
463
+
464
+ Raise :exc:`RuntimeError` if the status code indicates an error
465
+ (4xx client error or 5xx server error).
466
+ """
467
+ if self._status_code >= 400:
468
+ raise RuntimeError(
469
+ f"{self._status_code} {self.reason} for url: {self._url or '(unknown)'}"
470
+ )
471
+
472
+ # -- dunder methods ----------------------------------------------------
473
+
474
+ def __bool__(self) -> bool:
475
+ """``bool(resp)`` → ``resp.ok``。"""
476
+ return self.ok
477
+
478
+ def __repr__(self) -> str:
479
+ return f"<Response [{self._status_code}]>"
480
+
481
+ def __str__(self) -> str:
482
+ return self.__repr__()
483
+
484
+
485
+ # ---------------------------------------------------------------------------
486
+ # CFFI cdef – must stay byte‑identical with main.go `import "C"` block
487
+ # ---------------------------------------------------------------------------
488
+
489
+ CDEF = """
490
+ typedef struct {
491
+ const char* key;
492
+ const char* value;
493
+ } HttpHeader;
494
+
495
+ typedef struct {
496
+ const char* host;
497
+ const char** pins;
498
+ int pins_len;
499
+ } PinEntry;
500
+
501
+ typedef struct {
502
+ unsigned int streamDep;
503
+ int exclusive;
504
+ unsigned char weight;
505
+ } PriorityParam;
506
+
507
+ typedef struct {
508
+ PriorityParam priorityParam;
509
+ unsigned int streamID;
510
+ } PriorityFrame;
511
+
512
+ typedef struct {
513
+ const char* kdfId;
514
+ const char* aeadId;
515
+ } CandidateCipherSuite;
516
+
517
+ typedef struct {
518
+ const char* cert_pem;
519
+ int cert_pem_len;
520
+ const char* key_pem;
521
+ int key_pem_len;
522
+ } ClientCertificate;
523
+
524
+ typedef struct {
525
+ const char** h2_settings_keys;
526
+ unsigned int* h2_settings_values;
527
+ int h2_settings_len;
528
+ const char** h2_settings_order;
529
+ int h2_settings_order_len;
530
+ const char** h3_settings_keys;
531
+ unsigned long long* h3_settings_values;
532
+ int h3_settings_len;
533
+ const char** h3_settings_order;
534
+ int h3_settings_order_len;
535
+ const char** h3_pseudo_header_order;
536
+ int h3_pseudo_header_order_len;
537
+ PriorityParam* header_priority;
538
+ const char** cert_compression_algos;
539
+ int cert_compression_algos_len;
540
+ const char* ja3_string;
541
+ const char** key_share_curves;
542
+ int key_share_curves_len;
543
+ const char** alpn_protocols;
544
+ int alpn_protocols_len;
545
+ const char** alps_protocols;
546
+ int alps_protocols_len;
547
+ unsigned short* ech_candidate_payloads;
548
+ int ech_candidate_payloads_len;
549
+ CandidateCipherSuite* ech_candidate_cipher_suites;
550
+ int ech_candidate_cipher_suites_len;
551
+ PriorityFrame* priority_frames;
552
+ int priority_frames_len;
553
+ const char** pseudo_header_order;
554
+ int pseudo_header_order_len;
555
+ const char** supported_delegated_credentials_algorithms;
556
+ int supported_delegated_credentials_algorithms_len;
557
+ const char** supported_signature_algorithms;
558
+ int supported_signature_algorithms_len;
559
+ const char** supported_versions;
560
+ int supported_versions_len;
561
+ unsigned int connection_flow;
562
+ unsigned short record_size_limit;
563
+ unsigned int stream_id;
564
+ unsigned int h3_priority_param;
565
+ int h3_send_grease_frames;
566
+ int allow_http;
567
+ } CustomTlsClient;
568
+
569
+ typedef struct {
570
+ const char* method;
571
+ const char* url;
572
+ const char* body;
573
+ int body_len;
574
+ const char* proxy;
575
+ const char* client_identifier;
576
+ HttpHeader* headers;
577
+ int headers_len;
578
+ const char** header_order;
579
+ int header_order_len;
580
+ const char** pseudo_header_order;
581
+ int pseudo_header_order_len;
582
+ const char** h3_pseudo_header_order;
583
+ int h3_pseudo_header_order_len;
584
+ int timeout_seconds;
585
+ int timeout_milliseconds;
586
+ int follow_redirects;
587
+ int insecure_skip_verify;
588
+ int force_http1;
589
+ int with_random_tls_extension_order;
590
+ int with_protocol_racing;
591
+ const char* server_name_overwrite;
592
+ const char* request_host_override;
593
+ const char* local_address;
594
+ int max_idle_connections;
595
+ int max_idle_connections_per_host;
596
+ int max_connections_per_host;
597
+ int max_response_header_bytes;
598
+ int write_buffer_size;
599
+ int read_buffer_size;
600
+ int idle_conn_timeout_seconds;
601
+ int disable_keep_alives;
602
+ int disable_compression;
603
+ int allow_empty_cookies;
604
+ int disable_http3;
605
+ int disable_ipv4;
606
+ int disable_ipv6;
607
+ int without_cookie_jar;
608
+ int catch_panics;
609
+ int with_debug;
610
+ const char* stream_output_path;
611
+ int stream_output_block_size;
612
+ const char* stream_output_eof_symbol;
613
+ HttpHeader* default_headers;
614
+ int default_headers_len;
615
+ HttpHeader* connect_headers;
616
+ int connect_headers_len;
617
+ PinEntry* certificate_pinning_hosts;
618
+ int certificate_pinning_hosts_len;
619
+ int with_default_bad_pin_handler;
620
+ HttpHeader* request_cookies;
621
+ int request_cookies_len;
622
+ ClientCertificate* client_certificates;
623
+ int client_certificates_len;
624
+ CustomTlsClient* custom_tls_client;
625
+ const char* cache_key_hash;
626
+ } RequestOptions;
627
+
628
+ typedef struct {
629
+ int status_code;
630
+ char* body;
631
+ int body_len;
632
+ char* err_msg;
633
+ char* target_url;
634
+ char* used_protocol;
635
+ HttpHeader* response_headers;
636
+ int response_headers_len;
637
+ HttpHeader* cookies;
638
+ int cookies_len;
639
+ char* _resp_strings;
640
+ } ResponseResult;
641
+
642
+ ResponseResult* ExecuteRequest(RequestOptions* opts);
643
+ void FreeResponse(ResponseResult* res);
644
+ void ClearClientPool(void);
645
+
646
+ void SetPoolTTL(int seconds);
647
+ void SetPoolScanInterval(int seconds);
648
+
649
+ typedef void (*async_callback_fn)(uintptr_t request_id, ResponseResult* response);
650
+ int RequestAsync(RequestOptions* opts, uintptr_t request_id, async_callback_fn cb);
651
+ """
652
+
653
+ # ---------------------------------------------------------------------------
654
+ # Platform detection & shared‑library loading
655
+ # ---------------------------------------------------------------------------
656
+
657
+ def _find_library() -> str:
658
+ """定位平台对应的动态链接库。
659
+
660
+ 搜索顺序:
661
+ 1. 读取 ``TLS_CLIENT_LIB`` 环境变量(显式用户覆盖)。
662
+ 2. 寻找包目录内 ``tls_client/bin/`` 下的平台专属统一命名文件。
663
+ 3. 寻找同级开发目录 ``dist/`` 下的文件。
664
+
665
+ 若未找到任何匹配文件,抛出 :exc:`FileNotFoundError`。
666
+ """
667
+ # 1. 环境变量显式覆盖
668
+ env_lib = os.environ.get("TLS_CLIENT_LIB")
669
+ if env_lib:
670
+ p = Path(env_lib)
671
+ if p.exists():
672
+ return str(p)
673
+ raise FileNotFoundError(
674
+ f"TLS_CLIENT_LIB is set to '{env_lib}' but the file does not exist."
675
+ )
676
+
677
+ # 2. 根据系统平台直接映射标准统一文件名
678
+ if sys.platform == "win32":
679
+ name = "tls-client.dll"
680
+ elif sys.platform == "darwin":
681
+ name = "tls-client.dylib"
682
+ else:
683
+ name = "tls-client.so"
684
+
685
+ here = Path(__file__).resolve().parent
686
+
687
+ # 3. 寻找分平台 Wheel 安装后的专属内置路径
688
+ bundled = here / "bin" / name
689
+ if bundled.exists():
690
+ return str(bundled)
691
+
692
+ # 4. 本地开发调试路径
693
+ dev = here / "dist" / name
694
+ if dev.exists():
695
+ return str(dev)
696
+
697
+ # 详细的异常诊断提示
698
+ parts = [
699
+ f"Cannot locate shared library '{name}' inside the package.",
700
+ "",
701
+ f" Searched: {bundled}",
702
+ f" {dev}",
703
+ "",
704
+ " If you are developing locally, ensure the shared library is compiled and placed",
705
+ " in either 'tls_client/bin/' or 'tls_client/dist/'.",
706
+ " Alternatively, set the 'TLS_CLIENT_LIB' environment variable to point directly to your binary."
707
+ ]
708
+ raise FileNotFoundError("\n".join(parts))
709
+
710
+
711
+ def _load_ffi():
712
+ """Lazy‑import cffi so the wrapper is importable without it installed."""
713
+ from cffi import FFI
714
+
715
+ ffi = FFI()
716
+ ffi.cdef(CDEF)
717
+ libpath = _find_library()
718
+
719
+ try:
720
+ lib = ffi.dlopen(libpath)
721
+ except OSError as exc:
722
+ raise OSError(
723
+ f"Shared library at '{libpath}' failed to load. "
724
+ f"The binary may be corrupt, built for a different architecture, "
725
+ f"or missing system dependencies.\n"
726
+ f"Underlying error: {exc}"
727
+ ) from exc
728
+
729
+ return ffi, lib
730
+
731
+
732
+ # Global singletons – initialised on first use
733
+ _ffi = None
734
+ _lib = None
735
+ _ffi_lock = threading.Lock()
736
+
737
+
738
+ def _get_ffi():
739
+ global _ffi, _lib
740
+ if _ffi is None:
741
+ with _ffi_lock:
742
+ if _ffi is None:
743
+ _ffi, _lib = _load_ffi()
744
+ return _ffi, _lib
745
+
746
+
747
+ # ---------------------------------------------------------------------------
748
+ # Helpers
749
+ # ---------------------------------------------------------------------------
750
+
751
+ def _charset_from_content_type(content_type: str) -> str:
752
+ """Extract charset from Content-Type header, default to ``"utf-8"``.
753
+
754
+ Mirrors ``golang.org/x/net/html/charset.NewReader`` behaviour.
755
+ """
756
+ if not content_type:
757
+ return "utf-8"
758
+ # Parse 'text/html; charset=gbk' → 'gbk'
759
+ for part in content_type.lower().split(";"):
760
+ part = part.strip()
761
+ if part.startswith("charset=") or part.startswith("charset ="):
762
+ enc = part.split("=", 1)[1].strip().strip('"').strip("'")
763
+ if enc:
764
+ return enc
765
+ return "utf-8"
766
+
767
+
768
+ def _c_string(ffi, value: Optional[str]) -> Any:
769
+ """Allocate a null‑terminated C string (or ``ffi.NULL``)."""
770
+ if value is None:
771
+ return ffi.NULL
772
+ return ffi.new("char[]", value.encode("utf-8"))
773
+
774
+
775
+ def _build_headers(ffi, headers: Optional[Dict[str, str]], keep_alive: list):
776
+ """Convert a Python dict → C HttpHeader[]. Returns ``(ptr, length)``."""
777
+ if not headers:
778
+ return ffi.NULL, 0
779
+
780
+ n = len(headers)
781
+ arr = ffi.new("HttpHeader[]", n)
782
+ keep_alive.append(arr)
783
+
784
+ for i, (k, v) in enumerate(headers.items()):
785
+ ck = ffi.new("char[]", k.encode("utf-8"))
786
+ cv = ffi.new("char[]", v.encode("utf-8"))
787
+ keep_alive.extend([ck, cv])
788
+ arr[i].key = ck
789
+ arr[i].value = cv
790
+
791
+ return arr, n
792
+
793
+
794
+ def _build_string_array(ffi, items: Optional[List[str]], keep_alive: list):
795
+ """Convert a Python list[str] → C const char**. Returns ``(ptr, length)``."""
796
+ if not items:
797
+ return ffi.NULL, 0
798
+
799
+ n = len(items)
800
+ arr = ffi.new("const char*[]", n)
801
+ keep_alive.append(arr)
802
+
803
+ for i, s in enumerate(items):
804
+ cs = ffi.new("char[]", s.encode("utf-8"))
805
+ keep_alive.append(cs)
806
+ arr[i] = cs
807
+
808
+ return arr, n
809
+
810
+
811
+ def _build_pin_entries(ffi, pins: Optional[Dict[str, List[str]]], keep_alive: list):
812
+ """Convert a Python dict[str, list[str]] → C PinEntry[]. Returns ``(ptr, length)``."""
813
+ if not pins:
814
+ return ffi.NULL, 0
815
+
816
+ n = len(pins)
817
+ arr = ffi.new("PinEntry[]", n)
818
+ keep_alive.append(arr)
819
+
820
+ for i, (host, pin_list) in enumerate(pins.items()):
821
+ ch = ffi.new("char[]", host.encode("utf-8"))
822
+ keep_alive.append(ch)
823
+ arr[i].host = ch
824
+
825
+ if pin_list:
826
+ pn = len(pin_list)
827
+ parr = ffi.new("const char*[]", pn)
828
+ keep_alive.append(parr)
829
+ for j, pin in enumerate(pin_list):
830
+ cp = ffi.new("char[]", pin.encode("utf-8"))
831
+ keep_alive.append(cp)
832
+ parr[j] = cp
833
+ arr[i].pins = parr
834
+ arr[i].pins_len = pn
835
+ else:
836
+ arr[i].pins = ffi.NULL
837
+ arr[i].pins_len = 0
838
+
839
+ return arr, n
840
+
841
+
842
+ def _build_client_certificates(ffi, certs: Optional[List[Dict[str, bytes]]], keep_alive: list):
843
+ """Convert a Python list[dict] → C ClientCertificate[]. Returns ``(ptr, length)``.
844
+
845
+ Each dict must have ``"cert_pem"`` and ``"key_pem"`` keys with bytes values.
846
+ """
847
+ if not certs:
848
+ return ffi.NULL, 0
849
+
850
+ n = len(certs)
851
+ arr = ffi.new("ClientCertificate[]", n)
852
+ keep_alive.append(arr)
853
+
854
+ for i, c in enumerate(certs):
855
+ cert_bytes = c.get("cert_pem", b"")
856
+ key_bytes = c.get("key_pem", b"")
857
+
858
+ cc = ffi.new("char[]", cert_bytes)
859
+ ck = ffi.new("char[]", key_bytes)
860
+ keep_alive.extend([cc, ck])
861
+ arr[i].cert_pem = cc
862
+ arr[i].cert_pem_len = len(cert_bytes)
863
+ arr[i].key_pem = ck
864
+ arr[i].key_pem_len = len(key_bytes)
865
+
866
+ return arr, n
867
+
868
+
869
+ def _build_custom_tls_client(ffi, cfg: Optional[Dict[str, Any]], keep_alive: list):
870
+ """Convert a Python dict → C CustomTlsClient*. Returns ``ffi.NULL`` when
871
+ *cfg* is None or empty."""
872
+ if not cfg:
873
+ return ffi.NULL
874
+
875
+ ctc = ffi.new("CustomTlsClient *")
876
+ keep_alive.append(ctc)
877
+
878
+ # JA3 string
879
+ ja3 = _c_string(ffi, cfg.get("ja3_string"))
880
+ if ja3 != ffi.NULL:
881
+ keep_alive.append(ja3)
882
+ ctc.ja3_string = ja3
883
+
884
+ # Simple scalar fields
885
+ ctc.connection_flow = cfg.get("connection_flow", 0)
886
+ ctc.record_size_limit = cfg.get("record_size_limit", 0)
887
+ ctc.stream_id = cfg.get("stream_id", 0)
888
+ ctc.h3_priority_param = cfg.get("h3_priority_param", 0)
889
+ ctc.h3_send_grease_frames = 1 if cfg.get("h3_send_grease_frames") else 0
890
+ ctc.allow_http = 1 if cfg.get("allow_http") else 0
891
+
892
+ # String arrays
893
+ ctc.h2_settings_order, ctc.h2_settings_order_len = _build_string_array(
894
+ ffi, cfg.get("h2_settings_order"), keep_alive
895
+ )
896
+ ctc.h3_settings_order, ctc.h3_settings_order_len = _build_string_array(
897
+ ffi, cfg.get("h3_settings_order"), keep_alive
898
+ )
899
+ ctc.h3_pseudo_header_order, ctc.h3_pseudo_header_order_len = _build_string_array(
900
+ ffi, cfg.get("h3_pseudo_header_order"), keep_alive
901
+ )
902
+ ctc.cert_compression_algos, ctc.cert_compression_algos_len = _build_string_array(
903
+ ffi, cfg.get("cert_compression_algos"), keep_alive
904
+ )
905
+ ctc.key_share_curves, ctc.key_share_curves_len = _build_string_array(
906
+ ffi, cfg.get("key_share_curves"), keep_alive
907
+ )
908
+ ctc.alpn_protocols, ctc.alpn_protocols_len = _build_string_array(
909
+ ffi, cfg.get("alpn_protocols"), keep_alive
910
+ )
911
+ ctc.alps_protocols, ctc.alps_protocols_len = _build_string_array(
912
+ ffi, cfg.get("alps_protocols"), keep_alive
913
+ )
914
+ ctc.pseudo_header_order, ctc.pseudo_header_order_len = _build_string_array(
915
+ ffi, cfg.get("pseudo_header_order"), keep_alive
916
+ )
917
+ ctc.supported_delegated_credentials_algorithms, ctc.supported_delegated_credentials_algorithms_len = _build_string_array(
918
+ ffi, cfg.get("supported_delegated_credentials_algorithms"), keep_alive
919
+ )
920
+ ctc.supported_signature_algorithms, ctc.supported_signature_algorithms_len = _build_string_array(
921
+ ffi, cfg.get("supported_signature_algorithms"), keep_alive
922
+ )
923
+ ctc.supported_versions, ctc.supported_versions_len = _build_string_array(
924
+ ffi, cfg.get("supported_versions"), keep_alive
925
+ )
926
+
927
+ # H2/H3 settings key-value pairs
928
+ h2_settings = cfg.get("h2_settings")
929
+ if h2_settings:
930
+ n = len(h2_settings)
931
+ keys = ffi.new("const char*[]", n)
932
+ vals = ffi.new("unsigned int[]", n)
933
+ keep_alive.extend([keys, vals])
934
+ for i, (k, v) in enumerate(h2_settings.items()):
935
+ ck = ffi.new("char[]", k.encode("utf-8"))
936
+ keep_alive.append(ck)
937
+ keys[i] = ck
938
+ vals[i] = v
939
+ ctc.h2_settings_keys = keys
940
+ ctc.h2_settings_values = vals
941
+ ctc.h2_settings_len = n
942
+
943
+ h3_settings = cfg.get("h3_settings")
944
+ if h3_settings:
945
+ n = len(h3_settings)
946
+ keys = ffi.new("const char*[]", n)
947
+ vals = ffi.new("unsigned long long[]", n)
948
+ keep_alive.extend([keys, vals])
949
+ for i, (k, v) in enumerate(h3_settings.items()):
950
+ ck = ffi.new("char[]", k.encode("utf-8"))
951
+ keep_alive.append(ck)
952
+ keys[i] = ck
953
+ vals[i] = v
954
+ ctc.h3_settings_keys = keys
955
+ ctc.h3_settings_values = vals
956
+ ctc.h3_settings_len = n
957
+
958
+ # ECH candidate payloads
959
+ ech_payloads = cfg.get("ech_candidate_payloads")
960
+ if ech_payloads:
961
+ n = len(ech_payloads)
962
+ arr = ffi.new("unsigned short[]", ech_payloads)
963
+ keep_alive.append(arr)
964
+ ctc.ech_candidate_payloads = arr
965
+ ctc.ech_candidate_payloads_len = n
966
+
967
+ # ECH candidate cipher suites
968
+ ech_suites = cfg.get("ech_candidate_cipher_suites")
969
+ if ech_suites:
970
+ n = len(ech_suites)
971
+ arr = ffi.new("CandidateCipherSuite[]", n)
972
+ keep_alive.append(arr)
973
+ for i, suite in enumerate(ech_suites):
974
+ kdf = _c_string(ffi, suite.get("kdfId"))
975
+ aead = _c_string(ffi, suite.get("aeadId"))
976
+ if kdf != ffi.NULL:
977
+ keep_alive.append(kdf)
978
+ if aead != ffi.NULL:
979
+ keep_alive.append(aead)
980
+ arr[i].kdfId = kdf
981
+ arr[i].aeadId = aead
982
+ ctc.ech_candidate_cipher_suites = arr
983
+ ctc.ech_candidate_cipher_suites_len = n
984
+
985
+ # Priority frames
986
+ pri_frames = cfg.get("priority_frames")
987
+ if pri_frames:
988
+ n = len(pri_frames)
989
+ arr = ffi.new("PriorityFrame[]", n)
990
+ keep_alive.append(arr)
991
+ for i, pf in enumerate(pri_frames):
992
+ pp = pf.get("priorityParam", {})
993
+ arr[i].priorityParam.streamDep = pp.get("streamDep", 0)
994
+ arr[i].priorityParam.exclusive = 1 if pp.get("exclusive") else 0
995
+ arr[i].priorityParam.weight = pp.get("weight", 0)
996
+ arr[i].streamID = pf.get("streamID", 0)
997
+ ctc.priority_frames = arr
998
+ ctc.priority_frames_len = n
999
+
1000
+ # Header priority (single optional struct)
1001
+ hp = cfg.get("header_priority")
1002
+ if hp:
1003
+ chp = ffi.new("PriorityParam *")
1004
+ keep_alive.append(chp)
1005
+ chp.streamDep = hp.get("streamDep", 0)
1006
+ chp.exclusive = 1 if hp.get("exclusive") else 0
1007
+ chp.weight = hp.get("weight", 0)
1008
+ ctc.header_priority = chp
1009
+
1010
+ return ctc
1011
+
1012
+
1013
+ # ---------------------------------------------------------------------------
1014
+ # Cache-key pre-computation — mirrors Go's buildCacheKey format EXACTLY.
1015
+ # Python computes the SHA-256 hash natively so Go can skip 50–200 C.GoString()
1016
+ # CGO calls on every cache hit. The hash is passed to Go via
1017
+ # RequestOptions.cache_key_hash — if non-empty, Go uses it directly for
1018
+ # clientPool.Load, bypassing buildCacheKey entirely.
1019
+ #
1020
+ # WARNING: This function must produce byte-for-byte identical output to
1021
+ # Go's buildCacheKey in cffi_binding/main.go. If either side drifts,
1022
+ # cache entries will be stored under different keys, causing silent
1023
+ # cache poisoning (duplicate clients). The test_cache_key_parity.py
1024
+ # test catches format drift BEFORE it reaches production.
1025
+ # ---------------------------------------------------------------------------
1026
+
1027
+ def _compute_cache_key_hash(r: dict) -> str:
1028
+ """Return the SHA-256 hex digest of resolved config values.
1029
+
1030
+ The format matches Go's buildCacheKey exactly — same field order,
1031
+ same separators, same sort order for maps, same hex encoding.
1032
+
1033
+ FORMAT VERSION: 1
1034
+ If you change the hash format below, increment the version AND update
1035
+ Go's buildCacheKey / buildCacheKeyFromConfig in cffi_binding/main.go
1036
+ and the corresponding test in test_cache_key_parity.py. Format drift
1037
+ causes silent cache poisoning (different keys → duplicate clients).
1038
+ """
1039
+ h = hashlib.sha256()
1040
+
1041
+ ci = r.get("client_identifier") or ""
1042
+ px = r.get("proxy") or ""
1043
+ sn = r.get("server_name_overwrite") or ""
1044
+ la = r.get("local_address") or ""
1045
+
1046
+ # ── 22 int fields (matching Go's 22 %%d format verbs) ──────────────
1047
+ main = (
1048
+ f"{ci}|{px}|{sn}|{la}|"
1049
+ f"{r['insecure_skip_verify']}|{r['force_http1']}|"
1050
+ f"{r['with_random_tls_extension_order']}|{r['with_protocol_racing']}|"
1051
+ f"{r['max_idle_connections']}|{r['max_idle_connections_per_host']}|"
1052
+ f"{r['max_connections_per_host']}|{r['max_response_header_bytes']}|"
1053
+ f"{r['write_buffer_size']}|{r['read_buffer_size']}|"
1054
+ f"{r['idle_conn_timeout_seconds']}|{r['disable_keep_alives']}|"
1055
+ f"{r['disable_compression']}|{r['disable_http3']}|"
1056
+ f"{r['disable_ipv4']}|{r['disable_ipv6']}|{r['follow_redirects']}|"
1057
+ f"{r['without_cookie_jar']}|{r['allow_empty_cookies']}|"
1058
+ f"{r['with_default_bad_pin_handler']}|"
1059
+ f"{r['timeout_seconds']}|{r['timeout_milliseconds']}"
1060
+ )
1061
+ h.update(main.encode("utf-8"))
1062
+
1063
+ # ── Pseudo-header orders ──────────────────────────────────────────
1064
+ ph = r.get("pseudo_header_order")
1065
+ if ph:
1066
+ for s in ph:
1067
+ h.update(f":{s}".encode("utf-8"))
1068
+ else:
1069
+ h.update(b":<default>")
1070
+
1071
+ h3ph = r.get("h3_pseudo_header_order")
1072
+ if h3ph:
1073
+ for s in h3ph:
1074
+ h.update(f"#{s}".encode("utf-8"))
1075
+ else:
1076
+ h.update(b"#<default>")
1077
+
1078
+ # ── Default / connect headers (sorted by key) ─────────────────────
1079
+ for prefix, key in [("~dh:", "default_headers"), ("~ch:", "connect_headers")]:
1080
+ headers = r.get(key)
1081
+ if headers:
1082
+ for k in sorted(headers.keys()):
1083
+ h.update(f"{prefix}{k}={headers[k]}".encode("utf-8"))
1084
+
1085
+ # ── Certificate pinning (sorted by host) ──────────────────────────
1086
+ cp = r.get("certificate_pinning_hosts")
1087
+ if cp:
1088
+ for host in sorted(cp.keys()):
1089
+ h.update(f"^cp:{host}=".encode("utf-8"))
1090
+ for pin in cp[host]:
1091
+ h.update(f"{pin},".encode("utf-8"))
1092
+
1093
+ # ── Client certificates ───────────────────────────────────────────
1094
+ cc = r.get("client_certificates")
1095
+ if cc:
1096
+ for cert in cc:
1097
+ cert_pem = cert.get("cert_pem", b"")
1098
+ key_pem = cert.get("key_pem", b"")
1099
+ h.update(f"|cc:{hashlib.sha256(cert_pem).hexdigest()}".encode("utf-8"))
1100
+ h.update(f"|ck:{hashlib.sha256(key_pem).hexdigest()}".encode("utf-8"))
1101
+
1102
+ # ── Custom TLS client profile ─────────────────────────────────────
1103
+ ctc = r.get("custom_tls_client")
1104
+ if ctc:
1105
+ h.update(f"|ja3={ctc.get('ja3_string', '')}".encode("utf-8"))
1106
+ h.update(f"|cf={ctc.get('connection_flow', 0)}".encode("utf-8"))
1107
+ h.update(f"|rsl={ctc.get('record_size_limit', 0)}".encode("utf-8"))
1108
+ h.update(f"|sid={ctc.get('stream_id', 0)}".encode("utf-8"))
1109
+ h.update(f"|h3pp={ctc.get('h3_priority_param', 0)}".encode("utf-8"))
1110
+ h.update(f"|h3sgf={1 if ctc.get('h3_send_grease_frames') else 0}".encode("utf-8"))
1111
+ h.update(f"|ah={1 if ctc.get('allow_http') else 0}".encode("utf-8"))
1112
+
1113
+ str_arrays = {
1114
+ "h2_settings_order": "|h2so=", "h3_settings_order": "|h3so=",
1115
+ "h3_pseudo_header_order": "|h3ph=", "cert_compression_algos": "|cca=",
1116
+ "key_share_curves": "|ksc=", "alpn_protocols": "|alpn=",
1117
+ "alps_protocols": "|alps=", "pseudo_header_order": "|ph=",
1118
+ "supported_delegated_credentials_algorithms": "|sdca=",
1119
+ "supported_signature_algorithms": "|ssa=", "supported_versions": "|sv=",
1120
+ }
1121
+ for key, pfx in str_arrays.items():
1122
+ arr = ctc.get(key)
1123
+ if arr:
1124
+ h.update(pfx.encode("utf-8"))
1125
+ for i, s in enumerate(arr):
1126
+ if i > 0:
1127
+ h.update(b",")
1128
+ h.update(str(s).encode("utf-8"))
1129
+
1130
+ for skey, pfx in [("h2_settings", "|h2s:"), ("h3_settings", "|h3s:")]:
1131
+ settings = ctc.get(skey)
1132
+ if settings:
1133
+ for k in sorted(settings.keys()):
1134
+ h.update(f"{pfx}{k}={settings[k]}".encode("utf-8"))
1135
+
1136
+ ech_payloads = ctc.get("ech_candidate_payloads")
1137
+ if ech_payloads:
1138
+ for pld in ech_payloads:
1139
+ h.update(f"|echp:{pld}".encode("utf-8"))
1140
+
1141
+ ech_suites = ctc.get("ech_candidate_cipher_suites")
1142
+ if ech_suites:
1143
+ for s in sorted(ech_suites, key=lambda x: (x.get("kdfId", ""), x.get("aeadId", ""))):
1144
+ h.update(f"|echcs:{s.get('kdfId', '')},{s.get('aeadId', '')}".encode("utf-8"))
1145
+
1146
+ pri_frames = ctc.get("priority_frames")
1147
+ if pri_frames:
1148
+ for pf in pri_frames:
1149
+ pp = pf.get("priorityParam", {})
1150
+ h.update(
1151
+ f"|pf:{pf.get('streamID', 0)},{pp.get('streamDep', 0)},"
1152
+ f"{1 if pp.get('exclusive') else 0},{pp.get('weight', 0)}".encode("utf-8")
1153
+ )
1154
+
1155
+ hp = ctc.get("header_priority")
1156
+ if hp:
1157
+ h.update(
1158
+ f"|hp:{hp.get('streamDep', 0)},{1 if hp.get('exclusive') else 0},"
1159
+ f"{hp.get('weight', 0)}".encode("utf-8")
1160
+ )
1161
+
1162
+ return h.hexdigest()
1163
+
1164
+
1165
+ # ---------------------------------------------------------------------------
1166
+ # Shared RequestOptions builder — eliminates ~80 lines of duplicated
1167
+ # C‑struct logic between Session.execute_request and AsyncSession._execute_async
1168
+ # ---------------------------------------------------------------------------
1169
+
1170
+ def _populate_request_options(
1171
+ ffi: Any,
1172
+ opts: Any,
1173
+ keep_alive: list,
1174
+ defaults: Dict[str, Any],
1175
+ overrides: Dict[str, Any],
1176
+ ) -> None:
1177
+ """Set every field on *opts* by looking up ``overrides[name]`` first,
1178
+ then falling back to ``defaults[name]``. Bool fields are auto‑converted
1179
+ to C ``int`` (0/1). String / array / dict fields call the appropriate
1180
+ ``_build_*`` helper and extend *keep_alive*."""
1181
+
1182
+ def _val(name: str, as_bool: bool = False) -> Any:
1183
+ v = overrides.get(name)
1184
+ if v is None:
1185
+ v = defaults.get(name) # defensive: missing key → None instead of KeyError
1186
+ if as_bool:
1187
+ return 1 if v else 0
1188
+ return v
1189
+
1190
+ # ---- String fields (nullable C strings) -------------------------------
1191
+ for field in (
1192
+ "proxy",
1193
+ "client_identifier",
1194
+ "server_name_overwrite",
1195
+ "request_host_override",
1196
+ "local_address",
1197
+ ):
1198
+ c_val = _c_string(ffi, _val(field))
1199
+ setattr(opts, field, c_val)
1200
+ if c_val != ffi.NULL:
1201
+ keep_alive.append(c_val)
1202
+
1203
+ # ---- Array / dict fields (C arrays of structs) ------------------------
1204
+ (
1205
+ opts.pseudo_header_order,
1206
+ opts.pseudo_header_order_len,
1207
+ ) = _build_string_array(ffi, _val("pseudo_header_order"), keep_alive)
1208
+
1209
+ (
1210
+ opts.h3_pseudo_header_order,
1211
+ opts.h3_pseudo_header_order_len,
1212
+ ) = _build_string_array(ffi, _val("h3_pseudo_header_order"), keep_alive)
1213
+
1214
+ opts.default_headers, opts.default_headers_len = _build_headers(
1215
+ ffi, _val("default_headers"), keep_alive
1216
+ )
1217
+ opts.connect_headers, opts.connect_headers_len = _build_headers(
1218
+ ffi, _val("connect_headers"), keep_alive
1219
+ )
1220
+ (
1221
+ opts.certificate_pinning_hosts,
1222
+ opts.certificate_pinning_hosts_len,
1223
+ ) = _build_pin_entries(
1224
+ ffi, _val("certificate_pinning_hosts"), keep_alive
1225
+ )
1226
+ opts.request_cookies, opts.request_cookies_len = _build_headers(
1227
+ ffi, _val("request_cookies"), keep_alive
1228
+ )
1229
+ (
1230
+ opts.client_certificates,
1231
+ opts.client_certificates_len,
1232
+ ) = _build_client_certificates(
1233
+ ffi, _val("client_certificates"), keep_alive
1234
+ )
1235
+ opts.custom_tls_client = _build_custom_tls_client(
1236
+ ffi, _val("custom_tls_client"), keep_alive
1237
+ )
1238
+
1239
+ # ---- Scalar fields (int / bool→int) -----------------------------------
1240
+ opts.timeout_seconds = _val("timeout_seconds")
1241
+ opts.timeout_milliseconds = _val("timeout_milliseconds")
1242
+ opts.follow_redirects = _val("follow_redirects", True)
1243
+ opts.insecure_skip_verify = _val("insecure_skip_verify", True)
1244
+ opts.force_http1 = _val("force_http1", True)
1245
+ opts.with_random_tls_extension_order = _val(
1246
+ "with_random_tls_extension_order", True
1247
+ )
1248
+ opts.with_protocol_racing = _val("with_protocol_racing", True)
1249
+ opts.with_default_bad_pin_handler = _val(
1250
+ "with_default_bad_pin_handler", True
1251
+ )
1252
+ opts.max_idle_connections = _val("max_idle_connections")
1253
+ opts.max_idle_connections_per_host = _val("max_idle_connections_per_host")
1254
+ opts.max_connections_per_host = _val("max_connections_per_host")
1255
+ opts.disable_keep_alives = _val("disable_keep_alives", True)
1256
+ opts.disable_compression = _val("disable_compression", True)
1257
+ opts.idle_conn_timeout_seconds = _val("idle_conn_timeout_seconds")
1258
+ opts.max_response_header_bytes = _val("max_response_header_bytes")
1259
+ opts.write_buffer_size = _val("write_buffer_size")
1260
+ opts.read_buffer_size = _val("read_buffer_size")
1261
+ opts.allow_empty_cookies = _val("allow_empty_cookies", True)
1262
+ opts.without_cookie_jar = _val("without_cookie_jar", True)
1263
+ opts.disable_http3 = _val("disable_http3", True)
1264
+ opts.disable_ipv4 = _val("disable_ipv4", True)
1265
+ opts.disable_ipv6 = _val("disable_ipv6", True)
1266
+ opts.catch_panics = _val("catch_panics", True)
1267
+ opts.with_debug = _val("with_debug", True)
1268
+
1269
+
1270
+ # ---------------------------------------------------------------------------
1271
+ # Response unpacking — shared between sync ExecuteRequest and async callback
1272
+ # ---------------------------------------------------------------------------
1273
+
1274
+ def _unpack_c_response(ffi, raw_res) -> Response:
1275
+ """Unpack a C ResponseResult* into a Python Response object.
1276
+
1277
+ Used by both the synchronous execute_request path and the async
1278
+ CFFI callback path. Does NOT call FreeResponse — the caller is
1279
+ responsible for that.
1280
+ """
1281
+ status = raw_res.status_code
1282
+ blen = raw_res.body_len
1283
+
1284
+ if blen > 0 and raw_res.body != ffi.NULL:
1285
+ body_bytes = ffi.buffer(raw_res.body, blen)[:]
1286
+ else:
1287
+ body_bytes = b""
1288
+
1289
+ response_headers: Dict[str, List[str]] = {}
1290
+ rh_len = raw_res.response_headers_len
1291
+ if rh_len > 0 and raw_res.response_headers != ffi.NULL:
1292
+ for i in range(rh_len):
1293
+ h = raw_res.response_headers[i]
1294
+ if h.key != ffi.NULL and h.value != ffi.NULL:
1295
+ k = ffi.string(h.key).decode("utf-8", errors="replace")
1296
+ v = ffi.string(h.value).decode("utf-8", errors="replace")
1297
+ response_headers.setdefault(k, []).append(v)
1298
+
1299
+ ct = ""
1300
+ for k, v in response_headers.items():
1301
+ if k.lower() == "content-type":
1302
+ ct = v[0] if v else ""
1303
+ break
1304
+ encoding = _charset_from_content_type(ct)
1305
+ try:
1306
+ text = body_bytes.decode(encoding)
1307
+ except (UnicodeDecodeError, LookupError):
1308
+ encoding = "utf-8"
1309
+ text = body_bytes.decode("utf-8", errors="replace")
1310
+
1311
+ response_cookies: Dict[str, str] = {}
1312
+ ck_len = raw_res.cookies_len
1313
+ if ck_len > 0 and raw_res.cookies != ffi.NULL:
1314
+ for i in range(ck_len):
1315
+ ck_entry = raw_res.cookies[i]
1316
+ if ck_entry.key != ffi.NULL and ck_entry.value != ffi.NULL:
1317
+ cn = ffi.string(ck_entry.key).decode("utf-8", errors="replace")
1318
+ cv = ffi.string(ck_entry.value).decode("utf-8", errors="replace")
1319
+ response_cookies[cn] = cv
1320
+
1321
+ target_url: Optional[str] = None
1322
+ if raw_res.target_url != ffi.NULL:
1323
+ target_url = ffi.string(raw_res.target_url).decode("utf-8", errors="replace")
1324
+
1325
+ used_protocol: Optional[str] = None
1326
+ if raw_res.used_protocol != ffi.NULL:
1327
+ used_protocol = ffi.string(raw_res.used_protocol).decode("utf-8", errors="replace")
1328
+
1329
+ return Response(
1330
+ status_code=status,
1331
+ headers=response_headers,
1332
+ content=body_bytes,
1333
+ text=text,
1334
+ encoding=encoding,
1335
+ url=target_url,
1336
+ cookies=response_cookies,
1337
+ used_protocol=used_protocol,
1338
+ )
1339
+
1340
+ # ---------------------------------------------------------------------------
1341
+ # Synchronous Session
1342
+ # ---------------------------------------------------------------------------
1343
+
1344
+ class Session:
1345
+ """同步 HTTP 客户端,封装 Go tls-client 引擎。
1346
+
1347
+ Synchronous HTTP client wrapping the Go tls-client engine.
1348
+ """
1349
+
1350
+ defaults: Dict[str, Any]
1351
+
1352
+ # ------------------------------------------------------------------
1353
+ # Writable session properties — users can read/write after construction.
1354
+ # e.g. session.headers = {"User-Agent": "..."}
1355
+ # session.cookies = {"foo": "bar"}
1356
+ # session.proxy = "http://127.0.0.1:8080"
1357
+ # session.timeout = 10
1358
+ # ------------------------------------------------------------------
1359
+
1360
+ # -- fingerprint / protocol --------------------------------------------
1361
+
1362
+ @property
1363
+ def client_identifier(self) -> str:
1364
+ """TLS 指纹标识 / TLS fingerprint identifier."""
1365
+ return self.defaults["client_identifier"]
1366
+
1367
+ @client_identifier.setter
1368
+ def client_identifier(self, value: str) -> None:
1369
+ self.defaults["client_identifier"] = value
1370
+
1371
+ @property
1372
+ def force_http1(self) -> bool:
1373
+ """是否强制 HTTP/1.1 / Whether to force HTTP/1.1."""
1374
+ return bool(self.defaults["force_http1"])
1375
+
1376
+ @force_http1.setter
1377
+ def force_http1(self, value: bool) -> None:
1378
+ self.defaults["force_http1"] = 1 if value else 0
1379
+
1380
+ @property
1381
+ def disable_http3(self) -> bool:
1382
+ """是否完全禁用 HTTP/3 / Whether to disable HTTP/3."""
1383
+ return bool(self.defaults["disable_http3"])
1384
+
1385
+ @disable_http3.setter
1386
+ def disable_http3(self, value: bool) -> None:
1387
+ self.defaults["disable_http3"] = 1 if value else 0
1388
+
1389
+ @property
1390
+ def with_protocol_racing(self) -> bool:
1391
+ """是否启用协议竞速 / Whether to enable protocol racing."""
1392
+ return bool(self.defaults["with_protocol_racing"])
1393
+
1394
+ @with_protocol_racing.setter
1395
+ def with_protocol_racing(self, value: bool) -> None:
1396
+ self.defaults["with_protocol_racing"] = 1 if value else 0
1397
+
1398
+ @property
1399
+ def random_tls_extension_order(self) -> bool:
1400
+ """是否随机 TLS 扩展顺序 / Whether to randomise TLS extension order."""
1401
+ return bool(self.defaults["with_random_tls_extension_order"])
1402
+
1403
+ @random_tls_extension_order.setter
1404
+ def random_tls_extension_order(self, value: bool) -> None:
1405
+ self.defaults["with_random_tls_extension_order"] = 1 if value else 0
1406
+
1407
+ # -- timeout / redirect -------------------------------------------------
1408
+
1409
+ @property
1410
+ def timeout(self) -> int:
1411
+ """请求超时时间(秒) / Request timeout in seconds."""
1412
+ return self.defaults["timeout_seconds"]
1413
+
1414
+ @timeout.setter
1415
+ def timeout(self, value: int) -> None:
1416
+ self.defaults["timeout_seconds"] = value
1417
+
1418
+ @property
1419
+ def timeout_milliseconds(self) -> int:
1420
+ """请求超时时间(毫秒) / Request timeout in milliseconds."""
1421
+ return self.defaults["timeout_milliseconds"]
1422
+
1423
+ @timeout_milliseconds.setter
1424
+ def timeout_milliseconds(self, value: int) -> None:
1425
+ self.defaults["timeout_milliseconds"] = value
1426
+
1427
+ @property
1428
+ def follow_redirects(self) -> bool:
1429
+ """是否跟随重定向 / Whether to follow redirects."""
1430
+ return bool(self.defaults["follow_redirects"])
1431
+
1432
+ @follow_redirects.setter
1433
+ def follow_redirects(self, value: bool) -> None:
1434
+ self.defaults["follow_redirects"] = 1 if value else 0
1435
+
1436
+ # -- TLS / certificate --------------------------------------------------
1437
+
1438
+ @property
1439
+ def verify(self) -> bool:
1440
+ """是否验证 TLS 证书 / Whether to verify the TLS certificate."""
1441
+ return not bool(self.defaults["insecure_skip_verify"])
1442
+
1443
+ @verify.setter
1444
+ def verify(self, value: bool) -> None:
1445
+ self.defaults["insecure_skip_verify"] = 0 if value else 1
1446
+
1447
+ @property
1448
+ def server_name_overwrite(self) -> Optional[str]:
1449
+ """SNI 主机名覆盖 / SNI hostname override."""
1450
+ return self.defaults["server_name_overwrite"]
1451
+
1452
+ @server_name_overwrite.setter
1453
+ def server_name_overwrite(self, value: Optional[str]) -> None:
1454
+ self.defaults["server_name_overwrite"] = value
1455
+
1456
+ # -- proxy / local address ----------------------------------------------
1457
+
1458
+ @property
1459
+ def proxy(self) -> Optional[str]:
1460
+ """代理 URL / Proxy URL."""
1461
+ return self.defaults["proxy"]
1462
+
1463
+ @proxy.setter
1464
+ def proxy(self, value: Optional[str]) -> None:
1465
+ self.defaults["proxy"] = value
1466
+
1467
+ @property
1468
+ def proxies(self) -> Optional[str]:
1469
+ """代理 URL(别名)/ Proxy URL (alias for :attr:`proxy`)."""
1470
+ return self.defaults["proxy"]
1471
+
1472
+ @proxies.setter
1473
+ def proxies(self, value: Optional[str]) -> None:
1474
+ self.defaults["proxy"] = value
1475
+
1476
+ @property
1477
+ def local_address(self) -> Optional[str]:
1478
+ """本地绑定地址 / Local bind address."""
1479
+ return self.defaults["local_address"]
1480
+
1481
+ @local_address.setter
1482
+ def local_address(self, value: Optional[str]) -> None:
1483
+ self.defaults["local_address"] = value
1484
+
1485
+ # -- header control -----------------------------------------------------
1486
+
1487
+ @property
1488
+ def request_host_override(self) -> Optional[str]:
1489
+ """Host 请求头覆盖 / Host header override."""
1490
+ return self.defaults["request_host_override"]
1491
+
1492
+ @request_host_override.setter
1493
+ def request_host_override(self, value: Optional[str]) -> None:
1494
+ self.defaults["request_host_override"] = value
1495
+
1496
+ @property
1497
+ def pseudo_header_order(self) -> Optional[List[str]]:
1498
+ """HTTP/2 伪头顺序 / HTTP/2 pseudo-header order."""
1499
+ return self.defaults["pseudo_header_order"]
1500
+
1501
+ @pseudo_header_order.setter
1502
+ def pseudo_header_order(self, value: Optional[List[str]]) -> None:
1503
+ self.defaults["pseudo_header_order"] = value
1504
+
1505
+ @property
1506
+ def h3_pseudo_header_order(self) -> Optional[List[str]]:
1507
+ """HTTP/3 伪头顺序 / HTTP/3 pseudo-header order."""
1508
+ return self.defaults["h3_pseudo_header_order"]
1509
+
1510
+ @h3_pseudo_header_order.setter
1511
+ def h3_pseudo_header_order(self, value: Optional[List[str]]) -> None:
1512
+ self.defaults["h3_pseudo_header_order"] = value
1513
+
1514
+ @property
1515
+ def default_headers(self) -> Optional[Dict[str, str]]:
1516
+ """默认请求头字典 / Default headers dict."""
1517
+ return self.defaults["default_headers"]
1518
+
1519
+ @default_headers.setter
1520
+ def default_headers(self, value: Optional[Dict[str, str]]) -> None:
1521
+ self.defaults["default_headers"] = value
1522
+
1523
+ @property
1524
+ def headers(self) -> Optional[Dict[str, str]]:
1525
+ """默认请求头字典(别名)/ Default headers dict (alias for :attr:`default_headers`)."""
1526
+ return self.defaults["default_headers"]
1527
+
1528
+ @headers.setter
1529
+ def headers(self, value: Optional[Dict[str, str]]) -> None:
1530
+ self.defaults["default_headers"] = value
1531
+
1532
+ @property
1533
+ def connect_headers(self) -> Optional[Dict[str, str]]:
1534
+ """代理 CONNECT 隧道请求头字典 / Proxy CONNECT tunnel headers."""
1535
+ return self.defaults["connect_headers"]
1536
+
1537
+ @connect_headers.setter
1538
+ def connect_headers(self, value: Optional[Dict[str, str]]) -> None:
1539
+ self.defaults["connect_headers"] = value
1540
+
1541
+ # -- certificate pinning ------------------------------------------------
1542
+
1543
+ @property
1544
+ def certificate_pinning_hosts(self) -> Optional[Dict[str, List[str]]]:
1545
+ """SSL 证书固定字典 / SSL certificate pinning dict."""
1546
+ return self.defaults["certificate_pinning_hosts"]
1547
+
1548
+ @certificate_pinning_hosts.setter
1549
+ def certificate_pinning_hosts(self, value: Optional[Dict[str, List[str]]]) -> None:
1550
+ self.defaults["certificate_pinning_hosts"] = value
1551
+
1552
+ @property
1553
+ def with_default_bad_pin_handler(self) -> bool:
1554
+ """是否调用默认 Bad-Pin 处理器 / Whether to invoke the default bad-pin handler."""
1555
+ return bool(self.defaults["with_default_bad_pin_handler"])
1556
+
1557
+ @with_default_bad_pin_handler.setter
1558
+ def with_default_bad_pin_handler(self, value: bool) -> None:
1559
+ self.defaults["with_default_bad_pin_handler"] = 1 if value else 0
1560
+
1561
+ # -- cookies -------------------------------------------------------------
1562
+
1563
+ @property
1564
+ def request_cookies(self) -> Optional[Dict[str, str]]:
1565
+ """预置 Cookie 字典 / Pre-populated cookie dict."""
1566
+ return self.defaults["request_cookies"]
1567
+
1568
+ @request_cookies.setter
1569
+ def request_cookies(self, value: Optional[Dict[str, str]]) -> None:
1570
+ self.defaults["request_cookies"] = value
1571
+
1572
+ @property
1573
+ def cookies(self) -> Optional[Dict[str, str]]:
1574
+ """预置 Cookie 字典(别名)/ Pre-populated cookie dict (alias for :attr:`request_cookies`)."""
1575
+ return self.defaults["request_cookies"]
1576
+
1577
+ @cookies.setter
1578
+ def cookies(self, value: Optional[Dict[str, str]]) -> None:
1579
+ self.defaults["request_cookies"] = value
1580
+
1581
+ # -- custom TLS / client certs ------------------------------------------
1582
+
1583
+ @property
1584
+ def custom_tls_client(self) -> Optional[Dict[str, Any]]:
1585
+ """完全自定义的 TLS 客户端配置 / Fully custom TLS client configuration."""
1586
+ return self.defaults["custom_tls_client"]
1587
+
1588
+ @custom_tls_client.setter
1589
+ def custom_tls_client(self, value: Optional[Dict[str, Any]]) -> None:
1590
+ self.defaults["custom_tls_client"] = value
1591
+
1592
+ @property
1593
+ def client_certificates(self) -> Optional[List[Dict[str, bytes]]]:
1594
+ """客户端证书列表 (mTLS) / Client certificates for mTLS."""
1595
+ return self.defaults["client_certificates"]
1596
+
1597
+ @client_certificates.setter
1598
+ def client_certificates(self, value: Optional[List[Dict[str, bytes]]]) -> None:
1599
+ self.defaults["client_certificates"] = value
1600
+
1601
+ # -- connection pool tuning ---------------------------------------------
1602
+
1603
+ @property
1604
+ def max_idle_connections(self) -> int:
1605
+ """全局最大空闲连接数 / Global max idle connections."""
1606
+ return self.defaults["max_idle_connections"]
1607
+
1608
+ @max_idle_connections.setter
1609
+ def max_idle_connections(self, value: int) -> None:
1610
+ self.defaults["max_idle_connections"] = value
1611
+
1612
+ @property
1613
+ def max_idle_connections_per_host(self) -> int:
1614
+ """每 Host 最大空闲连接数 / Max idle connections per host."""
1615
+ return self.defaults["max_idle_connections_per_host"]
1616
+
1617
+ @max_idle_connections_per_host.setter
1618
+ def max_idle_connections_per_host(self, value: int) -> None:
1619
+ self.defaults["max_idle_connections_per_host"] = value
1620
+
1621
+ @property
1622
+ def max_connections_per_host(self) -> int:
1623
+ """每 Host 最大总连接数 / Max total connections per host."""
1624
+ return self.defaults["max_connections_per_host"]
1625
+
1626
+ @max_connections_per_host.setter
1627
+ def max_connections_per_host(self, value: int) -> None:
1628
+ self.defaults["max_connections_per_host"] = value
1629
+
1630
+ @property
1631
+ def disable_keep_alives(self) -> bool:
1632
+ """是否禁用 Keep-Alive / Whether to disable Keep-Alive."""
1633
+ return bool(self.defaults["disable_keep_alives"])
1634
+
1635
+ @disable_keep_alives.setter
1636
+ def disable_keep_alives(self, value: bool) -> None:
1637
+ self.defaults["disable_keep_alives"] = 1 if value else 0
1638
+
1639
+ @property
1640
+ def disable_compression(self) -> bool:
1641
+ """是否禁用响应解压 / Whether to disable decompression."""
1642
+ return bool(self.defaults["disable_compression"])
1643
+
1644
+ @disable_compression.setter
1645
+ def disable_compression(self, value: bool) -> None:
1646
+ self.defaults["disable_compression"] = 1 if value else 0
1647
+
1648
+ @property
1649
+ def idle_conn_timeout_seconds(self) -> int:
1650
+ """空闲连接超时(秒) / Idle connection timeout (seconds)."""
1651
+ return self.defaults["idle_conn_timeout_seconds"]
1652
+
1653
+ @idle_conn_timeout_seconds.setter
1654
+ def idle_conn_timeout_seconds(self, value: int) -> None:
1655
+ self.defaults["idle_conn_timeout_seconds"] = value
1656
+
1657
+ @property
1658
+ def max_response_header_bytes(self) -> int:
1659
+ """响应头最大字节数 / Max response header bytes."""
1660
+ return self.defaults["max_response_header_bytes"]
1661
+
1662
+ @max_response_header_bytes.setter
1663
+ def max_response_header_bytes(self, value: int) -> None:
1664
+ self.defaults["max_response_header_bytes"] = value
1665
+
1666
+ @property
1667
+ def write_buffer_size(self) -> int:
1668
+ """写缓冲区大小 / Write buffer size."""
1669
+ return self.defaults["write_buffer_size"]
1670
+
1671
+ @write_buffer_size.setter
1672
+ def write_buffer_size(self, value: int) -> None:
1673
+ self.defaults["write_buffer_size"] = value
1674
+
1675
+ @property
1676
+ def read_buffer_size(self) -> int:
1677
+ """读缓冲区大小 / Read buffer size."""
1678
+ return self.defaults["read_buffer_size"]
1679
+
1680
+ @read_buffer_size.setter
1681
+ def read_buffer_size(self, value: int) -> None:
1682
+ self.defaults["read_buffer_size"] = value
1683
+
1684
+ # -- IP stack / cookies / debug -----------------------------------------
1685
+
1686
+ @property
1687
+ def disable_ipv4(self) -> bool:
1688
+ """是否禁用 IPv4 / Whether to disable IPv4."""
1689
+ return bool(self.defaults["disable_ipv4"])
1690
+
1691
+ @disable_ipv4.setter
1692
+ def disable_ipv4(self, value: bool) -> None:
1693
+ self.defaults["disable_ipv4"] = 1 if value else 0
1694
+
1695
+ @property
1696
+ def disable_ipv6(self) -> bool:
1697
+ """是否禁用 IPv6 / Whether to disable IPv6."""
1698
+ return bool(self.defaults["disable_ipv6"])
1699
+
1700
+ @disable_ipv6.setter
1701
+ def disable_ipv6(self, value: bool) -> None:
1702
+ self.defaults["disable_ipv6"] = 1 if value else 0
1703
+
1704
+ @property
1705
+ def allow_empty_cookies(self) -> bool:
1706
+ """是否允许空 Cookie / Whether to allow empty cookies."""
1707
+ return bool(self.defaults["allow_empty_cookies"])
1708
+
1709
+ @allow_empty_cookies.setter
1710
+ def allow_empty_cookies(self, value: bool) -> None:
1711
+ self.defaults["allow_empty_cookies"] = 1 if value else 0
1712
+
1713
+ @property
1714
+ def without_cookie_jar(self) -> bool:
1715
+ """是否禁用 Cookie Jar / Whether to disable Cookie Jar."""
1716
+ return bool(self.defaults["without_cookie_jar"])
1717
+
1718
+ @without_cookie_jar.setter
1719
+ def without_cookie_jar(self, value: bool) -> None:
1720
+ self.defaults["without_cookie_jar"] = 1 if value else 0
1721
+
1722
+ @property
1723
+ def catch_panics(self) -> bool:
1724
+ """是否捕获 Go panic / Whether to catch Go panics."""
1725
+ return bool(self.defaults["catch_panics"])
1726
+
1727
+ @catch_panics.setter
1728
+ def catch_panics(self, value: bool) -> None:
1729
+ self.defaults["catch_panics"] = 1 if value else 0
1730
+
1731
+ @property
1732
+ def with_debug(self) -> bool:
1733
+ """是否启用调试日志 / Whether to enable debug logging."""
1734
+ return bool(self.defaults["with_debug"])
1735
+
1736
+ @with_debug.setter
1737
+ def with_debug(self, value: bool) -> None:
1738
+ self.defaults["with_debug"] = 1 if value else 0
1739
+
1740
+ def __init__(
1741
+ self,
1742
+ *,
1743
+ # ── 指纹 / 协议 ── / Fingerprint / Protocol ──
1744
+ # TLS 指纹标识 / TLS fingerprint identifier
1745
+ client_identifier: ClientIdentifiers = "chrome_120",
1746
+ # 强制使用 HTTP/1.1 / Force HTTP/1.1
1747
+ force_http1: bool = False,
1748
+ # 完全禁用 HTTP/3(QUIC) / Completely disable HTTP/3 (QUIC)
1749
+ disable_http3: bool = False,
1750
+ # 启用协议竞速 / Enable protocol racing
1751
+ with_protocol_racing: bool = False,
1752
+ # 随机打乱 TLS 扩展的发送顺序 / Randomize TLS extension send order
1753
+ random_tls_extension_order: bool = True,
1754
+ # ── 超时 / 重定向 ── / Timeout / Redirect ──
1755
+ # 请求整体超时时间(秒) / Total request timeout in seconds
1756
+ timeout: int = 30,
1757
+ # 请求超时时间(毫秒) / Request timeout in milliseconds
1758
+ timeout_milliseconds: int = 0,
1759
+ # 是否自动跟随 HTTP 重定向 / Whether to automatically follow HTTP redirects
1760
+ follow_redirects: bool = False,
1761
+ # ── TLS / 证书 ── / TLS / Cert ──
1762
+ # 是否验证服务端 TLS 证书 / Whether to verify the server TLS certificate
1763
+ verify: bool = True,
1764
+ # 自定义 SNI / Custom SNI
1765
+ server_name_overwrite: Optional[str] = None,
1766
+ # ── 代理 ── / Proxy ──
1767
+ # 代理 URL / Proxy URL
1768
+ proxy: Optional[str] = None,
1769
+ # 绑定到指定的本地 IP 地址 / Bind to a specific local IP address
1770
+ local_address: Optional[str] = None,
1771
+ # ── 请求头控制 ── / Header Control ──
1772
+ # 覆盖 HTTP Host 请求头 / Override the HTTP Host header
1773
+ request_host_override: Optional[str] = None,
1774
+ # HTTP/2 伪头发送顺序 / HTTP/2 pseudo-header send order
1775
+ pseudo_header_order: Optional[List[str]] = None,
1776
+ # HTTP/3 伪头的发送顺序 / HTTP/3 pseudo-header send order
1777
+ h3_pseudo_header_order: Optional[List[str]] = None,
1778
+ # 默认请求头字典 / Default headers dict
1779
+ default_headers: Optional[Dict[str, str]] = None,
1780
+ # 代理 CONNECT 隧道请求头字典 / Proxy CONNECT tunnel headers dict
1781
+ connect_headers: Optional[Dict[str, str]] = None,
1782
+ # ── 证书固定 ── / Certificate Pinning ──
1783
+ # SSL 证书固定字典 / SSL certificate pinning dict
1784
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
1785
+ # 是否调用默认 Bad-Pin 处理器 / Whether to invoke the default bad-pin handler
1786
+ with_default_bad_pin_handler: bool = False,
1787
+ # ── Cookie ──
1788
+ # 预置 Cookie 字典 / Pre-populated cookie dict
1789
+ request_cookies: Optional[Dict[str, str]] = None,
1790
+ # ── 自定义 TLS ── / Custom TLS ──
1791
+ # 完全自定义的 TLS 客户端配置 (26 fields) / Fully custom TLS client configuration
1792
+ custom_tls_client: Optional[Dict[str, Any]] = None,
1793
+ # 客户端证书 (mTLS) / Client certificates for mTLS
1794
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
1795
+ # ── 连接池调优 ── / Connection Pool Tuning ──
1796
+ # 全局最大空闲连接数 / Global max idle connections
1797
+ max_idle_connections: int = 0,
1798
+ # 每个 Host 的最大空闲连接数 / Max idle connections per host
1799
+ max_idle_connections_per_host: int = 0,
1800
+ # 每个 Host 的最大总连接数 / Max total connections per host
1801
+ max_connections_per_host: int = 0,
1802
+ # 禁用 HTTP Keep-Alive / Disable HTTP Keep-Alive
1803
+ disable_keep_alives: bool = False,
1804
+ # 禁用响应体自动解压 / Disable automatic response body decompression
1805
+ disable_compression: bool = False,
1806
+ # 空闲连接的最大保持时间(秒) / Max idle time for keep-alive connections
1807
+ idle_conn_timeout_seconds: int = 0,
1808
+ # HTTP 响应头的最大字节数限制 / Max response header bytes limit
1809
+ max_response_header_bytes: int = 0,
1810
+ # Socket 写缓冲区大小(字节) / Socket write buffer size (bytes)
1811
+ write_buffer_size: int = 0,
1812
+ # Socket 读缓冲区大小(字节) / Socket read buffer size (bytes)
1813
+ read_buffer_size: int = 0,
1814
+ # ── IP 协议栈控制 ── / IP Stack Control ──
1815
+ # 禁用 IPv4 / Disable IPv4
1816
+ disable_ipv4: bool = False,
1817
+ # 禁用 IPv6 / Disable IPv6
1818
+ disable_ipv6: bool = False,
1819
+ # ── Cookie ──
1820
+ # 是否允许空 Cookie / Whether to allow empty-value cookies
1821
+ allow_empty_cookies: bool = False,
1822
+ # 完全禁用 Cookie Jar / Completely disable Cookie Jar
1823
+ without_cookie_jar: bool = False,
1824
+ # ── 调试 / 安全 ── / Debug / Safety ──
1825
+ # 是否在 Go 侧捕获 panic / Whether to catch Go panics
1826
+ catch_panics: bool = True,
1827
+ # 启用调试日志输出 / Enable debug log output
1828
+ with_debug: bool = False,
1829
+ ) -> None:
1830
+ self.defaults = {
1831
+ "client_identifier": client_identifier,
1832
+ "timeout_seconds": timeout,
1833
+ "timeout_milliseconds": timeout_milliseconds,
1834
+ "follow_redirects": 1 if follow_redirects else 0,
1835
+ "insecure_skip_verify": 0 if verify else 1,
1836
+ "force_http1": 1 if force_http1 else 0,
1837
+ "with_random_tls_extension_order": (
1838
+ 1 if random_tls_extension_order else 0
1839
+ ),
1840
+ "with_protocol_racing": 1 if with_protocol_racing else 0,
1841
+ "server_name_overwrite": server_name_overwrite,
1842
+ "request_host_override": request_host_override,
1843
+ "local_address": local_address,
1844
+ "proxy": proxy,
1845
+ "pseudo_header_order": pseudo_header_order,
1846
+ "h3_pseudo_header_order": h3_pseudo_header_order,
1847
+ "default_headers": (
1848
+ default_headers
1849
+ if default_headers is not None
1850
+ else DEFAULT_HEADERS.get(client_identifier)
1851
+ ),
1852
+ "connect_headers": connect_headers,
1853
+ "certificate_pinning_hosts": certificate_pinning_hosts,
1854
+ "with_default_bad_pin_handler": (
1855
+ 1 if with_default_bad_pin_handler else 0
1856
+ ),
1857
+ "request_cookies": request_cookies,
1858
+ "custom_tls_client": custom_tls_client,
1859
+ "client_certificates": client_certificates,
1860
+ "max_idle_connections": max_idle_connections,
1861
+ "max_idle_connections_per_host": max_idle_connections_per_host,
1862
+ "max_connections_per_host": max_connections_per_host,
1863
+ "disable_keep_alives": 1 if disable_keep_alives else 0,
1864
+ "disable_compression": 1 if disable_compression else 0,
1865
+ "idle_conn_timeout_seconds": idle_conn_timeout_seconds,
1866
+ "max_response_header_bytes": max_response_header_bytes,
1867
+ "write_buffer_size": write_buffer_size,
1868
+ "read_buffer_size": read_buffer_size,
1869
+ "allow_empty_cookies": 1 if allow_empty_cookies else 0,
1870
+ "without_cookie_jar": 1 if without_cookie_jar else 0,
1871
+ "disable_http3": 1 if disable_http3 else 0,
1872
+ "disable_ipv4": 1 if disable_ipv4 else 0,
1873
+ "disable_ipv6": 1 if disable_ipv6 else 0,
1874
+ "catch_panics": 1 if catch_panics else 0,
1875
+ "with_debug": 1 if with_debug else 0,
1876
+ }
1877
+
1878
+ def stream_to_file(
1879
+ self,
1880
+ # HTTP 方法 / HTTP method
1881
+ method: str,
1882
+ # 请求 URL / Request URL
1883
+ url: str,
1884
+ # 输出文件路径 / Output file path
1885
+ output_path: str,
1886
+ *,
1887
+ # 请求头字典 / Request headers dict
1888
+ headers: Optional[Dict[str, str]] = None,
1889
+ # 请求头发送顺序 / Header send order
1890
+ header_order: Optional[List[str]] = None,
1891
+ # 请求体原始字节串 / Request body as raw bytes
1892
+ body: Optional[bytes] = None,
1893
+ # 块大小(字节) / Chunk size per read (bytes)
1894
+ chunk_size: int = 8192,
1895
+ # 可选的 EOF 标记字符串 / Optional EOF marker string
1896
+ eof_marker: Optional[str] = None,
1897
+ **kwargs: Any,
1898
+ ) -> Response:
1899
+ """执行请求并将响应体流式写入磁盘。
1900
+
1901
+ Execute a request and stream the response body to disk.
1902
+ """
1903
+
1904
+ ffi, _ = _get_ffi()
1905
+
1906
+ keep_alive: list = []
1907
+ c_path = _c_string(ffi, output_path)
1908
+ keep_alive.append(c_path)
1909
+
1910
+ c_eof = _c_string(ffi, eof_marker)
1911
+ if c_eof != ffi.NULL:
1912
+ keep_alive.append(c_eof)
1913
+
1914
+ return self.execute_request(
1915
+ method,
1916
+ url,
1917
+ headers=headers,
1918
+ header_order=header_order,
1919
+ body=body,
1920
+ _stream_output_path=c_path,
1921
+ _stream_output_block_size=chunk_size,
1922
+ _stream_output_eof_symbol=c_eof,
1923
+ _stream_keep_alive=keep_alive,
1924
+ **kwargs,
1925
+ )
1926
+
1927
+ def __enter__(self) -> "Session":
1928
+ return self
1929
+
1930
+ def __exit__(self, *args: Any) -> None:
1931
+ pass
1932
+
1933
+ def execute_request(
1934
+ self,
1935
+ # HTTP 方法 / HTTP method
1936
+ method: str,
1937
+ # 完整的请求 URL / Full request URL including scheme and hostname
1938
+ url: str,
1939
+ *,
1940
+ # 请求头字典 / Request headers dict
1941
+ headers: Optional[Dict[str, str]] = None,
1942
+ # 请求头的发送顺序列表 / Header send-order list
1943
+ header_order: Optional[List[str]] = None,
1944
+ # 请求体原始字节串 / Request body as raw bytes
1945
+ body: Optional[bytes] = None,
1946
+ # ── 每请求覆盖参数 / Per-request overrides ──
1947
+ # 覆盖 TLS 指纹标识 / Override TLS fingerprint identifier
1948
+ client_identifier: Optional[str] = None,
1949
+ # 覆盖超时时间(秒) / Override timeout (seconds)
1950
+ timeout: Optional[int] = None,
1951
+ # 覆盖超时时间(毫秒) / Override timeout (milliseconds)
1952
+ timeout_milliseconds: Optional[int] = None,
1953
+ # 覆盖重定向跟随策略 / Override redirect-following policy
1954
+ follow_redirects: Optional[bool] = None,
1955
+ # 覆盖 TLS 证书校验 / Override TLS certificate verification
1956
+ verify: Optional[bool] = None,
1957
+ # 覆盖 HTTP/1.1 强制开关 / Override force HTTP/1.1
1958
+ force_http1: Optional[bool] = None,
1959
+ # 覆盖 TLS 扩展随机化 / Override TLS extension randomisation
1960
+ random_tls_extension_order: Optional[bool] = None,
1961
+ # 覆盖协议竞速开关 / Override protocol racing
1962
+ with_protocol_racing: Optional[bool] = None,
1963
+ # 覆盖 SNI 主机名 / Override SNI hostname
1964
+ server_name_overwrite: Optional[str] = None,
1965
+ # 覆盖 HTTP Host 请求头 / Override HTTP Host header
1966
+ request_host_override: Optional[str] = None,
1967
+ # 覆盖代理 URL / Override proxy URL
1968
+ proxy: Optional[str] = None,
1969
+ # 覆盖本地绑定地址 / Override local bind address
1970
+ local_address: Optional[str] = None,
1971
+ # 覆盖 HTTP/2 伪头顺序 / Override HTTP/2 pseudo-header order
1972
+ pseudo_header_order: Optional[List[str]] = None,
1973
+ # 覆盖 HTTP/3 伪头顺序 / Override HTTP/3 pseudo-header order
1974
+ h3_pseudo_header_order: Optional[List[str]] = None,
1975
+ # 覆盖默认请求头字典 / Override default headers dict
1976
+ default_headers: Optional[Dict[str, str]] = None,
1977
+ # 覆盖代理 CONNECT 隧道请求头 / Override proxy CONNECT tunnel headers
1978
+ connect_headers: Optional[Dict[str, str]] = None,
1979
+ # 覆盖 SSL 证书固定字典 / Override SSL certificate pinning dict
1980
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
1981
+ # 覆盖 Bad-Pin 处理器开关 / Override default bad-pin handler toggle
1982
+ with_default_bad_pin_handler: Optional[bool] = None,
1983
+ # 覆盖预置 Cookie 字典 / Override pre-populated cookie dict
1984
+ request_cookies: Optional[Dict[str, str]] = None,
1985
+ # 覆盖客户端证书列表 / Override client certificate list
1986
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
1987
+ # 覆盖自定义 TLS 客户端配置 / Override custom TLS client configuration
1988
+ custom_tls_client: Optional[Dict[str, Any]] = None,
1989
+ # 覆盖全局最大空闲连接数 / Override global max idle connections
1990
+ max_idle_connections: Optional[int] = None,
1991
+ # 覆盖每 Host 最大空闲连接数 / Override max idle connections per host
1992
+ max_idle_connections_per_host: Optional[int] = None,
1993
+ # 覆盖每 Host 最大总连接数 / Override max total connections per host
1994
+ max_connections_per_host: Optional[int] = None,
1995
+ # 覆盖 Keep-Alive 禁用 / Override disable Keep-Alive
1996
+ disable_keep_alives: Optional[bool] = None,
1997
+ # 覆盖压缩禁用 / Override disable compression
1998
+ disable_compression: Optional[bool] = None,
1999
+ # 覆盖空闲连接超时 / Override idle connection timeout
2000
+ idle_conn_timeout_seconds: Optional[int] = None,
2001
+ # 覆盖响应头最大字节数 / Override max response header bytes
2002
+ max_response_header_bytes: Optional[int] = None,
2003
+ # 覆盖写缓冲区大小 / Override write buffer size
2004
+ write_buffer_size: Optional[int] = None,
2005
+ # 覆盖读缓冲区大小 / Override read buffer size
2006
+ read_buffer_size: Optional[int] = None,
2007
+ # 覆盖空 Cookie 允许 / Override allow-empty-cookies
2008
+ allow_empty_cookies: Optional[bool] = None,
2009
+ # 覆盖禁用 Cookie Jar / Override disable Cookie Jar
2010
+ without_cookie_jar: Optional[bool] = None,
2011
+ # 覆盖 HTTP/3 禁用 / Override disable HTTP/3
2012
+ disable_http3: Optional[bool] = None,
2013
+ # 覆盖 IPv4 禁用 / Override disable IPv4
2014
+ disable_ipv4: Optional[bool] = None,
2015
+ # 覆盖 IPv6 禁用 / Override disable IPv6
2016
+ disable_ipv6: Optional[bool] = None,
2017
+ # 覆盖 panic 捕获 / Override catch-panics
2018
+ catch_panics: Optional[bool] = None,
2019
+ # 覆盖调试日志 / Override debug logging
2020
+ with_debug: Optional[bool] = None,
2021
+ **kwargs: Any,
2022
+ ) -> Response:
2023
+ """通过 Go 引擎执行单次 HTTP 请求。
2024
+
2025
+ Execute a single HTTP request through the Go engine.
2026
+ """
2027
+ ffi, lib = _get_ffi()
2028
+
2029
+ def _val(name: str, override, as_bool: bool = False):
2030
+ v = override if override is not None else self.defaults.get(name)
2031
+ if as_bool:
2032
+ return 1 if v else 0
2033
+ return v
2034
+
2035
+ keep_alive: list = []
2036
+
2037
+ # ---- build C HttpHeader array -------------------------------------
2038
+ hdr_ptr, hdr_len = _build_headers(ffi, headers, keep_alive)
2039
+
2040
+ # ---- build header_order array -------------------------------------
2041
+ ho_ptr, ho_len = _build_string_array(ffi, header_order, keep_alive)
2042
+
2043
+ # ---- build pseudo_header_order array ------------------------------
2044
+ ph_ptr, ph_len = _build_string_array(
2045
+ ffi, _val("pseudo_header_order", pseudo_header_order), keep_alive
2046
+ )
2047
+
2048
+ # ---- build h3_pseudo_header_order array ---------------------------
2049
+ h3ph_ptr, h3ph_len = _build_string_array(
2050
+ ffi, _val("h3_pseudo_header_order", h3_pseudo_header_order), keep_alive
2051
+ )
2052
+
2053
+ # ---- build default_headers array ----------------------------------
2054
+ dh_ptr, dh_len = _build_headers(
2055
+ ffi, _val("default_headers", default_headers), keep_alive
2056
+ )
2057
+
2058
+ # ---- build connect_headers array ----------------------------------
2059
+ ch_ptr, ch_len = _build_headers(
2060
+ ffi, _val("connect_headers", connect_headers), keep_alive
2061
+ )
2062
+
2063
+ # ---- build certificate_pinning_hosts array -------------------------
2064
+ cp_ptr, cp_len = _build_pin_entries(
2065
+ ffi, _val("certificate_pinning_hosts", certificate_pinning_hosts), keep_alive
2066
+ )
2067
+
2068
+ # ---- build request_cookies array -----------------------------------
2069
+ rc_ptr, rc_len = _build_headers(
2070
+ ffi, _val("request_cookies", request_cookies), keep_alive
2071
+ )
2072
+
2073
+ # ---- build client_certificates array --------------------------------
2074
+ cc_ptr, cc_len = _build_client_certificates(
2075
+ ffi, _val("client_certificates", client_certificates), keep_alive
2076
+ )
2077
+
2078
+ # ---- build custom_tls_client --------------------------------------
2079
+ ctc_ptr = _build_custom_tls_client(
2080
+ ffi, _val("custom_tls_client", custom_tls_client), keep_alive
2081
+ )
2082
+
2083
+ # ---- pre-compute cache key hash (avoids ~50 CGO calls on cache hit) --------
2084
+ # Resolve insecure_skip_verify considering the verify override
2085
+ if verify is not None:
2086
+ _isv = 0 if verify else 1
2087
+ else:
2088
+ _isv = _val("insecure_skip_verify", None, True)
2089
+ ck_hash = _compute_cache_key_hash({
2090
+ "client_identifier": _val("client_identifier", client_identifier) or "",
2091
+ "proxy": _val("proxy", proxy) or "",
2092
+ "server_name_overwrite": _val("server_name_overwrite", server_name_overwrite) or "",
2093
+ "local_address": _val("local_address", local_address) or "",
2094
+ "insecure_skip_verify": _isv,
2095
+ "force_http1": _val("force_http1", force_http1, True),
2096
+ "with_random_tls_extension_order": _val("with_random_tls_extension_order", random_tls_extension_order, True),
2097
+ "with_protocol_racing": _val("with_protocol_racing", with_protocol_racing, True),
2098
+ "max_idle_connections": _val("max_idle_connections", max_idle_connections),
2099
+ "max_idle_connections_per_host": _val("max_idle_connections_per_host", max_idle_connections_per_host),
2100
+ "max_connections_per_host": _val("max_connections_per_host", max_connections_per_host),
2101
+ "max_response_header_bytes": _val("max_response_header_bytes", max_response_header_bytes),
2102
+ "write_buffer_size": _val("write_buffer_size", write_buffer_size),
2103
+ "read_buffer_size": _val("read_buffer_size", read_buffer_size),
2104
+ "idle_conn_timeout_seconds": _val("idle_conn_timeout_seconds", idle_conn_timeout_seconds),
2105
+ "disable_keep_alives": _val("disable_keep_alives", disable_keep_alives, True),
2106
+ "disable_compression": _val("disable_compression", disable_compression, True),
2107
+ "disable_http3": _val("disable_http3", disable_http3, True),
2108
+ "disable_ipv4": _val("disable_ipv4", disable_ipv4, True),
2109
+ "disable_ipv6": _val("disable_ipv6", disable_ipv6, True),
2110
+ "follow_redirects": _val("follow_redirects", follow_redirects, True),
2111
+ "without_cookie_jar": _val("without_cookie_jar", without_cookie_jar, True),
2112
+ "allow_empty_cookies": _val("allow_empty_cookies", allow_empty_cookies, True),
2113
+ "with_default_bad_pin_handler": _val("with_default_bad_pin_handler", with_default_bad_pin_handler, True),
2114
+ "timeout_seconds": _val("timeout_seconds", timeout),
2115
+ "timeout_milliseconds": _val("timeout_milliseconds", timeout_milliseconds),
2116
+ "pseudo_header_order": _val("pseudo_header_order", pseudo_header_order),
2117
+ "h3_pseudo_header_order": _val("h3_pseudo_header_order", h3_pseudo_header_order),
2118
+ "default_headers": _val("default_headers", default_headers),
2119
+ "connect_headers": _val("connect_headers", connect_headers),
2120
+ "certificate_pinning_hosts": _val("certificate_pinning_hosts", certificate_pinning_hosts),
2121
+ "client_certificates": _val("client_certificates", client_certificates),
2122
+ "custom_tls_client": _val("custom_tls_client", custom_tls_client),
2123
+ })
2124
+ c_ck = _c_string(ffi, ck_hash)
2125
+ if c_ck != ffi.NULL:
2126
+ keep_alive.append(c_ck)
2127
+
2128
+ # ---- build body (zero-copy) ---------------------------------------
2129
+ # ffi.from_buffer returns a pointer into Python's bytes buffer without
2130
+ # copying. keep_alive anchors the pointer so Python does not GC the
2131
+ # buffer while Go reads from it (sync: blocked; async: _pending_requests).
2132
+ if body is not None:
2133
+ body_ptr = ffi.from_buffer(body)
2134
+ keep_alive.append(body_ptr)
2135
+ body_len = len(body)
2136
+ else:
2137
+ body_ptr = ffi.NULL
2138
+ body_len = 0
2139
+
2140
+ # ---- build RequestOptions -----------------------------------------
2141
+ opts = ffi.new("RequestOptions *")
2142
+ keep_alive.append(opts)
2143
+
2144
+ c_method = ffi.new("char[]", method.encode("utf-8"))
2145
+ c_url = ffi.new("char[]", url.encode("utf-8"))
2146
+ keep_alive.extend([c_method, c_url])
2147
+
2148
+ opts.method = c_method
2149
+ opts.url = c_url
2150
+ opts.body = body_ptr
2151
+ opts.body_len = body_len
2152
+
2153
+ c_proxy = _c_string(ffi, _val("proxy", proxy))
2154
+ c_ci = _c_string(ffi, _val("client_identifier", client_identifier))
2155
+ c_sni = _c_string(ffi, _val("server_name_overwrite", server_name_overwrite))
2156
+ c_host_override = _c_string(ffi, _val("request_host_override", request_host_override))
2157
+ c_local_addr = _c_string(ffi, _val("local_address", local_address))
2158
+ for c in (c_proxy, c_ci, c_sni, c_host_override, c_local_addr):
2159
+ if c != ffi.NULL:
2160
+ keep_alive.append(c)
2161
+
2162
+ opts.proxy = c_proxy
2163
+ opts.client_identifier = c_ci
2164
+ opts.headers = hdr_ptr
2165
+ opts.headers_len = hdr_len
2166
+ opts.header_order = ho_ptr
2167
+ opts.header_order_len = ho_len
2168
+ opts.pseudo_header_order = ph_ptr
2169
+ opts.pseudo_header_order_len = ph_len
2170
+ opts.h3_pseudo_header_order = h3ph_ptr
2171
+ opts.h3_pseudo_header_order_len = h3ph_len
2172
+ opts.default_headers = dh_ptr
2173
+ opts.default_headers_len = dh_len
2174
+ opts.connect_headers = ch_ptr
2175
+ opts.connect_headers_len = ch_len
2176
+ opts.certificate_pinning_hosts = cp_ptr
2177
+ opts.certificate_pinning_hosts_len = cp_len
2178
+ opts.with_default_bad_pin_handler = _val(
2179
+ "with_default_bad_pin_handler", with_default_bad_pin_handler, True
2180
+ )
2181
+ opts.request_cookies = rc_ptr
2182
+ opts.request_cookies_len = rc_len
2183
+ opts.client_certificates = cc_ptr
2184
+ opts.client_certificates_len = cc_len
2185
+ opts.custom_tls_client = ctc_ptr
2186
+ opts.cache_key_hash = c_ck
2187
+
2188
+ opts.timeout_seconds = _val("timeout_seconds", timeout)
2189
+ opts.timeout_milliseconds = _val("timeout_milliseconds", timeout_milliseconds)
2190
+ opts.follow_redirects = _val("follow_redirects", follow_redirects, True)
2191
+ if verify is not None:
2192
+ opts.insecure_skip_verify = 0 if verify else 1
2193
+ else:
2194
+ opts.insecure_skip_verify = self.defaults["insecure_skip_verify"]
2195
+ opts.force_http1 = _val("force_http1", force_http1, True)
2196
+ opts.with_random_tls_extension_order = _val(
2197
+ "with_random_tls_extension_order", random_tls_extension_order, True
2198
+ )
2199
+ opts.with_protocol_racing = _val(
2200
+ "with_protocol_racing", with_protocol_racing, True
2201
+ )
2202
+ opts.server_name_overwrite = c_sni
2203
+ opts.request_host_override = c_host_override
2204
+ opts.local_address = c_local_addr
2205
+ opts.max_idle_connections = _val("max_idle_connections", max_idle_connections)
2206
+ opts.max_idle_connections_per_host = _val(
2207
+ "max_idle_connections_per_host", max_idle_connections_per_host
2208
+ )
2209
+ opts.max_connections_per_host = _val(
2210
+ "max_connections_per_host", max_connections_per_host
2211
+ )
2212
+ opts.disable_keep_alives = _val("disable_keep_alives", disable_keep_alives, True)
2213
+ opts.disable_compression = _val("disable_compression", disable_compression, True)
2214
+ opts.idle_conn_timeout_seconds = _val(
2215
+ "idle_conn_timeout_seconds", idle_conn_timeout_seconds
2216
+ )
2217
+ opts.max_response_header_bytes = _val(
2218
+ "max_response_header_bytes", max_response_header_bytes
2219
+ )
2220
+ opts.write_buffer_size = _val("write_buffer_size", write_buffer_size)
2221
+ opts.read_buffer_size = _val("read_buffer_size", read_buffer_size)
2222
+ opts.allow_empty_cookies = _val("allow_empty_cookies", allow_empty_cookies, True)
2223
+ opts.without_cookie_jar = _val("without_cookie_jar", without_cookie_jar, True)
2224
+ opts.disable_http3 = _val("disable_http3", disable_http3, True)
2225
+ opts.disable_ipv4 = _val("disable_ipv4", disable_ipv4, True)
2226
+ opts.disable_ipv6 = _val("disable_ipv6", disable_ipv6, True)
2227
+ opts.catch_panics = _val("catch_panics", catch_panics, True)
2228
+ opts.with_debug = _val("with_debug", with_debug, True)
2229
+
2230
+ # ---- streaming fields (injected by stream_to_file) -----------------
2231
+ stream_path = kwargs.pop("_stream_output_path", ffi.NULL)
2232
+ stream_bs = kwargs.pop("_stream_output_block_size", 0)
2233
+ stream_eof = kwargs.pop("_stream_output_eof_symbol", ffi.NULL)
2234
+ stream_keep = kwargs.pop("_stream_keep_alive", None)
2235
+ if stream_keep is not None:
2236
+ keep_alive.extend(stream_keep)
2237
+ opts.stream_output_path = stream_path
2238
+ opts.stream_output_block_size = stream_bs
2239
+ opts.stream_output_eof_symbol = stream_eof
2240
+
2241
+ # ---- call Go ------------------------------------------------------
2242
+ raw_res = lib.ExecuteRequest(opts)
2243
+
2244
+ if raw_res == ffi.NULL:
2245
+ raise RuntimeError("Go engine returned NULL – likely memory allocation failure")
2246
+
2247
+ raw_res = ffi.gc(raw_res, lib.FreeResponse)
2248
+
2249
+ if raw_res.err_msg != ffi.NULL:
2250
+ err = ffi.string(raw_res.err_msg).decode("utf-8", errors="replace")
2251
+ raise RuntimeError(err)
2252
+
2253
+ return _unpack_c_response(ffi, raw_res)
2254
+
2255
+ def typed_request(self, req: Request) -> Response:
2256
+ """使用 :class:`Request` 强类型对象执行 HTTP 请求。
2257
+
2258
+ Execute an HTTP request using a :class:`Request` strongly-typed object.
2259
+ """
2260
+ method = req["method"]
2261
+ url = req["url"]
2262
+ kwargs = {k: v for k, v in req.items() if k not in ("method", "url")}
2263
+ return self.execute_request(method, url, **kwargs)
2264
+
2265
+ def get(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
2266
+ return self.execute_request("GET", url, headers=headers, **kwargs)
2267
+
2268
+ def post(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
2269
+ return self.execute_request("POST", url, headers=headers, body=body, **kwargs)
2270
+
2271
+ def head(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
2272
+ return self.execute_request("HEAD", url, headers=headers, **kwargs)
2273
+
2274
+ def put(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
2275
+ return self.execute_request("PUT", url, headers=headers, body=body, **kwargs)
2276
+
2277
+ def delete(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
2278
+ return self.execute_request("DELETE", url, headers=headers, **kwargs)
2279
+
2280
+ def patch(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
2281
+ return self.execute_request("PATCH", url, headers=headers, body=body, **kwargs)
2282
+
2283
+ @staticmethod
2284
+ def clear_client_pool() -> None:
2285
+ """Close all idle connections in the global Go client pool."""
2286
+ _, lib = _get_ffi()
2287
+ lib.ClearClientPool()
2288
+
2289
+ @staticmethod
2290
+ def set_pool_ttl(seconds: int) -> None:
2291
+ """Set the TTL for cached HttpClient entries (default 300 s = 5 min).
2292
+
2293
+ Entries not accessed within this duration are evicted by the
2294
+ background scanner. Set to a large value to keep clients longer;
2295
+ set lower for memory-constrained environments.
2296
+ """
2297
+ _, lib = _get_ffi()
2298
+ lib.SetPoolTTL(seconds)
2299
+
2300
+ @staticmethod
2301
+ def set_pool_scan_interval(seconds: int) -> None:
2302
+ """Set the interval for the background eviction scanner (default 60 s).
2303
+
2304
+ Shorter intervals catch stale entries sooner but consume more CPU.
2305
+ """
2306
+ _, lib = _get_ffi()
2307
+ lib.SetPoolScanInterval(seconds)
2308
+
2309
+
2310
+ # ---------------------------------------------------------------------------
2311
+ # Async callback bridge — Go goroutine → Python CFFI callback → asyncio Future
2312
+ # ---------------------------------------------------------------------------
2313
+
2314
+ # Registry of pending async requests.
2315
+ # request_id → (future, keep_alive, timeout_handle)
2316
+ # future — asyncio.Future resolved by the CFFI callback
2317
+ # keep_alive — list of CFFI pointers that must outlive the Go goroutine
2318
+ # timeout_handle — asyncio.Handle; cancelled when callback fires, fires a
2319
+ # defensive cleanup if the Go goroutine never responds
2320
+ _pending_requests: Dict[int, tuple] = {}
2321
+ _pending_lock = threading.Lock()
2322
+ _request_counter = 0
2323
+
2324
+
2325
+ def _next_request_id() -> int:
2326
+ global _request_counter
2327
+ _request_counter += 1
2328
+ return _request_counter
2329
+
2330
+
2331
+ def _make_async_callback(ffi, lib):
2332
+ """Create a CFFI callback that Go goroutines invoke with results.
2333
+
2334
+ The callback is called from a Go-managed OS thread (not the Python main
2335
+ thread). CFFI internally calls PyGILState_Ensure to safely acquire the
2336
+ GIL before entering Python code.
2337
+
2338
+ Lifecycle (per the 9-step user blueprint):
2339
+ 1. Python calls RequestAsync → Go deep-copies → returns immediately
2340
+ 2. Go goroutine executes HTTP request
2341
+ 3. Go allocates CResponseResult on C heap via C.malloc
2342
+ 4. Go calls this callback with (request_id, CResponseResult*)
2343
+ 5. Python unpacks CResponseResult → Response object
2344
+ 6. Python calls FreeResponse to release C memory
2345
+ 7. Python uses loop.call_soon_threadsafe to resolve the Future
2346
+ """
2347
+
2348
+ @ffi.callback("void(uintptr_t, ResponseResult*)")
2349
+ def _on_async_response(request_id: int, raw_res: Any) -> None:
2350
+ # The ENTIRE callback body MUST be wrapped in try/except Exception.
2351
+ # This callback executes on a Go-managed OS thread. If any Python
2352
+ # exception escapes uncaught, the Python interpreter crashes with
2353
+ # Fatal Python error: Segmentation fault (Constraint 3).
2354
+ try:
2355
+ # Step 5-6: Unpack response
2356
+ if raw_res == ffi.NULL or raw_res.err_msg != ffi.NULL:
2357
+ err = "Go engine returned NULL"
2358
+ if raw_res != ffi.NULL and raw_res.err_msg != ffi.NULL:
2359
+ err = ffi.string(raw_res.err_msg).decode("utf-8", errors="replace")
2360
+ response: Any = RuntimeError(err)
2361
+ else:
2362
+ response = _unpack_c_response(ffi, raw_res)
2363
+ except Exception as exc:
2364
+ response = exc
2365
+ finally:
2366
+ # Step 6: Free C memory in all code paths (success, error, panic)
2367
+ if raw_res != ffi.NULL:
2368
+ lib.FreeResponse(raw_res)
2369
+
2370
+ # Step 9: Schedule Future resolution on the event loop thread.
2371
+ # Must use call_soon_threadsafe — direct set_result/set_exception
2372
+ # from a non-event-loop thread is NOT thread-safe (Constraint 4).
2373
+ try:
2374
+ with _pending_lock:
2375
+ future, _keep_alive, timeout_handle = _pending_requests.pop(
2376
+ request_id, (None, None, None)
2377
+ )
2378
+ # _keep_alive is now released — the goroutine has finished,
2379
+ # so the C pointers it held via unsafe.Slice are no longer needed.
2380
+
2381
+ # Cancel the defensive timeout — the Go goroutine completed.
2382
+ if timeout_handle is not None:
2383
+ timeout_handle.cancel()
2384
+
2385
+ if future is None:
2386
+ return # request was cancelled or timed out
2387
+
2388
+ if not future.done():
2389
+ loop = future.get_loop()
2390
+ if isinstance(response, Exception):
2391
+ loop.call_soon_threadsafe(future.set_exception, response)
2392
+ else:
2393
+ loop.call_soon_threadsafe(future.set_result, response)
2394
+ except Exception:
2395
+ # If even Future resolution fails, there is nothing we can do —
2396
+ # the event loop may be shut down. Silently swallow to prevent
2397
+ # a process crash.
2398
+ pass
2399
+
2400
+ return _on_async_response
2401
+
2402
+
2403
+ # Lazy-initialised callback — must be created after ffi is loaded and kept alive.
2404
+ # Protected by a lock to prevent race conditions when multiple AsyncSession
2405
+ # instances are created concurrently from different threads.
2406
+ _async_callback = None
2407
+ _async_callback_lock = threading.Lock()
2408
+
2409
+
2410
+ def _get_async_callback(ffi, lib):
2411
+ """Return the singleton CFFI callback, creating it once under lock.
2412
+
2413
+ Always acquires _async_callback_lock — double‑checked locking is unsafe
2414
+ under free‑threaded Python (PEP 703) because _async_callback may be
2415
+ partially visible without a synchronisation edge. Contention is
2416
+ negligible: the callback is created once and cached thereafter.
2417
+ """
2418
+ global _async_callback
2419
+ with _async_callback_lock:
2420
+ if _async_callback is None:
2421
+ _async_callback = _make_async_callback(ffi, lib)
2422
+ return _async_callback
2423
+
2424
+
2425
+ class AsyncSession:
2426
+ """True async HTTP client — no thread pool, no blocking.
2427
+
2428
+ Uses Go goroutines + CFFI callbacks + asyncio Future:
2429
+ - Python calls RequestAsync (returns instantly after Go deep-copies)
2430
+ - Go goroutine executes HTTP I/O in the background
2431
+ - Go invokes CFFI callback when done
2432
+ - Python resolves asyncio.Future via call_soon_threadsafe
2433
+
2434
+ Compatible with uvloop / winloop for maximum event-loop performance.
2435
+ """
2436
+
2437
+ def __init__(
2438
+ self,
2439
+ *,
2440
+ # ── 指纹 / 协议 ── / Fingerprint / Protocol ──
2441
+ # TLS 指纹标识 / TLS fingerprint identifier
2442
+ client_identifier: ClientIdentifiers = "chrome_120",
2443
+ # 强制使用 HTTP/1.1 / Force HTTP/1.1
2444
+ force_http1: bool = False,
2445
+ # 完全禁用 HTTP/3(QUIC) / Completely disable HTTP/3 (QUIC)
2446
+ disable_http3: bool = False,
2447
+ # 启用协议竞速 / Enable protocol racing
2448
+ with_protocol_racing: bool = False,
2449
+ # 随机打乱 TLS 扩展的发送顺序 / Randomize TLS extension send order
2450
+ random_tls_extension_order: bool = True,
2451
+ # ── 超时 / 重定向 ── / Timeout / Redirect ──
2452
+ # 请求整体超时时间(秒) / Total request timeout in seconds
2453
+ timeout: int = 30,
2454
+ # 请求超时时间(毫秒) / Request timeout in milliseconds
2455
+ timeout_milliseconds: int = 0,
2456
+ # 是否自动跟随 HTTP 重定向 / Whether to automatically follow HTTP redirects
2457
+ follow_redirects: bool = False,
2458
+ # ── TLS / 证书 ── / TLS / Cert ──
2459
+ # 是否验证服务端 TLS 证书 / Whether to verify the server TLS certificate
2460
+ verify: bool = True,
2461
+ # 自定义 SNI / Custom SNI
2462
+ server_name_overwrite: Optional[str] = None,
2463
+ # ── 代理 ── / Proxy ──
2464
+ # 代理 URL / Proxy URL
2465
+ proxy: Optional[str] = None,
2466
+ # 绑定到指定的本地 IP 地址 / Bind to a specific local IP address
2467
+ local_address: Optional[str] = None,
2468
+ # ── 请求头控制 ── / Header Control ──
2469
+ # 覆盖 HTTP Host 请求头 / Override the HTTP Host header
2470
+ request_host_override: Optional[str] = None,
2471
+ # HTTP/2 伪头发送顺序 / HTTP/2 pseudo-header send order
2472
+ pseudo_header_order: Optional[List[str]] = None,
2473
+ # HTTP/3 伪头的发送顺序 / HTTP/3 pseudo-header send order
2474
+ h3_pseudo_header_order: Optional[List[str]] = None,
2475
+ # 默认请求头字典 / Default headers dict
2476
+ default_headers: Optional[Dict[str, str]] = None,
2477
+ # 代理 CONNECT 隧道请求头字典 / Proxy CONNECT tunnel headers dict
2478
+ connect_headers: Optional[Dict[str, str]] = None,
2479
+ # ── 证书固定 ── / Certificate Pinning ──
2480
+ # SSL 证书固定字典 / SSL certificate pinning dict
2481
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
2482
+ # 是否调用默认 Bad-Pin 处理器 / Whether to invoke the default bad-pin handler
2483
+ with_default_bad_pin_handler: bool = False,
2484
+ # ── Cookie ──
2485
+ # 预置 Cookie 字典 / Pre-populated cookie dict
2486
+ request_cookies: Optional[Dict[str, str]] = None,
2487
+ # ── 自定义 TLS ── / Custom TLS ──
2488
+ # 完全自定义的 TLS 客户端配置 (26 fields) / Fully custom TLS client configuration
2489
+ custom_tls_client: Optional[Dict[str, Any]] = None,
2490
+ # 客户端证书 (mTLS) / Client certificates for mTLS
2491
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
2492
+ # ── 连接池调优 ── / Connection Pool Tuning ──
2493
+ # 全局最大空闲连接数 / Global max idle connections
2494
+ max_idle_connections: int = 0,
2495
+ # 每个 Host 的最大空闲连接数 / Max idle connections per host
2496
+ max_idle_connections_per_host: int = 0,
2497
+ # 每个 Host 的最大总连接数 / Max total connections per host
2498
+ max_connections_per_host: int = 0,
2499
+ # 禁用 HTTP Keep-Alive / Disable HTTP Keep-Alive
2500
+ disable_keep_alives: bool = False,
2501
+ # 禁用响应体自动解压 / Disable automatic response body decompression
2502
+ disable_compression: bool = False,
2503
+ # 空闲连接的最大保持时间(秒) / Max idle time for keep-alive connections
2504
+ idle_conn_timeout_seconds: int = 0,
2505
+ # HTTP 响应头的最大字节数限制 / Max response header bytes limit
2506
+ max_response_header_bytes: int = 0,
2507
+ # Socket 写缓冲区大小(字节) / Socket write buffer size (bytes)
2508
+ write_buffer_size: int = 0,
2509
+ # Socket 读缓冲区大小(字节) / Socket read buffer size (bytes)
2510
+ read_buffer_size: int = 0,
2511
+ # ── IP 协议栈控制 ── / IP Stack Control ──
2512
+ # 禁用 IPv4 / Disable IPv4
2513
+ disable_ipv4: bool = False,
2514
+ # 禁用 IPv6 / Disable IPv6
2515
+ disable_ipv6: bool = False,
2516
+ # ── Cookie ──
2517
+ # 是否允许空 Cookie / Whether to allow empty-value cookies
2518
+ allow_empty_cookies: bool = False,
2519
+ # 完全禁用 Cookie Jar / Completely disable Cookie Jar
2520
+ without_cookie_jar: bool = False,
2521
+ # ── 调试 / 安全 ── / Debug / Safety ──
2522
+ # 是否在 Go 侧捕获 panic / Whether to catch Go panics
2523
+ catch_panics: bool = True,
2524
+ # 启用调试日志输出 / Enable debug log output
2525
+ with_debug: bool = False,
2526
+ ) -> None:
2527
+ self._session = Session(
2528
+ client_identifier=client_identifier,
2529
+ force_http1=force_http1,
2530
+ disable_http3=disable_http3,
2531
+ with_protocol_racing=with_protocol_racing,
2532
+ random_tls_extension_order=random_tls_extension_order,
2533
+ timeout=timeout,
2534
+ timeout_milliseconds=timeout_milliseconds,
2535
+ follow_redirects=follow_redirects,
2536
+ verify=verify,
2537
+ server_name_overwrite=server_name_overwrite,
2538
+ proxy=proxy,
2539
+ local_address=local_address,
2540
+ request_host_override=request_host_override,
2541
+ pseudo_header_order=pseudo_header_order,
2542
+ h3_pseudo_header_order=h3_pseudo_header_order,
2543
+ default_headers=default_headers,
2544
+ connect_headers=connect_headers,
2545
+ certificate_pinning_hosts=certificate_pinning_hosts,
2546
+ with_default_bad_pin_handler=with_default_bad_pin_handler,
2547
+ request_cookies=request_cookies,
2548
+ custom_tls_client=custom_tls_client,
2549
+ client_certificates=client_certificates,
2550
+ max_idle_connections=max_idle_connections,
2551
+ max_idle_connections_per_host=max_idle_connections_per_host,
2552
+ max_connections_per_host=max_connections_per_host,
2553
+ disable_keep_alives=disable_keep_alives,
2554
+ disable_compression=disable_compression,
2555
+ idle_conn_timeout_seconds=idle_conn_timeout_seconds,
2556
+ max_response_header_bytes=max_response_header_bytes,
2557
+ write_buffer_size=write_buffer_size,
2558
+ read_buffer_size=read_buffer_size,
2559
+ disable_ipv4=disable_ipv4,
2560
+ disable_ipv6=disable_ipv6,
2561
+ allow_empty_cookies=allow_empty_cookies,
2562
+ without_cookie_jar=without_cookie_jar,
2563
+ catch_panics=catch_panics,
2564
+ with_debug=with_debug,
2565
+ )
2566
+
2567
+ # -- attribute delegation → underlying Session ------------------------
2568
+ # Allows: async_session.headers = {...}
2569
+ # async_session.proxy = "http://..."
2570
+ # async_session.cookies = {...}
2571
+ # All readable/writable Session properties are transparently delegated.
2572
+
2573
+ def __getattr__(self, name: str) -> Any:
2574
+ # Delegate non-private attribute access to the underlying Session.
2575
+ if name.startswith("_"):
2576
+ raise AttributeError(name)
2577
+ return getattr(self._session, name)
2578
+
2579
+ def __setattr__(self, name: str, value: Any) -> None:
2580
+ # Delegate non-private attribute writes to the underlying Session.
2581
+ if name.startswith("_"):
2582
+ super().__setattr__(name, value)
2583
+ else:
2584
+ setattr(self._session, name, value)
2585
+
2586
+ async def __aenter__(self) -> "AsyncSession":
2587
+ return self
2588
+
2589
+ async def __aexit__(self, *args: Any) -> None:
2590
+ pass
2591
+
2592
+ async def _execute_async(self, method: str, url: str, **kwargs: Any) -> Response:
2593
+ ffi, lib = _get_ffi()
2594
+ callback = _get_async_callback(ffi, lib)
2595
+ loop = asyncio.get_running_loop()
2596
+
2597
+ # Build RequestOptions (same as sync path)
2598
+ keep_alive: list = []
2599
+ opts = ffi.new("RequestOptions *")
2600
+ keep_alive.append(opts)
2601
+
2602
+ c_method = ffi.new("char[]", method.encode("utf-8"))
2603
+ c_url = ffi.new("char[]", url.encode("utf-8"))
2604
+ keep_alive.extend([c_method, c_url])
2605
+ opts.method = c_method
2606
+ opts.url = c_url
2607
+
2608
+ # Headers
2609
+ headers = kwargs.pop("headers", None)
2610
+ hdr_ptr, hdr_len = _build_headers(ffi, headers, keep_alive)
2611
+ opts.headers = hdr_ptr
2612
+ opts.headers_len = hdr_len
2613
+
2614
+ header_order = kwargs.pop("header_order", None)
2615
+ ho_ptr, ho_len = _build_string_array(ffi, header_order, keep_alive)
2616
+ opts.header_order = ho_ptr
2617
+ opts.header_order_len = ho_len
2618
+
2619
+ # Body (zero-copy — ffi.from_buffer avoids copying Python bytes to C heap)
2620
+ body = kwargs.pop("body", None)
2621
+ if body is not None:
2622
+ body_ptr = ffi.from_buffer(body)
2623
+ keep_alive.append(body_ptr)
2624
+ opts.body = body_ptr
2625
+ opts.body_len = len(body)
2626
+
2627
+ # Overrides (use defaults from the session, overridden by kwargs)
2628
+ def _val(name: str, as_bool: bool = False):
2629
+ v = kwargs.pop(name, None)
2630
+ if v is None:
2631
+ v = self._session.defaults.get(name)
2632
+ if as_bool:
2633
+ return 1 if v else 0
2634
+ return v
2635
+
2636
+ opts.timeout_seconds = _val("timeout_seconds")
2637
+ opts.timeout_milliseconds = _val("timeout_milliseconds")
2638
+ opts.follow_redirects = _val("follow_redirects", True)
2639
+ opts.insecure_skip_verify = _val("insecure_skip_verify", True)
2640
+ opts.force_http1 = _val("force_http1", True)
2641
+ opts.with_random_tls_extension_order = _val("with_random_tls_extension_order", True)
2642
+ opts.with_protocol_racing = _val("with_protocol_racing", True)
2643
+ opts.max_idle_connections = _val("max_idle_connections")
2644
+ opts.max_idle_connections_per_host = _val("max_idle_connections_per_host")
2645
+ opts.max_connections_per_host = _val("max_connections_per_host")
2646
+ opts.disable_keep_alives = _val("disable_keep_alives", True)
2647
+ opts.disable_compression = _val("disable_compression", True)
2648
+ opts.idle_conn_timeout_seconds = _val("idle_conn_timeout_seconds")
2649
+ opts.max_response_header_bytes = _val("max_response_header_bytes")
2650
+ opts.write_buffer_size = _val("write_buffer_size")
2651
+ opts.read_buffer_size = _val("read_buffer_size")
2652
+ opts.allow_empty_cookies = _val("allow_empty_cookies", True)
2653
+ opts.without_cookie_jar = _val("without_cookie_jar", True)
2654
+ opts.disable_http3 = _val("disable_http3", True)
2655
+ opts.disable_ipv4 = _val("disable_ipv4", True)
2656
+ opts.disable_ipv6 = _val("disable_ipv6", True)
2657
+ opts.catch_panics = _val("catch_panics", True)
2658
+ opts.with_debug = _val("with_debug", True)
2659
+
2660
+ # String fields
2661
+ for name, field in [
2662
+ ("client_identifier", "client_identifier"),
2663
+ ("proxy", "proxy"),
2664
+ ("server_name_overwrite", "server_name_overwrite"),
2665
+ ("request_host_override", "request_host_override"),
2666
+ ("local_address", "local_address"),
2667
+ ]:
2668
+ c_val = _c_string(ffi, _val(name))
2669
+ setattr(opts, field, c_val)
2670
+ if c_val != ffi.NULL:
2671
+ keep_alive.append(c_val)
2672
+
2673
+ # Pseudo-header orders
2674
+ pho = _val("pseudo_header_order")
2675
+ ph_ptr, ph_len = _build_string_array(ffi, pho, keep_alive)
2676
+ opts.pseudo_header_order = ph_ptr
2677
+ opts.pseudo_header_order_len = ph_len
2678
+
2679
+ h3pho = _val("h3_pseudo_header_order")
2680
+ h3ph_ptr, h3ph_len = _build_string_array(ffi, h3pho, keep_alive)
2681
+ opts.h3_pseudo_header_order = h3ph_ptr
2682
+ opts.h3_pseudo_header_order_len = h3ph_len
2683
+
2684
+ # Default/connect headers
2685
+ dh = _val("default_headers")
2686
+ dh_ptr, dh_len = _build_headers(ffi, dh, keep_alive)
2687
+ opts.default_headers = dh_ptr
2688
+ opts.default_headers_len = dh_len
2689
+
2690
+ ch = _val("connect_headers")
2691
+ ch_ptr, ch_len = _build_headers(ffi, ch, keep_alive)
2692
+ opts.connect_headers = ch_ptr
2693
+ opts.connect_headers_len = ch_len
2694
+
2695
+ # Certificate pinning
2696
+ cp = _val("certificate_pinning_hosts")
2697
+ cp_ptr, cp_len = _build_pin_entries(ffi, cp, keep_alive)
2698
+ opts.certificate_pinning_hosts = cp_ptr
2699
+ opts.certificate_pinning_hosts_len = cp_len
2700
+ opts.with_default_bad_pin_handler = _val("with_default_bad_pin_handler", True)
2701
+
2702
+ # Request cookies
2703
+ rc = _val("request_cookies")
2704
+ rc_ptr, rc_len = _build_headers(ffi, rc, keep_alive)
2705
+ opts.request_cookies = rc_ptr
2706
+ opts.request_cookies_len = rc_len
2707
+
2708
+ # Client certificates
2709
+ cc = _val("client_certificates")
2710
+ cc_ptr, cc_len = _build_client_certificates(ffi, cc, keep_alive)
2711
+ opts.client_certificates = cc_ptr
2712
+ opts.client_certificates_len = cc_len
2713
+
2714
+ # Custom TLS client
2715
+ ctc = _val("custom_tls_client")
2716
+ ctc_ptr = _build_custom_tls_client(ffi, ctc, keep_alive)
2717
+ opts.custom_tls_client = ctc_ptr
2718
+
2719
+ # Pre-compute cache key hash and attach to opts (avoids ~50 CGO calls on hit).
2720
+ # Use kwargs.get() (non-destructive) so later _val() calls still find overrides.
2721
+ def _ck(name): return kwargs.get(name, self._session.defaults.get(name))
2722
+ def _ckb(name): v = kwargs.get(name, self._session.defaults.get(name)); return 1 if v else 0
2723
+ ck_hash = _compute_cache_key_hash({
2724
+ "client_identifier": _ck("client_identifier") or "",
2725
+ "proxy": _ck("proxy") or "",
2726
+ "server_name_overwrite": _ck("server_name_overwrite") or "",
2727
+ "local_address": _ck("local_address") or "",
2728
+ "insecure_skip_verify": _ckb("insecure_skip_verify"),
2729
+ "force_http1": _ckb("force_http1"),
2730
+ "with_random_tls_extension_order": _ckb("with_random_tls_extension_order"),
2731
+ "with_protocol_racing": _ckb("with_protocol_racing"),
2732
+ "max_idle_connections": _ck("max_idle_connections"),
2733
+ "max_idle_connections_per_host": _ck("max_idle_connections_per_host"),
2734
+ "max_connections_per_host": _ck("max_connections_per_host"),
2735
+ "max_response_header_bytes": _ck("max_response_header_bytes"),
2736
+ "write_buffer_size": _ck("write_buffer_size"),
2737
+ "read_buffer_size": _ck("read_buffer_size"),
2738
+ "idle_conn_timeout_seconds": _ck("idle_conn_timeout_seconds"),
2739
+ "disable_keep_alives": _ckb("disable_keep_alives"),
2740
+ "disable_compression": _ckb("disable_compression"),
2741
+ "disable_http3": _ckb("disable_http3"),
2742
+ "disable_ipv4": _ckb("disable_ipv4"),
2743
+ "disable_ipv6": _ckb("disable_ipv6"),
2744
+ "follow_redirects": _ckb("follow_redirects"),
2745
+ "without_cookie_jar": _ckb("without_cookie_jar"),
2746
+ "allow_empty_cookies": _ckb("allow_empty_cookies"),
2747
+ "with_default_bad_pin_handler": _ckb("with_default_bad_pin_handler"),
2748
+ "timeout_seconds": _ck("timeout_seconds"),
2749
+ "timeout_milliseconds": _ck("timeout_milliseconds"),
2750
+ "pseudo_header_order": _ck("pseudo_header_order"),
2751
+ "h3_pseudo_header_order": _ck("h3_pseudo_header_order"),
2752
+ "default_headers": _ck("default_headers"),
2753
+ "connect_headers": _ck("connect_headers"),
2754
+ "certificate_pinning_hosts": _ck("certificate_pinning_hosts"),
2755
+ "client_certificates": _ck("client_certificates"),
2756
+ "custom_tls_client": _ck("custom_tls_client"),
2757
+ })
2758
+ c_ck = _c_string(ffi, ck_hash)
2759
+ if c_ck != ffi.NULL:
2760
+ keep_alive.append(c_ck)
2761
+ opts.cache_key_hash = c_ck
2762
+
2763
+ # ---- streaming fields (injected by stream_to_file) -----------------
2764
+ stream_path = kwargs.pop("_stream_output_path", ffi.NULL)
2765
+ stream_bs = kwargs.pop("_stream_output_block_size", 0)
2766
+ stream_eof = kwargs.pop("_stream_output_eof_symbol", ffi.NULL)
2767
+ stream_keep = kwargs.pop("_stream_keep_alive", None)
2768
+ if stream_keep is not None:
2769
+ keep_alive.extend(stream_keep)
2770
+ opts.stream_output_path = stream_path
2771
+ opts.stream_output_block_size = stream_bs
2772
+ opts.stream_output_eof_symbol = stream_eof
2773
+
2774
+ # ── Register Future with defensive timeout ────────────────────────
2775
+ # Go's RequestAsync has its own timeout (timeout_seconds / timeout_milliseconds),
2776
+ # but if the Go goroutine hangs indefinitely (network partition, OS bug),
2777
+ # the _pending_requests entry would leak the Future + keep_alive forever.
2778
+ # A defensive timeout (2× Go timeout + 10 s grace, clamped [60, 600] s)
2779
+ # cleans up zombie entries so the Python process does not accumulate
2780
+ # leaked memory under high-concurrency workloads.
2781
+ go_timeout = float(opts.timeout_seconds) if opts.timeout_seconds > 0 else 30.0
2782
+ if opts.timeout_milliseconds > 0:
2783
+ go_timeout = float(opts.timeout_milliseconds) / 1000.0
2784
+ safe_timeout = max(60.0, min(go_timeout * 2.0 + 10.0, 600.0))
2785
+
2786
+ def _on_zombie_timeout(rid: int) -> None:
2787
+ # Safe: by this point the Go goroutine has either completed
2788
+ # (callback fired) or is hung. If completed, _pending_requests
2789
+ # already popped and we return early. If hung, the goroutine
2790
+ # owns its own body copy (deepCopyRequestOptions copies via
2791
+ # C.GoBytes — Bug #5 fix), so releasing keep_alive is safe.
2792
+ with _pending_lock:
2793
+ entry = _pending_requests.pop(rid, None)
2794
+ if entry is None:
2795
+ return # already resolved via callback
2796
+ fut, _ka, _ = entry
2797
+ if not fut.done():
2798
+ try:
2799
+ fut.get_loop().call_soon_threadsafe(
2800
+ fut.set_exception,
2801
+ asyncio.TimeoutError(
2802
+ f"Async request {rid} did not complete within "
2803
+ f"{safe_timeout:.0f}s — Go goroutine may be hung"
2804
+ ),
2805
+ )
2806
+ except RuntimeError:
2807
+ # Event loop closed — nothing can be done (graceful shutdown).
2808
+ pass
2809
+
2810
+ request_id = _next_request_id()
2811
+ future: asyncio.Future = loop.create_future()
2812
+ timeout_handle = loop.call_later(safe_timeout, _on_zombie_timeout, request_id)
2813
+
2814
+ with _pending_lock:
2815
+ # Store keep_alive alongside the Future — the goroutine reads
2816
+ # from C memory via unsafe.Slice, so Python must keep the
2817
+ # original buffers alive until the callback fires.
2818
+ _pending_requests[request_id] = (future, keep_alive, timeout_handle)
2819
+
2820
+ # Step 1-2: Call RequestAsync — Go deep-copies, dispatches goroutine,
2821
+ # returns immediately. Python can free keep_alive memory after return.
2822
+ ret = lib.RequestAsync(opts, request_id, callback)
2823
+
2824
+ if ret != 0:
2825
+ # RequestAsync returned an error — clean up the pending entry
2826
+ # and cancel the defensive zombie timeout. keep_alive is
2827
+ # already safe to release because RequestAsync deep-copies
2828
+ # before returning.
2829
+ with _pending_lock:
2830
+ entry = _pending_requests.pop(request_id, None)
2831
+ if entry is not None:
2832
+ _, _, th = entry
2833
+ th.cancel()
2834
+ raise RuntimeError("RequestAsync failed — opts or callback is nil")
2835
+
2836
+ # Await the Future — event loop is free to run other tasks
2837
+ return await future
2838
+
2839
+ async def stream_to_file(
2840
+ self,
2841
+ # HTTP 方法 / HTTP method
2842
+ method: str,
2843
+ # 请求 URL / Request URL
2844
+ url: str,
2845
+ # 输出文件路径 / Output file path
2846
+ output_path: str,
2847
+ *,
2848
+ # 请求头字典 / Request headers dict
2849
+ headers: Optional[Dict[str, str]] = None,
2850
+ # 请求头发送顺序 / Header send order
2851
+ header_order: Optional[List[str]] = None,
2852
+ # 请求体原始字节串 / Request body as raw bytes
2853
+ body: Optional[bytes] = None,
2854
+ # 块大小(字节) / Chunk size per read (bytes)
2855
+ chunk_size: int = 8192,
2856
+ # 可选的 EOF 标记字符串 / Optional EOF marker string
2857
+ eof_marker: Optional[str] = None,
2858
+ **kwargs: Any,
2859
+ ) -> Response:
2860
+ """执行请求并将响应体流式写入磁盘(异步)。
2861
+
2862
+ Execute a request and stream the response body to disk (async).
2863
+ """
2864
+ ffi, _ = _get_ffi()
2865
+
2866
+ keep_alive: list = []
2867
+ c_path = _c_string(ffi, output_path)
2868
+ keep_alive.append(c_path)
2869
+
2870
+ c_eof = _c_string(ffi, eof_marker)
2871
+ if c_eof != ffi.NULL:
2872
+ keep_alive.append(c_eof)
2873
+
2874
+ return await self._execute_async(
2875
+ method,
2876
+ url,
2877
+ headers=headers,
2878
+ header_order=header_order,
2879
+ body=body,
2880
+ _stream_output_path=c_path,
2881
+ _stream_output_block_size=chunk_size,
2882
+ _stream_output_eof_symbol=c_eof,
2883
+ _stream_keep_alive=keep_alive,
2884
+ **kwargs,
2885
+ )
2886
+
2887
+ async def execute_request(
2888
+ self,
2889
+ # HTTP 方法 / HTTP method
2890
+ method: str,
2891
+ # 完整的请求 URL / Full request URL including scheme and hostname
2892
+ url: str,
2893
+ *,
2894
+ # 请求头字典 / Request headers dict
2895
+ headers: Optional[Dict[str, str]] = None,
2896
+ # 请求头的发送顺序列表 / Header send-order list
2897
+ header_order: Optional[List[str]] = None,
2898
+ # 请求体原始字节串 / Request body as raw bytes
2899
+ body: Optional[bytes] = None,
2900
+ # ── 每请求覆盖参数 / Per-request overrides ──
2901
+ # 覆盖 TLS 指纹标识 / Override TLS fingerprint identifier
2902
+ client_identifier: Optional[str] = None,
2903
+ # 覆盖超时时间(秒) / Override timeout (seconds)
2904
+ timeout: Optional[int] = None,
2905
+ # 覆盖超时时间(毫秒) / Override timeout (milliseconds)
2906
+ timeout_milliseconds: Optional[int] = None,
2907
+ # 覆盖重定向跟随策略 / Override redirect-following policy
2908
+ follow_redirects: Optional[bool] = None,
2909
+ # 覆盖 TLS 证书校验 / Override TLS certificate verification
2910
+ verify: Optional[bool] = None,
2911
+ # 覆盖 HTTP/1.1 强制开关 / Override force HTTP/1.1
2912
+ force_http1: Optional[bool] = None,
2913
+ # 覆盖 TLS 扩展随机化 / Override TLS extension randomisation
2914
+ random_tls_extension_order: Optional[bool] = None,
2915
+ # 覆盖协议竞速开关 / Override protocol racing
2916
+ with_protocol_racing: Optional[bool] = None,
2917
+ # 覆盖 SNI 主机名 / Override SNI hostname
2918
+ server_name_overwrite: Optional[str] = None,
2919
+ # 覆盖 HTTP Host 请求头 / Override HTTP Host header
2920
+ request_host_override: Optional[str] = None,
2921
+ # 覆盖代理 URL / Override proxy URL
2922
+ proxy: Optional[str] = None,
2923
+ # 覆盖本地绑定地址 / Override local bind address
2924
+ local_address: Optional[str] = None,
2925
+ # 覆盖 HTTP/2 伪头顺序 / Override HTTP/2 pseudo-header order
2926
+ pseudo_header_order: Optional[List[str]] = None,
2927
+ # 覆盖 HTTP/3 伪头顺序 / Override HTTP/3 pseudo-header order
2928
+ h3_pseudo_header_order: Optional[List[str]] = None,
2929
+ # 覆盖默认请求头字典 / Override default headers dict
2930
+ default_headers: Optional[Dict[str, str]] = None,
2931
+ # 覆盖代理 CONNECT 隧道请求头 / Override proxy CONNECT tunnel headers
2932
+ connect_headers: Optional[Dict[str, str]] = None,
2933
+ # 覆盖 SSL 证书固定字典 / Override SSL certificate pinning dict
2934
+ certificate_pinning_hosts: Optional[Dict[str, List[str]]] = None,
2935
+ # 覆盖 Bad-Pin 处理器开关 / Override default bad-pin handler toggle
2936
+ with_default_bad_pin_handler: Optional[bool] = None,
2937
+ # 覆盖预置 Cookie 字典 / Override pre-populated cookie dict
2938
+ request_cookies: Optional[Dict[str, str]] = None,
2939
+ # 覆盖客户端证书列表 / Override client certificate list
2940
+ client_certificates: Optional[List[Dict[str, bytes]]] = None,
2941
+ # 覆盖自定义 TLS 客户端配置 / Override custom TLS client configuration
2942
+ custom_tls_client: Optional[Dict[str, Any]] = None,
2943
+ # 覆盖全局最大空闲连接数 / Override global max idle connections
2944
+ max_idle_connections: Optional[int] = None,
2945
+ # 覆盖每 Host 最大空闲连接数 / Override max idle connections per host
2946
+ max_idle_connections_per_host: Optional[int] = None,
2947
+ # 覆盖每 Host 最大总连接数 / Override max total connections per host
2948
+ max_connections_per_host: Optional[int] = None,
2949
+ # 覆盖 Keep-Alive 禁用 / Override disable Keep-Alive
2950
+ disable_keep_alives: Optional[bool] = None,
2951
+ # 覆盖压缩禁用 / Override disable compression
2952
+ disable_compression: Optional[bool] = None,
2953
+ # 覆盖空闲连接超时 / Override idle connection timeout
2954
+ idle_conn_timeout_seconds: Optional[int] = None,
2955
+ # 覆盖响应头最大字节数 / Override max response header bytes
2956
+ max_response_header_bytes: Optional[int] = None,
2957
+ # 覆盖写缓冲区大小 / Override write buffer size
2958
+ write_buffer_size: Optional[int] = None,
2959
+ # 覆盖读缓冲区大小 / Override read buffer size
2960
+ read_buffer_size: Optional[int] = None,
2961
+ # 覆盖空 Cookie 允许 / Override allow-empty-cookies
2962
+ allow_empty_cookies: Optional[bool] = None,
2963
+ # 覆盖禁用 Cookie Jar / Override disable Cookie Jar
2964
+ without_cookie_jar: Optional[bool] = None,
2965
+ # 覆盖 HTTP/3 禁用 / Override disable HTTP/3
2966
+ disable_http3: Optional[bool] = None,
2967
+ # 覆盖 IPv4 禁用 / Override disable IPv4
2968
+ disable_ipv4: Optional[bool] = None,
2969
+ # 覆盖 IPv6 禁用 / Override disable IPv6
2970
+ disable_ipv6: Optional[bool] = None,
2971
+ # 覆盖 panic 捕获 / Override catch-panics
2972
+ catch_panics: Optional[bool] = None,
2973
+ # 覆盖调试日志 / Override debug logging
2974
+ with_debug: Optional[bool] = None,
2975
+ **kwargs: Any,
2976
+ ) -> Response:
2977
+ """通过 Go 引擎执行单次 HTTP 请求(异步)。
2978
+
2979
+ Execute a single HTTP request through the Go engine (async).
2980
+ """
2981
+ # Remap user-facing names → defaults-dict keys where they differ.
2982
+ # timeout → timeout_seconds
2983
+ # verify → insecure_skip_verify (inverted: True→0, False→1)
2984
+ # random_tls_extension_order → with_random_tls_extension_order
2985
+ return await self._execute_async(
2986
+ method, url,
2987
+ headers=headers, header_order=header_order, body=body,
2988
+ timeout_seconds=timeout,
2989
+ insecure_skip_verify=None if verify is None else (0 if verify else 1),
2990
+ with_random_tls_extension_order=random_tls_extension_order,
2991
+ client_identifier=client_identifier,
2992
+ timeout_milliseconds=timeout_milliseconds, follow_redirects=follow_redirects,
2993
+ force_http1=force_http1,
2994
+ with_protocol_racing=with_protocol_racing,
2995
+ server_name_overwrite=server_name_overwrite,
2996
+ request_host_override=request_host_override, proxy=proxy,
2997
+ local_address=local_address, pseudo_header_order=pseudo_header_order,
2998
+ h3_pseudo_header_order=h3_pseudo_header_order,
2999
+ default_headers=default_headers, connect_headers=connect_headers,
3000
+ certificate_pinning_hosts=certificate_pinning_hosts,
3001
+ with_default_bad_pin_handler=with_default_bad_pin_handler,
3002
+ request_cookies=request_cookies, client_certificates=client_certificates,
3003
+ custom_tls_client=custom_tls_client,
3004
+ max_idle_connections=max_idle_connections,
3005
+ max_idle_connections_per_host=max_idle_connections_per_host,
3006
+ max_connections_per_host=max_connections_per_host,
3007
+ disable_keep_alives=disable_keep_alives,
3008
+ disable_compression=disable_compression,
3009
+ idle_conn_timeout_seconds=idle_conn_timeout_seconds,
3010
+ max_response_header_bytes=max_response_header_bytes,
3011
+ write_buffer_size=write_buffer_size, read_buffer_size=read_buffer_size,
3012
+ allow_empty_cookies=allow_empty_cookies,
3013
+ without_cookie_jar=without_cookie_jar,
3014
+ disable_http3=disable_http3, disable_ipv4=disable_ipv4,
3015
+ disable_ipv6=disable_ipv6, catch_panics=catch_panics,
3016
+ with_debug=with_debug,
3017
+ **kwargs,
3018
+ )
3019
+
3020
+ async def typed_request(self, req: Request) -> Response:
3021
+ """使用 :class:`Request` 强类型对象执行 HTTP 请求(异步)。
3022
+
3023
+ Execute an HTTP request using a :class:`Request` strongly-typed object (async).
3024
+ """
3025
+ method = req["method"]
3026
+ url = req["url"]
3027
+ kwargs = {k: v for k, v in req.items() if k not in ("method", "url")}
3028
+ return await self.execute_request(method, url, **kwargs)
3029
+
3030
+ async def get(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
3031
+ return await self.execute_request("GET", url, headers=headers, **kwargs)
3032
+
3033
+ async def post(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
3034
+ return await self.execute_request("POST", url, headers=headers, body=body, **kwargs)
3035
+
3036
+ async def head(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
3037
+ return await self.execute_request("HEAD", url, headers=headers, **kwargs)
3038
+
3039
+ async def put(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
3040
+ return await self.execute_request("PUT", url, headers=headers, body=body, **kwargs)
3041
+
3042
+ async def delete(self, url: str, *, headers: Optional[Dict[str, str]] = None, **kwargs: Any) -> Response:
3043
+ return await self.execute_request("DELETE", url, headers=headers, **kwargs)
3044
+
3045
+ async def patch(self, url: str, *, headers: Optional[Dict[str, str]] = None, body: Optional[bytes] = None, **kwargs: Any) -> Response:
3046
+ return await self.execute_request("PATCH", url, headers=headers, body=body, **kwargs)
3047
+
3048
+ @staticmethod
3049
+ def clear_client_pool() -> None:
3050
+ """Close all idle connections in the global Go client pool.
3051
+
3052
+ Calls the Go C function directly. ClearClientPool iterates the
3053
+ internal client map and closes idle connections — it is fast and
3054
+ non-blocking, so no thread pool is needed (Constraint 4).
3055
+ """
3056
+ _, lib = _get_ffi()
3057
+ lib.ClearClientPool()
3058
+
3059
+
3060
+ # Convenience top-level function
3061
+ def clear_client_pool() -> None:
3062
+ """Close all idle connections in the global Go client pool (synchronous)."""
3063
+ Session.clear_client_pool()