forked from wbond/package_control
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPackage Control.py
4771 lines (3810 loc) · 176 KB
/
Package Control.py
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
# coding=utf-8
import sublime
import sublime_plugin
import os
import sys
import subprocess
import zipfile
import urllib
import urllib2
import json
from fnmatch import fnmatch
import re
import threading
import datetime
import time
import shutil
import tempfile
import httplib
import socket
import hashlib
import base64
import locale
import urlparse
import gzip
import StringIO
import zlib
if os.name == 'nt':
from ctypes import windll, create_unicode_buffer
def add_to_path(path):
# Python 2.x on Windows can't properly import from non-ASCII paths, so
# this code added the DOC 8.3 version of the lib folder to the path in
# case the user's username includes non-ASCII characters
if os.name == 'nt':
buf = create_unicode_buffer(512)
if windll.kernel32.GetShortPathNameW(path, buf, len(buf)):
path = buf.value
if path not in sys.path:
sys.path.append(path)
lib_folder = os.path.join(sublime.packages_path(), 'Package Control', 'lib')
add_to_path(os.path.join(lib_folder, 'all'))
import semver
if os.name == 'nt':
add_to_path(os.path.join(lib_folder, 'windows'))
from ntlm import ntlm
def unicode_from_os(e):
# This is needed as some exceptions coming from the OS are
# already encoded and so just calling unicode(e) will result
# in an UnicodeDecodeError as the string isn't in ascii form.
try:
# Sublime Text on OS X does not seem to report the correct encoding
# so we hard-code that to UTF-8
encoding = 'UTF-8' if os.name == 'darwin' else locale.getpreferredencoding()
return unicode(str(e), encoding)
# If the "correct" encoding did not work, try some defaults, and then just
# obliterate characters that we can't seen to decode properly
except UnicodeDecodeError:
encodings = ['utf-8', 'cp1252']
for encoding in encodings:
try:
return unicode(str(e), encoding, errors='strict')
except:
pass
return unicode(str(e), errors='replace')
def create_cmd(args, basename_binary=False):
if basename_binary:
args[0] = os.path.basename(args[0])
if os.name == 'nt':
return subprocess.list2cmdline(args)
else:
escaped_args = []
for arg in args:
if re.search('^[a-zA-Z0-9/_^\\-\\.:=]+$', arg) == None:
arg = u"'" + arg.replace(u"'", u"'\\''") + u"'"
escaped_args.append(arg)
return u' '.join(escaped_args)
# Monkey patch AbstractBasicAuthHandler to prevent infinite recursion
def non_recursive_http_error_auth_reqed(self, authreq, host, req, headers):
authreq = headers.get(authreq, None)
if not hasattr(self, 'retried'):
self.retried = 0
if self.retried > 5:
raise urllib2.HTTPError(req.get_full_url(), 401, "basic auth failed",
headers, None)
else:
self.retried += 1
if authreq:
mo = urllib2.AbstractBasicAuthHandler.rx.search(authreq)
if mo:
scheme, quote, realm = mo.groups()
if scheme.lower() == 'basic':
return self.retry_http_basic_auth(host, req, realm)
urllib2.AbstractBasicAuthHandler.http_error_auth_reqed = non_recursive_http_error_auth_reqed
class DebuggableHTTPResponse(httplib.HTTPResponse):
"""
A custom HTTPResponse that formats debugging info for Sublime Text
"""
_debug_protocol = 'HTTP'
def __init__(self, sock, debuglevel=0, strict=0, method=None):
# We have to use a positive debuglevel to get it passed to here,
# however we don't want to use it because by default debugging prints
# to the stdout and we can't capture it, so we use a special -1 value
if debuglevel == 5:
debuglevel = -1
httplib.HTTPResponse.__init__(self, sock, debuglevel, strict, method)
def begin(self):
return_value = httplib.HTTPResponse.begin(self)
if self.debuglevel == -1:
print '%s: Urllib2 %s Debug Read' % (__name__, self._debug_protocol)
headers = self.msg.headers
versions = {
9: 'HTTP/0.9',
10: 'HTTP/1.0',
11: 'HTTP/1.1'
}
status_line = versions[self.version] + ' ' + str(self.status) + ' ' + self.reason
headers.insert(0, status_line)
for line in headers:
print u" %s" % line.rstrip()
return return_value
def read(self, *args):
try:
return httplib.HTTPResponse.read(self, *args)
except (httplib.IncompleteRead) as (e):
return e.partial
class DebuggableHTTPSResponse(DebuggableHTTPResponse):
"""
A version of DebuggableHTTPResponse that sets the debug protocol to HTTPS
"""
_debug_protocol = 'HTTPS'
class DebuggableHTTPConnection(httplib.HTTPConnection):
"""
A custom HTTPConnection that formats debugging info for Sublime Text
"""
response_class = DebuggableHTTPResponse
_debug_protocol = 'HTTP'
def __init__(self, host, port=None, strict=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kwargs):
self.passwd = kwargs.get('passwd')
# Python 2.6.1 on OS X 10.6 does not include these
self._tunnel_host = None
self._tunnel_port = None
self._tunnel_headers = {}
httplib.HTTPConnection.__init__(self, host, port, strict, timeout)
def connect(self):
if self.debuglevel == -1:
print '%s: Urllib2 %s Debug General' % (__name__, self._debug_protocol)
print u" Connecting to %s on port %s" % (self.host, self.port)
httplib.HTTPConnection.connect(self)
def send(self, string):
# We have to use a positive debuglevel to get it passed to the
# HTTPResponse object, however we don't want to use it because by
# default debugging prints to the stdout and we can't capture it, so
# we temporarily set it to -1 for the standard httplib code
reset_debug = False
if self.debuglevel == 5:
reset_debug = 5
self.debuglevel = -1
httplib.HTTPConnection.send(self, string)
if reset_debug or self.debuglevel == -1:
if len(string.strip()) > 0:
print '%s: Urllib2 %s Debug Write' % (__name__, self._debug_protocol)
for line in string.strip().splitlines():
print ' ' + line
if reset_debug:
self.debuglevel = reset_debug
def request(self, method, url, body=None, headers={}):
original_headers = headers.copy()
# Handles the challenge request response cycle before the real request
proxy_auth = headers.get('Proxy-Authorization')
if os.name == 'nt' and proxy_auth and proxy_auth.lstrip()[0:4] == 'NTLM':
# The default urllib2.AbstractHTTPHandler automatically sets the
# Connection header to close because of urllib.addinfourl(), but in
# this case we are going to do some back and forth first for the NTLM
# proxy auth
headers['Connection'] = 'Keep-Alive'
self._send_request(method, url, body, headers)
response = self.getresponse()
content_length = int(response.getheader('content-length', 0))
if content_length:
response._safe_read(content_length)
proxy_authenticate = response.getheader('proxy-authenticate', None)
if not proxy_authenticate:
raise URLError('Invalid NTLM proxy authentication response')
ntlm_challenge = re.sub('^\s*NTLM\s+', '', proxy_authenticate)
if self.host.find(':') != -1:
host_port = self.host
else:
host_port = "%s:%s" % (self.host, self.port)
username, password = self.passwd.find_user_password(None, host_port)
domain = ''
user = username
if username.find('\\') != -1:
domain, user = username.split('\\', 1)
challenge, negotiate_flags = ntlm.parse_NTLM_CHALLENGE_MESSAGE(ntlm_challenge)
new_proxy_authorization = 'NTLM %s' % ntlm.create_NTLM_AUTHENTICATE_MESSAGE(challenge, user,
domain, password, negotiate_flags)
original_headers['Proxy-Authorization'] = new_proxy_authorization
response.close()
httplib.HTTPConnection.request(self, method, url, body, original_headers)
class DebuggableHTTPHandler(urllib2.HTTPHandler):
"""
A custom HTTPHandler that formats debugging info for Sublime Text
"""
def __init__(self, debuglevel=0, debug=False, **kwargs):
# This is a special value that will not trigger the standard debug
# functionality, but custom code where we can format the output
if debug:
self._debuglevel = 5
else:
self._debuglevel = debuglevel
self.passwd = kwargs.get('passwd')
def http_open(self, req):
def http_class_wrapper(host, **kwargs):
kwargs['passwd'] = self.passwd
return DebuggableHTTPConnection(host, **kwargs)
return self.do_open(http_class_wrapper, req)
class RateLimitException(httplib.HTTPException, urllib2.URLError):
"""
An exception for when the rate limit of an API has been exceeded.
"""
def __init__(self, host, limit):
httplib.HTTPException.__init__(self)
self.host = host
self.limit = limit
def __str__(self):
return ('Rate limit of %s exceeded for %s' % (self.limit, self.host))
if os.name == 'nt':
class ProxyNtlmAuthHandler(urllib2.BaseHandler):
handler_order = 300
auth_header = 'Proxy-Authorization'
def __init__(self, password_manager=None):
if password_manager is None:
password_manager = HTTPPasswordMgr()
self.passwd = password_manager
self.retried = 0
def http_error_407(self, req, fp, code, msg, headers):
proxy_authenticate = headers.get('proxy-authenticate')
if os.name != 'nt' or proxy_authenticate[0:4] != 'NTLM':
return None
type1_flags = ntlm.NTLM_TYPE1_FLAGS
if req.host.find(':') != -1:
host_port = req.host
else:
host_port = "%s:%s" % (req.host, req.port)
username, password = self.passwd.find_user_password(None, host_port)
if not username:
return None
if username.find('\\') == -1:
type1_flags &= ~ntlm.NTLM_NegotiateOemDomainSupplied
negotiate_message = ntlm.create_NTLM_NEGOTIATE_MESSAGE(username, type1_flags)
auth = 'NTLM %s' % negotiate_message
if req.headers.get(self.auth_header, None) == auth:
return None
req.add_unredirected_header(self.auth_header, auth)
return self.parent.open(req, timeout=req.timeout)
# The following code is wrapped in a try because the Linux versions of Sublime
# Text do not include the ssl module due to the fact that different distros
# have different versions
try:
import ssl
class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
"""
An exception for when an SSL certification is not valid for the URL
it was presented for.
"""
def __init__(self, host, cert, reason):
httplib.HTTPException.__init__(self)
self.host = host
self.cert = cert
self.reason = reason
def __str__(self):
return ('Host %s returned an invalid certificate (%s) %s\n' %
(self.host, self.reason, self.cert))
class ValidatingHTTPSConnection(DebuggableHTTPConnection):
"""
A custom HTTPConnection class that validates SSL certificates, and
allows proxy authentication for HTTPS connections.
"""
default_port = httplib.HTTPS_PORT
response_class = DebuggableHTTPSResponse
_debug_protocol = 'HTTPS'
def __init__(self, host, port=None, key_file=None, cert_file=None,
ca_certs=None, strict=None, **kwargs):
passed_args = {}
if 'timeout' in kwargs:
passed_args['timeout'] = kwargs['timeout']
DebuggableHTTPConnection.__init__(self, host, port, strict, **passed_args)
self.passwd = kwargs.get('passwd')
self.key_file = key_file
self.cert_file = cert_file
self.ca_certs = ca_certs
if 'user_agent' in kwargs:
self.user_agent = kwargs['user_agent']
if self.ca_certs:
self.cert_reqs = ssl.CERT_REQUIRED
else:
self.cert_reqs = ssl.CERT_NONE
def get_valid_hosts_for_cert(self, cert):
"""
Returns a list of valid hostnames for an SSL certificate
:param cert: A dict from SSLSocket.getpeercert()
:return: An array of hostnames
"""
if 'subjectAltName' in cert:
return [x[1] for x in cert['subjectAltName']
if x[0].lower() == 'dns']
else:
return [x[0][1] for x in cert['subject']
if x[0][0].lower() == 'commonname']
def validate_cert_host(self, cert, hostname):
"""
Checks if the cert is valid for the hostname
:param cert: A dict from SSLSocket.getpeercert()
:param hostname: A string hostname to check
:return: A boolean if the cert is valid for the hostname
"""
hosts = self.get_valid_hosts_for_cert(cert)
for host in hosts:
host_re = host.replace('.', '\.').replace('*', '[^.]*')
if re.search('^%s$' % (host_re,), hostname, re.I):
return True
return False
def _tunnel(self, ntlm_follow_up=False):
"""
This custom _tunnel method allows us to read and print the debug
log for the whole response before throwing an error, and adds
support for proxy authentication
"""
self._proxy_host = self.host
self._proxy_port = self.port
self._set_hostport(self._tunnel_host, self._tunnel_port)
self._tunnel_headers['Host'] = u"%s:%s" % (self.host, self.port)
self._tunnel_headers['User-Agent'] = self.user_agent
self._tunnel_headers['Proxy-Connection'] = 'Keep-Alive'
request = "CONNECT %s:%d HTTP/1.1\r\n" % (self.host, self.port)
for header, value in self._tunnel_headers.iteritems():
request += "%s: %s\r\n" % (header, value)
self.send(request + "\r\n")
response = self.response_class(self.sock, strict=self.strict,
method=self._method)
(version, code, message) = response._read_status()
status_line = u"%s %s %s" % (version, code, message.rstrip())
headers = [status_line]
if self.debuglevel in [-1, 5]:
print '%s: Urllib2 %s Debug Read' % (__name__, self._debug_protocol)
print u" %s" % status_line
content_length = 0
close_connection = False
while True:
line = response.fp.readline()
if line == '\r\n': break
headers.append(line.rstrip())
parts = line.rstrip().split(': ', 1)
name = parts[0].lower()
value = parts[1].lower().strip()
if name == 'content-length':
content_length = int(value)
if name in ['connection', 'proxy-connection'] and value == 'close':
close_connection = True
if self.debuglevel in [-1, 5]:
print u" %s" % line.rstrip()
# Handle proxy auth for SSL connections since regular urllib2 punts on this
if code == 407 and self.passwd and ('Proxy-Authorization' not in self._tunnel_headers or ntlm_follow_up):
if content_length:
response._safe_read(content_length)
supported_auth_methods = {}
for line in headers:
parts = line.split(': ', 1)
if parts[0].lower() != 'proxy-authenticate':
continue
details = parts[1].split(' ', 1)
supported_auth_methods[details[0].lower()] = details[1] if len(details) > 1 else ''
username, password = self.passwd.find_user_password(None, "%s:%s" % (
self._proxy_host, self._proxy_port))
do_ntlm_follow_up = False
if 'digest' in supported_auth_methods:
response_value = self.build_digest_response(
supported_auth_methods['digest'], username, password)
if response_value:
self._tunnel_headers['Proxy-Authorization'] = u"Digest %s" % response_value
elif 'basic' in supported_auth_methods:
response_value = u"%s:%s" % (username, password)
response_value = base64.b64encode(response_value).strip()
self._tunnel_headers['Proxy-Authorization'] = u"Basic %s" % response_value
elif 'ntlm' in supported_auth_methods and os.name == 'nt':
ntlm_challenge = supported_auth_methods['ntlm']
if not len(ntlm_challenge):
type1_flags = ntlm.NTLM_TYPE1_FLAGS
if username.find('\\') == -1:
type1_flags &= ~ntlm.NTLM_NegotiateOemDomainSupplied
negotiate_message = ntlm.create_NTLM_NEGOTIATE_MESSAGE(username, type1_flags)
self._tunnel_headers['Proxy-Authorization'] = 'NTLM %s' % negotiate_message
do_ntlm_follow_up = True
else:
domain = ''
user = username
if username.find('\\') != -1:
domain, user = username.split('\\', 1)
challenge, negotiate_flags = ntlm.parse_NTLM_CHALLENGE_MESSAGE(ntlm_challenge)
self._tunnel_headers['Proxy-Authorization'] = 'NTLM %s' % ntlm.create_NTLM_AUTHENTICATE_MESSAGE(challenge, user,
domain, password, negotiate_flags)
if 'Proxy-Authorization' in self._tunnel_headers:
self.host = self._proxy_host
self.port = self._proxy_port
# If the proxy wanted the connection closed, we need to make a new connection
if close_connection:
self.sock.close()
self.sock = socket.create_connection((self.host, self.port), self.timeout)
return self._tunnel(do_ntlm_follow_up)
if code != 200:
self.close()
raise socket.error("Tunnel connection failed: %d %s" % (code,
message.strip()))
def build_digest_response(self, fields, username, password):
"""
Takes a Proxy-Authenticate: Digest header and creates a response
header
:param fields:
The string portion of the Proxy-Authenticate header after
"Digest "
:param username:
The username to use for the response
:param password:
The password to use for the response
:return:
None if invalid Proxy-Authenticate header, otherwise the
string of fields for the Proxy-Authorization: Digest header
"""
fields = urllib2.parse_keqv_list(urllib2.parse_http_list(fields))
realm = fields.get('realm')
nonce = fields.get('nonce')
qop = fields.get('qop')
algorithm = fields.get('algorithm')
if algorithm:
algorithm = algorithm.lower()
opaque = fields.get('opaque')
if algorithm in ['md5', None]:
def hash(string):
return hashlib.md5(string).hexdigest()
elif algorithm == 'sha':
def hash(string):
return hashlib.sha1(string).hexdigest()
else:
return None
host_port = u"%s:%s" % (self.host, self.port)
a1 = "%s:%s:%s" % (username, realm, password)
a2 = "CONNECT:%s" % host_port
ha1 = hash(a1)
ha2 = hash(a2)
if qop == None:
response = hash(u"%s:%s:%s" % (ha1, nonce, ha2))
elif qop == 'auth':
nc = '00000001'
cnonce = hash(urllib2.randombytes(8))[:8]
response = hash(u"%s:%s:%s:%s:%s:%s" % (ha1, nonce, nc, cnonce, qop, ha2))
else:
return None
response_fields = {
'username': username,
'realm': realm,
'nonce': nonce,
'response': response,
'uri': host_port
}
if algorithm:
response_fields['algorithm'] = algorithm
if qop == 'auth':
response_fields['nc'] = nc
response_fields['cnonce'] = cnonce
response_fields['qop'] = qop
if opaque:
response_fields['opaque'] = opaque
return ', '.join([u"%s=\"%s\"" % (field, response_fields[field]) for field in response_fields])
def connect(self):
"""
Adds debugging and SSL certification validation
"""
if self.debuglevel == -1:
print '%s: Urllib2 HTTPS Debug General' % __name__
print u" Connecting to %s on port %s" % (self.host, self.port)
self.sock = socket.create_connection((self.host, self.port), self.timeout)
if self._tunnel_host:
self._tunnel()
if self.debuglevel == -1:
print u"%s: Urllib2 HTTPS Debug General" % __name__
print u" Connecting to %s on port %s" % (self.host, self.port)
print u" CA certs file at %s" % (self.ca_certs)
self.sock = ssl.wrap_socket(self.sock, keyfile=self.key_file,
certfile=self.cert_file, cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs)
if self.debuglevel == -1:
print u" Successfully upgraded connection to %s:%s with SSL" % (
self.host, self.port)
# This debugs and validates the SSL certificate
if self.cert_reqs & ssl.CERT_REQUIRED:
cert = self.sock.getpeercert()
if self.debuglevel == -1:
subjectMap = {
'organizationName': 'O',
'commonName': 'CN',
'organizationalUnitName': 'OU',
'countryName': 'C',
'serialNumber': 'serialNumber',
'commonName': 'CN',
'localityName': 'L',
'stateOrProvinceName': 'S'
}
subject_list = list(cert['subject'])
subject_list.reverse()
subject_parts = []
for pair in subject_list:
if pair[0][0] in subjectMap:
field_name = subjectMap[pair[0][0]]
else:
field_name = pair[0][0]
subject_parts.append(field_name + '=' + pair[0][1])
print u" Server SSL certificate:"
print u" subject: " + ','.join(subject_parts)
if 'subjectAltName' in cert:
print u" common name: " + cert['subjectAltName'][0][1]
if 'notAfter' in cert:
print u" expire date: " + cert['notAfter']
hostname = self.host.split(':', 0)[0]
if not self.validate_cert_host(cert, hostname):
if self.debuglevel == -1:
print u" Certificate INVALID"
raise InvalidCertificateException(hostname, cert,
'hostname mismatch')
if self.debuglevel == -1:
print u" Certificate validated for %s" % hostname
if hasattr(urllib2, 'HTTPSHandler'):
class ValidatingHTTPSHandler(urllib2.HTTPSHandler):
"""
A urllib2 handler that validates SSL certificates for HTTPS requests
"""
def __init__(self, **kwargs):
# This is a special value that will not trigger the standard debug
# functionality, but custom code where we can format the output
self._debuglevel = 0
if 'debug' in kwargs and kwargs['debug']:
self._debuglevel = 5
elif 'debuglevel' in kwargs:
self._debuglevel = kwargs['debuglevel']
self._connection_args = kwargs
def https_open(self, req):
def http_class_wrapper(host, **kwargs):
full_kwargs = dict(self._connection_args)
full_kwargs.update(kwargs)
return ValidatingHTTPSConnection(host, **full_kwargs)
try:
return self.do_open(http_class_wrapper, req)
except urllib2.URLError, e:
if type(e.reason) == ssl.SSLError and e.reason.args[0] == 1:
raise InvalidCertificateException(req.host, '',
e.reason.args[1])
raise
https_request = urllib2.AbstractHTTPHandler.do_request_
except (ImportError):
pass
def preferences_filename():
""":return: The appropriate settings filename based on the version of Sublime Text"""
if int(sublime.version()) >= 2174:
return 'Preferences.sublime-settings'
return 'Global.sublime-settings'
class ThreadProgress():
"""
Animates an indicator, [= ], in the status area while a thread runs
:param thread:
The thread to track for activity
:param message:
The message to display next to the activity indicator
:param success_message:
The message to display once the thread is complete
"""
def __init__(self, thread, message, success_message):
self.thread = thread
self.message = message
self.success_message = success_message
self.addend = 1
self.size = 8
sublime.set_timeout(lambda: self.run(0), 100)
def run(self, i):
if not self.thread.is_alive():
if hasattr(self.thread, 'result') and not self.thread.result:
sublime.status_message('')
return
sublime.status_message(self.success_message)
return
before = i % self.size
after = (self.size - 1) - before
sublime.status_message('%s [%s=%s]' % \
(self.message, ' ' * before, ' ' * after))
if not after:
self.addend = -1
if not before:
self.addend = 1
i += self.addend
sublime.set_timeout(lambda: self.run(i), 100)
class PlatformComparator():
def get_best_platform(self, platforms):
ids = [sublime.platform() + '-' + sublime.arch(), sublime.platform(),
'*']
for id in ids:
if id in platforms:
return id
return None
class ChannelProvider(PlatformComparator):
"""
Retrieves a channel and provides an API into the information
The current channel/repository infrastructure caches repository info into
the channel to improve the Package Control client performance. This also
has the side effect of lessening the load on the GitHub and BitBucket APIs
and getting around not-infrequent HTTP 503 errors from those APIs.
:param channel:
The URL of the channel
:param package_manager:
An instance of :class:`PackageManager` used to download the file
"""
def __init__(self, channel, package_manager):
self.channel_info = None
self.channel = channel
self.package_manager = package_manager
self.unavailable_packages = []
def match_url(self):
"""Indicates if this provider can handle the provided channel"""
return True
def fetch_channel(self):
"""Retrieves and loads the JSON for other methods to use"""
if self.channel_info != None:
return
channel_json = self.package_manager.download_url(self.channel,
'Error downloading channel.')
if channel_json == False:
self.channel_info = False
return
try:
channel_info = json.loads(channel_json)
except (ValueError):
print '%s: Error parsing JSON from channel %s.' % (__name__,
self.channel)
channel_info = False
self.channel_info = channel_info
def get_name_map(self):
""":return: A dict of the mapping for URL slug -> package name"""
self.fetch_channel()
if self.channel_info == False:
return False
return self.channel_info.get('package_name_map', {})
def get_renamed_packages(self):
""":return: A dict of the packages that have been renamed"""
self.fetch_channel()
if self.channel_info == False:
return False
return self.channel_info.get('renamed_packages', {})
def get_repositories(self):
""":return: A list of the repository URLs"""
self.fetch_channel()
if self.channel_info == False:
return False
return self.channel_info['repositories']
def get_certs(self):
"""
Provides a secure way for distribution of SSL CA certificates
Unfortunately Python does not include a bundle of CA certs with urllib2
to perform SSL certificate validation. To circumvent this issue,
Package Control acts as a distributor of the CA certs for all HTTPS
URLs of package downloads.
The default channel scrapes and caches info about all packages
periodically, and in the process it checks the CA certs for all of
the HTTPS URLs listed in the repositories. The contents of the CA cert
files are then hashed, and the CA cert is stored in a filename with
that hash. This is a fingerprint to ensure that Package Control has
the appropriate CA cert for a domain name.
Next, the default channel file serves up a JSON object of the domain
names and the hashes of their current CA cert files. If Package Control
does not have the appropriate hash for a domain, it may retrieve it
from the channel server. To ensure that Package Control is talking to
a trusted authority to get the CA certs from, the CA cert for
sublime.wbond.net is bundled with Package Control. Then when downloading
the channel file, Package Control can ensure that the channel file's
SSL certificate is valid, thus ensuring the resulting CA certs are
legitimate.
As a matter of optimization, the distribution of Package Control also
includes the current CA certs for all known HTTPS domains that are
included in the channel, as of the time when Package Control was
last released.
:return: A dict of {'Domain Name': ['cert_file_hash', 'cert_file_download_url']}
"""
self.fetch_channel()
if self.channel_info == False:
return False
return self.channel_info.get('certs', {})
def get_packages(self, repo):
"""
Provides access to the repository info that is cached in a channel
:param repo:
The URL of the repository to get the cached info of
:return:
A dict in the format:
{
'Package Name': {
# Package details - see example-packages.json for format
},
...
}
or False if there is an error
"""
self.fetch_channel()
if self.channel_info == False:
return False
if self.channel_info.get('packages', False) == False:
return False
if self.channel_info['packages'].get(repo, False) == False:
return False
output = {}
for package in self.channel_info['packages'][repo]:
copy = package.copy()
platforms = copy['platforms'].keys()
best_platform = self.get_best_platform(platforms)
if not best_platform:
self.unavailable_packages.append(copy['name'])
continue
copy['downloads'] = copy['platforms'][best_platform]
del copy['platforms']
copy['url'] = copy['homepage']
del copy['homepage']
output[copy['name']] = copy
return output
def get_unavailable_packages(self):
"""
Provides a list of packages that are unavailable for the current
platform/architecture that Sublime Text is running on.
This list will be empty unless get_packages() is called first.
:return: A list of package names
"""
return self.unavailable_packages
# The providers (in order) to check when trying to download a channel
_channel_providers = [ChannelProvider]
class PackageProvider(PlatformComparator):
"""
Generic repository downloader that fetches package info
With the current channel/repository architecture where the channel file
caches info from all includes repositories, these package providers just
serve the purpose of downloading packages not in the default channel.
The structure of the JSON a repository should contain is located in
example-packages.json.
:param repo:
The URL of the package repository
:param package_manager:
An instance of :class:`PackageManager` used to download the file
"""
def __init__(self, repo, package_manager):
self.repo_info = None
self.repo = repo
self.package_manager = package_manager
self.unavailable_packages = []
def match_url(self):
"""Indicates if this provider can handle the provided repo"""
return True
def fetch_repo(self):
"""Retrieves and loads the JSON for other methods to use"""
if self.repo_info != None:
return
repository_json = self.package_manager.download_url(self.repo,
'Error downloading repository.')
if repository_json == False:
self.repo_info = False
return
try:
self.repo_info = json.loads(repository_json)
except (ValueError):
print '%s: Error parsing JSON from repository %s.' % (__name__,
self.repo)
self.repo_info = False
def get_packages(self):
"""
Provides access to the repository info that is cached in a channel
:return:
A dict in the format:
{
'Package Name': {