去除 import t, c 以及 FL

This commit is contained in:
TermiNexus committed 2026-10-17 21:58:05 +08:00
1 parent 7556264d22
commit 7a329f7d1e
1674 files changed
+1227 -560449

No files matched your search

+96 -98
View File
@@ -1,5 +1,3 @@
import t, c
from stdint import *
import string
import socket
import stdio
@@ -34,23 +32,23 @@ define HTTPS_PORT = 443
# Module-internal state
_ossl_ready: bool = False
_socket_ready: bool = False
_err_store: t.CArray[char, 512] # last failure reason (static buffer)
_info_store: t.CArray[char, 512] # TLS metadata of last successful handshake
_scratch_store: t.CArray[char, 512] # scratch concat buffer
_last_verify_val: INT = -1 # last SSL_get_verify_result (0=ok; -1=disabled)
_last_verify_flag: INT = -1 # last request verify flag (1=on; 0=off; -1=unknown)
_err_store: [512]char # last failure reason (static buffer)
_info_store: [512]char # TLS metadata of last successful handshake
_scratch_store: [512]char # scratch concat buffer
_last_verify_val: int = -1 # last SSL_get_verify_result (0=ok; -1=disabled)
_last_verify_flag: int = -1 # last request verify flag (1=on; 0=off; -1=unknown)
# ============================================================
# SSE streaming receive area (post_stream only; single request, polled by UI thread).
# _st_len written bytes; _st_consumed consumed cursor; _st_state 0=running 1=done(2xx) 2=fail; _st_status HTTP code.
# ============================================================
define STREAM_CAP = 262144
_st_buf: t.CArray[char, 262144]
_st_buf: [STREAM_CAP]char
_st_len: sizet = 0
_st_consumed: sizet = 0
_st_state: INT = 0
_st_status: INT = 0
_st_err: t.CArray[char, 512]
_st_state: int = 0
_st_status: int = 0
_st_err: [512]char
def stream_begin():
@@ -63,14 +61,14 @@ def stream_begin():
_st_err[0] = 0
def stream_pull(out: str, cap: INT) -> INT:
def stream_pull(out: str, cap: int) -> int:
"""Copy unconsumed delta into out (NUL-terminated); return bytes copied."""
global _st_consumed
if out is None or cap <= 1:
return 0
avail: INT = 0
avail: int = 0
if _st_len > _st_consumed:
avail = INT(_st_len - _st_consumed)
avail = int(_st_len - _st_consumed)
if avail > cap - 1:
avail = cap - 1
for i in range(int(sizet(avail))):
@@ -80,12 +78,12 @@ def stream_pull(out: str, cap: INT) -> INT:
return avail
def stream_state() -> INT:
def stream_state() -> int:
"""0=running 1=done(2xx) 2=failed."""
return _st_state
def stream_status() -> INT:
def stream_status() -> int:
"""HTTP status code; negative means network/parse error."""
return _st_status
@@ -106,7 +104,7 @@ def last_verify_enabled() -> int:
# ============================================================
# Internal helpers
# internal helpers
# ============================================================
def last_error() -> str:
@@ -133,7 +131,7 @@ def _RecordInfoText(text: str):
stdio.snprintf(_info_store, 512, "%s", text)
def _EnsureReady() -> INT:
def _EnsureReady() -> int:
"""Initialize socket and openssl (both idempotent)."""
global _socket_ready, _ossl_ready
if not _socket_ready:
@@ -149,7 +147,7 @@ def _EnsureReady() -> INT:
return 0
def _ParseHttpsUrl(url: str, host_buf: str, host_size: INT, path_buf: str, path_size: INT, port: INT*) -> INT:
def _ParseHttpsUrl(url: str, host_buf: str, host_size: int, path_buf: str, path_size: int, port: int*) -> int:
"""Parse https://host[:port][/path]; default port 443."""
if url is None: return -1
if host_buf is None or path_buf is None or port is None: return -1
@@ -162,7 +160,7 @@ def _ParseHttpsUrl(url: str, host_buf: str, host_size: INT, path_buf: str, path_
# Parse host
host_start: str = p
host_len: INT = 0
host_len: int = 0
while p[0] != '\0' and p[0] != ':' and p[0] != '/':
host_len += 1
p += 1
@@ -174,18 +172,18 @@ def _ParseHttpsUrl(url: str, host_buf: str, host_size: INT, path_buf: str, path_
# Parse port
if p[0] == ':':
p += 1
port_val: INT = 0
port_val: int = 0
while p[0] >= '0' and p[0] <= '9':
port_val = port_val * 10 + INT(p[0] - '0')
port_val = port_val * 10 + int(p[0] - '0')
p += 1
c.DerefAs(port, port_val)
*port = port_val
else:
c.DerefAs(port, HTTPS_PORT)
*port = HTTPS_PORT
# Parse path
if p[0] == '/':
path_start: str = p
path_len: INT = 0
path_len: int = 0
while p[0] != '\0':
path_len += 1
p += 1
@@ -242,9 +240,9 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
return None
# ---- Parse URL ----
host_buf: t.CArray[char, 256]
path_buf: t.CArray[char, 1024]
port: INT = 0
host_buf: [256]char
path_buf: [1024]char
port: int = 0
if _ParseHttpsUrl(url, host_buf, 256, path_buf, 1024, &port) != 0:
stdio.snprintf(errmsg, 512, "bad https url: %s", url)
@@ -313,9 +311,9 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
openssl.SSL_set1_host(ssl, host_buf)
# ---- Handshake ----
hret: INT = openssl.SSL_connect(ssl)
hret: int = openssl.SSL_connect(ssl)
if hret <= 0:
want: INT = openssl.SSL_get_error(ssl, hret)
want: int = openssl.SSL_get_error(ssl, hret)
_TlsErrText()
stdio.snprintf(errmsg, 512, "SSL_connect failed (want=%d): %s", want, _ScratchBuf())
_RecordErrorText(errmsg)
@@ -328,7 +326,7 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
# ---- Record last cert verify result (for last_verify_result) ----
if verify:
_last_verify_val = INT(openssl.SSL_get_verify_result(ssl))
_last_verify_val = int(openssl.SSL_get_verify_result(ssl))
else:
_last_verify_val = -1
@@ -338,9 +336,9 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
if vres != 0:
reason: str = openssl.X509_verify_cert_error_string(vres)
if reason is None:
stdio.snprintf(errmsg, 512, "SSL certificate verify failed: error %d", INT(vres))
stdio.snprintf(errmsg, 512, "SSL certificate verify failed: error %d", int(vres))
else:
stdio.snprintf(errmsg, 512, "SSL certificate verify failed (%d): %s", INT(vres), reason)
stdio.snprintf(errmsg, 512, "SSL certificate verify failed (%d): %s", int(vres), reason)
_RecordErrorText(errmsg)
openssl.SSL_free(ssl)
openssl.SSL_CTX_free(ctx)
@@ -382,19 +380,19 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
requests.release(resp)
return None
body_len: INT = 0
body_len: int = 0
is_post: bool = string.strcmp(method, "POST") == 0
if is_post:
body_len = INT(string.strlen(data)) if data is not None else 0
body_len = int(string.strlen(data)) if data is not None else 0
ct: str = content_type if content_type is not None else "application/x-www-form-urlencoded"
# Build header in stages so Authorization can be inserted on demand (only when auth non-empty).
hdr_off: INT = 0
hdr_cap: INT = requests.HTTP_BUFSIZ
hdr_off: int = 0
hdr_cap: int = requests.HTTP_BUFSIZ
stdio.snprintf(req_buf, hdr_cap, "POST %s HTTP/1.1\r\nHost: %s\r\n", path_buf, host_buf)
hdr_off = INT(string.strlen(req_buf))
hdr_off = int(string.strlen(req_buf))
if auth is not None and auth[0] != 0:
stdio.snprintf(req_buf + hdr_off, hdr_cap - hdr_off, "Authorization: %s\r\n", auth)
hdr_off = INT(string.strlen(req_buf))
hdr_off = int(string.strlen(req_buf))
stdio.snprintf(req_buf + hdr_off, hdr_cap - hdr_off,
"Content-Type: %s\r\nContent-Length: %d\r\nAccept-Encoding: gzip\r\nConnection: close\r\n\r\n",
ct, body_len)
@@ -403,8 +401,8 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
"GET %s HTTP/1.1\r\nHost: %s\r\nAccept-Encoding: gzip\r\nConnection: close\r\n\r\n",
path_buf, host_buf)
hdr_len: INT = INT(string.strlen(req_buf))
sent: INT = openssl.SSL_write(ssl, req_buf, hdr_len)
hdr_len: int = int(string.strlen(req_buf))
sent: int = openssl.SSL_write(ssl, req_buf, hdr_len)
if sent <= 0:
_TlsErrText()
stdio.snprintf(errmsg, 512, "SSL_write header failed: %s", _ScratchBuf())
@@ -423,7 +421,7 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
requests._mbuddy.free(req_buf)
# ---- Receive response (buffer auto-doubles, supports MB bodies) ----
resp_cap: INT = requests.HTTP_BUFSIZ
resp_cap: int = requests.HTTP_BUFSIZ
resp_buf: str = requests._mbuddy.alloc(sizet(resp_cap))
if resp_buf is None:
_RecordErrorText("alloc response buffer failed")
@@ -434,15 +432,15 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
requests.release(resp)
return None
total: INT = 0
total: int = 0
while True:
room: INT = resp_cap - 1 - total
room: int = resp_cap - 1 - total
if room <= 0:
# Buffer full but more data may follow: double capacity (hard cap 256MB, runaway-guard).
if resp_cap >= 268435456:
break
resp_cap = resp_cap * 2
nb: t.CPtr = requests._mbuddy.realloc(resp_buf, sizet(resp_cap))
nb: rawptr = requests._mbuddy.realloc(resp_buf, sizet(resp_cap))
if nb is None:
_RecordErrorText("realloc response buffer failed")
requests._mbuddy.free(resp_buf)
@@ -452,9 +450,9 @@ def _HttpsRequest(method: str, url: str, verify: bool, ca_file: str, data: str,
requests._mbuddy.free(errmsg)
requests.release(resp)
return None
resp_buf = char(uint64(nb), t.CPtr)
resp_buf = bytes(uint64(nb))
room = resp_cap - 1 - total
n: INT = openssl.SSL_read(ssl, resp_buf + total, room)
n: int = openssl.SSL_read(ssl, resp_buf + total, room)
if n <= 0:
break
total += n
@@ -486,7 +484,7 @@ def _HttpsRedirectLoop(method: str, url: str, verify: bool, ca_file: str, data:
cur: str = requests._mbuddy.alloc(2048)
if cur is None: return None
if INT(string.strlen(url)) >= 2047:
if int(string.strlen(url)) >= 2047:
_RecordErrorText("url too long")
requests._mbuddy.free(cur)
return None
@@ -498,7 +496,7 @@ def _HttpsRedirectLoop(method: str, url: str, verify: bool, ca_file: str, data:
requests._mbuddy.free(cur)
return None
code: INT = resp.status_code
code: int = resp.status_code
if not (code >= 300 and code < 400):
requests._mbuddy.free(cur)
return resp
@@ -598,7 +596,7 @@ def _StreamAppendContent(txt: str):
_st_len = pos
def _SetStreamFail(rc: INT):
def _SetStreamFail(rc: int):
"""Finish stream failure: copy reason from _err_store and set state."""
global _st_state, _st_status
_st_state = 2
@@ -607,7 +605,7 @@ def _SetStreamFail(rc: INT):
def post_stream(url: str, data: str, content_type: str = "application/json",
verify: bool = True, ca_file: str = None, auth: str = None) -> INT:
verify: bool = True, ca_file: str = None, auth: str = None) -> int:
"""SSE streaming POST (blocking; call from a background thread). data must be a JSON body
containing "stream":true. Returns HTTP status; negative means network/parse failure.
"""
@@ -628,9 +626,9 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
if errmsg is None:
return -1
host_buf: t.CArray[char, 256]
path_buf: t.CArray[char, 1024]
port: INT = 0
host_buf: [256]char
path_buf: [1024]char
port: int = 0
if _ParseHttpsUrl(url, host_buf, 256, path_buf, 1024, &port) != 0:
stdio.snprintf(errmsg, 512, "bad https url: %s", url)
_RecordErrorText(errmsg)
@@ -691,9 +689,9 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
if verify:
openssl.SSL_set1_host(ssl, host_buf)
hret: INT = openssl.SSL_connect(ssl)
hret: int = openssl.SSL_connect(ssl)
if hret <= 0:
want: INT = openssl.SSL_get_error(ssl, hret)
want: int = openssl.SSL_get_error(ssl, hret)
_TlsErrText()
stdio.snprintf(errmsg, 512, "SSL_connect failed (want=%d): %s", want, _ScratchBuf())
_RecordErrorText(errmsg)
@@ -709,9 +707,9 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
if vres != 0:
reason: str = openssl.X509_verify_cert_error_string(vres)
if reason is None:
stdio.snprintf(errmsg, 512, "SSL certificate verify failed: error %d", INT(vres))
stdio.snprintf(errmsg, 512, "SSL certificate verify failed: error %d", int(vres))
else:
stdio.snprintf(errmsg, 512, "SSL certificate verify failed (%d): %s", INT(vres), reason)
stdio.snprintf(errmsg, 512, "SSL certificate verify failed (%d): %s", int(vres), reason)
_RecordErrorText(errmsg)
_SetStreamFail(-1)
openssl.SSL_free(ssl)
@@ -731,20 +729,20 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
requests._mbuddy.free(errmsg)
return -1
body_len: INT = INT(string.strlen(data)) if data is not None else 0
body_len: int = int(string.strlen(data)) if data is not None else 0
ct: str = content_type if content_type is not None else "application/json"
hdr_off: INT = 0
hdr_off: int = 0
stdio.snprintf(req_buf, requests.HTTP_BUFSIZ, "POST %s HTTP/1.1\r\nHost: %s\r\n", path_buf, host_buf)
hdr_off = INT(string.strlen(req_buf))
hdr_off = int(string.strlen(req_buf))
if auth is not None and auth[0] != 0:
stdio.snprintf(req_buf + hdr_off, requests.HTTP_BUFSIZ - hdr_off, "Authorization: %s\r\n", auth)
hdr_off = INT(string.strlen(req_buf))
hdr_off = int(string.strlen(req_buf))
stdio.snprintf(req_buf + hdr_off, requests.HTTP_BUFSIZ - hdr_off,
"Content-Type: %s\r\nContent-Length: %d\r\nAccept: text/event-stream\r\nConnection: close\r\n\r\n",
ct, body_len)
hdr_len: INT = INT(string.strlen(req_buf))
sent: INT = openssl.SSL_write(ssl, req_buf, hdr_len)
hdr_len: int = int(string.strlen(req_buf))
sent: int = openssl.SSL_write(ssl, req_buf, hdr_len)
if sent <= 0:
_TlsErrText()
stdio.snprintf(errmsg, 512, "SSL_write header failed: %s", _ScratchBuf())
@@ -784,19 +782,19 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
return -1
jpool: memhub.MemPool* = memhub.MemPool(pmem, 524288)
leftover: t.CArray[char, 16384]
llen: INT = 0
header_done: INT = 0
status_code: INT = 0
had_read: INT = 0
leftover: [16384]char
llen: int = 0
header_done: int = 0
status_code: int = 0
had_read: int = 0
while True:
n: INT = openssl.SSL_read(ssl, rd, 16384)
n: int = openssl.SSL_read(ssl, rd, 16384)
if n <= 0:
break
had_read = 1
# 1) Append to leftover
ai: INT = 0
ai: int = 0
while ai < n and llen < 16383:
leftover[llen] = rd[ai]
llen += 1
@@ -804,14 +802,14 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
# 2) Process line by line
while True:
# Find line end \n
nl: INT = -1
nl: int = -1
for k in range(int(llen)):
if leftover[k] == 10:
nl = k
break
if nl < 0:
break
e: INT = nl
e: int = nl
if e > 0 and leftover[e - 1] == 13:
e -= 1
leftover[e] = 0
@@ -819,14 +817,14 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
if header_done == 0:
if string.strncmp(line, "HTTP/", 5) == 0:
# Status code: HTTP/1.1 200 OK
sp: INT = 0
sp: int = 0
while line[sp] != 0 and line[sp] != ' ':
sp += 1
if line[sp] == ' ':
sp += 1
code_val: INT = 0
code_val: int = 0
while line[sp] >= '0' and line[sp] <= '9':
code_val = code_val * 10 + INT(line[sp] - '0')
code_val = code_val * 10 + int(line[sp] - '0')
sp += 1
status_code = code_val
if e == 0:
@@ -845,7 +843,7 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
if dtx is not None:
_StreamAppendContent(dtx)
# 3) Remove processed line
rem: INT = llen - (nl + 1)
rem: int = llen - (nl + 1)
for j2 in range(int(rem)):
leftover[j2] = leftover[nl + 1 + j2]
llen = rem
@@ -881,10 +879,10 @@ def post_stream(url: str, data: str, content_type: str = "application/json",
# independent SSL_CTX/SSL/socket per connection. Returns body bytes>=0; -1 arg; -2 redirect; -3 failure.
# ============================================================
def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
dst: str, dst_cap: INT, out_status: INT*,
out_loc: str, out_loccap: INT,
out_total: sizet*) -> INT:
def _DlOnce(url: str, start: sizet, count: int, verify: bool, ca_file: str,
dst: str, dst_cap: int, out_status: int*,
out_loc: str, out_loccap: int,
out_total: sizet*) -> int:
"""HTTPS single Range fetch (thread-safe; see module comment)."""
global _last_verify_val, _last_verify_flag
if url is None or dst is None or dst_cap <= 0 \
@@ -899,9 +897,9 @@ def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
if _EnsureReady() != 0:
return -3
host_buf: t.CArray[char, 256]
path_buf: t.CArray[char, 1024]
port: INT = 0
host_buf: [256]char
path_buf: [1024]char
port: int = 0
if _ParseHttpsUrl(url, host_buf, 256, path_buf, 1024, &port) != 0:
_RecordErrorText("bad https url")
return -3
@@ -946,7 +944,7 @@ def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
if verify:
openssl.SSL_set1_host(ssl, host_buf)
hret: INT = openssl.SSL_connect(ssl)
hret: int = openssl.SSL_connect(ssl)
if hret <= 0:
_RecordErrorText("SSL_connect failed")
openssl.SSL_free(ssl)
@@ -955,7 +953,7 @@ def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
return -3
if verify:
_last_verify_val = INT(openssl.SSL_get_verify_result(ssl))
_last_verify_val = int(openssl.SSL_get_verify_result(ssl))
if _last_verify_val != 0:
_RecordErrorText("SSL certificate verify failed")
openssl.SSL_free(ssl)
@@ -972,7 +970,7 @@ def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
openssl.SSL_CTX_free(ctx)
sock.close()
return -3
cnt: INT = count
cnt: int = count
if cnt < 0:
cnt = 0
end: sizet = start + sizet(cnt) - 1
@@ -981,7 +979,7 @@ def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
stdio.snprintf(req, 1024,
"GET %s HTTP/1.1\r\nHost: %s\r\nRange: bytes=%zu-%zu\r\nConnection: close\r\n\r\n",
path_buf, host_buf, start, end)
sent: INT = openssl.SSL_write(ssl, req, INT(string.strlen(req)))
sent: int = openssl.SSL_write(ssl, req, int(string.strlen(req)))
stdlib.free(req)
if sent <= 0:
_RecordErrorText("SSL_write failed")
@@ -990,20 +988,20 @@ def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
sock.close()
return -3
total: INT = 0
tgt: INT = -1
total: int = 0
tgt: int = -1
while total < dst_cap - 1:
room: INT = dst_cap - 1 - total
room: int = dst_cap - 1 - total
if room > 4096:
room = 4096
n: INT = openssl.SSL_read(ssl, dst + total, room)
n: int = openssl.SSL_read(ssl, dst + total, room)
if n <= 0:
break
total += n
if tgt < 0:
bo: INT = requests._FindBodyStart(dst, total)
bo: int = requests._FindBodyStart(dst, total)
if bo >= 0:
cl: INT = requests._CLenOf(dst, total)
cl: int = requests._CLenOf(dst, total)
if cl >= 0:
tgt = bo + cl
if tgt >= 0 and total >= tgt:
@@ -1015,7 +1013,7 @@ def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
sock.close()
dst[total] = 0
st: INT = requests._StatusRaw(dst)
st: int = requests._StatusRaw(dst)
*out_status = st
if st == 0:
_RecordErrorText("empty response")
@@ -1032,13 +1030,13 @@ def _DlOnce(url: str, start: sizet, count: INT, verify: bool, ca_file: str,
if st == 206:
*out_total = requests._CRTotalOf(dst, total)
else:
cl2: INT = requests._CLenOf(dst, total)
cl2: int = requests._CLenOf(dst, total)
if cl2 > 0:
*out_total = sizet(cl2)
bo: INT = requests._FindBodyStart(dst, total)
bo: int = requests._FindBodyStart(dst, total)
if bo < 0 or bo >= total:
return 0
blen: INT = total - bo
blen: int = total - bo
if blen > cnt and cnt > 0:
blen = cnt
return blen