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.

196 lines
5.9 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 <gurney_j@resnet.uroegon.edu>
  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 doStop(self):
  33. '''Make sure we send out the byebye notifications.'''
  34. for st in self.known.keys():
  35. self.doByebye(st)
  36. del self.known[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, port))
  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=%d' % self.maxage
  91. self.doNotifySchedule(st)
  92. reactor.callLater(random.uniform(.5, 1), lambda: self.doNotify(st))
  93. reactor.callLater(random.uniform(1, 5), lambda: self.doNotify(st))
  94. def doNotifySchedule(self, st):
  95. self.doNotify(st)
  96. reactor.callLater(random.uniform(self.maxage / 3,
  97. self.maxage / 2), lambda: self.doNotifySchedule(st))
  98. def doByebye(self, st):
  99. """Do byebye"""
  100. log.msg('Sending byebye notification for %s' % st)
  101. resp = [ 'NOTIFY * HTTP/1.1',
  102. 'Host: %s:%d' % (SSDP_ADDR, SSDP_PORT),
  103. 'NTS: ssdp:byebye',
  104. ]
  105. stcpy = dict(self.known[st].iteritems())
  106. stcpy['NT'] = stcpy['ST']
  107. del stcpy['ST']
  108. resp.extend(map(lambda x: ': '.join(x), stcpy.iteritems()))
  109. resp.extend(('', ''))
  110. resp = '\r\n'.join(resp)
  111. self.transport.write(resp, (SSDP_ADDR, SSDP_PORT))
  112. self.transport.write(resp, (SSDP_ADDR, SSDP_PORT))
  113. def doNotify(self, st):
  114. """Do notification"""
  115. log.msg('Sending alive notification for %s' % st)
  116. resp = [ 'NOTIFY * HTTP/1.1',
  117. 'Host: %s:%d' % (SSDP_ADDR, SSDP_PORT),
  118. 'NTS: ssdp:alive',
  119. ]
  120. stcpy = dict(self.known[st].iteritems())
  121. stcpy['NT'] = stcpy['ST']
  122. del stcpy['ST']
  123. resp.extend(map(lambda x: ': '.join(x), stcpy.iteritems()))
  124. resp.extend(('', ''))
  125. self.transport.write('\r\n'.join(resp), (SSDP_ADDR, SSDP_PORT))
  126. def notifyReceived(self, headers, (host, port)):
  127. """Process a presence announcement. We just remember the
  128. details of the SSDP service announced."""
  129. if headers['nts'] == 'ssdp:alive':
  130. if not self.elements.has_key(headers['nt']):
  131. # Register device/service
  132. self.elements[headers['nt']] = {}
  133. self.elements[headers['nt']]['USN'] = headers['usn']
  134. self.elements[headers['nt']]['host'] = (host, port)
  135. log.msg('Detected presence of %s' % headers['nt'])
  136. elif headers['nts'] == 'ssdp:byebye':
  137. if self.elements.has_key(headers['nt']):
  138. # Unregister device/service
  139. del(self.elements[headers['nt']])
  140. log.msg('Detected absence for %s' % headers['nt'])
  141. else:
  142. log.msg('Unknown subtype %s for notification type %s' %
  143. (headers['nts'], headers['nt']))
  144. def findService(self, name):
  145. """Return information about a service registered over SSDP."""
  146. # TODO: Implement me.
  147. # TODO: Send out a discovery request if we haven't registered
  148. # a presence announcement.
  149. def findDevice(self, name):
  150. """Return information about a device registered over SSDP."""
  151. # TODO: Implement me.
  152. # TODO: Send out a discovery request if we haven't registered
  153. # a presence announcement.