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.

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