-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpywwwget_py3_optimized_bluetooth.py
More file actions
8701 lines (7626 loc) · 297 KB
/
pywwwget_py3_optimized_bluetooth.py
File metadata and controls
8701 lines (7626 loc) · 297 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import io
import re
import sys
import logging
from typing import Any, Dict, Optional, Tuple, Union, BinaryIO, IO, Iterable, List, Mapping, Callable
import json
import getpass
import random
import platform
import socket
import ipaddress
try:
import socks # type: ignore
except Exception:
socks = None
# Optional Bluetooth support: works via stdlib on Linux (AF_BLUETOOTH/BTPROTO_RFCOMM and BTPROTO_L2CAP)
# and via PyBluez if installed.
try:
import bluetooth as _pybluez # type: ignore
except Exception:
_pybluez = None
import shutil
import time
import struct
import hmac
import hashlib
import tempfile
import zlib
import gzip
import ssl
import mimetypes
try:
mimetypes.init()
except Exception:
pass
import base64
import threading
try:
from mimetypes import guess_type
except ImportError:
guess_type = None
try:
from secrets import randbits
except Exception:
def randbits(k):
if k < 0:
raise ValueError('number of bits must be non-negative')
num_bytes = (k + 7) // 8
raw_bytes = os.urandom(num_bytes)
value = int.from_bytes(raw_bytes, 'big')
return value >> (num_bytes * 8 - k)
import http.cookiejar as cookielib
from http.cookies import SimpleCookie
defcert = None
try:
import certifi
defcert = certifi.where()
except ImportError:
pass
from io import BytesIO
from urllib.parse import quote_from_bytes, unquote_to_bytes, urlencode
from urllib.request import install_opener, build_opener
_TEXT_MIME_DEFAULT = 'text/plain; charset=utf-8'
_BIN_MIME_DEFAULT = 'application/octet-stream'
def get_readable_size(bytes, precision=1, unit="IEC"):
unit = unit.upper()
if(unit != "IEC" and unit != "SI"):
unit = "IEC"
if(unit == "IEC"):
units = [" B", " KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB"]
unitswos = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"]
unitsize = 1024.0
if(unit == "SI"):
units = [" B", " kB", " MB", " GB", " TB", " PB", " EB", " ZB"]
unitswos = ["B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB"]
unitsize = 1000.0
return_val = {}
orgbytes = bytes
for unit in units:
if abs(bytes) < unitsize:
strformat = "%3."+str(precision)+"f%s"
pre_return_val = (strformat % (bytes, unit))
pre_return_val = re.sub(
r"([0]+) ([A-Za-z]+)", r" \2", pre_return_val)
pre_return_val = re.sub(r"\. ([A-Za-z]+)", r" \1", pre_return_val)
alt_return_val = pre_return_val.split()
return_val = {'Bytes': orgbytes, 'ReadableWithSuffix': pre_return_val,
'ReadableWithoutSuffix': alt_return_val[0], 'ReadableSuffix': alt_return_val[1]}
return return_val
bytes /= unitsize
strformat = "%."+str(precision)+"f%s"
pre_return_val = (strformat % (bytes, "YiB"))
pre_return_val = re.sub(r"([0]+) ([A-Za-z]+)", r" \2", pre_return_val)
pre_return_val = re.sub(r"\. ([A-Za-z]+)", r" \1", pre_return_val)
alt_return_val = pre_return_val.split()
return_val = {'Bytes': orgbytes, 'ReadableWithSuffix': pre_return_val,
'ReadableWithoutSuffix': alt_return_val[0], 'ReadableSuffix': alt_return_val[1]}
return return_val
def get_readable_size_from_file(infile, precision=1, unit="IEC", usehashes=False, usehashtypes="md5,sha1"):
unit = unit.upper()
usehashtypes = usehashtypes.lower()
getfilesize = os.path.getsize(infile)
return_val = get_readable_size(getfilesize, precision, unit)
if(usehashes):
hashtypelist = usehashtypes.split(",")
openfile = open(infile, "rb")
filecontents = openfile.read()
openfile.close()
listnumcount = 0
listnumend = len(hashtypelist)
while(listnumcount < listnumend):
hashtypelistlow = hashtypelist[listnumcount].strip()
hashtypelistup = hashtypelistlow.upper()
filehash = hashlib.new(hashtypelistup)
filehash.update(filecontents)
filegethash = filehash.hexdigest()
return_val.update({hashtypelistup: filegethash})
listnumcount += 1
return return_val
def _is_probably_text(data_bytes):
if not data_bytes:
return True
if b'\x00' in data_bytes:
return False
try:
decoded = data_bytes.decode('utf-8')
except Exception:
return False
control = 0
for ch in decoded:
o = ord(ch)
if (o < 32 and ch not in u'\t\n\r') or o == 127:
control += 1
return control <= max(1, len(decoded) // 200)
def data_url_encode(fileobj,
mime=None,
is_text=None,
charset='utf-8',
base64_encode=None):
raw = fileobj.read()
if isinstance(raw, text_type):
raw_bytes = raw.encode(charset)
detected_text = True
else:
raw_bytes = raw
detected_text = _is_probably_text(raw_bytes)
if is_text is None:
is_text = detected_text
if mime is None:
mime = _TEXT_MIME_DEFAULT if is_text else _BIN_MIME_DEFAULT
else:
mlow = mime.lower()
if mlow.startswith('text/') and 'charset=' not in mlow:
mime = mime + '; charset=' + charset
if base64_encode is None:
base64_encode = not is_text
if base64_encode:
b64 = base64.b64encode(raw_bytes)
if not isinstance(b64, text_type):
b64 = b64.decode('ascii')
return u'data:{0};base64,{1}'.format(mime, b64)
else:
encoded = quote_from_bytes(raw_bytes, safe="!$&'()*+,;=:@-._~")
if not isinstance(encoded, text_type):
encoded = encoded.decode('ascii')
return u'data:{0},{1}'.format(mime, encoded)
_DATA_URL_RE = re.compile(r'^data:(?P<meta>[^,]*?),(?P<data>.*)$', re.DOTALL)
def data_url_decode(data_url):
if not isinstance(data_url, text_type):
try:
data_url = data_url.decode('utf-8')
except Exception:
data_url = data_url.decode('ascii')
m = _DATA_URL_RE.match(data_url)
if not m:
raise ValueError('Not a valid data: URL')
meta = m.group('meta')
data_part = m.group('data')
meta_parts = [p for p in meta.split(';') if p] if meta else []
is_base64 = False
mime = None
if meta_parts:
if '/' in meta_parts[0]:
mime = meta_parts[0]
rest = meta_parts[1:]
else:
rest = meta_parts
for p in rest:
if p.lower() == 'base64':
is_base64 = True
else:
if mime is None:
mime = p
else:
mime = mime + ';' + p
if is_base64:
try:
decoded_bytes = base64.b64decode(data_part.encode('ascii'))
except Exception:
cleaned = ''.join(data_part.split())
decoded_bytes = base64.b64decode(cleaned.encode('ascii'))
else:
decoded_bytes = unquote_to_bytes(data_part)
if isinstance(decoded_bytes, text_type):
decoded_bytes = decoded_bytes.encode('latin-1')
if mime is None:
mime = "text/plain;charset=US-ASCII"
is_text = str(mime).lower().startswith("text/")
return MkTempFile(decoded_bytes), mime, is_text
from urllib.parse import urlparse, urlunparse, parse_qs, unquote
from urllib.request import (
Request,
build_opener,
HTTPBasicAuthHandler,
HTTPCookieProcessor,
HTTPSHandler,
HTTPPasswordMgrWithDefaultRealm,
)
from urllib.error import URLError, HTTPError
from http.client import HTTPException
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver as _socketserver
haverequests = False
try:
import requests
haverequests = True
except Exception:
pass
haveurllib3 = False
try:
import urllib3
haveurllib3 = True
except Exception:
pass
havehttpx = False
try:
import httpx
havehttpx = True
except Exception:
pass
havehttpcore = False
try:
import httpcore
havehttpcore = True
except ImportError:
pass
havemechanize = False
try:
import mechanize
havemechanize = True
except Exception:
pass
havepycurl = False
try:
import pycurl
havepycurl = True
except ImportError:
pass
haveparamiko = False
try:
import paramiko
haveparamiko = True
except Exception:
pass
havepysftp = False
try:
import pysftp
havepysftp = True
except Exception:
pass
ftpssl = True
try:
from ftplib import FTP, FTP_TLS, all_errors
except Exception:
ftpssl = False
from ftplib import FTP, all_errors
__use_pysftp__ = False
if(not havepysftp):
__use_pysftp__ = False
__use_http_lib__ = "httpx"
if(__use_http_lib__ == "httpx" and haverequests and not havehttpx):
__use_http_lib__ = "requests"
if(__use_http_lib__ == "requests" and havehttpx and not haverequests):
__use_http_lib__ = "httpx"
if((__use_http_lib__ == "httpx" or __use_http_lib__ == "requests") and not havehttpx and not haverequests):
__use_http_lib__ = "urllib"
__program_name__ = "PyNeoWWW-Get"
__program_alt_name__ = "PyWWWGet"
__program_small_name__ = "wwwget"
__project__ = __program_name__
__project_url__ = "https://github.com/GameMaker2k/PyNeoWWW-Get"
__version_info__ = (2, 2, 0, "RC 1", 1)
__version_date_info__ = (2026, 1, 23, "RC 1", 1)
__version_date__ = str(__version_date_info__[0])+"."+str(__version_date_info__[
1]).zfill(2)+"."+str(__version_date_info__[2]).zfill(2)
__revision__ = __version_info__[3]
__revision_id__ = "$Id$"
if(__version_info__[4] is not None):
__version_date_plusrc__ = __version_date__ + \
"-"+str(__version_date_info__[4])
if(__version_info__[4] is None):
__version_date_plusrc__ = __version_date__
if(__version_info__[3] is not None):
__version__ = str(__version_info__[0])+"."+str(__version_info__[1])+"."+str(
__version_info__[2])+" "+str(__version_info__[3])
if(__version_info__[3] is None):
__version__ = str(
__version_info__[0])+"."+str(__version_info__[1])+"."+str(__version_info__[2])
PyBitness = platform.architecture()
if(PyBitness == "32bit" or PyBitness == "32"):
PyBitness = "32"
elif(PyBitness == "64bit" or PyBitness == "64"):
PyBitness = "64"
else:
PyBitness = "32"
geturls_cj = cookielib.CookieJar()
geturls_ua_pywwwget_python = "Mozilla/5.0 (compatible; {proname}/{prover}; +{prourl})".format(
proname=__project__, prover=__version__, prourl=__project_url__)
if(platform.python_implementation() != ""):
py_implementation = platform.python_implementation()
if(platform.python_implementation() == ""):
py_implementation = "Python"
geturls_ua_pywwwget_python_alt = "Mozilla/5.0 ({osver}; {archtype}; +{prourl}) {pyimp}/{pyver} (KHTML, like Gecko) {proname}/{prover}".format(osver=platform.system(
)+" "+platform.release(), archtype=platform.machine(), prourl=__project_url__, pyimp=py_implementation, pyver=platform.python_version(), proname=__project__, prover=__version__)
geturls_ua_googlebot_google = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
geturls_ua_googlebot_google_old = "Googlebot/2.1 (+http://www.google.com/bot.html)"
geturls_headers_pywwwget_python = {'Referer': "http://google.com/", 'User-Agent': geturls_ua_pywwwget_python, 'Accept-Encoding': "none", 'Accept-Language': "en-US,en;q=0.8,en-CA,en-GB;q=0.6", 'Accept-Charset': "ISO-8859-1,ISO-8859-15,utf-8;q=0.7,*;q=0.7", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Connection': "close",
'SEC-CH-UA': "\""+__project__+"\";v=\""+str(__version__)+"\", \"Not;A=Brand\";v=\"8\", \""+py_implementation+"\";v=\""+str(platform.release())+"\"", 'SEC-CH-UA-FULL-VERSION': str(__version__), 'SEC-CH-UA-PLATFORM': ""+py_implementation+"", 'SEC-CH-UA-ARCH': ""+platform.machine()+"", 'SEC-CH-UA-PLATFORM-VERSION': str(__version__), 'SEC-CH-UA-BITNESS': str(PyBitness)}
geturls_headers_pywwwget_python_alt = {'Referer': "http://google.com/", 'User-Agent': geturls_ua_pywwwget_python_alt, 'Accept-Encoding': "none", 'Accept-Language': "en-US,en;q=0.8,en-CA,en-GB;q=0.6", 'Accept-Charset': "ISO-8859-1,ISO-8859-15,utf-8;q=0.7,*;q=0.7", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Connection': "close",
'SEC-CH-UA': "\""+__project__+"\";v=\""+str(__version__)+"\", \"Not;A=Brand\";v=\"8\", \""+py_implementation+"\";v=\""+str(platform.release())+"\"", 'SEC-CH-UA-FULL-VERSION': str(__version__), 'SEC-CH-UA-PLATFORM': ""+py_implementation+"", 'SEC-CH-UA-ARCH': ""+platform.machine()+"", 'SEC-CH-UA-PLATFORM-VERSION': str(__version__), 'SEC-CH-UA-BITNESS': str(PyBitness)}
geturls_headers_googlebot_google = {'Referer': "http://google.com/", 'User-Agent': geturls_ua_googlebot_google, 'Accept-Encoding': "none", 'Accept-Language': "en-US,en;q=0.8,en-CA,en-GB;q=0.6",
'Accept-Charset': "ISO-8859-1,ISO-8859-15,utf-8;q=0.7,*;q=0.7", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Connection': "close"}
geturls_headers_googlebot_google_old = {'Referer': "http://google.com/", 'User-Agent': geturls_ua_googlebot_google_old, 'Accept-Encoding': "none", 'Accept-Language': "en-US,en;q=0.8,en-CA,en-GB;q=0.6",
'Accept-Charset': "ISO-8859-1,ISO-8859-15,utf-8;q=0.7,*;q=0.7", 'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 'Connection': "close"}
def fix_header_names(header_dict):
if(sys.version[0] == "2"):
header_dict = {k.title(): v for k, v in header_dict.items()}
if(sys.version[0] >= "3"):
header_dict = {k.title(): v for k, v in header_dict.items()}
return header_dict
def make_http_headers_from_dict_to_list(headers):
if isinstance(headers, dict):
returnval = []
if(sys.version[0] == "2"):
for headkey, headvalue in headers.items():
returnval.append((headkey, headvalue))
if(sys.version[0] >= "3"):
for headkey, headvalue in headers.items():
returnval.append((headkey, headvalue))
elif isinstance(headers, list):
returnval = headers
else:
returnval = False
return returnval
def make_http_headers_from_dict_to_pycurl(headers):
if isinstance(headers, dict):
returnval = []
if(sys.version[0] == "2"):
for headkey, headvalue in headers.items():
returnval.append(headkey+": "+headvalue)
if(sys.version[0] >= "3"):
for headkey, headvalue in headers.items():
returnval.append(headkey+": "+headvalue)
elif isinstance(headers, list):
returnval = headers
else:
returnval = False
return returnval
def make_http_headers_from_pycurl_to_dict(headers):
header_dict = {}
headers = headers.strip().split('\r\n')
for header in headers:
parts = header.split(': ', 1)
if(len(parts) == 2):
key, value = parts
header_dict[key.title()] = value
return header_dict
def make_http_headers_from_list_to_dict(headers):
if isinstance(headers, list):
returnval = {}
mli = 0
mlil = len(headers)
while(mli < mlil):
returnval.update({headers[mli][0]: headers[mli][1]})
mli = mli + 1
elif isinstance(headers, dict):
returnval = headers
else:
returnval = False
return returnval
__use_inmem__ = True
__use_memfd__ = True
__use_spoolfile__ = False
__use_spooldir__ = tempfile.gettempdir()
BYTES_PER_KiB = 1024
BYTES_PER_MiB = 1024 * BYTES_PER_KiB
DEFAULT_SPOOL_MAX = 4 * BYTES_PER_MiB
__spoolfile_size__ = DEFAULT_SPOOL_MAX
DEFAULT_BUFFER_MAX = 256 * BYTES_PER_KiB
__filebuff_size__ = DEFAULT_BUFFER_MAX
text_type = str
binary_types = (bytes, bytearray, memoryview)
# ---------------------------------------------------------------------------
# Logging helpers
# ---------------------------------------------------------------------------
_LOG = logging.getLogger(__name__)
def _emit(msg: str, *, logger: Optional[logging.Logger] = None, level: int = logging.INFO, stream: str = "stderr") -> None:
"""Emit a human-facing message.
- If `logger` is provided, log there.
- Otherwise, write to stderr/stdout (default: stderr).
"""
try:
if logger is not None:
logger.log(level, msg)
return
except Exception:
# Fall back to stream output
pass
out = sys.stderr if stream != "stdout" else sys.stdout
try:
out.write(msg + "\n")
out.flush()
except Exception:
pass
def _logger_from_kwargs(kwargs: Mapping[str, Any]) -> Optional[logging.Logger]:
try:
lg = kwargs.get("logger") # type: ignore[attr-defined]
return lg if isinstance(lg, logging.Logger) else None
except Exception:
return None
def _strip_ipv6_brackets(host):
host = "" if host is None else str(host)
host = host.strip()
if host.startswith("[") and host.endswith("]") and len(host) >= 2:
return host[1:-1]
return host
def _is_ipv6_literal(host):
host = _strip_ipv6_brackets(host)
# allow RFC6874 zone indices (e.g. "fe80::1%en0")
base = host.split("%", 1)[0]
try:
return isinstance(ipaddress.ip_address(base), ipaddress.IPv6Address)
except Exception:
return False
def _url_host(host):
host = _strip_ipv6_brackets(host)
if _is_ipv6_literal(host):
# RFC6874: zone id must be percent-encoded inside brackets
if "%" in host:
host = host.replace("%", "%25")
return "[" + host + "]"
return host
def _set_ipv6_dualstack(sock):
# Best-effort dual-stack (IPv4-mapped) support on AF_INET6 sockets.
try:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
except Exception:
pass
def _gai_list(host, port, socktype, flags=0):
host = _strip_ipv6_brackets(host) if host else None
try:
infos = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socktype, 0, flags)
except Exception:
infos = []
# Prefer IPv6 first (helps dual-stack bind & AAAA-first environments)
af6 = getattr(socket, "AF_INET6", None)
infos.sort(key=lambda it: 0 if it[0] == af6 else 1)
return infos
def _tcp_listen_socket(host, port, backlog=1, reuse=True):
flags = getattr(socket, "AI_PASSIVE", 0)
h = host
if h in ("", None, "0.0.0.0", "::"):
h = None
infos = _gai_list(h, int(port), socket.SOCK_STREAM, flags=flags)
if not infos:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if reuse:
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except Exception:
pass
s.bind((host or "", int(port)))
s.listen(int(backlog))
return s
except Exception:
return None
for fam, st, pr, _cn, sa in infos:
s = None
try:
s = socket.socket(fam, st, pr)
if reuse:
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except Exception:
pass
if fam == getattr(socket, "AF_INET6", None):
_set_ipv6_dualstack(s)
s.bind(sa)
s.listen(int(backlog))
return s
except Exception:
try:
if s:
s.close()
except Exception:
pass
continue
return None
def _tcp_connect_socket(host, port, timeout=None, wait=False, wait_timeout=None, verbose=False, logger=None):
# socket.create_connection uses AF_UNSPEC internally (IPv4+IPv6)
start_t = time.time()
while True:
try:
to = float(timeout) if timeout is not None else None
except Exception:
to = None
try:
s = socket.create_connection((_strip_ipv6_brackets(host), int(port)), timeout=to)
return s
except Exception:
if not wait:
return None
if wait_timeout is not None:
try:
wt = float(wait_timeout)
if wt >= 0 and (time.time() - start_t) >= wt:
return None
except Exception:
pass
_net_log(verbose, "TCP: waiting for receiver, retrying...", logger=logger)
try:
time.sleep(0.1)
except Exception:
pass
def _ipproto_sctp() -> int:
"""Best-effort IPPROTO_SCTP constant (stdlib may omit it on some builds)."""
try:
return int(getattr(socket, "IPPROTO_SCTP"))
except Exception:
# IANA assigned SCTP protocol number
return 132
def _is_seqpacket_socket(sock) -> bool:
try:
return getattr(sock, "type", None) == socket.SOCK_SEQPACKET
except Exception:
return False
def _recv_line(sock, max_len: int = 4096) -> bytes:
"""Read a single \n-terminated control line safely.
For stream sockets, we use MSG_PEEK to find the newline and then consume exactly
that many bytes, so we don't accidentally eat file payload data.
For SOCK_SEQPACKET sockets (e.g., SCTP SEQPACKET, BT L2CAP), control messages
must be sent in a single record; we recv() once.
Returns raw bytes (may not include trailing \n if sender didn't include one).
"""
try:
max_len = int(max_len)
except Exception:
max_len = 4096
if max_len <= 0:
max_len = 4096
if _is_seqpacket_socket(sock):
try:
b = sock.recv(max_len)
return b if isinstance(b, (bytes, bytearray)) else bytes(b)
except Exception:
return b""
# stream socket: peek then recv exact up-to-newline
try:
if hasattr(socket, "MSG_PEEK"):
buf = sock.recv(max_len, socket.MSG_PEEK)
else:
buf = b""
except Exception:
buf = b""
if not buf:
try:
b = sock.recv(max_len)
return b if isinstance(b, (bytes, bytearray)) else bytes(b)
except Exception:
return b""
nl = buf.find(b"\n")
to_read = (nl + 1) if nl >= 0 else len(buf)
out = bytearray()
while len(out) < to_read:
try:
chunk = sock.recv(to_read - len(out))
except Exception:
break
if not chunk:
break
out.extend(chunk if isinstance(chunk, (bytes, bytearray)) else bytes(chunk))
return bytes(out)
def _sctp_listen_socket(host, port, backlog: int = 1, reuse: bool = True):
"""Create an SCTP SOCK_SEQPACKET listening socket (IPv4/IPv6 via getaddrinfo)."""
proto = _ipproto_sctp()
flags = getattr(socket, "AI_PASSIVE", 0)
h = host
if h in ("", None, "0.0.0.0", "::"):
h = None
infos = _gai_list(h, int(port), socket.SOCK_SEQPACKET, flags=flags)
if not infos:
# fallback (IPv4)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_SEQPACKET, proto)
if reuse:
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except Exception:
pass
s.bind((_strip_ipv6_brackets(host or ""), int(port)))
s.listen(int(backlog))
return s
except Exception:
return None
for fam, _st, _pr, _cn, sa in infos:
s = None
try:
s = socket.socket(fam, socket.SOCK_SEQPACKET, proto)
if reuse:
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except Exception:
pass
if fam == getattr(socket, "AF_INET6", None):
_set_ipv6_dualstack(s)
s.bind(sa)
s.listen(int(backlog))
return s
except Exception:
try:
if s:
s.close()
except Exception:
pass
continue
return None
def _sctp_connect_socket(host, port, timeout=None, wait: bool = False, wait_timeout=None, verbose: bool = False, logger=None):
"""Connect to an SCTP SOCK_SEQPACKET endpoint (IPv4/IPv6)."""
proto = _ipproto_sctp()
start_t = time.time()
while True:
try:
to = float(timeout) if timeout is not None else None
except Exception:
to = None
infos = _gai_list(host, int(port), socket.SOCK_SEQPACKET, flags=0)
if not infos:
infos = [(socket.AF_INET, socket.SOCK_SEQPACKET, proto, "", (_strip_ipv6_brackets(host), int(port)))]
last_err = None
for fam, _st, _pr, _cn, sa in infos:
s = None
try:
s = socket.socket(fam, socket.SOCK_SEQPACKET, proto)
if fam == getattr(socket, "AF_INET6", None):
_set_ipv6_dualstack(s)
if to is not None:
s.settimeout(to)
s.connect(sa)
return s
except Exception as e:
last_err = e
try:
if s:
s.close()
except Exception:
pass
continue
if not wait:
return None
if wait_timeout is not None:
try:
wt = float(wait_timeout)
if wt >= 0 and (time.time() - start_t) >= wt:
return None
except Exception:
pass
_net_log(verbose, "SCTP: waiting for receiver, retrying...", logger=logger)
try:
time.sleep(0.1)
except Exception:
pass
def _udp_bind_socket(host, port, reuse=True):
flags = getattr(socket, "AI_PASSIVE", 0)
h = host
if h in ("", None, "0.0.0.0", "::"):
h = None
infos = _gai_list(h, int(port), socket.SOCK_DGRAM, flags=flags)
if not infos:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if reuse:
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except Exception:
pass
s.bind((host or "", int(port)))
return s
except Exception:
return None
for fam, st, pr, _cn, sa in infos:
s = None
try:
s = socket.socket(fam, st, pr)
if reuse:
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except Exception:
pass
if fam == getattr(socket, "AF_INET6", None):
_set_ipv6_dualstack(s)
s.bind(sa)
return s
except Exception:
try:
if s:
s.close()
except Exception:
pass
continue
return None
def _udp_socket_and_addr(host, port):
infos = _gai_list(host, int(port), socket.SOCK_DGRAM, flags=0)
for fam, st, pr, _cn, sa in infos:
s = None
try:
s = socket.socket(fam, st, pr)
if fam == getattr(socket, "AF_INET6", None):
_set_ipv6_dualstack(s)
return s, sa
except Exception:
try:
if s:
s.close()
except Exception:
pass
continue
# fallback (IPv4)
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM), (_strip_ipv6_brackets(host), int(port))
def _best_lan_ip():
"""Attempt to find the best LAN IPv4 address."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
except Exception:
try:
return socket.gethostbyname(socket.gethostname())
except Exception:
return "127.0.0.1"
finally:
try:
s.close()
except Exception:
pass
def _best_lan_ip6():
"""Attempt to find the best LAN IPv6 address (best-effort)."""
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
except Exception:
return "::1"
try:
# public IPv6 anycast resolver (route selection only; no packets sent)
s.connect(("2001:4860:4860::8888", 80, 0, 0))
return s.getsockname()[0]
except Exception:
# fallback: try hostname AAAA
try:
hn = socket.gethostname()
infos = socket.getaddrinfo(hn, None, socket.AF_INET6)
for it in infos:
ip = it[4][0]
if ip:
return ip
except Exception:
pass
return "::1"
finally:
try:
s.close()
except Exception:
pass
def _listen_urls(scheme, bind_host, port, path, query=""):
if not path:
path = "/"
if not path.startswith("/"):
path = "/" + path
q = ""
if query:
q = "?" + query.lstrip("?")
urls = []
def _add(h):
h = _strip_ipv6_brackets(h)
if not h:
return
urls.append("%s://%s:%d%s%s" % (scheme, _url_host(h), int(port), path, q))
bh = _strip_ipv6_brackets(bind_host or "")
# If binding to "all", show loopback + LAN (v4 + v6).
if not bh or bh in ("0.0.0.0", "::"):
_add("127.0.0.1")
_add("::1")
ip4 = _best_lan_ip()
if ip4 and ip4 not in ("127.0.0.1", "0.0.0.0"):
_add(ip4)
ip6 = _best_lan_ip6()
if ip6 and ip6 not in ("::1", "::"):
_add(ip6)
else:
_add(bh)
return urls
def _parse_kv_headers(qs, prefix="hdr_"):
out = {}
for k in qs.keys():
if k.startswith(prefix):
hk = k[len(prefix):].replace("_", "-")
try:
out[hk] = qs.get(k)[0]
except Exception:
try:
out[hk] = qs[k][0]
except Exception:
pass
return out
def _throttle_bps(rate_bps, sent, started):
"""Sleep to enforce approximate bytes/sec rate."""
try:
rate_bps = float(rate_bps)
except Exception:
return
if rate_bps <= 0:
return
elapsed = time.time() - started
if elapsed <= 0:
return
should = float(sent) / rate_bps
if should > elapsed:
time.sleep(should - elapsed)
def MkTempFile(data=None,
inmem=__use_inmem__, usememfd=__use_memfd__,
isbytes=True,
prefix=__program_name__,
delete=True,
encoding="utf-8",
newline=None,
text_errors="strict",
dir=None,
suffix="",
use_spool=__use_spoolfile__,
autoswitch_spool=False,
spool_max=__spoolfile_size__,
spool_dir=__use_spooldir__,
reset_to_start=True,
memfd_name=__program_name__,
memfd_allow_sealing=False,
memfd_flags_extra=0,
on_create=None):
prefix = prefix or ""
suffix = suffix or ""
init = None
if data is not None:
if isbytes:
if isinstance(data, binary_types):
init = bytes(data) if not isinstance(data, bytes) else data
elif isinstance(data, text_type):