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