A Python UPnP Media Server
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.

168 lines
5.1 KiB

  1. # Licensed under the MIT license
  2. # http://opensource.org/licenses/mit-license.php
  3. # (c) 2005, Tim Potter <tpot@samba.org>
  4. #
  5. # Implementation of SSDP server under Twisted Python.
  6. #
  7. import random
  8. import string
  9. from twisted.python import log
  10. from twisted.internet.protocol import DatagramProtocol
  11. from twisted.internet import reactor
  12. # TODO: Is there a better way of hooking the SSDPServer into a reactor
  13. # without having to know the default SSDP port and multicast address?
  14. # There must be a twisted idiom for doing this.
  15. SSDP_PORT = 1900
  16. SSDP_ADDR = '239.255.255.250'
  17. # TODO: Break out into a HTTPOverUDP class and implement
  18. # process_SEARCH(), process_NOTIFY() methods. Create UPNP specific
  19. # class to handle services etc.
  20. class SSDPServer(DatagramProtocol):
  21. """A class implementing a SSDP server. The notifyReceived and
  22. searchReceived methods are called when the appropriate type of
  23. datagram is received by the server."""
  24. # not used yet
  25. stdheaders = [ ('Server', 'Twisted, UPnP/1.0, python-upnp'), ]
  26. elements = {}
  27. known = {}
  28. def datagramReceived(self, data, (host, port)):
  29. """Handle a received multicast datagram."""
  30. # Break up message in to command and headers
  31. log.msg('respond to: %s:%d' % (host, port))
  32. header, payload = data.split('\r\n\r\n')
  33. lines = header.split('\r\n')
  34. cmd = string.split(lines[0], ' ')
  35. lines = map(lambda x: x.replace(': ', ':', 1), lines[1:])
  36. lines = filter(lambda x: len(x) > 0, lines)
  37. headers = [string.split(x, ':', 1) for x in lines]
  38. headers = dict(map(lambda x: (x[0].lower(), x[1]), headers))
  39. if cmd[0] == 'M-SEARCH' and cmd[1] == '*':
  40. # SSDP discovery
  41. self.discoveryRequest(headers, (host, port))
  42. elif cmd[0] == 'NOTIFY' and cmd[1] == '*':
  43. # SSDP presence
  44. self.notifyReceived(headers, (host, port))
  45. else:
  46. log.msg('Unknown SSDP command %s %s' % cmd)
  47. def discoveryRequest(self, headers, (host, port)):
  48. """Process a discovery request. The response must be sent to
  49. the address specified by (host, port)."""
  50. log.msg('Discovery request for %s' % headers['st'])
  51. # Do we know about this service?
  52. if headers['st'] == 'ssdp:all':
  53. for i in self.known:
  54. hcopy = dict(headers.iteritems())
  55. hcopy['st'] = i
  56. self.discoveryRequest(hcopy, (host, post))
  57. return
  58. if not self.known.has_key(headers['st']):
  59. return
  60. # Generate a response
  61. response = []
  62. response.append('HTTP/1.1 200 OK')
  63. for k, v in self.known[headers['st']].items():
  64. response.append('%s: %s' % (k, v))
  65. response.extend(('', ''))
  66. delay = random.randint(0, int(headers['mx']))
  67. reactor.callLater(delay, self.transport.write,
  68. '\r\n'.join(response), (host, port))
  69. def register(self, usn, st, location):
  70. """Register a service or device that this SSDP server will
  71. respond to."""
  72. log.msg('Registering %s' % st)
  73. self.known[st] = {}
  74. self.known[st]['USN'] = usn
  75. self.known[st]['LOCATION'] = location
  76. self.known[st]['ST'] = st
  77. self.known[st]['EXT'] = ''
  78. self.known[st]['SERVER'] = 'Twisted, UPnP/1.0, python-upnp'
  79. self.known[st]['CACHE-CONTROL'] = 'max-age=1800'
  80. self.doNotify(st)
  81. def doNotify(self, st):
  82. """Do notification"""
  83. log.msg('Sending alive notification for %s' % st)
  84. resp = [ 'NOTIFY * HTTP/1.1',
  85. 'Host: %s:%d' % (SSDP_ADDR, SSDP_PORT),
  86. 'NTS: ssdp:alive',
  87. ]
  88. stcpy = dict(self.known[st].iteritems())
  89. stcpy['NT'] = stcpy['ST']
  90. del stcpy['ST']
  91. resp.extend(map(lambda x: ': '.join(x), stcpy.iteritems()))
  92. resp.extend(('', ''))
  93. self.transport.write('\r\n'.join(resp), (SSDP_ADDR, SSDP_PORT))
  94. def notifyReceived(self, headers, (host, port)):
  95. """Process a presence announcement. We just remember the
  96. details of the SSDP service announced."""
  97. if headers['nts'] == 'ssdp:alive':
  98. if not self.elements.has_key(headers['nt']):
  99. # Register device/service
  100. self.elements[headers['nt']] = {}
  101. self.elements[headers['nt']]['USN'] = headers['usn']
  102. self.elements[headers['nt']]['host'] = (host, port)
  103. log.msg('Detected presence for %s' % headers['nt'])
  104. elif headers['nts'] == 'ssdp:byebye':
  105. if self.elements.has_key(headers['nt']):
  106. # Unregister device/service
  107. del(self.elements[headers['nt']])
  108. log.msg('Detected absence for %s' % headers['nt'])
  109. else:
  110. log.msg('Unknown subtype %s for notification type %s' %
  111. (headers['nts'], headers['nt']))
  112. def findService(self, name):
  113. """Return information about a service registered over SSDP."""
  114. # TODO: Implement me.
  115. # TODO: Send out a discovery request if we haven't registered
  116. # a presence announcement.
  117. def findDevice(self, name):
  118. """Return information about a device registered over SSDP."""
  119. # TODO: Implement me.
  120. # TODO: Send out a discovery request if we haven't registered
  121. # a presence announcement.