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.

290 lines
8.5 KiB

4 years ago
  1. """Module that implements SSDP protocol."""
  2. import re
  3. import select
  4. import socket
  5. import logging
  6. from datetime import datetime, timedelta
  7. from xml.etree import ElementTree
  8. import requests
  9. import zeroconf
  10. from netdisco.util import etree_to_dict
  11. DISCOVER_TIMEOUT = 2
  12. # MX is a suggested random wait time for a device to reply, so should be
  13. # bound by our discovery timeout.
  14. SSDP_MX = DISCOVER_TIMEOUT
  15. SSDP_TARGET = ("239.255.255.250", 1900)
  16. RESPONSE_REGEX = re.compile(r'\n(.*?)\: *(.*)\r')
  17. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=59)
  18. # Devices and services
  19. ST_ALL = "ssdp:all"
  20. # Devices only, some devices will only respond to this query
  21. ST_ROOTDEVICE = "upnp:rootdevice"
  22. class SSDP:
  23. """Control the scanning of uPnP devices and services and caches output."""
  24. def __init__(self):
  25. """Initialize the discovery."""
  26. self.entries = []
  27. self.last_scan = None
  28. def scan(self):
  29. """Scan the network."""
  30. self.update()
  31. def all(self):
  32. """Return all found entries.
  33. Will scan for entries if not scanned recently.
  34. """
  35. self.update()
  36. return list(self.entries)
  37. # pylint: disable=invalid-name
  38. def find_by_st(self, st):
  39. """Return a list of entries that match the ST."""
  40. self.update()
  41. return [entry for entry in self.entries
  42. if entry.st == st]
  43. def find_by_device_description(self, values):
  44. """Return a list of entries that match the description.
  45. Pass in a dict with values to match against the device tag in the
  46. description.
  47. """
  48. self.update()
  49. seen = set()
  50. results = []
  51. # Make unique based on the location since we don't care about ST here
  52. for entry in self.entries:
  53. location = entry.location
  54. if location not in seen and entry.match_device_description(values):
  55. results.append(entry)
  56. seen.add(location)
  57. return results
  58. def update(self, force_update=False):
  59. """Scan for new uPnP devices and services."""
  60. if self.last_scan is None or force_update or \
  61. datetime.now()-self.last_scan > MIN_TIME_BETWEEN_SCANS:
  62. self.remove_expired()
  63. self.entries.extend(
  64. entry for entry in scan()
  65. if entry not in self.entries)
  66. self.last_scan = datetime.now()
  67. def remove_expired(self):
  68. """Filter out expired entries."""
  69. self.entries = [entry for entry in self.entries
  70. if not entry.is_expired]
  71. class UPNPEntry:
  72. """Found uPnP entry."""
  73. DESCRIPTION_CACHE = {'_NO_LOCATION': {}}
  74. def __init__(self, values):
  75. """Initialize the discovery."""
  76. self.values = values
  77. self.created = datetime.now()
  78. if 'cache-control' in self.values:
  79. cache_directive = self.values['cache-control']
  80. max_age = re.findall(r'max-age *= *\d+', cache_directive)
  81. if max_age:
  82. cache_seconds = int(max_age[0].split('=')[1])
  83. self.expires = self.created + timedelta(seconds=cache_seconds)
  84. else:
  85. self.expires = None
  86. else:
  87. self.expires = None
  88. @property
  89. def is_expired(self):
  90. """Return if the entry is expired or not."""
  91. return self.expires is not None and datetime.now() > self.expires
  92. # pylint: disable=invalid-name
  93. @property
  94. def st(self):
  95. """Return ST value."""
  96. return self.values.get('st')
  97. @property
  98. def location(self):
  99. """Return Location value."""
  100. return self.values.get('location')
  101. @property
  102. def description(self):
  103. """Return the description from the uPnP entry."""
  104. url = self.values.get('location', '_NO_LOCATION')
  105. if url not in UPNPEntry.DESCRIPTION_CACHE:
  106. try:
  107. xml = requests.get(url, timeout=5).text
  108. if not xml:
  109. # Samsung Smart TV sometimes returns an empty document the
  110. # first time. Retry once.
  111. xml = requests.get(url, timeout=5).text
  112. tree = ElementTree.fromstring(xml)
  113. UPNPEntry.DESCRIPTION_CACHE[url] = \
  114. etree_to_dict(tree).get('root', {})
  115. except requests.RequestException:
  116. logging.getLogger(__name__).debug(
  117. "Error fetching description at %s", url)
  118. UPNPEntry.DESCRIPTION_CACHE[url] = {}
  119. except ElementTree.ParseError:
  120. logging.getLogger(__name__).debug(
  121. "Found malformed XML at %s: %s", url, xml)
  122. UPNPEntry.DESCRIPTION_CACHE[url] = {}
  123. return UPNPEntry.DESCRIPTION_CACHE[url]
  124. def match_device_description(self, values):
  125. """Fetch description and matches against it.
  126. Values should only contain lowercase keys.
  127. """
  128. device = self.description.get('device')
  129. if device is None:
  130. return False
  131. return all(device.get(key) in val
  132. if isinstance(val, list)
  133. else val == device.get(key)
  134. for key, val in values.items())
  135. @classmethod
  136. def from_response(cls, response):
  137. """Create a uPnP entry from a response."""
  138. return UPNPEntry({key.lower(): item for key, item
  139. in RESPONSE_REGEX.findall(response)})
  140. def __eq__(self, other):
  141. """Return the comparison."""
  142. return (self.__class__ == other.__class__ and
  143. self.values == other.values)
  144. def __repr__(self):
  145. """Return the entry."""
  146. return "<UPNPEntry {} - {}>".format(self.location or '', self.st or '')
  147. def ssdp_request(ssdp_st, ssdp_mx=SSDP_MX):
  148. """Return request bytes for given st and mx."""
  149. return "\r\n".join([
  150. 'M-SEARCH * HTTP/1.1',
  151. 'ST: {}'.format(ssdp_st),
  152. 'MX: {:d}'.format(ssdp_mx),
  153. 'MAN: "ssdp:discover"',
  154. 'HOST: {}:{}'.format(*SSDP_TARGET),
  155. '', '']).encode('utf-8')
  156. # pylint: disable=invalid-name,too-many-locals,too-many-branches
  157. def scan(timeout=DISCOVER_TIMEOUT):
  158. """Send a message over the network to discover uPnP devices.
  159. Inspired by Crimsdings
  160. https://github.com/crimsdings/ChromeCast/blob/master/cc_discovery.py
  161. Protocol explanation:
  162. https://embeddedinn.wordpress.com/tutorials/upnp-device-architecture/
  163. """
  164. ssdp_requests = ssdp_request(ST_ALL), ssdp_request(ST_ROOTDEVICE)
  165. stop_wait = datetime.now() + timedelta(seconds=timeout)
  166. sockets = []
  167. for addr in zeroconf.get_all_addresses():
  168. try:
  169. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  170. # Set the time-to-live for messages for local network
  171. sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL,
  172. SSDP_MX)
  173. sock.bind((addr, 0))
  174. sockets.append(sock)
  175. except socket.error:
  176. pass
  177. entries = {}
  178. for sock in [s for s in sockets]:
  179. try:
  180. for req in ssdp_requests:
  181. sock.sendto(req, SSDP_TARGET)
  182. sock.setblocking(False)
  183. except socket.error:
  184. sockets.remove(sock)
  185. sock.close()
  186. try:
  187. while sockets:
  188. time_diff = stop_wait - datetime.now()
  189. seconds_left = time_diff.total_seconds()
  190. if seconds_left <= 0:
  191. break
  192. ready = select.select(sockets, [], [], seconds_left)[0]
  193. for sock in ready:
  194. try:
  195. data, address = sock.recvfrom(1024)
  196. response = data.decode("utf-8")
  197. except UnicodeDecodeError:
  198. logging.getLogger(__name__).debug(
  199. 'Ignoring invalid unicode response from %s', address)
  200. continue
  201. except socket.error:
  202. logging.getLogger(__name__).exception(
  203. "Socket error while discovering SSDP devices")
  204. sockets.remove(sock)
  205. sock.close()
  206. continue
  207. entry = UPNPEntry.from_response(response)
  208. entries[(entry.st, entry.location)] = entry
  209. finally:
  210. for s in sockets:
  211. s.close()
  212. return sorted(entries.values(), key=lambda entry: entry.location or '')
  213. def main():
  214. """Test SSDP discovery."""
  215. from pprint import pprint
  216. print("Scanning SSDP..")
  217. pprint(scan())
  218. if __name__ == "__main__":
  219. main()