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.

184 lines
5.4 KiB

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