update.py 6.9 KB

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