update.py 6.9 KB

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