Respect --prefer-insecure while updating (closes #15497)
[youtube-dl] / 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, prefer_insecure=False):
32     """Update the program file with the latest version from the repository"""
33
34     UPDATE_URL = '//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     def guess_scheme(url, insecure=False):
44         return 'http%s:%s' % ('' if insecure is True else 's', url)
45
46     # Check if there is a new version
47     try:
48         newversion = opener.open(guess_scheme(
49             VERSION_URL, prefer_insecure)).read().decode('utf-8').strip()
50     except Exception:
51         if verbose:
52             to_screen(encode_compat_str(traceback.format_exc()))
53         to_screen('ERROR: can\'t find the current version. Please try again later.')
54         return
55     if newversion == __version__:
56         to_screen('youtube-dl is up-to-date (' + __version__ + ')')
57         return
58
59     # Download and check versions info
60     try:
61         versions_info = opener.open(guess_scheme(
62             JSON_URL, prefer_insecure)).read().decode('utf-8')
63         versions_info = json.loads(versions_info)
64     except Exception:
65         if verbose:
66             to_screen(encode_compat_str(traceback.format_exc()))
67         to_screen('ERROR: can\'t obtain versions info. Please try again later.')
68         return
69     if 'signature' not in versions_info:
70         to_screen('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('ERROR: the versions file signature is invalid. Aborting.')
76         return
77
78     version_id = versions_info['latest']
79
80     def version_tuple(version_str):
81         return tuple(map(int, version_str.split('.')))
82     if version_tuple(__version__) >= version_tuple(version_id):
83         to_screen('youtube-dl is up to date (%s)' % __version__)
84         return
85
86     to_screen('Updating to version ' + version_id + ' ...')
87     version = versions_info['versions'][version_id]
88
89     print_notes(to_screen, versions_info['versions'])
90
91     # sys.executable is set to the full pathname of the exe-file for py2exe
92     filename = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
93
94     if not os.access(filename, os.W_OK):
95         to_screen('ERROR: no write permissions on %s' % filename)
96         return
97
98     # Py2EXE
99     if hasattr(sys, 'frozen'):
100         exe = filename
101         directory = os.path.dirname(exe)
102         if not os.access(directory, os.W_OK):
103             to_screen('ERROR: no write permissions on %s' % directory)
104             return
105
106         try:
107             urlh = opener.open(version['exe'][0])
108             newcontent = urlh.read()
109             urlh.close()
110         except (IOError, OSError):
111             if verbose:
112                 to_screen(encode_compat_str(traceback.format_exc()))
113             to_screen('ERROR: unable to download latest version')
114             return
115
116         newcontent_hash = hashlib.sha256(newcontent).hexdigest()
117         if newcontent_hash != version['exe'][1]:
118             to_screen('ERROR: the downloaded file hash does not match. Aborting.')
119             return
120
121         try:
122             with open(exe + '.new', 'wb') as outf:
123                 outf.write(newcontent)
124         except (IOError, OSError):
125             if verbose:
126                 to_screen(encode_compat_str(traceback.format_exc()))
127             to_screen('ERROR: unable to write the new version')
128             return
129
130         try:
131             bat = os.path.join(directory, 'youtube-dl-updater.bat')
132             with io.open(bat, 'w') as batfile:
133                 batfile.write('''
134 @echo off
135 echo Waiting for file handle to be closed ...
136 ping 127.0.0.1 -n 5 -w 1000 > NUL
137 move /Y "%s.new" "%s" > NUL
138 echo Updated youtube-dl to version %s.
139 start /b "" cmd /c del "%%~f0"&exit /b"
140                 \n''' % (exe, exe, version_id))
141
142             subprocess.Popen([bat])  # Continues to run in the background
143             return  # Do not show premature success messages
144         except (IOError, OSError):
145             if verbose:
146                 to_screen(encode_compat_str(traceback.format_exc()))
147             to_screen('ERROR: unable to overwrite current version')
148             return
149
150     # Zip unix package
151     elif isinstance(globals().get('__loader__'), zipimporter):
152         try:
153             urlh = opener.open(version['bin'][0])
154             newcontent = urlh.read()
155             urlh.close()
156         except (IOError, OSError):
157             if verbose:
158                 to_screen(encode_compat_str(traceback.format_exc()))
159             to_screen('ERROR: unable to download latest version')
160             return
161
162         newcontent_hash = hashlib.sha256(newcontent).hexdigest()
163         if newcontent_hash != version['bin'][1]:
164             to_screen('ERROR: the downloaded file hash does not match. Aborting.')
165             return
166
167         try:
168             with open(filename, 'wb') as outf:
169                 outf.write(newcontent)
170         except (IOError, OSError):
171             if verbose:
172                 to_screen(encode_compat_str(traceback.format_exc()))
173             to_screen('ERROR: unable to overwrite current version')
174             return
175
176     to_screen('Updated youtube-dl. Restart youtube-dl to use the new version.')
177
178
179 def get_notes(versions, fromVersion):
180     notes = []
181     for v, vdata in sorted(versions.items()):
182         if v > fromVersion:
183             notes.extend(vdata.get('notes', []))
184     return notes
185
186
187 def print_notes(to_screen, versions, fromVersion=__version__):
188     notes = get_notes(versions, fromVersion)
189     if notes:
190         to_screen('PLEASE NOTE:')
191         for note in notes:
192             to_screen(note)