Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathurlutils.py
More file actions
Latest commit
948 lines (843 loc) · 31.8 KB
/
Copy pathurlutils.py
File metadata and controls
948 lines (843 loc) · 31.8 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
importos
importtime
from .loggingimportLOGGER
from .fsutilsimportensure_tree, rmtree, unlink
from .pathutilsimportPath, PurePath
from .exceptionsimportInvalidFeedError
try:
from_nativeimportfile_url_to_path
exceptImportError:
fromnturl2pathimporturl2pathnameasfile_url_to_path
# Indexes into winhttp_urlsplit result for readability
U_SCHEME=0
U_USERNAME=1
U_PASSWORD=2
U_NETLOC=3
U_PORT=4
U_PATH=5
U_EXTRA=6
try:
from_nativeimportwinhttp_urlsplit, winhttp_urlunsplit
exceptImportError:
importurllib.parse
defwinhttp_urlsplit(u):
p=urllib.parse.urlsplit(u)
extra=f"?{p.query}"ifp.queryelse""
extra=f"{extra}#{p.fragment}"ifp.fragmentelseextra
return (p.scheme, p.username, p.password, p.hostname, p.port, p.path, extra)
defwinhttp_urlunsplit(*a):
netloc=a[U_NETLOC]
ifa[U_USERNAME]:
ifa[U_PASSWORD]:
netloc=f"{a[U_USERNAME]}:{a[U_PASSWORD]}@{netloc}"
else:
netloc=f"{a[U_USERNAME]}@{netloc}"
ifa[U_PORT]:
ifa[U_PORT] ==80anda[U_SCHEME].casefold() =="http":
pass
elifa[U_PORT] ==443anda[U_SCHEME].casefold() =="https":
pass
else:
netloc=f"{netloc}:{a[U_PORT]}"
ifa[U_EXTRA]:
query, _, fragment=a[U_EXTRA].rpartition("#")
ifquery[:1] =="?":
query=query[1:]
else:
query=fragment=""
returnurllib.parse.urlunsplit((a[0], netloc, a[U_PATH], query, fragment))
ENABLE_BITS=os.getenv("PYMANAGER_ENABLE_BITS_DOWNLOAD", "1").lower()[:1] in"1yt"
ENABLE_WINHTTP=os.getenv("PYMANAGER_ENABLE_WINHTTP_DOWNLOAD", "1").lower()[:1] in"1yt"
ENABLE_URLLIB=os.getenv("PYMANAGER_ENABLE_URLLIB_DOWNLOAD", "1").lower()[:1] in"1yt"
ENABLE_POWERSHELL=os.getenv("PYMANAGER_ENABLE_POWERSHELL_DOWNLOAD", "1").lower()[:1] in"1yt"
SUPPORTED_SCHEMES="http".casefold(), "https".casefold(), "file".casefold()
PROXY_MODE_AUTO=0
PROXY_MODE_DIRECT=1
PROXY_MODE_OVERRIDE=2
class_ProxySettings:
def__init__(
self,
mode=PROXY_MODE_AUTO,
proxy_list=None,
powershell_proxy=None,
username=None,
password=None,
):
self.mode=mode
self.proxy_list=proxy_list
self.powershell_proxy=powershell_proxy
self.username=username
self.password=password
defas_native(self):
returnself.mode, self.proxy_list, self.username, self.password
def_parse_proxy(value):
parts=list(winhttp_urlsplit(valueif"://"invalueelsef"http://{value}"))
ifnotparts[U_NETLOC]:
raiseValueError("Proxy URL does not contain a host")
has_credentials=parts[U_USERNAME] isnotNoneorparts[U_PASSWORD] isnotNone
credentials=None
ifhas_credentials:
credentials=parts[U_USERNAME] or"", parts[U_PASSWORD] or""
parts[U_USERNAME] =None
parts[U_PASSWORD] =None
parts[U_PATH] =""
parts[U_EXTRA] =""
proxy=winhttp_urlunsplit(*parts).removesuffix("/")
returnproxy, credentials
def_proxy_settings_from_env():
ifos.getenv("NO_PROXY"):
return_ProxySettings(mode=PROXY_MODE_DIRECT)
http_value=os.getenv("HTTP_PROXY")
https_value=os.getenv("HTTPS_PROXY")
ifnothttp_valueandnothttps_value:
return_ProxySettings()
http_proxy=http_credentials=None
https_proxy=https_credentials=None
ifhttp_value:
http_proxy, http_credentials=_parse_proxy(http_value)
ifhttps_value:
https_proxy, https_credentials=_parse_proxy(https_value)
proxy_list=" ".join(
valueforvaluein (
f"http={http_proxy}"ifhttp_proxyelseNone,
f"https={https_proxy}"ifhttps_proxyelseNone,
) ifvalue
)
credentials=https_credentialsorhttp_credentialsor (None, None)
return_ProxySettings(
mode=PROXY_MODE_OVERRIDE,
proxy_list=proxy_list,
powershell_proxy=https_proxyorhttp_proxy,
username=credentials[0],
password=credentials[1],
)
classNoInternetError(Exception):
pass
class_Request:
def__init__(self, url, method="GET", headers={}, outfile=None):
self.url=url
self.method=method.upper()
self.headers=dict(headers)
self.chunksize=64*1024
self.username=None
self.password=None
self.outfile=Path(outfile) ifoutfileelseNone
self.proxy_settings=_proxy_settings_from_env()
self._on_progress=None
self._on_auth_request=None
self._on_cancel=None
def__str__(self):
returnsanitise_url(self.url)
defon_progress(self, progress):
ifself._on_progress:
self._on_progress(progress)
defon_auth_request(self, url=None):
ifurlisNone:
url=self.url
ifself._on_auth_request:
returnself._on_auth_request(url)
ifself.usernameorself.password:
returnself.username, self.password
returnNone
defon_cancel(self):
ifself._on_cancel:
returnself._on_cancel()
returnFalse
def_bits_urlretrieve(request):
from_nativeimport (coinitialize, bits_connect, bits_begin, bits_cancel,
bits_get_progress, bits_retry_with_auth, bits_find_job, bits_serialize_job)
assertrequest.outfile
LOGGER.debug("_bits_urlretrieve: %s", request)
coinitialize()
bits=bits_connect()
outfile=request.outfile
job=None
jobfile=outfile.with_suffix(".job")
last_progress=None
tried_auth=False
try:
job_id=jobfile.read_bytes()
exceptOSError:
job_id=None
else:
LOGGER.debug("Recovering job %s from %s", job_id, jobfile)
try:
ifjob_id:
try:
job=bits_find_job(bits, job_id)
exceptOSErrorasex:
LOGGER.debug("Failed to recover job due to %s", ex)
job=None
else:
last_progress=bits_get_progress(bits, job)
ifnotjob:
LOGGER.debug("Starting new BITS job: %s -> %s", request, outfile)
ensure_tree(outfile)
job=bits_begin(
bits,
PurePath(outfile).name,
request.url,
outfile,
proxy_settings=request.proxy_settings.as_native(),
)
LOGGER.debug("Writing %s", jobfile)
jobfile.write_bytes(bits_serialize_job(bits, job))
LOGGER.debug("Downloading %s", request)
last_progress=-1
whilelast_progress<100:
try:
progress=bits_get_progress(bits, job)
exceptOSErrorasex:
if (ex.winerroror0) &0xFFFFFFFF==0x80190191:
# Returned HTTP status 401 (0x191)
ifnottried_auth:
auth=request.on_auth_request()
ifauth:
tried_auth=True
bits_retry_with_auth(bits, job, *auth)
continue
if (ex.winerroror0) &0xFFFFFFFF==0x80190194:
# Returned HTTP status 404 (0x194)
raiseFileNotFoundError() fromex
raise
ifprogress>last_progress:
request.on_progress(progress)
last_progress=progress
time.sleep(0.1)
exceptKeyboardInterrupt:
request.on_progress(None)
ifjobandrequest.on_cancel():
try:
bits_cancel(bits, job)
exceptOSError:
LOGGER.warn("Failed to cancel background download.")
LOGGER.debug("ERROR:", exc_info=True)
else:
ifjobfile.is_file():
unlink(jobfile)
raise
exceptOSErrorasex:
ifjob:
bits_cancel(bits, job)
ifjobfile.is_file():
unlink(jobfile)
if (ex.winerroror0) &0xFFFFFFFF==0x80200010:
raiseNoInternetError() fromex
raise
unlink(jobfile)
def_winhttp_urlopen(request):
from_nativeimportwinhttp_urlopen, winhttp_isconnected
headers= {k.lower(): vfork, vinrequest.headers.items()}
accept=headers.pop("accept", "application/*;text/*")
header_str="\r\n".join(f"{k}: {v}"fork, vinheaders.items())
method=request.method.upper()
LOGGER.debug("winhttp_urlopen: %s", request)
try:
data=winhttp_urlopen(request.url, method, header_str, accept,
request.chunksize, request.on_progress, request.on_auth_request,
request.proxy_settings.as_native())
exceptOSErrorasex:
ifex.winerror==0x00002EE7:
LOGGER.debug("winhttp_isconnected: %s", winhttp_isconnected())
ifnotwinhttp_isconnected():
raiseNoInternetError() fromex
if (ex.winerroror0) &0xFFFFFFFF==0x80190194:
# Returned HTTP status 404 (0x194)
raiseFileNotFoundError() fromex
raise
ifdata[:3] ==b"\xEF\xBB\xBF":
data=data[3:]
returndata
def_winhttp_urlretrieve(request):
assertrequest.outfile
request.outfile.write_bytes(_winhttp_urlopen(request))
def_basic_auth_header(username, password):
frombase64importb64encode
pair=f"{username}:{password}".encode("utf-8")
token=b64encode(pair)
return"Basic "+token.decode("ascii")
def_urllib_urlopen(request):
importurllib.error
fromurllib.requestimportRequest, urlopen
LOGGER.debug("urlopen: %s", request)
req=Request(request.url, method=request.method, headers=request.headers)
try:
request.on_progress(0)
try:
r=urlopen(req)
excepturllib.error.HTTPErrorasex:
ifex.status==401:
auth=request.on_auth_request()
ifnotauth:
raise
req.headers["Authorization"] =_basic_auth_header(*auth)
r=urlopen(req)
elifex.status==404:
raiseFileNotFoundErrorfromex
else:
raise
withr:
data=r.read()
request.on_progress(100)
returndata
finally:
LOGGER.debug("urlopen: complete")
def_urllib_urlretrieve(request):
importurllib.error
fromurllib.requestimportRequest, urlopen
outfile=request.outfile
LOGGER.debug("urlretrieve: %s -> %s", request, outfile)
ensure_tree(outfile)
unlink(outfile)
req=Request(request.url, method=request.method, headers=request.headers)
try:
request.on_progress(0)
try:
r=urlopen(req)
excepturllib.error.HTTPErrorasex:
ifex.status==401:
req.auth=request.on_auth_request()
ifnotreq.auth:
raise
r=urlopen(req)
else:
raise
withr:
progress=0
try:
total=int(r.headers.get("Content-Length", 0))
exceptValueError:
total=1
withopen(outfile, "wb") asf:
forchunkiniter(lambda: r.read(request.chunksize), b""):
f.write(chunk)
progress+=len(chunk)
request.on_progress((progress*100) //total)
request.on_progress(100)
finally:
LOGGER.debug("urlretrieve: complete")
def_powershell_urlopen(request):
importtempfile
cwd=tempfile.mkdtemp()
try:
request.outfile=Path(cwd) /"response.dat"
_powershell_urlretrieve(request)
returnrequest.outfile.read_bytes()
finally:
rmtree(cwd)
def_powershell_urlretrieve(request):
frombase64importb64encode
importjson
importsubprocess
headers=request.headers
if"Authorization"notinheaders:
auth=extract_url_auth(request.url)
ifnotauth:
auth=request.on_auth_request(request.url)
ifauth:
headers= {**headers, "Authorization": _basic_auth_header(*auth)}
powershell=Path(os.getenv("SystemRoot")) /"System32/WindowsPowerShell/v1.0/powershell.exe"
# Security hardening: avoid PowerShell command injection by using env vars instead of interpolation
script=r"""$ProgressPreference = "SilentlyContinue"
$url = $env:PYMANAGER_URL
$outfile = $env:PYMANAGER_OUTFILE
$method = $env:PYMANAGER_METHOD
$proxyMode = $env:PYMANAGER_PROXY_MODE
$proxy = $env:PYMANAGER_PROXY
$proxyUser = $env:PYMANAGER_PROXY_USERNAME
$proxyPassword = $env:PYMANAGER_PROXY_PASSWORD
$proxyHasCredentials = $env:PYMANAGER_PROXY_HAS_CREDENTIALS -eq "1"
$proxyArgs = @{}
if ($proxyMode -eq "direct") {
[System.Net.WebRequest]::DefaultWebProxy = [System.Net.WebProxy]::new()
} elseif ($proxyMode -eq "override") {
$proxyArgs["Proxy"] = [Uri]$proxy
if ($proxyHasCredentials) {
$securePassword = ConvertTo-SecureString $proxyPassword -AsPlainText -Force
$proxyArgs["ProxyCredential"] = [pscredential]::new($proxyUser, $securePassword)
} else {
$proxyArgs["ProxyUseDefaultCredentials"] = $true
}
}
$headersObj = ConvertFrom-Json $env:PYMANAGER_HEADERS
$headers = @{}
if ($headersObj -ne $null) {
$headersObj.PSObject.Properties | ForEach-Object {
$name = $_.Name
$value = $_.Value
$headers[$name] = if ($value -eq $null) { "" } else { $value.ToString() }
}
}
$r = Invoke-WebRequest -Uri $url -UseBasicParsing `
-Headers $headers `
-UseDefaultCredentials `
-Method $method `
-OutFile $outfile `
@proxyArgs
"""
LOGGER.debug("PowerShell download invoked (env-based)")
env=os.environ.copy()
env.update({
"PYMANAGER_URL": request.url,
"PYMANAGER_OUTFILE": str(request.outfile),
"PYMANAGER_METHOD": request.method,
"PYMANAGER_HEADERS": json.dumps(headers),
"PYMANAGER_PROXY_MODE": {
PROXY_MODE_AUTO: "auto",
PROXY_MODE_DIRECT: "direct",
PROXY_MODE_OVERRIDE: "override",
}[request.proxy_settings.mode],
"PYMANAGER_PROXY": request.proxy_settings.powershell_proxyor"",
"PYMANAGER_PROXY_USERNAME": request.proxy_settings.usernameor"",
"PYMANAGER_PROXY_PASSWORD": request.proxy_settings.passwordor"",
"PYMANAGER_PROXY_HAS_CREDENTIALS": (
"1"ifany(
valueisnotNone
forvaluein (
request.proxy_settings.username,
request.proxy_settings.password,
)
) else"0"
),
})
withsubprocess.Popen(
[powershell,
"-ExecutionPolicy", "Bypass",
"-OutputFormat", "Text",
"-NonInteractive",
"-EncodedCommand", b64encode(script.encode("utf-16-le"))
],
cwd=request.outfile.parent,
env=env,
creationflags=subprocess.CREATE_NO_WINDOW,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
) asp:
request.on_progress(0)
start=time.time()
whileTrue:
try:
try:
out=p.communicate(b'', timeout=10.0)[0].decode("utf-8", "replace")
if'<S S="Error">Invoke-WebRequest'inout:
raiseRuntimeError("Powershell download failed:"+out)
request.on_progress(100)
LOGGER.debug("PowerShell Output: %s", out)
return
exceptsubprocess.TimeoutExpired:
ifnotrequest.outfile.exists():
# Suppress the original exception to avoid leaking the command
raisesubprocess.TimeoutExpired(powershell, int(time.time() -start)) fromNone
except:
p.terminate()
out=p.communicate()[0]
LOGGER.debug("PowerShell Output: %s", out.decode("utf-8", "replace"))
raise
defurlopen(url, method="GET", headers={}, on_progress=None, on_auth_request=None):
scheme, sep, path=url.partition("://")
ifnotsep:
scheme="file"
url=Path(url).absolute().as_uri()
elifscheme.casefold() notinSUPPORTED_SCHEMES:
raiseValueError(f"Unsupported scheme: {scheme}")
ifscheme.casefold() =="file".casefold():
withopen(file_url_to_path(url), "rb") asf:
returnf.read()
request=_Request(url, method=method, headers=headers)
request._on_progress=on_progress
request._on_auth_request=on_auth_request
first_error=None
ifENABLE_WINHTTP:
try:
return_winhttp_urlopen(request)
exceptImportError:
LOGGER.debug("WinHTTP module unavailable - using fallback")
exceptNoInternetErrorasex:
# No point going any further if WinHTTP has detected no internet
# connection.
request.on_progress(None)
LOGGER.error("Failed to download. Please connect to the internet and try again.")
raiseRuntimeError("Failed to download. Please connect to the internet and try again.") fromex
exceptFileNotFoundError:
# Indicates a successful 404, so let it bubble out
raise
exceptOSErrorasex:
request.on_progress(None)
LOGGER.verbose("Failed to download using WinHTTP. Retrying with fallback method.")
LOGGER.debug("ERROR:", exc_info=True)
first_error=ex
ifENABLE_URLLIB:
try:
return_urllib_urlopen(request)
exceptImportError:
LOGGER.debug("urllib download unavailable - using fallback")
except (AttributeError, TypeError, ValueError):
# Blame the caller for these errors and let them bubble out
raise
exceptFileNotFoundError:
# Indicates a successful 404, so let it bubble out
raise
exceptExceptionasex:
request.on_progress(None)
LOGGER.verbose("Failed to download using urllib. Retrying with fallback method.")
LOGGER.debug("ERROR:", exc_info=True)
first_error=first_errororex
ifENABLE_POWERSHELL:
try:
return_powershell_urlopen(request)
exceptFileNotFoundError:
LOGGER.debug("PowerShell download unavailable - using fallback")
exceptExceptionasex:
request.on_progress(None)
LOGGER.verbose("Failed to download using PowerShell. Retrying with fallback method.")
LOGGER.debug("ERROR:", exc_info=True)
first_error=first_errororex
iffirst_error:
raisefirst_error
raiseRuntimeError("Unable to download from the internet")
defurlretrieve(url, outfile, method="GET", headers={}, chunksize=64*1024,
on_progress=None, on_auth_request=None, on_cancel=None):
scheme, sep, path=url.partition("://")
ifnotsep:
scheme="file"
url=Path(url).absolute().as_uri()
elifscheme.casefold() notinSUPPORTED_SCHEMES:
raiseValueError(f"Unsupported scheme: {scheme}")
ifscheme.casefold() =="file".casefold():
ifon_progressisNone:
defon_progress(_): pass
withopen(file_url_to_path(url), "rb") asr:
ifr.seekable:
total=r.seek(0, os.SEEK_END)
r.seek(0, os.SEEK_SET)
else:
total=None
on_progress(0)
withopen(outfile, "wb") asf:
forchunkiniter(lambda: r.read(chunksize), b""):
f.write(chunk)
iftotal:
on_progress((100*f.tell()) //total)
on_progress(100)
return
request=_Request(url, method=method, headers=headers)
request.outfile=Path(outfile)
request.chunksize=chunksize
request._on_progress=on_progress
request._on_auth_request=on_auth_request
request._on_cancel=on_cancel
first_error=None
ifENABLE_BITSandmethod.upper() =="GET":
try:
return_bits_urlretrieve(request)
exceptImportError:
LOGGER.debug("BITS module unavailable - using fallback")
exceptNoInternetError:
request.on_progress(None)
LOGGER.verbose("Failed to download using BITS, "+
"possibly due to no internet. Retrying with fallback method.")
exceptFileNotFoundError:
# Indicates a successful 404, so let it bubble out
raise
exceptOSErrorasex:
request.on_progress(None)
LOGGER.verbose("Failed to download using BITS. Retrying with fallback method.")
LOGGER.debug("ERROR:", exc_info=True)
first_error=ex
ifENABLE_WINHTTP:
try:
return_winhttp_urlretrieve(request)
exceptImportError:
LOGGER.debug("WinHTTP module unavailable - using fallback")
exceptNoInternetErrorasex:
# No point going any further if WinHTTP has detected no internet
# connection.
request.on_progress(None)
LOGGER.error("Failed to download. Please connect to the internet and try again.")
raiseRuntimeError("Failed to download. Please connect to the internet and try again.") fromex
exceptFileNotFoundError:
# Indicates a successful 404, so let it bubble out
raise
exceptOSErrorasex:
request.on_progress(None)
LOGGER.verbose("Failed to download using WinHTTP. Retrying with fallback method.")
LOGGER.debug("ERROR:", exc_info=True)
first_error=first_errororex
ifENABLE_URLLIB:
try:
return_urllib_urlretrieve(request)
exceptImportError:
LOGGER.debug("urllib module unavailable - using fallback")
except (AttributeError, TypeError, ValueError):
# Blame the caller for these errors and let them bubble out
raise
exceptFileNotFoundError:
# Indicates a successful 404, so let it bubble out
raise
exceptExceptionasex:
request.on_progress(None)
LOGGER.verbose("Failed to download using urllib. Retrying with fallback method.")
LOGGER.debug("ERROR:", exc_info=True)
first_error=first_errororex
ifENABLE_POWERSHELL:
try:
return_powershell_urlretrieve(request)
exceptFileNotFoundError:
LOGGER.debug("PowerShell download unavailable - using fallback")
exceptExceptionasex:
request.on_progress(None)
LOGGER.verbose("Failed to download using PowerShell. Retrying with fallback method.")
LOGGER.debug("ERROR:", exc_info=True)
first_error=first_errororex
iffirst_error:
raisefirst_error
raiseRuntimeError("Unable to download from the internet")
defextract_url_auth(url):
ifnoturl:
returnurl
p=winhttp_urlsplit(url)
user, passw=p[U_USERNAME], p[U_PASSWORD]
ifuserorpassw:
returnuseror"", passwor""
returnNone
defsanitise_url(url):
ifnoturl:
returnurl
try:
p=list(winhttp_urlsplit(url))
exceptOSErrorasex:
# Errors for an invalid URL
ifex.winerrorin (12005, 12006):
returnurl
raise
u=p[U_USERNAME]
ifuandnot (u.startswith("%") andu.endswith("%")):
p[U_USERNAME] =None
pw=p[U_PASSWORD]
ifpwandnot (pw.startswith("%") andpw.endswith("%")):
p[U_PASSWORD] =None
returnwinhttp_urlunsplit(*p)
defunsanitise_url(url, candidates):
ifnoturl:
returnurl
try:
p=list(winhttp_urlsplit(url))
exceptOSErrorasex:
# Errors for an invalid URL
ifex.winerrorin (12005, 12006):
returnurl
raise
ifp[U_USERNAME] orp[U_PASSWORD]:
# URL contains user/pass info, so just return it
returnurl
best=None
forurl2incandidates:
p2=winhttp_urlsplit(url2)
if (
p[U_SCHEME].casefold() ==p2[U_SCHEME].casefold() and
p[U_NETLOC].casefold() ==p2[U_NETLOC].casefold() and
p[U_PORT] ==p2[U_PORT] and
p[U_PATH].casefold().startswith(p2[U_PATH].casefold())
):
ifbestisNoneorlen(p2[U_PATH]) >len(best[U_PATH]):
best=p2
ifbest:
p=list(p)
p[U_USERNAME] =best[U_USERNAME]
p[U_PASSWORD] =best[U_PASSWORD]
returnwinhttp_urlunsplit(*p)
defurljoin(base_url, other_url, *, to_parent=False):
ifnotother_url:
returnbase_url
scheme, sep, rest=other_url.partition("://")
ifsep:
returnother_url
scheme, _, base=base_url.partition("://")
path=base.lstrip("/")
trimmed="/"* (len(base) -len(path))
root, _, path=path.partition("/")
path=PurePath(path)
ifother_url.startswith("//"):
root, sep, other_url=other_url[2:].partition("/")
ifsep:
path=PurePath()
else:
to_parent=False
other_url=PurePath(other_url)
ifto_parent:
path=path.parent
url_path=str(path/other_url).replace("\\", "/").lstrip("/")
returnf"{scheme}://{trimmed}{root.rstrip('/')}/{url_path}"
defis_valid_url(url):
try:
winhttp_urlsplit(url)
returnTrue
exceptOSError:
pass
ifnoturl.lower().startswith("file://"):
returnFalse
try:
file_url_to_path(url)
returnTrue
exceptOSError:
pass
returnFalse
classIndexDownloader:
def__init__(self, cmd, source, index_cls, auth=None, cache=None):
self.cmd=cmd
self.index_cls=index_cls
self._url=source.rstrip("/")
ifnotself._url.casefold().endswith(".json".casefold()):
self._url+="/index.json"
self._auth=authifauthisnotNoneelse {}
self._cache=cacheifcacheisnotNoneelse {}
self._urlopen=urlopen
self.quiet=False
def__iter__(self):
returnself
defon_auth(self, url):
# TODO: Try looking for parent paths from URL
try:
returnself._auth[url]
exceptLookupError:
returnNone
defurlopen_index(self, url):
try:
returnself._urlopen(
url,
"GET",
{"Accept": "application/json"},
on_auth_request=self.on_auth,
)
exceptFileNotFoundError: # includes 404
(LOGGER.verboseifself.quietelseLOGGER.error)(
"Unable to find runtimes index at %s",
sanitise_url(url),
)
raise
exceptOSErrorasex:
(LOGGER.verboseifself.quietelseLOGGER.error)(
"Unable to access runtimes index at %s: %s",
sanitise_url(url),
ex.args[1] iflen(ex.args) >=2elseex,
)
raise
defverify(self, url, data, params, show_settings=False):
ifnotparamsornotparams.get("requires_signature"):
returnNone
ifshow_settings:
relevant_params= {k: params[k] forkin [
"requires_signature",
"required_root_subject",
"required_publisher_subject",
"required_publisher_eku",
] ifkinparams}
ifrelevant_params:
LOGGER.info("Using verification settings from the index.")
LOGGER.info(
"Check the log file or verbose output for the settings "
"being used. Copying these into your configuration "
"file's !G!'source_settings'!W! section to detect "
"changes."
)
LOGGER.verbose(
"Verifying with the below settings.\n%r",
{sanitise_url(url): relevant_params}
)
try:
cat=self._cache[url+".cat"]
exceptKeyError:
cat=None
ifnotcat:
try:
cat=self._urlopen(
url+".cat",
"GET",
{"Accept": "application/octet-stream"},
on_auth_request=self.on_auth,
)
self._cache[url+".cat"] =cat
exceptOSErrorasex:
LOGGER.error(
"The signature for %s could not be loaded.",
sanitise_url(url),
)
LOGGER.debug("TRACEBACK", exc_info=True)
ifself.cmdandnotself.cmd.ask_ny("Continue to install?"):
returnFalse
raiseInvalidFeedError(feed_url=url) fromex
fromtempfileimportmkdtemp
from_nativeimportverify_trust
tmp_dir=Path(mkdtemp(prefix="pymanager-"))
try:
tmp_data=tmp_dir/"index.json"
tmp_cat=tmp_dir/"index.json.cat"
tmp_data.write_bytes(data)
tmp_cat.write_bytes(cat)
verify_trust(
tmp_data,
tmp_cat,
params.get("required_root_subject"),
params.get("required_publisher_subject"),
params.get("required_publisher_eku"),
)
returnTrue
exceptOSErrorasex:
LOGGER.error(
"The signature for %s could not be verified.",
sanitise_url(url),
)
LOGGER.debug("TRACEBACK", exc_info=True)
ifself.cmdandnotself.cmd.ask_ny("Continue to install?"):
returnFalse
raiseInvalidFeedError(feed_url=url) fromex
finally:
rmtree(tmp_dir)
def__next__(self):
ifnotself._url:
raiseStopIteration
importjson
url=self._url
s_url=sanitise_url(url)
LOGGER.debug("Fetching: %s", url)
try:
data=self._cache[url]
parsed=json.loads(data)
LOGGER.debug("Fetched from cache")
except (LookupError, ValueError):
data=None
parsed=None
ifnotdata:
verified=None
try:
data=self.urlopen_index(url)
exceptRuntimeErrorasex:
(LOGGER.verboseifself.quietelseLOGGER.error)(
"An unexpected error occurred while downloading the index: %s",
ex,
)
raise
source_settings=self.cmd.source_settings.get(s_url) ifself.cmdelseNone
verified=self.verify(url, data, source_settings)
parsed=json.loads(data)
# The parsed index may also have its own verification parameters
ifnotsource_settingsandnotverified:
verified=self.verify(url, data, parsed, show_settings=True)
ifverifiedisTrue:
(LOGGER.verboseifself.quietelseLOGGER.info)(
"!G!The signature for %s was successfully verified.!W!",
s_url,
)
elifverifiedisFalse:
LOGGER.warn("Signature verification failure ignored for %s", s_url)
else:
(LOGGER.verboseifself.quietelseLOGGER.info)(
"No signature to verify for %s", s_url
)
self._cache[url] =data
index=self.index_cls(self._url, parsed)
ifparsed.get("next"):
self._url=urljoin(url, parsed["next"], to_parent=True)
else:
self._url=None
returnindex