You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

187 lines
6.7 KiB

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