This repository has been archived by the owner on May 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathssdp.py
167 lines (131 loc) · 5.3 KB
/
ssdp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#!/usr/bin/env python
#
# Copyright 2013 Jeff Rebeiro ([email protected]) All rights reserved
# Simple SSDP implementation for PC Autobackup
__author__ = '[email protected] (Jeff Rebeiro)'
import ConfigParser
import logging
import re
import socket
from twisted.internet import reactor
from twisted.internet.protocol import DatagramProtocol
import common
MSEARCH = re.compile(r'^M-SEARCH \* HTTP/1.1', re.DOTALL)
MSEARCH_DATA = re.compile(r'^([^:]+):\s+(.*)')
class SSDPServer(DatagramProtocol):
def __init__(self, config_file=None):
self.logger = logging.getLogger('pc_autobackup.ssdp')
self.config = common.LoadOrCreateConfig(config_file)
def startProtocol(self):
self.transport.setTTL(5)
self.transport.joinGroup('239.255.255.250')
def datagramReceived(self, datagram, address):
m = MSEARCH.match(datagram)
if m:
# TODO(jrebeiro): Verify that MediaServer is the only discovery request
# PCAutoBackup responds to.
msearch_data = self.ParseSSDPDiscovery(datagram)
address_info = ':'.join([str(x) for x in address])
if msearch_data.get('discovery_type'):
self.logger.debug('Received SSDP M-SEARCH for %s from %s',
msearch_data.get('discovery_type'), address_info)
else:
self.logger.debug('Received SSDP M-SEARCH from %s', address_info)
host_ip,host_port = self.GetHostAddress(address)
self.logger.debug('Received SSDP M-SEARCH on interface %s', host_ip)
if self.config.has_option('AUTOBACKUP', 'default_interface'):
if self.config.get('AUTOBACKUP', 'default_interface') != host_ip:
return
if msearch_data.get('discovery_type') == 'MediaServer':
self.SendSSDPResponse(address)
def GenerateSSDPResponse(self, response_type, ip_address, uuid,
notify_fields={}):
"""Generate an SSDP response.
Args:
response_type: One of m-search or notify
ip_address: IP address to use for the response
uuid: UUID to use for the response
notify_fields: A dictionary containing NT, NTS, and USN fields
Returns:
A string containing an SSDP response
"""
location = 'LOCATION: http://%s:52235/DMS/SamsungDmsDesc.xml' % ip_address
if response_type == 'm-search':
response = ['HTTP/1.1 200 OK',
'CACHE-CONTROL: max-age = 1800',
'EXT:',
location,
'SERVER: MS-Windows/XP UPnP/1.0 PROTOTYPE/1.0',
'ST: urn:schemas-upnp-org:device:MediaServer:1',
'USN: uuid:%s::urn:schemas-upnp-org:device:MediaServer:1' % uuid]
elif response_type == 'notify':
response = ['NOTIFY * HTTP/1.1',
'HOST: 239.255.255.250:1900',
'CACHE-CONTROL: max-age=1800',
location,
'NT: %s' % notify_fields.get('NT', ''),
'NTS: %s' % notify_fields.get('NTS', ''),
'USN: %s' % notify_fields.get('USN', ''),
'SERVER: MS-Windows/XP UPnP/1.0 PROTOTYPE/1.0']
response.append('CONTENT-LENGTH: 0')
response.append('')
response.append('')
return '\r\n'.join(response)
def ParseSSDPDiscovery(self, datagram):
"""Parse an SSDP UDP datagram.
Args:
datagram: A string containing an SSDP request data
Returns:
A dict containing the parsed data
"""
parsed_data = {}
for line in datagram.splitlines():
if line.startswith('M-SEARCH'):
continue
m = MSEARCH_DATA.match(line)
if m:
parsed_data[m.group(1)] = m.group(2)
# ST: urn:schemas-upnp-org:device:MediaServer:1
if m.group(1) == 'ST':
if m.group(2).startswith('urn:schemas-upnp-org:device:'):
parsed_data['discovery_type'] = m.group(2).split(':')[3]
return parsed_data
def SendSSDPResponse(self, address):
"""Send a response to an SSDP MediaServer discovery request.
Args:
address: A tuple of destination IP (string) and port (int)
"""
host_ip,host_port = self.GetHostAddress(address)
response = self.GenerateSSDPResponse('m-search',
host_ip,
self.config.get('AUTOBACKUP', 'uuid'))
address_info = ':'.join([str(x) for x in address])
self.logger.info('Sending SSDP response to %s', address_info)
self.logger.debug('Sending SSDP response to %s: %r', address_info,
response)
self.transport.write(response, address)
def GetHostAddress(self, address):
"""Get host address used when communicating with given udp address.
Args:
address: A tuple of destination IP (string) and port (int)
Returns:
A tuple of host IP (string) and port (int)
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(address)
return s.getsockname()
def StartSSDPServer():
"""Start an SSDP server.
Used for debugging/testing just an SSDP server.
"""
logging.info('SSDPServer started')
reactor.listenMulticast(1900, SSDPServer(), listenMultiple=True)
reactor.run()
def main():
logging_options = common.LOG_DEFAULTS
logging_options['filename'] = 'ssdpserver.log'
logging_options['level'] = logging.DEBUG
logging.basicConfig(**logging_options)
StartSSDPServer()
if __name__ == "__main__":
main()