update.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import json
  2. import traceback
  3. import hashlib
  4. import sys
  5. from zipimport import zipimporter
  6. from .utils import *
  7. from .version import __version__
  8. def rsa_verify(message, signature, key):
  9. from struct import pack
  10. from hashlib import sha256
  11. from sys import version_info
  12. def b(x):
  13. if version_info[0] == 2: return x
  14. else: return x.encode('latin1')
  15. assert(type(message) == type(b('')))
  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'): return False
  28. signature = signature[2:]
  29. if not b('\x00') in signature: return False
  30. signature = signature[signature.index(b('\x00'))+1:]
  31. 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
  32. signature = signature[19:]
  33. if signature != sha256(message).digest(): return False
  34. return True
  35. def update_self(to_screen, verbose):
  36. """Update the program file with the latest version from the repository"""
  37. UPDATE_URL = "http://rg3.github.io/youtube-dl/update/"
  38. VERSION_URL = UPDATE_URL + 'LATEST_VERSION'
  39. JSON_URL = UPDATE_URL + 'versions.json'
  40. UPDATES_RSA_KEY = (0x9d60ee4d8f805312fdb15a62f87b95bd66177b91df176765d13514a0f1754bcd2057295c5b6f1d35daa6742c3ffc9a82d3e118861c207995a8031e151d863c9927e304576bc80692bc8e094896fcf11b66f3e29e04e3a71e9a11558558acea1840aec37fc396fb6b65dc81a1c4144e03bd1c011de62e3f1357b327d08426fe93, 65537)
  41. if not isinstance(globals().get('__loader__'), zipimporter) and not hasattr(sys, "frozen"):
  42. to_screen(u'It looks like you installed youtube-dl with a package manager, pip, setup.py or a tarball. Please use that to update.')
  43. return
  44. # Check if there is a new version
  45. try:
  46. newversion = compat_urllib_request.urlopen(VERSION_URL).read().decode('utf-8').strip()
  47. except:
  48. if verbose: to_screen(compat_str(traceback.format_exc()))
  49. to_screen(u'ERROR: can\'t find the current version. Please try again later.')
  50. return
  51. if newversion == __version__:
  52. to_screen(u'youtube-dl is up-to-date (' + __version__ + ')')
  53. return
  54. # Download and check versions info
  55. try:
  56. versions_info = compat_urllib_request.urlopen(JSON_URL).read().decode('utf-8')
  57. versions_info = json.loads(versions_info)
  58. except:
  59. if verbose: to_screen(compat_str(traceback.format_exc()))
  60. to_screen(u'ERROR: can\'t obtain versions info. Please try again later.')
  61. return
  62. if not 'signature' in versions_info:
  63. to_screen(u'ERROR: the versions file is not signed or corrupted. Aborting.')
  64. return
  65. signature = versions_info['signature']
  66. del versions_info['signature']
  67. if not rsa_verify(json.dumps(versions_info, sort_keys=True).encode('utf-8'), signature, UPDATES_RSA_KEY):
  68. to_screen(u'ERROR: the versions file signature is invalid. Aborting.')
  69. return
  70. to_screen(u'Updating to version ' + versions_info['latest'] + '...')
  71. version = versions_info['versions'][versions_info['latest']]
  72. print_notes(to_screen, versions_info['versions'])
  73. filename = sys.argv[0]
  74. # Py2EXE: Filename could be different
  75. if hasattr(sys, "frozen") and not os.path.isfile(filename):
  76. if os.path.isfile(filename + u'.exe'):
  77. filename += u'.exe'
  78. if not os.access(filename, os.W_OK):
  79. to_screen(u'ERROR: no write permissions on %s' % filename)
  80. return
  81. # Py2EXE
  82. if hasattr(sys, "frozen"):
  83. exe = os.path.abspath(filename)
  84. directory = os.path.dirname(exe)
  85. if not os.access(directory, os.W_OK):
  86. to_screen(u'ERROR: no write permissions on %s' % directory)
  87. return
  88. try:
  89. urlh = compat_urllib_request.urlopen(version['exe'][0])
  90. newcontent = urlh.read()
  91. urlh.close()
  92. except (IOError, OSError) as err:
  93. if verbose: to_screen(compat_str(traceback.format_exc()))
  94. to_screen(u'ERROR: unable to download latest version')
  95. return
  96. newcontent_hash = hashlib.sha256(newcontent).hexdigest()
  97. if newcontent_hash != version['exe'][1]:
  98. to_screen(u'ERROR: the downloaded file hash does not match. Aborting.')
  99. return
  100. try:
  101. with open(exe + '.new', 'wb') as outf:
  102. outf.write(newcontent)
  103. except (IOError, OSError) as err:
  104. if verbose: to_screen(compat_str(traceback.format_exc()))
  105. to_screen(u'ERROR: unable to write the new version')
  106. return
  107. try:
  108. bat = os.path.join(directory, 'youtube-dl-updater.bat')
  109. b = open(bat, 'w')
  110. b.write("""
  111. echo Updating youtube-dl...
  112. ping 127.0.0.1 -n 5 -w 1000 > NUL
  113. move /Y "%s.new" "%s"
  114. del "%s"
  115. \n""" %(exe, exe, bat))
  116. b.close()
  117. os.startfile(bat)
  118. except (IOError, OSError) as err:
  119. if verbose: to_screen(compat_str(traceback.format_exc()))
  120. to_screen(u'ERROR: unable to overwrite current version')
  121. return
  122. # Zip unix package
  123. elif isinstance(globals().get('__loader__'), zipimporter):
  124. try:
  125. urlh = compat_urllib_request.urlopen(version['bin'][0])
  126. newcontent = urlh.read()
  127. urlh.close()
  128. except (IOError, OSError) as err:
  129. if verbose: to_screen(compat_str(traceback.format_exc()))
  130. to_screen(u'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(u'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) as err:
  140. if verbose: to_screen(compat_str(traceback.format_exc()))
  141. to_screen(u'ERROR: unable to overwrite current version')
  142. return
  143. to_screen(u'Updated youtube-dl. Restart youtube-dl to use the new version.')
  144. def get_notes(versions, fromVersion):
  145. notes = []
  146. for v,vdata in sorted(versions.items()):
  147. if v > fromVersion:
  148. notes.extend(vdata.get('notes', []))
  149. return notes
  150. def print_notes(to_screen, versions, fromVersion=__version__):
  151. notes = get_notes(versions, fromVersion)
  152. if notes:
  153. to_screen(u'PLEASE NOTE:')
  154. for note in notes:
  155. to_screen(note)