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.

171 lines
5.3 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. delay = random.randint(0, int(headers['mx']))
  66. log.msg('responding in %d with: %s' % (delay, response))
  67. # TODO: we should wait random(headers['mx'])
  68. reactor.callLater(delay, self.transport.write,
  69. string.join(response, '\r\n') + '\r\n\r\n', (host, port))
  70. def register(self, usn, st, location):
  71. """Register a service or device that this SSDP server will
  72. respond to."""
  73. log.msg('Registering %s' % st)
  74. self.known[st] = {}
  75. self.known[st]['USN'] = usn
  76. self.known[st]['LOCATION'] = location
  77. self.known[st]['ST'] = st
  78. self.known[st]['EXT'] = ''
  79. self.known[st]['SERVER'] = 'Twisted, UPnP/1.0, python-upnp'
  80. self.known[st]['CACHE-CONTROL'] = 'max-age=1800'
  81. self.doNotify(st)
  82. def doNotify(self, st):
  83. """Do notification"""
  84. log.msg('Sending alive notification for %s' % st)
  85. resp = [ 'NOTIFY * HTTP/1.1',
  86. 'Host: %s:%d' % (SSDP_ADDR, SSDP_PORT),
  87. 'NTS: ssdp:alive',
  88. ]
  89. stcpy = dict(self.known[st].iteritems())
  90. stcpy['NT'] = stcpy['ST']
  91. del stcpy['ST']
  92. resp.extend(map(lambda x: ': '.join(x), stcpy.iteritems()))
  93. log.msg(repr(resp))
  94. self.transport.write(
  95. string.join(resp, '\r\n') + '\r\n\r\n', (SSDP_ADDR, SSDP_PORT))
  96. def notifyReceived(self, headers, (host, port)):
  97. """Process a presence announcement. We just remember the
  98. details of the SSDP service announced."""
  99. if headers['nts'] == 'ssdp:alive':
  100. if not self.elements.has_key(headers['nt']):
  101. # Register device/service
  102. self.elements[headers['nt']] = {}
  103. self.elements[headers['nt']]['USN'] = headers['usn']
  104. self.elements[headers['nt']]['host'] = (host, port)
  105. log.msg('Detected presence for %s' % headers['nt'])
  106. elif headers['nts'] == 'ssdp:byebye':
  107. if self.elements.has_key(headers['nt']):
  108. # Unregister device/service
  109. del(self.elements[headers['nt']])
  110. log.msg('Detected absence for %s' % headers['nt'])
  111. else:
  112. log.msg('Unknown subtype %s for notification type %s' %
  113. (headers['nts'], headers['nt']))
  114. def findService(self, name):
  115. """Return information about a service registered over SSDP."""
  116. # TODO: Implement me.
  117. # TODO: Send out a discovery request if we haven't registered
  118. # a presence announcement.
  119. def findDevice(self, name):
  120. """Return information about a device registered over SSDP."""
  121. # TODO: Implement me.
  122. # TODO: Send out a discovery request if we haven't registered
  123. # a presence announcement.