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.

215 lines
6.3 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. self.__notifyqueue = []
  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. self.doNotify = self.realdoNotify
  41. for i in self.__notifyqueue:
  42. self.doNotify(i)
  43. self.__notifyqueue = None
  44. def doStop(self):
  45. '''Make sure we send out the byebye notifications.'''
  46. for st in self.known.keys():
  47. self.doByebye(st)
  48. del self.known[st]
  49. DatagramProtocol.doStop(self)
  50. def datagramReceived(self, data, (host, port)):
  51. """Handle a received multicast datagram."""
  52. # Break up message in to command and headers
  53. # TODO: use the email module after trimming off the request line..
  54. # This gets us much better header support.
  55. header, payload = data.split('\r\n\r\n')
  56. lines = header.split('\r\n')
  57. cmd = string.split(lines[0], ' ')
  58. lines = map(lambda x: x.replace(': ', ':', 1), lines[1:])
  59. lines = filter(lambda x: len(x) > 0, lines)
  60. headers = [string.split(x, ':', 1) for x in lines]
  61. headers = dict(map(lambda x: (x[0].lower(), x[1]), headers))
  62. if cmd[0] == 'M-SEARCH' and cmd[1] == '*':
  63. # SSDP discovery
  64. self.discoveryRequest(headers, (host, port))
  65. elif cmd[0] == 'NOTIFY' and cmd[1] == '*':
  66. # SSDP presence
  67. self.notifyReceived(headers, (host, port))
  68. else:
  69. log.msg('Unknown SSDP command %s %s' % cmd)
  70. def discoveryRequest(self, headers, (host, port)):
  71. """Process a discovery request. The response must be sent to
  72. the address specified by (host, port)."""
  73. log.msg('Discovery request for %s' % headers['st'])
  74. # Do we know about this service?
  75. if headers['st'] == 'ssdp:all':
  76. for i in self.known:
  77. hcopy = dict(headers.iteritems())
  78. hcopy['st'] = i
  79. self.discoveryRequest(hcopy, (host, port))
  80. return
  81. if not self.known.has_key(headers['st']):
  82. return
  83. # Generate a response
  84. response = []
  85. response.append('HTTP/1.1 200 OK')
  86. for k, v in self.known[headers['st']].items():
  87. response.append('%s: %s' % (k, v))
  88. response.extend(('', ''))
  89. delay = random.randint(0, int(headers['mx']))
  90. reactor.callLater(delay, self.transport.write,
  91. '\r\n'.join(response), (host, port))
  92. def register(self, usn, st, location):
  93. """Register a service or device that this SSDP server will
  94. respond to."""
  95. log.msg('Registering %s' % st)
  96. self.known[st] = {}
  97. self.known[st]['USN'] = usn
  98. self.known[st]['LOCATION'] = location
  99. self.known[st]['ST'] = st
  100. self.known[st]['EXT'] = ''
  101. self.known[st]['SERVER'] = 'Twisted, UPnP/1.0, python-upnp'
  102. self.known[st]['CACHE-CONTROL'] = 'max-age=%d' % self.maxage
  103. self.doNotifySchedule(st)
  104. reactor.callLater(random.uniform(.5, 1), lambda: self.doNotify(st))
  105. reactor.callLater(random.uniform(1, 5), lambda: self.doNotify(st))
  106. def doNotifySchedule(self, st):
  107. self.doNotify(st)
  108. reactor.callLater(random.uniform(self.maxage / 3,
  109. self.maxage / 2), lambda: self.doNotifySchedule(st))
  110. def doByebye(self, st):
  111. """Do byebye"""
  112. log.msg('Sending byebye notification for %s' % st)
  113. resp = [ 'NOTIFY * HTTP/1.1',
  114. 'Host: %s:%d' % (SSDP_ADDR, SSDP_PORT),
  115. 'NTS: ssdp:byebye',
  116. ]
  117. stcpy = dict(self.known[st].iteritems())
  118. stcpy['NT'] = stcpy['ST']
  119. del stcpy['ST']
  120. resp.extend(map(lambda x: ': '.join(x), stcpy.iteritems()))
  121. resp.extend(('', ''))
  122. resp = '\r\n'.join(resp)
  123. self.transport.write(resp, (SSDP_ADDR, SSDP_PORT))
  124. self.transport.write(resp, (SSDP_ADDR, SSDP_PORT))
  125. def queueDoNotify(self, st):
  126. self.__notifyqueue.append(st)
  127. doNotify = queueDoNotify
  128. def realdoNotify(self, st):
  129. """Do notification"""
  130. log.msg('Sending alive notification for %s' % st)
  131. resp = [ 'NOTIFY * HTTP/1.1',
  132. 'Host: %s:%d' % (SSDP_ADDR, SSDP_PORT),
  133. 'NTS: ssdp:alive',
  134. ]
  135. stcpy = dict(self.known[st].iteritems())
  136. stcpy['NT'] = stcpy['ST']
  137. del stcpy['ST']
  138. resp.extend(map(lambda x: ': '.join(x), stcpy.iteritems()))
  139. resp.extend(('', ''))
  140. self.transport.write('\r\n'.join(resp), (SSDP_ADDR, SSDP_PORT))
  141. def notifyReceived(self, headers, (host, port)):
  142. """Process a presence announcement. We just remember the
  143. details of the SSDP service announced."""
  144. if headers['nts'] == 'ssdp:alive':
  145. if not self.elements.has_key(headers['nt']):
  146. # Register device/service
  147. self.elements[headers['nt']] = {}
  148. self.elements[headers['nt']]['USN'] = headers['usn']
  149. self.elements[headers['nt']]['host'] = (host, port)
  150. log.msg('Detected presence of %s' % headers['nt'])
  151. elif headers['nts'] == 'ssdp:byebye':
  152. if self.elements.has_key(headers['nt']):
  153. # Unregister device/service
  154. del(self.elements[headers['nt']])
  155. log.msg('Detected absence for %s' % headers['nt'])
  156. else:
  157. log.msg('Unknown subtype %s for notification type %s' %
  158. (headers['nts'], headers['nt']))
  159. def findService(self, name):
  160. """Return information about a service registered over SSDP."""
  161. # TODO: Implement me.
  162. # TODO: Send out a discovery request if we haven't registered
  163. # a presence announcement.
  164. def findDevice(self, name):
  165. """Return information about a device registered over SSDP."""
  166. # TODO: Implement me.
  167. # TODO: Send out a discovery request if we haven't registered
  168. # a presence announcement.