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.

190 lines
6.8 KiB

11 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 .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://rg3.github.io/youtube-dl/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. filename = sys.argv[0]
  71. # Py2EXE: Filename could be different
  72. if hasattr(sys, "frozen") and not os.path.isfile(filename):
  73. if os.path.isfile(filename + '.exe'):
  74. filename += '.exe'
  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 = os.path.abspath(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)