]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/update.py
debian/control: Remove B-D-I on perl.
[youtubedl] / youtube_dl / update.py
1 import json
2 import traceback
3 import hashlib
4 from zipimport import zipimporter
5
6 from .utils import *
7 from .version import __version__
8
9 def rsa_verify(message, signature, key):
10 from struct import pack
11 from hashlib import sha256
12 from sys import version_info
13 def b(x):
14 if version_info[0] == 2: return x
15 else: return x.encode('latin1')
16 assert(type(message) == type(b('')))
17 block_size = 0
18 n = key[0]
19 while n:
20 block_size += 1
21 n >>= 8
22 signature = pow(int(signature, 16), key[1], key[0])
23 raw_bytes = []
24 while signature:
25 raw_bytes.insert(0, pack("B", signature & 0xFF))
26 signature >>= 8
27 signature = (block_size - len(raw_bytes)) * b('\x00') + b('').join(raw_bytes)
28 if signature[0:2] != b('\x00\x01'): return False
29 signature = signature[2:]
30 if not b('\x00') in signature: return False
31 signature = signature[signature.index(b('\x00'))+1:]
32 if not signature.startswith(b('\x30\x31\x30\x0D\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20')): return False
33 signature = signature[19:]
34 if signature != sha256(message).digest(): return False
35 return True
36
37 def update_self(to_screen, verbose, filename):
38 """Update the program file with the latest version from the repository"""
39
40 UPDATE_URL = "http://rg3.github.io/youtube-dl/update/"
41 VERSION_URL = UPDATE_URL + 'LATEST_VERSION'
42 JSON_URL = UPDATE_URL + 'versions.json'
43 UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87b95bd66177b91df176765d13514a0f1754bcd2057295c5b6f1d35daa6742c3ffc9a82d3e118861c207995a8031e151d863c9927e304576bc80692bc8e094896fcf11b66f3e29e04e3a71e9a11558558acea1840aec37fc396fb6b65dc81a1c4144e03bd1c011de62e3f1357b327d08426fe93, 65537)
44
45
46 if not isinstance(globals().get('__loader__'), zipimporter) and not hasattr(sys, "frozen"):
47 to_screen(u'It looks like you installed youtube-dl with pip, setup.py or a tarball. Please use that to update.')
48 return
49
50 # Check if there is a new version
51 try:
52 newversion = compat_urllib_request.urlopen(VERSION_URL).read().decode('utf-8').strip()
53 except:
54 if verbose: to_screen(compat_str(traceback.format_exc()))
55 to_screen(u'ERROR: can\'t find the current version. Please try again later.')
56 return
57 if newversion == __version__:
58 to_screen(u'youtube-dl is up-to-date (' + __version__ + ')')
59 return
60
61 # Download and check versions info
62 try:
63 versions_info = compat_urllib_request.urlopen(JSON_URL).read().decode('utf-8')
64 versions_info = json.loads(versions_info)
65 except:
66 if verbose: to_screen(compat_str(traceback.format_exc()))
67 to_screen(u'ERROR: can\'t obtain versions info. Please try again later.')
68 return
69 if not 'signature' in versions_info:
70 to_screen(u'ERROR: the versions file is not signed or corrupted. Aborting.')
71 return
72 signature = versions_info['signature']
73 del versions_info['signature']
74 if not rsa_verify(json.dumps(versions_info, sort_keys=True).encode('utf-8'), signature, UPDATES_RSA_KEY):
75 to_screen(u'ERROR: the versions file signature is invalid. Aborting.')
76 return
77
78 to_screen(u'Updating to version ' + versions_info['latest'] + '...')
79 version = versions_info['versions'][versions_info['latest']]
80
81 print_notes(to_screen, versions_info['versions'])
82
83 if not os.access(filename, os.W_OK):
84 to_screen(u'ERROR: no write permissions on %s' % filename)
85 return
86
87 # Py2EXE
88 if hasattr(sys, "frozen"):
89 exe = os.path.abspath(filename)
90 directory = os.path.dirname(exe)
91 if not os.access(directory, os.W_OK):
92 to_screen(u'ERROR: no write permissions on %s' % directory)
93 return
94
95 try:
96 urlh = compat_urllib_request.urlopen(version['exe'][0])
97 newcontent = urlh.read()
98 urlh.close()
99 except (IOError, OSError) as err:
100 if verbose: to_screen(compat_str(traceback.format_exc()))
101 to_screen(u'ERROR: unable to download latest version')
102 return
103
104 newcontent_hash = hashlib.sha256(newcontent).hexdigest()
105 if newcontent_hash != version['exe'][1]:
106 to_screen(u'ERROR: the downloaded file hash does not match. Aborting.')
107 return
108
109 try:
110 with open(exe + '.new', 'wb') as outf:
111 outf.write(newcontent)
112 except (IOError, OSError) as err:
113 if verbose: to_screen(compat_str(traceback.format_exc()))
114 to_screen(u'ERROR: unable to write the new version')
115 return
116
117 try:
118 bat = os.path.join(directory, 'youtube-dl-updater.bat')
119 b = open(bat, 'w')
120 b.write("""
121 echo Updating youtube-dl...
122 ping 127.0.0.1 -n 5 -w 1000 > NUL
123 move /Y "%s.new" "%s"
124 del "%s"
125 \n""" %(exe, exe, bat))
126 b.close()
127
128 os.startfile(bat)
129 except (IOError, OSError) as err:
130 if verbose: to_screen(compat_str(traceback.format_exc()))
131 to_screen(u'ERROR: unable to overwrite current version')
132 return
133
134 # Zip unix package
135 elif isinstance(globals().get('__loader__'), zipimporter):
136 try:
137 urlh = compat_urllib_request.urlopen(version['bin'][0])
138 newcontent = urlh.read()
139 urlh.close()
140 except (IOError, OSError) as err:
141 if verbose: to_screen(compat_str(traceback.format_exc()))
142 to_screen(u'ERROR: unable to download latest version')
143 return
144
145 newcontent_hash = hashlib.sha256(newcontent).hexdigest()
146 if newcontent_hash != version['bin'][1]:
147 to_screen(u'ERROR: the downloaded file hash does not match. Aborting.')
148 return
149
150 try:
151 with open(filename, 'wb') as outf:
152 outf.write(newcontent)
153 except (IOError, OSError) as err:
154 if verbose: to_screen(compat_str(traceback.format_exc()))
155 to_screen(u'ERROR: unable to overwrite current version')
156 return
157
158 to_screen(u'Updated youtube-dl. Restart youtube-dl to use the new version.')
159
160 def get_notes(versions, fromVersion):
161 notes = []
162 for v,vdata in sorted(versions.items()):
163 if v > fromVersion:
164 notes.extend(vdata.get('notes', []))
165 return notes
166
167 def print_notes(to_screen, versions, fromVersion=__version__):
168 notes = get_notes(versions, fromVersion)
169 if notes:
170 to_screen(u'PLEASE NOTE:')
171 for note in notes:
172 to_screen(note)