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