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.

206 lines
7.1 KiB

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