-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpywwwget_chatgpt.py
More file actions
6755 lines (6010 loc) · 236 KB
/
pywwwget_chatgpt.py
File metadata and controls
6755 lines (6010 loc) · 236 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 -*-
"""
pywwwgetadv_clean.py
A small, self-contained subset of PyNeoWWW-Get style helpers that keeps the same
public API shape you were using:
- download_file_from_internet_file(url, headers=..., usehttp=...)
- download_file_from_internet_bytes(url, headers=..., usehttp=...)
- upload_file_to_internet_file(fileobj, url)
- upload_file_to_internet_bytes(bytestr, url)
Plus protocol-specific helpers (http/ftp/ftps/sftp/tcp/udp) and detect_cwd_ftp().
Design goals:
- Python 2.7 + Python 3.x compatible
- Minimal dependencies (stdlib first; requests/httpx/mechanize/paramiko/pysftp optional)
- TCP: stream + explicit end (FIN)
- UDP: reliable "udpseq" mode with explicit DONE frame (no silence wait), plus resume support
- Same "file-like object returned" behavior: caller can .read() and write it elsewhere.
URL formats (examples):
HTTP:
http://example.com/file
http://user:pass@example.com/file
FTP/FTPS:
ftp://user:pass@host:21/path/to/file
ftps://user:pass@host:990/path/to/file
SFTP:
sftp://user:pass@host:22/path/to/file
TCP receive (download):
tcp://0.0.0.0:7000/test.png?print_url=1&bind=0.0.0.0
tcp://0.0.0.0:0/test.png?print_url=1 (port=0 => auto-pick)
TCP send (upload):
tcp://host:7000/test.png
UDPSEQ receive (download, reliable UDP):
udp://0.0.0.0:7000/test.png?mode=seq&print_url=1
udp://0.0.0.0:0/test.png?mode=seq&print_url=1
UDPSEQ resume (receiver resumes into a file on disk):
udp://0.0.0.0:7000/test.png?mode=seq&resume=1&resume_to=/sdcard/Download/test.png&print_url=1
UDPSEQ send:
udp://host:7000/test.png?mode=seq&resume=1 (sender will ask receiver for offset)
Notes:
- For HTTP resume, use ?resume=1&resume_to=/path to append using Range header.
- For FTP/FTPS, see detect_cwd_ftp() (cwd fallback to absolute RETR paths).
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import io
import re
import sys
import json
import getpass
import random
import platform
import socket
import shutil
import time
import struct
import hmac
import hashlib
import tempfile
import zlib
import gzip
import ssl
import mimetypes
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)
defcert = None
try:
import certifi
defcert = certifi.where()
except ImportError:
pass
# Initialize mimetypes
try:
mimetypes.init()
except Exception:
pass
try:
import cookielib
except ImportError:
import http.cookiejar as cookielib
try:
from Cookie import SimpleCookie # Py2
except ImportError:
from http.cookies import SimpleCookie # Py3
try:
from io import BytesIO
except ImportError:
try:
from cStringIO import StringIO as BytesIO # py2 fallback
except Exception:
from StringIO import StringIO as BytesIO
try:
# Py3
from urllib.parse import quote_from_bytes, unquote_to_bytes, urlencode
from urllib.request import install_opener, build_opener
except ImportError:
# Py2
from urllib import urlencode
from urllib import quote as _quote
from urllib import unquote as _unquote
from urllib2 import install_opener, build_opener
def quote_from_bytes(b, safe=''):
# Py2 urllib.quote expects "str" (bytes)
return _quote(b, safe=safe)
def unquote_to_bytes(s):
# Returns "str" (bytes) in Py2
return _unquote(s)
_TEXT_MIME_DEFAULT = 'text/plain; charset=utf-8'
_BIN_MIME_DEFAULT = 'application/octet-stream'
PY2 = (sys.version_info[0] == 2)
# get_readable_size by Lipis
# http://stackoverflow.com/posts/14998888/revisions
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):
"""
Heuristic: treat as text if it decodes as UTF-8 and does not contain many
control bytes (except common whitespace).
"""
if not data_bytes:
return True
# Fast path: NUL strongly suggests binary
if b'\x00' in data_bytes:
return False
try:
decoded = data_bytes.decode('utf-8')
except Exception:
return False
# Count "control" chars excluding common whitespace
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
# Allow a small fraction of control chars
return control <= max(1, len(decoded) // 200)
def data_url_encode(fileobj,
mime=None,
is_text=None,
charset='utf-8',
base64_encode=None):
"""
Read all bytes from a file-like object and return a data: URL string.
Args:
fileobj: file-like (must support read()) returning bytes/str.
mime: optional MIME type (e.g. 'image/png', 'text/plain').
If not provided, defaults to text/plain; charset=utf-8 for text
or application/octet-stream for binary.
is_text: force text/binary decision (True/False). If None, auto-detect.
charset: charset used when defaulting to text/* or when mime starts with text/
and mime doesn't already declare a charset.
base64_encode: if True, always base64. If False, always percent-encode.
If None, choose percent-encode for text and base64 for binary.
Returns:
A unicode/text string containing the full data URL.
"""
raw = fileobj.read()
# Normalize to bytes
if isinstance(raw, text_type):
# If someone passed a text stream, encode it as utf-8 bytes
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:
# If it's a text/* mime and no charset declared, append one
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 # text => percent, binary => base64
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:
# Percent-encode bytes
encoded = quote_from_bytes(raw_bytes, safe="!$&'()*+,;=:@-._~")
if not isinstance(encoded, text_type):
# Py2 quote returns bytes-str; ensure unicode
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 _normalize_b64(s):
# Remove whitespace and newlines
s = ''.join(s.split())
# Normalize URL-safe base64 just in case
s = s.replace('-', '+').replace('_', '/')
# Fix missing padding
s = s + '=' * (-len(s) % 4)
return s
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:
cleaned = _normalize_b64(data_part)
decoded_bytes = base64.b64decode(cleaned.encode('ascii'), validate=False)
except (binascii.Error, ValueError) as e:
raise ValueError(
"Invalid base64 data URL payload: {0}".format(e)
)
else:
decoded_bytes = unquote_to_bytes(data_part)
if isinstance(decoded_bytes, text_type):
decoded_bytes = decoded_bytes.encode('latin-1')
return MkTempFile(decoded_bytes), mime, is_base64
try:
from urllib.parse import urlparse, urlunparse, parse_qs, unquote
from urllib.request import Request, build_opener, HTTPBasicAuthHandler, HTTPCookieProcessor, HTTPSHandler
from urllib.error import URLError, HTTPError
from urllib.request import HTTPPasswordMgrWithDefaultRealm
except Exception:
from urlparse import urlparse, urlunparse, parse_qs # type: ignore
from urllib2 import Request, build_opener, HTTPBasicAuthHandler, HTTPCookieProcessor, HTTPSHandler, URLError, HTTPError # type: ignore
from urllib2 import HTTPPasswordMgrWithDefaultRealm # type: ignore
try:
from urllib import unquote # py2
except Exception:
def unquote(x): # very small fallback
return x
# HTTP server (for send-file mode)
try:
# py3
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver as _socketserver
except Exception:
# py2
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer # type: ignore
import SocketServer as _socketserver # type: ignore
# Optional deps
haverequests = False
try:
import requests # noqa
haverequests = True
except Exception:
pass
haveurllib3 = False
try:
import urllib3 # noqa
haveurllib3 = True
except Exception:
pass
havehttpx = False
try:
import httpx # noqa
havehttpx = True
except Exception:
pass
havehttpcore = False
try:
import httpcore
havehttpcore = True
except ImportError:
pass
havemechanize = False
try:
import mechanize # noqa
havemechanize = True
except Exception:
pass
havepycurl = False
try:
import pycurl
havepycurl = True
except ImportError:
pass
haveparamiko = False
try:
import paramiko # noqa
haveparamiko = True
except Exception:
pass
havepysftp = False
try:
import pysftp # noqa
havepysftp = True
except Exception:
pass
# FTP
ftpssl = True
try:
from ftplib import FTP, FTP_TLS, all_errors
except Exception:
ftpssl = False
from ftplib import FTP, all_errors # type: ignore
try:
basestring
except NameError:
basestring = str
# --- Configuration ---
__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.iteritems()}
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.iteritems():
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.iteritems():
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 # 4 MiB per spooled temp file
__spoolfile_size__ = DEFAULT_SPOOL_MAX
DEFAULT_BUFFER_MAX = 256 * BYTES_PER_KiB # 256 KiB copy buffer
__filebuff_size__ = DEFAULT_BUFFER_MAX
# ---- Py2/Py3 type helpers ----
try:
text_type = unicode # noqa: F821 (Py2)
except NameError:
text_type = str # Py3
binary_types = (bytes, bytearray)
try:
binary_types = (bytes, bytearray, memoryview) # Py3 has memoryview; Py2 does too, but keep safe
except NameError:
pass
# --------------------------
# Small helpers
# --------------------------
def _best_lan_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
finally:
s.close()
except Exception:
return None
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 = []
if not bind_host or bind_host == "0.0.0.0":
urls.append("%s://127.0.0.1:%d%s%s" % (scheme, port, path, q))
ip = _best_lan_ip()
if ip and ip != "127.0.0.1":
urls.append("%s://%s:%d%s%s" % (scheme, ip, port, path, q))
else:
urls.append("%s://%s:%d%s%s" % (scheme, bind_host, port, path, q))
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):
"""
Return a file-like handle with consistent behavior on Py2.7 and Py3.x.
Storage:
- inmem=True, usememfd=True, isbytes=True and memfd available
-> memfd-backed anonymous file (binary)
- inmem=True, otherwise
-> BytesIO (bytes) or StringIO (text)
- inmem=False, use_spool=True
-> SpooledTemporaryFile (binary), optionally TextIOWrapper for text
- inmem=False, use_spool=False
-> NamedTemporaryFile (binary), optionally TextIOWrapper for text
Text vs bytes:
- isbytes=True -> file expects bytes; 'data' must be bytes-like (or str which will be encoded)
- isbytes=False -> file expects text; 'data' must be text (or bytes which will be decoded)
Notes:
- On Windows, NamedTemporaryFile(delete=True) keeps the file open and cannot be reopened by
other processes. Use delete=False if you need to pass the path elsewhere.
- For text: in-memory StringIO ignores 'newline' and 'text_errors' (as usual).
- When available, and if usememfd=True, memfd is used only for inmem=True and isbytes=True
(Linux-only).
- If autoswitch_spool=True and initial data size exceeds spool_max, in-memory storage is
skipped and a spooled file is used instead (if use_spool=True).
- If on_create is not None, it is called as on_create(fp, kind) where kind is one of:
"memfd", "bytesio", "stringio", "spool", "disk".
"""
# ---- sanitize params (avoid None surprises) ----
prefix = prefix or ""
suffix = suffix or ""
# dir/spool_dir may be None (allowed)
# ---- normalize initial data to the right type early ----
init = None
if data is not None:
if isbytes:
# Require bytes-like; allow common safe conversions
if isinstance(data, binary_types):
# bytes / bytearray / memoryview
init = bytes(data) if not isinstance(data, bytes) else data
elif isinstance(data, text_type):
init = data.encode(encoding)
else:
raise TypeError("data must be bytes-like for isbytes=True")
else:
# Require text; allow decoding from bytes-like
if isinstance(data, binary_types):
# NOTE: preserve original behavior: STRICT decode here (not text_errors)
init = bytes(data).decode(encoding, errors="strict")
elif isinstance(data, text_type):
init = data
else:
raise TypeError("data must be text (str/unicode) for isbytes=False")
init_len = len(init) if (init is not None and isbytes) else None
# ---- helper: callback ----
def _created(fp, kind):
if on_create is not None:
on_create(fp, kind)
# ---- helper: wrap binary handle as text with encoding/newline/errors ----
def _wrap_text(binary_handle):
# Prefer TextIOWrapper when available/usable.
# In Py2, io.TextIOWrapper exists and works with binary handles.
return io.TextIOWrapper(binary_handle, encoding=encoding,
newline=newline, errors=text_errors)
# =========================
# In-memory branch
# =========================
if inmem:
# optional autoswitch to spool for large initial bytes payload
if autoswitch_spool and use_spool and init_len is not None and init_len > spool_max:
# fall through to spool/disk branches below
pass
else:
# memfd only for bytes and only where available (Linux + Python that exposes it)
memfd_create = getattr(os, "memfd_create", None)
if usememfd and isbytes and callable(memfd_create):
name = memfd_name or prefix or "MkTempFile"
flags = 0
# Close-on-exec is almost always what you want for temps
if hasattr(os, "MFD_CLOEXEC"):
flags |= os.MFD_CLOEXEC
# Optional sealing support
if memfd_allow_sealing and hasattr(os, "MFD_ALLOW_SEALING"):
flags |= os.MFD_ALLOW_SEALING
if memfd_flags_extra:
flags |= int(memfd_flags_extra)
fd = memfd_create(name, flags)
f = os.fdopen(fd, "w+b")
if init is not None:
f.write(init)
if reset_to_start:
f.seek(0)
_created(f, "memfd")
return f
# Fallback: pure-Python in-memory objects
if isbytes:
f = BytesIO(init if init is not None else b"")
if reset_to_start:
f.seek(0)
_created(f, "bytesio")
return f
else:
# StringIO ignores newline/text_errors by design
f = io.StringIO(init if init is not None else u"")
if reset_to_start:
f.seek(0)
_created(f, "stringio")
return f
# =========================
# Spooled (RAM then disk)
# =========================
if use_spool:
# Always create binary spooled file; wrap for text if needed
b = tempfile.SpooledTemporaryFile(max_size=spool_max, mode="w+b", dir=spool_dir)
f = b if isbytes else _wrap_text(b)
if init is not None:
f.write(init)
if reset_to_start:
f.seek(0)
_created(f, "spool")
return f
# =========================
# On-disk temp (NamedTemporaryFile)
# =========================
b = tempfile.NamedTemporaryFile(mode="w+b", prefix=prefix, suffix=suffix, dir=dir, delete=delete)
f = b if isbytes else _wrap_text(b)
if init is not None:
f.write(init)
if reset_to_start:
f.seek(0)
_created(f, "disk")
return f
def _hs_token():
# short ascii token for handshake correlation
try:
import random
return ('%x' % random.getrandbits(64)).encode('ascii')
except Exception:
try:
return ('%x' % (int(time.time()*1000000) ^ os.getpid())).encode('ascii')
except Exception:
return ('%x' % int(time.time()*1000000)).encode('ascii')
def _byte_at(b, i):
"""Get integer value of byte at index i for Py2/Py3."""
v = b[i]
return v if isinstance(v, int) else ord(v)
def _to_bytes(x):
if x is None:
return b""
if isinstance(x, bytes):
return x
try:
return x.encode("utf-8")
except Exception:
return bytes(x)
def _to_text(x):
if x is None:
return u""
if isinstance(x, bytes):
try:
return x.decode("utf-8", "replace")
except Exception:
return x.decode("latin-1", "replace")
return x
def _rand_u64():
# os.urandom works on py2/py3
return struct.unpack("!Q", os.urandom(8))[0]
def _set_query_param(url, key, value):
"""Return url with query param key set to value (string)."""
try:
up = urlparse(url)
qs = up.query or ""
parts = []
if qs:
for kv in qs.split("&"):
if not kv:
continue
if kv.split("=", 1)[0] != key:
parts.append(kv)
parts.append("%s=%s" % (key, value))
newq = "&".join(parts)
return urlunparse((up.scheme, up.netloc, up.path, up.params, newq, up.fragment))
except Exception:
return url
def _qflag(qs, key, default=False):
v = qs.get(key, [None])[0]
if v is None:
return default
v = _to_text(v).strip().lower()
return v in ("1", "true", "yes", "on", "y")
def _qnum(qs, key, default, cast=int):
v = qs.get(key, [None])[0]
if v is None or v == "":
return default
try:
return cast(v)
except Exception:
try:
return cast(_to_text(v))
except Exception:
return default
def _qstr(qs, key, default=None):
v = qs.get(key, [None])[0]
if v is None:
return default
return _to_text(v)
def _ensure_dir(d):
if not d:
return
if not os.path.isdir(d):
try:
os.makedirs(d)
except Exception:
pass
def _guess_filename(url):
p = urlparse(url)
bn = os.path.basename(p.path or "")
return bn or "download.bin"
def _choose_output_path(fname, overwrite=False, save_dir=None):
if not save_dir:
save_dir = "."
_ensure_dir(save_dir)
base = os.path.join(save_dir, fname)
if overwrite or not os.path.exists(base):
return base
root, ext = os.path.splitext(base)
for i in range(1, 10000):
cand = "%s.%d%s" % (root, i, ext)
if not os.path.exists(cand):
return cand
return base
def _copy_fileobj_to_path(fileobj, path, overwrite=False):
if (not overwrite) and os.path.exists(path):
raise IOError("Refusing to overwrite: %s" % path)
_ensure_dir(os.path.dirname(path) or ".")
with open(path, "wb") as out:
try:
fileobj.seek(0, 0)
except Exception:
pass
shutil.copyfileobj(fileobj, out)
# TFTP opcodes
OP_RRQ = 1
OP_WRQ = 2
OP_DATA = 3
OP_ACK = 4
OP_ERROR = 5
BLOCK_SIZE = 512
class TFTPError(Exception):
pass
def _make_rrq(filename, mode=b"octet"):
# RRQ: 2 bytes opcode, filename, 0, mode, 0
return struct.pack("!H", OP_RRQ) + _to_bytes(filename) + b"\x00" + _to_bytes(mode) + b"\x00"
def _make_wrq(filename, mode=b"octet"):
return struct.pack("!H", OP_WRQ) + _to_bytes(filename) + b"\x00" + _to_bytes(mode) + b"\x00"
def _make_data(blockno, payload):
return struct.pack("!HH", OP_DATA, blockno) + payload
def _make_ack(blockno):
return struct.pack("!HH", OP_ACK, blockno)
def _parse_packet(pkt):