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.

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