-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpywwwgetadv.py
More file actions
4398 lines (3879 loc) · 159 KB
/
pywwwgetadv.py
File metadata and controls
4398 lines (3879 loc) · 159 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 python
# -*- coding: utf-8 -*-
'''
This program is free software; you can redistribute it and/or modify
it under the terms of the Revised BSD License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Revised BSD License for more details.
Copyright 2015-2024 Game Maker 2k - https://github.com/GameMaker2k
Copyright 2015-2024 Kazuki Przyborowski - https://github.com/KazukiPrzyborowski
$FileInfo: pywwwget.py - Last Update: 8/14/2025 Ver. 2.1.6 RC 1 - Author: cooldude2k $
'''
from __future__ import absolute_import, division, print_function, unicode_literals, generators, with_statement, nested_scopes
import os
import re
import sys
import time
import socket
import shutil
import logging
import platform
import tempfile
try:
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
except ImportError:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from urlparse import urlparse, parse_qs
# URL Parsing
try:
# Python 3
from urllib.parse import urlparse, urlunparse, parse_qs, unquote
from urllib.request import url2pathname
except ImportError:
# Python 2
from urlparse import urlparse, urlunparse, parse_qs
from urllib import unquote, url2pathname
# FTP Support
ftpssl = True
try:
from ftplib import FTP, FTP_TLS, all_errors
except ImportError:
ftpssl = False
from ftplib import FTP
all_errors = (Exception,)
try:
basestring
except NameError:
basestring = str
# URL Parsing
try:
from urllib.parse import urlparse, urlunparse
except ImportError:
from urlparse import urlparse, urlunparse
# Paramiko support
haveparamiko = False
try:
import paramiko
haveparamiko = True
except ImportError:
pass
# PySFTP support
havepysftp = False
try:
import pysftp
havepysftp = True
except ImportError:
pass
# Add the mechanize import check
havemechanize = False
try:
import mechanize
havemechanize = True
except ImportError:
pass
# Requests support
haverequests = False
try:
import requests
haverequests = True
try:
import urllib3
logging.getLogger("urllib3").setLevel(logging.WARNING)
except Exception:
pass
except ImportError:
pass
# HTTPX support
havehttpx = False
try:
import httpx
havehttpx = True
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
except ImportError:
pass
# HTTP and URL parsing (urllib)
try:
from urllib.request import Request, build_opener, HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm
except ImportError:
from urllib2 import Request, build_opener, HTTPBasicAuthHandler
try:
from urllib2 import HTTPPasswordMgrWithDefaultRealm
except Exception:
HTTPPasswordMgrWithDefaultRealm = None
# StringIO and BytesIO
try:
from io import StringIO, BytesIO
except ImportError:
try:
from cStringIO import StringIO
from cStringIO import StringIO as BytesIO
except ImportError:
from StringIO import StringIO
from StringIO import StringIO as BytesIO
try:
file
except NameError:
from io import IOBase
file = IOBase
#if isinstance(outfile, file) or isinstance(outfile, IOBase):
try:
basestring
except NameError:
basestring = str
PY2 = (sys.version_info[0] == 2)
try:
unicode # Py2
except NameError: # Py3
unicode = str
try:
long
except NameError: # Py3
long = int
try:
PermissionError
except NameError: # Py2
PermissionError = OSError
if PY2:
# In Py2, 'str' is bytes; define a 'bytes' alias for clarity
bytes_type = str
text_type = unicode # noqa: F821 (Py2-only)
else:
bytes_type = bytes
text_type = str
# Text streams (as provided by Python)
PY_STDIN_TEXT = sys.stdin
PY_STDOUT_TEXT = sys.stdout
PY_STDERR_TEXT = sys.stderr
# Binary-friendly streams (use .buffer on Py3, fall back on Py2)
PY_STDIN_BUF = getattr(sys.stdin, "buffer", sys.stdin)
PY_STDOUT_BUF = getattr(sys.stdout, "buffer", sys.stdout)
PY_STDERR_BUF = getattr(sys.stderr, "buffer", sys.stderr)
# Text vs bytes tuples you can use with isinstance()
TEXT_TYPES = (basestring,) # "str or unicode" on Py2, "str" on Py3
BINARY_TYPES = (bytes,) if not PY2 else (str,) # bytes on Py3, str on Py2
# Optional: support os.PathLike on Py3
try:
from os import PathLike
PATH_TYPES = (basestring, PathLike)
except Exception:
PATH_TYPES = (basestring,)
def running_interactively():
main = sys.modules.get("__main__")
no_main_file = not hasattr(main, "__file__")
interactive_flag = bool(getattr(sys.flags, "interactive", 0))
return no_main_file or interactive_flag
if running_interactively():
logging.basicConfig(format="%(message)s", stream=PY_STDOUT_TEXT, level=logging.DEBUG)
def _ensure_text(s, encoding="utf-8", errors="replace", allow_none=False):
"""
Normalize any input to text_type (unicode on Py2, str on Py3).
- bytes/bytearray/memoryview -> decode
- os.PathLike -> fspath then normalize
- None -> "" (unless allow_none=True, then return None)
- everything else -> text_type(s)
"""
if s is None:
return None if allow_none else text_type("")
if isinstance(s, text_type):
return s
if isinstance(s, (bytes_type, bytearray, memoryview)):
return bytes(s).decode(encoding, errors)
# Handle pathlib.Path & other path-like objects
try:
if hasattr(os, "fspath"):
fs = os.fspath(s)
if isinstance(fs, text_type):
return fs
if isinstance(fs, (bytes_type, bytearray, memoryview)):
return bytes(fs).decode(encoding, errors)
except Exception:
pass
return text_type(s)
def to_text(s, encoding="utf-8", errors="ignore"):
if s is None:
return u""
if isinstance(s, unicode):
return s
if isinstance(s, (bytes, bytearray)):
return s.decode(encoding, errors)
return unicode(s)
baseint = []
try:
baseint.append(long)
baseint.insert(0, int)
except NameError:
baseint.append(int)
baseint = tuple(baseint)
__use_inmem__ = True
__use_memfd__ = True
__use_spoolfile__ = False
__use_spooldir__ = tempfile.gettempdir()
BYTES_PER_KiB = 1024
BYTES_PER_MiB = 1024 * BYTES_PER_KiB
# Spool: not tiny, but won’t blow up RAM if many are in use
DEFAULT_SPOOL_MAX = 4 * BYTES_PER_MiB # 4 MiB per spooled temp file
__spoolfile_size__ = DEFAULT_SPOOL_MAX
# Buffer: bigger than stdlib default (16 KiB), but still modest
DEFAULT_BUFFER_MAX = 256 * BYTES_PER_KiB # 256 KiB copy buffer
__filebuff_size__ = DEFAULT_BUFFER_MAX
__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__ = "PyWWW-Get"
__program_alt_name__ = "PyWWWGet"
__program_small_name__ = "wwwget"
__project__ = __program_name__
__project_url__ = "https://github.com/GameMaker2k/PyWWW-Get"
__version_info__ = (2, 1, 6, "RC 1", 1)
__version_date_info__ = (2025, 8, 14, "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_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-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-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"
}
# Logger used throughout original code
log = logging.getLogger(__project__)
if not log.handlers:
logging.basicConfig(level=logging.INFO)
def to_ns(timestamp):
"""
Convert a second-resolution timestamp (int or float)
into a nanosecond timestamp (int) by zero-padding.
Works in Python 2 and Python 3.
"""
try:
# Convert incoming timestamp to float so it works for int or float
seconds = float(timestamp)
except (TypeError, ValueError):
raise ValueError("Timestamp must be int or float")
# Multiply by 1e9 to get nanoseconds, then cast to int
return int(seconds * 1000000000)
def format_ns_utc(ts_ns, fmt='%Y-%m-%d %H:%M:%S'):
ts_ns = int(ts_ns)
sec, ns = divmod(ts_ns, 10**9)
dt = datetime.datetime.utcfromtimestamp(sec).replace(microsecond=ns // 1000)
base = dt.strftime(fmt)
ns_str = "%09d" % ns
return base + "." + ns_str
def _split_posix(name):
"""
Return a list of path parts without collapsing '..'.
- Normalize backslashes to '/'
- Strip leading './' (repeated)
- Remove '' and '.' parts; keep '..' for traversal detection
"""
if not name:
return []
n = name.replace(u"\\", u"/")
while n.startswith(u"./"):
n = n[2:]
return [p for p in n.split(u"/") if p not in (u"", u".")]
def _is_abs_like(name):
"""Detect absolute-like paths across platforms (/, \\, drive letters, UNC)."""
if not name:
return False
n = name.replace(u"\\", u"/")
# POSIX absolute
if n.startswith(u"/"):
return True
# Windows UNC (\\server\share\...) -> after replace: startswith '//'
if n.startswith(u"//"):
return True
# Windows drive: 'C:/', 'C:\', or bare 'C:' (treat as absolute-like conservatively)
if len(n) >= 2 and n[1] == u":":
if len(n) == 2:
return True
if n[2:3] in (u"/", u"\\"):
return True
return False
def _resolves_outside(parent, target):
"""
Does a symlink from 'parent' to 'target' escape parent?
- Absolute-like target => escape.
- Compare normalized '/<parent>/<target>' against '/<parent>'.
- 'parent' is POSIX-style ('' means archive root).
"""
parent = _ensure_text(parent or u"")
target = _ensure_text(target or u"")
# Absolute target is unsafe by definition
if _is_abs_like(target):
return True
import posixpath as pp
root = u"/"
base = posixpath.normpath(posixpath.join(root, parent)) # '/dir/sub' or '/'
cand = posixpath.normpath(posixpath.join(base, target)) # resolved target under '/'
# ensure trailing slash on base for the prefix test
base_slash = base if base.endswith(u"/") else (base + u"/")
return not (cand == base or cand.startswith(base_slash))
def _to_bytes(data, encoding="utf-8", errors="strict"):
"""
Robustly coerce `data` to bytes:
- None -> b""
- bytes/bytearray/memoryview -> bytes(...)
- unicode/str -> .encode(encoding, errors)
- file-like (has .read) -> read all, return bytes
- int -> encode its decimal string (avoid bytes(int) => NULs)
- other -> try __bytes__, else str(...).encode(...)
"""
if data is None:
return b""
if isinstance(data, (bytes, bytearray, memoryview)):
return bytes(data)
if isinstance(data, unicode):
return data.encode(encoding, errors)
# file-like: read its content
if hasattr(data, "read"):
chunk = data.read()
return bytes(chunk) if isinstance(chunk, (bytes, bytearray, memoryview)) else (
(chunk if isinstance(chunk, unicode) else str(chunk)).encode(encoding, errors)
)
# avoid bytes(int) => NUL padding
if isinstance(data, int):
return str(data).encode(encoding, errors)
# prefer __bytes__ when available
to_bytes = getattr(data, "__bytes__", None)
if callable(to_bytes):
try:
return bytes(data)
except Exception:
pass
# fallback: string form
return (data if isinstance(data, unicode) else str(data)).encode(encoding, errors)
def _to_text(s, encoding="utf-8", errors="replace", normalize=None, prefer_surrogates=False):
"""
Coerce `s` to a text/unicode string safely.
Args:
s: Any object (bytes/bytearray/memoryview/str/unicode/other).
encoding: Used when decoding bytes-like objects (default: 'utf-8').
errors: Decoding error policy (default: 'replace').
Consider 'surrogateescape' when you need byte-preserving round-trip on Py3.
normalize: Optional unicode normalization form, e.g. 'NFC', 'NFKC', 'NFD', 'NFKD'.
prefer_surrogates: If True on Py3 and errors is the default, use 'surrogateescape'
to preserve undecodable bytes.
Returns:
A text string (unicode on Py2, str on Py3).
"""
# Fast path: already text
if isinstance(s, unicode):
out = s
else:
# Bytes-like → decode
if isinstance(s, (bytes, bytearray, memoryview)):
b = s if isinstance(s, (bytes, bytearray)) else bytes(s)
# Prefer surrogateescape on Py3 if requested (keeps raw bytes round-tripable)
eff_errors = errors
if prefer_surrogates and errors == "replace":
try:
# Only available on Py3
"".encode("utf-8", "surrogateescape")
eff_errors = "surrogateescape"
except LookupError:
pass
try:
out = b.decode(encoding, eff_errors)
except Exception:
# Last-resort: decode with 'latin-1' to avoid exceptions
out = b.decode("latin-1", "replace")
else:
# Not bytes-like: stringify
try:
# Py2: many objects implement __unicode__
if hasattr(s, "__unicode__"):
out = s.__unicode__() # noqa: E1101 (only on Py2 objects)
else:
out = unicode(s)
except Exception:
# Fallback to repr() if object’s __str__/__unicode__ is broken
out = unicode(repr(s))
# Optional normalization
if normalize:
try:
import unicodedata
out = unicodedata.normalize(normalize, out)
except Exception:
# Keep original if normalization fails
pass
return out
def _quote_path_for_wire(path_text):
# Percent-encode as UTF-8; return ASCII bytes text
try:
from urllib.parse import quote
return quote(path_text.encode('utf-8'))
except Exception:
try:
from urllib import quote as _q
return _q(path_text.encode('utf-8'))
except Exception:
return ''.join(ch for ch in path_text if ord(ch) < 128)
def _unquote_path_from_wire(s_bytes):
# s_bytes: bytes → return text/unicode
try:
from urllib.parse import unquote
txt = unquote(s_bytes.decode('ascii', 'replace'))
return _to_text(txt)
except Exception:
try:
from urllib import unquote as _uq
txt = _uq(s_bytes.decode('ascii', 'replace'))
return _to_text(txt)
except Exception:
return _to_text(s_bytes)
def _recv_line(sock, maxlen=4096, timeout=None):
"""TCP: read a single LF-terminated line (bytes). Returns None on timeout/EOF."""
if timeout is not None:
try: sock.settimeout(timeout)
except Exception: pass
buf = bytearray()
while True:
try:
b = sock.recv(1)
except socket.timeout:
return None
if not b:
break
buf += b
if b == b'\n' or len(buf) >= maxlen:
break
return bytes(buf)
# ---------- TLS helpers (TCP only) ----------
def _ssl_available():
try:
import ssl # noqa
return True
except Exception:
return False
def _build_ssl_context(server_side=False, verify=True, ca_file=None, certfile=None, keyfile=None):
import ssl
create_ctx = getattr(ssl, "create_default_context", None)
SSLContext = getattr(ssl, "SSLContext", None)
Purpose = getattr(ssl, "Purpose", None)
if create_ctx and Purpose:
ctx = create_ctx(ssl.Purpose.CLIENT_AUTH if server_side else ssl.Purpose.SERVER_AUTH)
elif SSLContext:
ctx = SSLContext(getattr(ssl, "PROTOCOL_TLS", getattr(ssl, "PROTOCOL_SSLv23")))
else:
return None
if hasattr(ctx, "check_hostname") and not server_side:
ctx.check_hostname = bool(verify)
if verify:
if hasattr(ctx, "verify_mode"):
ctx.verify_mode = getattr(ssl, "CERT_REQUIRED", 2)
if ca_file:
try: ctx.load_verify_locations(cafile=ca_file)
except Exception: pass
else:
load_default_certs = getattr(ctx, "load_default_certs", None)
if load_default_certs: load_default_certs()
else:
if hasattr(ctx, "verify_mode"):
ctx.verify_mode = getattr(ssl, "CERT_NONE", 0)
if hasattr(ctx, "check_hostname"):
ctx.check_hostname = False
if certfile:
ctx.load_cert_chain(certfile=certfile, keyfile=keyfile or None)
try:
ctx.set_ciphers("HIGH:!aNULL:!MD5:!RC4")
except Exception:
pass
return ctx
def _ssl_wrap_socket(sock, server_side=False, server_hostname=None,
verify=True, ca_file=None, certfile=None, keyfile=None):
import ssl
ctx = _build_ssl_context(server_side, verify, ca_file, certfile, keyfile)
if ctx is not None:
kwargs = {}
if not server_side and getattr(ssl, "HAS_SNI", False) and server_hostname:
kwargs["server_hostname"] = server_hostname
return ctx.wrap_socket(sock, server_side=server_side, **kwargs)
# Very old Python fallback
kwargs = {
"ssl_version": getattr(ssl, "PROTOCOL_TLS", getattr(ssl, "PROTOCOL_SSLv23")),
"certfile": certfile or None,
"keyfile": keyfile or None,
"cert_reqs": (getattr(ssl, "CERT_REQUIRED", 2) if (verify and ca_file) else getattr(ssl, "CERT_NONE", 0)),
}
if verify and ca_file:
kwargs["ca_certs"] = ca_file
return ssl.wrap_socket(sock, **kwargs)
# ---------- IPv6 / multi-A dialer + keepalive ----------
def _enable_keepalive(s, idle=60, intvl=15, cnt=4):
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
if hasattr(socket, 'TCP_KEEPIDLE'):
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, idle)
if hasattr(socket, 'TCP_KEEPINTVL'):
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, intvl)
if hasattr(socket, 'TCP_KEEPCNT'):
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, cnt)
except Exception:
pass
def _connect_stream(host, port, timeout):
err = None
for fam, st, proto, _, sa in socket.getaddrinfo(host, int(port), 0, socket.SOCK_STREAM):
try:
s = socket.socket(fam, st, proto)
if timeout is not None:
s.settimeout(timeout)
try: s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
except Exception: pass
s.connect(sa)
_enable_keepalive(s)
return s
except Exception as e:
err = e
try: s.close()
except Exception: pass
if err: raise err
raise RuntimeError("no usable address")
# ---------- Auth: AF1 (HMAC) + legacy fallback ----------
# AF1: single ASCII line ending with '\n':
# AF1 ts=<unix> user=<b64url> nonce=<b64url_12B> scope=<b64url> alg=sha256 mac=<hex>\n
def _b64url_encode(b):
s = base64.urlsafe_b64encode(b)
return _to_text(s.rstrip(b'='))
def _b64url_decode(s):
s = _to_bytes(s)
pad = b'=' * ((4 - (len(s) % 4)) % 4)
return base64.urlsafe_b64decode(s + pad)
def _auth_msg(ts_int, user_utf8, nonce_bytes, scope_utf8, length_str, sha_hex):
# canonical message for MAC: v1|ts|user|nonce_b64|scope|len|sha
return _to_bytes("v1|%d|%s|%s|%s|%s|%s" % (
ts_int,
_to_text(user_utf8),
_b64url_encode(nonce_bytes),
_to_text(scope_utf8),
length_str if length_str is not None else "",
sha_hex if sha_hex is not None else "",
))
def build_auth_blob_v1(user, secret, scope=u"", now=None, length=None, sha_hex=None):
"""
user: text; secret: text/bytes (HMAC key)
scope: optional text (e.g., path)
length: int or None (payload bytes)
sha_hex: ascii hex SHA-256 of payload (optional)
"""
ts = int(time.time() if now is None else now)
user_b = _to_bytes(user or u"")
scope_b = _to_bytes(scope or u"")
key_b = _to_bytes(secret or u"")
nonce = os.urandom(12)
length_str = (str(int(length)) if (length is not None and int(length) >= 0) else "")
sha_hex = (sha_hex or None)
mac = hmac.new(
key_b,
_auth_msg(ts, user_b, nonce, scope_b, length_str, sha_hex),
hashlib.sha256
).hexdigest()
line = "AF1 ts=%d user=%s nonce=%s scope=%s len=%s sha=%s alg=sha256 mac=%s\n" % (
ts,
_b64url_encode(user_b),
_b64url_encode(nonce),
_b64url_encode(scope_b),
length_str,
(sha_hex or ""),
mac,
)
return _to_bytes(line)
from collections import deque
class _NonceCache(object):
def __init__(self, max_items=10000, ttl_seconds=600):
self.max_items = int(max_items); self.ttl = int(ttl_seconds)
self.q = deque(); self.s = set()
def seen(self, nonce_b64, now_ts):
# evict old / over-capacity
while self.q and (now_ts - self.q[0][0] > self.ttl or len(self.q) > self.max_items):
_, n = self.q.popleft(); self.s.discard(n)
if nonce_b64 in self.s: return True
self.s.add(nonce_b64); self.q.append((now_ts, nonce_b64))
return False
_NONCES = _NonceCache()
def verify_auth_blob_v1(blob_bytes, expected_user=None, secret=None,
max_skew=600, expect_scope=None):
"""
Returns (ok_bool, user_text, scope_text, reason_text, length_or_None, sha_hex_or_None)
"""
try:
line = _to_text(blob_bytes).strip()
if not line.startswith("AF1 "):
return (False, None, None, "bad magic", None, None)
kv = {}
for tok in line.split()[1:]:
if '=' in tok:
k, v = tok.split('=', 1); kv[k] = v
for req in ("ts","user","nonce","mac","alg"):
if req not in kv:
return (False, None, None, "missing %s" % req, None, None)
if kv["alg"].lower() != "sha256":
return (False, None, None, "alg", None, None)
ts = int(kv["ts"])
userb = _b64url_decode(kv["user"])
nonce_b64 = kv["nonce"]; nonce = _b64url_decode(nonce_b64)
scopeb = _b64url_decode(kv.get("scope","")) if kv.get("scope") else b""
length_str = kv.get("len","")
sha_hex = kv.get("sha","") or None
mac = kv["mac"]
now = int(time.time())
if abs(now - ts) > int(max_skew):
return (False, None, None, "skew", None, None)
if _NONCES.seen(nonce_b64, now):
return (False, None, None, "replay", None, None)
if expected_user is not None and _to_bytes(expected_user) != userb:
return (False, None, None, "user", None, None)
calc = hmac.new(
_to_bytes(secret or u""),
_auth_msg(ts, userb, nonce, scopeb, length_str, sha_hex),
hashlib.sha256
).hexdigest()
if not hmac.compare_digest(calc, mac):
return (False, None, None, "mac", None, None)
if expect_scope is not None and _to_bytes(expect_scope) != scopeb:
return (False, None, None, "scope", None, None)
length = int(length_str) if (length_str and length_str.isdigit()) else None
return (True, _to_text(userb), _to_text(scopeb), "ok", length, sha_hex)
except Exception as e:
return (False, None, None, "exc:%s" % e, None, None)
# Legacy blob (kept for backward compatibility)
_MAGIC = b"AUTH\0"; _OK = b"OK"; _NO = b"NO"
def _build_auth_blob_legacy(user, pw):
return _MAGIC + _to_bytes(user) + b"\0" + _to_bytes(pw) + b"\0"
def _parse_auth_blob_legacy(data):
if not data.startswith(_MAGIC):
return (None, None)
rest = data[len(_MAGIC):]
try:
user, rest = rest.split(b"\0", 1)
pw, _tail = rest.split(b"\0", 1)
return (user, pw)
except Exception:
return (None, None)
# ---------- URL helpers ----------
def _qflag(qs, key, default=False):
v = qs.get(key, [None])[0]
if v is None: return bool(default)
return _to_text(v).lower() in ("1", "true", "yes", "on")
def _qnum(qs, key, default=None, cast=float):
v = qs.get(key, [None])[0]
if v is None or v == "": return default
try: return cast(v)
except Exception: return default
def _qstr(qs, key, default=None):
v = qs.get(key, [None])[0]
if v is None: return default
return v
def _parse_net_url(url):
parts = urlparse(url)
qs = parse_qs(parts.query or "")
proto = parts.scheme.lower()
if proto not in ("tcp", "udp"):
raise ValueError("Only tcp:// or udp:// supported here")
user = unquote(parts.username) if parts.username else None
pw = unquote(parts.password) if parts.password else None
use_ssl = _qflag(qs, "ssl", False) if proto == "tcp" else False
ssl_verify = _qflag(qs, "verify", True)
ssl_ca_file = _qstr(qs, "ca", None)
ssl_cert = _qstr(qs, "cert", None)
ssl_key = _qstr(qs, "key", None)
timeout = _qnum(qs, "timeout", None, float)
total_timeout = _qnum(qs, "total_timeout", None, float)
chunk_size = int(_qnum(qs, "chunk", 65536, float))
force_auth = _qflag(qs, "auth", False)
want_sha = _qflag(qs, "sha", True) # enable sha by default
enforce_path = _qflag(qs, "enforce_path", True) # enforce path by default
path_text = _to_text(parts.path or u"")
opts = dict(
proto=proto,
host=parts.hostname or "127.0.0.1",
port=int(parts.port or 0),
user=user, pw=pw, force_auth=force_auth,
use_ssl=use_ssl, ssl_verify=ssl_verify,
ssl_ca_file=ssl_ca_file, ssl_certfile=ssl_cert, ssl_keyfile=ssl_key,
timeout=timeout, total_timeout=total_timeout, chunk_size=chunk_size,
server_hostname=parts.hostname or None,
want_sha=want_sha,
enforce_path=enforce_path,
path=path_text, # also used as AF1 "scope"
)
return parts, opts
def _rewrite_url_without_auth(url):
u = urlparse(url)
netloc = u.hostname or ''
if u.port:
netloc += ':' + str(u.port)
rebuilt = urlunparse((u.scheme, netloc, u.path, u.params, u.query, u.fragment))
usr = unquote(u.username) if u.username else ''
pwd = unquote(u.password) if u.password else ''
return rebuilt, usr, pwd
def _guess_filename(url, filename):
if filename:
return filename
path = urlparse(url).path or ''
base = os.path.basename(path)
return base or 'CatFile'+__file_format_extension__
# ---- progress + rate limiting helpers ----
try:
monotonic = time.monotonic # Py3
except Exception:
# Py2 fallback: time.time() is good enough for coarse throttling
monotonic = time.time
def _progress_tick(now_bytes, total_bytes, last_ts, last_bytes, rate_limit_bps, min_interval=0.1):
"""
Returns (sleep_seconds, new_last_ts, new_last_bytes).
- If rate_limit_bps is set, computes how long to sleep to keep average <= limit.
- Also enforces a minimum interval between progress callbacks (handled by caller).
"""
now = monotonic()
elapsed = max(1e-9, now - last_ts)
# Desired time to have elapsed for the given rate:
desired = (now_bytes - last_bytes) / float(rate_limit_bps) if rate_limit_bps else 0.0
extra = desired - elapsed
return (max(0.0, extra), now, now_bytes)
def _discover_len_and_reset(fobj):
"""
Try to get total length and restore original position.
Returns (length_or_None, start_pos_or_None).
"""
# Generic seek/tell
try:
pos0 = fobj.tell()
fobj.seek(0, os.SEEK_END)
end = fobj.tell()
fobj.seek(pos0, os.SEEK_SET)
if end is not None and pos0 is not None and end >= pos0:
return (end - pos0, pos0)
except Exception:
pass
# BytesIO fast path
try:
getvalue = getattr(fobj, "getvalue", None)
if callable(getvalue):
buf = getvalue()
L = len(buf)
try: pos0 = fobj.tell()
except Exception: pos0 = 0
return (max(0, L - pos0), pos0)
except Exception:
pass
# Memoryview/getbuffer
try:
getbuffer = getattr(fobj, "getbuffer", None)
if callable(getbuffer):
mv = getbuffer()
L = len(mv)
try: pos0 = fobj.tell()
except Exception: pos0 = 0
return (max(0, L - pos0), pos0)
except Exception:
pass
return (None, None)
# ---------- helpers reused from your module ----------
# expects: _to_bytes, _to_text, _discover_len_and_reset, _qflag, _qnum, _qstr
# If you don't have _qflag/_qnum/_qstr here, reuse your existing ones.
# =========================
# URL parser for HTTP/HTTPS
# =========================
def _parse_http_url(url):
parts = urlparse(url)
qs = parse_qs(parts.query or "")
scheme = (parts.scheme or "").lower()
if scheme not in ("http", "https"):