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.

160 lines
6.1 KiB

  1. import json
  2. import traceback
  3. import hashlib
  4. from zipimport import zipimporter
  5. from .utils import *
  6. from .version import __version__
  7. def rsa_verify(message, signature, key):
  8. from struct import pack
  9. from hashlib import sha256
  10. from sys import version_info
  11. def b(x):
  12. if version_info[0] == 2: return x
  13. else: return x.encode('latin1')
  14. assert(type(message) == type(b('')))
  15. block_size = 0
  16. n = key[0]
  17. while n:
  18. block_size += 1
  19. n >>= 8
  20. signature = pow(int(signature, 16), key[1], key[0])
  21. raw_bytes = []
  22. while signature:
  23. raw_bytes.insert(0, pack("B", signature & 0xFF))
  24. signature >>= 8
  25. signature = (block_size - len(raw_bytes)) * b('\x00') + b('').join(raw_bytes)
  26. if signature[0:2] != b('\x00\x01'): return False
  27. signature = signature[2:]
  28. if not b('\x00') in signature: return False
  29. signature = signature[signature.index(b('\x00'))+1:]
  30. if not signature.startswith(b('\x30\x31\x30\x0D\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20')): return False
  31. signature = signature[19:]
  32. if signature != sha256(message).digest(): return False
  33. return True
  34. def update_self(to_screen, verbose, filename):
  35. """Update the program file with the latest version from the repository"""
  36. UPDATE_URL = "http://rg3.github.com/youtube-dl/update/"
  37. VERSION_URL = UPDATE_URL + 'LATEST_VERSION'
  38. JSON_URL = UPDATE_URL + 'versions.json'
  39. UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87b95bd66177b91df176765d13514a0f1754bcd2057295c5b6f1d35daa6742c3ffc9a82d3e118861c207995a8031e151d863c9927e304576bc80692bc8e094896fcf11b66f3e29e04e3a71e9a11558558acea1840aec37fc396fb6b65dc81a1c4144e03bd1c011de62e3f1357b327d08426fe93, 65537)
  40. if not isinstance(globals().get('__loader__'), zipimporter) and not hasattr(sys, "frozen"):
  41. to_screen(u'It looks like you installed youtube-dl with pip, setup.py or a tarball. Please use that to update.')
  42. return
  43. # Check if there is a new version
  44. try:
  45. newversion = compat_urllib_request.urlopen(VERSION_URL).read().decode('utf-8').strip()
  46. except:
  47. if verbose: to_screen(compat_str(traceback.format_exc()))
  48. to_screen(u'ERROR: can\'t find the current version. Please try again later.')
  49. return
  50. if newversion == __version__:
  51. to_screen(u'youtube-dl is up-to-date (' + __version__ + ')')
  52. return
  53. # Download and check versions info
  54. try:
  55. versions_info = compat_urllib_request.urlopen(JSON_URL).read().decode('utf-8')
  56. versions_info = json.loads(versions_info)
  57. except:
  58. if verbose: to_screen(compat_str(traceback.format_exc()))
  59. to_screen(u'ERROR: can\'t obtain versions info. Please try again later.')
  60. return
  61. if not 'signature' in versions_info:
  62. to_screen(u'ERROR: the versions file is not signed or corrupted. Aborting.')
  63. return
  64. signature = versions_info['signature']
  65. del versions_info['signature']
  66. if not rsa_verify(json.dumps(versions_info, sort_keys=True).encode('utf-8'), signature, UPDATES_RSA_KEY):
  67. to_screen(u'ERROR: the versions file signature is invalid. Aborting.')
  68. return
  69. to_screen(u'Updating to version ' + versions_info['latest'] + '...')
  70. version = versions_info['versions'][versions_info['latest']]
  71. if version.get('notes'):
  72. to_screen(u'PLEASE NOTE:')
  73. for note in version['notes']:
  74. to_screen(note)
  75. if not os.access(filename, os.W_OK):
  76. to_screen(u'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(u'ERROR: no write permissions on %s' % directory)
  84. return
  85. try:
  86. urlh = compat_urllib_request.urlopen(version['exe'][0])
  87. newcontent = urlh.read()
  88. urlh.close()
  89. except (IOError, OSError) as err:
  90. if verbose: to_screen(compat_str(traceback.format_exc()))
  91. to_screen(u'ERROR: unable to download latest version')
  92. return
  93. newcontent_hash = hashlib.sha256(newcontent).hexdigest()
  94. if newcontent_hash != version['exe'][1]:
  95. to_screen(u'ERROR: the downloaded file hash does not match. Aborting.')
  96. return
  97. try:
  98. with open(exe + '.new', 'wb') as outf:
  99. outf.write(newcontent)
  100. except (IOError, OSError) as err:
  101. if verbose: to_screen(compat_str(traceback.format_exc()))
  102. to_screen(u'ERROR: unable to write the new version')
  103. return
  104. try:
  105. bat = os.path.join(directory, 'youtube-dl-updater.bat')
  106. b = open(bat, 'w')
  107. b.write("""
  108. echo Updating youtube-dl...
  109. ping 127.0.0.1 -n 5 -w 1000 > NUL
  110. move /Y "%s.new" "%s"
  111. del "%s"
  112. \n""" %(exe, exe, bat))
  113. b.close()
  114. os.startfile(bat)
  115. except (IOError, OSError) as err:
  116. if verbose: to_screen(compat_str(traceback.format_exc()))
  117. to_screen(u'ERROR: unable to overwrite current version')
  118. return
  119. # Zip unix package
  120. elif isinstance(globals().get('__loader__'), zipimporter):
  121. try:
  122. urlh = compat_urllib_request.urlopen(version['bin'][0])
  123. newcontent = urlh.read()
  124. urlh.close()
  125. except (IOError, OSError) as err:
  126. if verbose: to_screen(compat_str(traceback.format_exc()))
  127. to_screen(u'ERROR: unable to download latest version')
  128. return
  129. newcontent_hash = hashlib.sha256(newcontent).hexdigest()
  130. if newcontent_hash != version['bin'][1]:
  131. to_screen(u'ERROR: the downloaded file hash does not match. Aborting.')
  132. return
  133. try:
  134. with open(filename, 'wb') as outf:
  135. outf.write(newcontent)
  136. except (IOError, OSError) as err:
  137. if verbose: to_screen(compat_str(traceback.format_exc()))
  138. to_screen(u'ERROR: unable to overwrite current version')
  139. return
  140. to_screen(u'Updated youtube-dl. Restart youtube-dl to use the new version.')