Plex plugin to to play various online streams (mostly Latvian).

ntlmpool.py 4.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. """
  2. NTLM authenticating pool, contributed by erikcederstran
  3. Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10
  4. """
  5. from __future__ import absolute_import
  6. try:
  7. from http.client import HTTPSConnection
  8. except ImportError:
  9. from httplib import HTTPSConnection
  10. from logging import getLogger
  11. from ntlm import ntlm
  12. from urllib3 import HTTPSConnectionPool
  13. log = getLogger(__name__)
  14. class NTLMConnectionPool(HTTPSConnectionPool):
  15. """
  16. Implements an NTLM authentication version of an urllib3 connection pool
  17. """
  18. scheme = 'https'
  19. def __init__(self, user, pw, authurl, *args, **kwargs):
  20. """
  21. authurl is a random URL on the server that is protected by NTLM.
  22. user is the Windows user, probably in the DOMAIN\\username format.
  23. pw is the password for the user.
  24. """
  25. super(NTLMConnectionPool, self).__init__(*args, **kwargs)
  26. self.authurl = authurl
  27. self.rawuser = user
  28. user_parts = user.split('\\', 1)
  29. self.domain = user_parts[0].upper()
  30. self.user = user_parts[1]
  31. self.pw = pw
  32. def _new_conn(self):
  33. # Performs the NTLM handshake that secures the connection. The socket
  34. # must be kept open while requests are performed.
  35. self.num_connections += 1
  36. log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s',
  37. self.num_connections, self.host, self.authurl)
  38. headers = {}
  39. headers['Connection'] = 'Keep-Alive'
  40. req_header = 'Authorization'
  41. resp_header = 'www-authenticate'
  42. conn = HTTPSConnection(host=self.host, port=self.port)
  43. # Send negotiation message
  44. headers[req_header] = (
  45. 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser))
  46. log.debug('Request headers: %s', headers)
  47. conn.request('GET', self.authurl, None, headers)
  48. res = conn.getresponse()
  49. reshdr = dict(res.getheaders())
  50. log.debug('Response status: %s %s', res.status, res.reason)
  51. log.debug('Response headers: %s', reshdr)
  52. log.debug('Response data: %s [...]', res.read(100))
  53. # Remove the reference to the socket, so that it can not be closed by
  54. # the response object (we want to keep the socket open)
  55. res.fp = None
  56. # Server should respond with a challenge message
  57. auth_header_values = reshdr[resp_header].split(', ')
  58. auth_header_value = None
  59. for s in auth_header_values:
  60. if s[:5] == 'NTLM ':
  61. auth_header_value = s[5:]
  62. if auth_header_value is None:
  63. raise Exception('Unexpected %s response header: %s' %
  64. (resp_header, reshdr[resp_header]))
  65. # Send authentication message
  66. ServerChallenge, NegotiateFlags = \
  67. ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value)
  68. auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge,
  69. self.user,
  70. self.domain,
  71. self.pw,
  72. NegotiateFlags)
  73. headers[req_header] = 'NTLM %s' % auth_msg
  74. log.debug('Request headers: %s', headers)
  75. conn.request('GET', self.authurl, None, headers)
  76. res = conn.getresponse()
  77. log.debug('Response status: %s %s', res.status, res.reason)
  78. log.debug('Response headers: %s', dict(res.getheaders()))
  79. log.debug('Response data: %s [...]', res.read()[:100])
  80. if res.status != 200:
  81. if res.status == 401:
  82. raise Exception('Server rejected request: wrong '
  83. 'username or password')
  84. raise Exception('Wrong server response: %s %s' %
  85. (res.status, res.reason))
  86. res.fp = None
  87. log.debug('Connection established')
  88. return conn
  89. def urlopen(self, method, url, body=None, headers=None, retries=3,
  90. redirect=True, assert_same_host=True):
  91. if headers is None:
  92. headers = {}
  93. headers['Connection'] = 'Keep-Alive'
  94. return super(NTLMConnectionPool, self).urlopen(method, url, body,
  95. headers, retries,
  96. redirect,
  97. assert_same_host)