[update] Look for .exe extension on Windows (Fixes #745)
[youtube-dl] / youtube_dl / update.py
1 import json
2 import traceback
3 import hashlib
4 import sys
5 from zipimport import zipimporter
6
7 from .utils import *
8 from .version import __version__
9
10 def rsa_verify(message, signature, key):
11     from struct import pack
12     from hashlib import sha256
13     from sys import version_info
14     def b(x):
15         if version_info[0] == 2: return x
16         else: return x.encode('latin1')
17     assert(type(message) == type(b('')))
18     block_size = 0
19     n = key[0]
20     while n:
21         block_size += 1
22         n >>= 8
23     signature = pow(int(signature, 16), key[1], key[0])
24     raw_bytes = []
25     while signature:
26         raw_bytes.insert(0, pack("B", signature & 0xFF))
27         signature >>= 8
28     signature = (block_size - len(raw_bytes)) * b('\x00') + b('').join(raw_bytes)
29     if signature[0:2] != b('\x00\x01'): return False
30     signature = signature[2:]
31     if not b('\x00') in signature: return False
32     signature = signature[signature.index(b('\x00'))+1:]
33     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
34     signature = signature[19:]
35     if signature != sha256(message).digest(): return False
36     return True
37
38 def update_self(to_screen, verbose):
39     """Update the program file with the latest version from the repository"""
40
41     UPDATE_URL = "http://rg3.github.io/youtube-dl/update/"
42     VERSION_URL = UPDATE_URL + 'LATEST_VERSION'
43     JSON_URL = UPDATE_URL + 'versions.json'
44     UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87b95bd66177b91df176765d13514a0f1754bcd2057295c5b6f1d35daa6742c3ffc9a82d3e118861c207995a8031e151d863c9927e304576bc80692bc8e094896fcf11b66f3e29e04e3a71e9a11558558acea1840aec37fc396fb6b65dc81a1c4144e03bd1c011de62e3f1357b327d08426fe93, 65537)
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 a package manager, 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     filename = sys.argv[0]
84     # Py2EXE: Filename could be different
85     if hasattr(sys, "frozen") and not os.path.isfile(filename):
86         if os.path.isfile(filename + u'.exe'):
87             filename += u'.exe'
88
89     if not os.access(filename, os.W_OK):
90         to_screen(u'ERROR: no write permissions on %s' % filename)
91         return
92
93     # Py2EXE
94     if hasattr(sys, "frozen"):
95         exe = os.path.abspath(filename)
96         directory = os.path.dirname(exe)
97         if not os.access(directory, os.W_OK):
98             to_screen(u'ERROR: no write permissions on %s' % directory)
99             return
100
101         try:
102             urlh = compat_urllib_request.urlopen(version['exe'][0])
103             newcontent = urlh.read()
104             urlh.close()
105         except (IOError, OSError) as err:
106             if verbose: to_screen(compat_str(traceback.format_exc()))
107             to_screen(u'ERROR: unable to download latest version')
108             return
109
110         newcontent_hash = hashlib.sha256(newcontent).hexdigest()
111         if newcontent_hash != version['exe'][1]:
112             to_screen(u'ERROR: the downloaded file hash does not match. Aborting.')
113             return
114
115         try:
116             with open(exe + '.new', 'wb') as outf:
117                 outf.write(newcontent)
118         except (IOError, OSError) as err:
119             if verbose: to_screen(compat_str(traceback.format_exc()))
120             to_screen(u'ERROR: unable to write the new version')
121             return
122
123         try:
124             bat = os.path.join(directory, 'youtube-dl-updater.bat')
125             b = open(bat, 'w')
126             b.write("""
127 echo Updating youtube-dl...
128 ping 127.0.0.1 -n 5 -w 1000 > NUL
129 move /Y "%s.new" "%s"
130 del "%s"
131             \n""" %(exe, exe, bat))
132             b.close()
133
134             os.startfile(bat)
135         except (IOError, OSError) as err:
136             if verbose: to_screen(compat_str(traceback.format_exc()))
137             to_screen(u'ERROR: unable to overwrite current version')
138             return
139
140     # Zip unix package
141     elif isinstance(globals().get('__loader__'), zipimporter):
142         try:
143             urlh = compat_urllib_request.urlopen(version['bin'][0])
144             newcontent = urlh.read()
145             urlh.close()
146         except (IOError, OSError) as err:
147             if verbose: to_screen(compat_str(traceback.format_exc()))
148             to_screen(u'ERROR: unable to download latest version')
149             return
150
151         newcontent_hash = hashlib.sha256(newcontent).hexdigest()
152         if newcontent_hash != version['bin'][1]:
153             to_screen(u'ERROR: the downloaded file hash does not match. Aborting.')
154             return
155
156         try:
157             with open(filename, 'wb') as outf:
158                 outf.write(newcontent)
159         except (IOError, OSError) as err:
160             if verbose: to_screen(compat_str(traceback.format_exc()))
161             to_screen(u'ERROR: unable to overwrite current version')
162             return
163
164     to_screen(u'Updated youtube-dl. Restart youtube-dl to use the new version.')
165
166 def get_notes(versions, fromVersion):
167     notes = []
168     for v,vdata in sorted(versions.items()):
169         if v > fromVersion:
170             notes.extend(vdata.get('notes', []))
171     return notes
172
173 def print_notes(to_screen, versions, fromVersion=__version__):
174     notes = get_notes(versions, fromVersion)
175     if notes:
176         to_screen(u'PLEASE NOTE:')
177         for note in notes:
178             to_screen(note)