-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
ssdpsearch.cpp
238 lines (211 loc) · 6.92 KB
/
ssdpsearch.cpp
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Copyright (c) 2013-2023 plan44.ch / Lukas Zeller, Zurich, Switzerland
//
// Author: Lukas Zeller <luz@plan44.ch>
//
// This file is part of p44utils.
//
// p44utils is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// p44utils is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with p44utils. If not, see <http://www.gnu.org/licenses/>.
//
// File scope debugging options
// - Set ALWAYS_DEBUG to 1 to enable DBGLOG output even in non-DEBUG builds of this file
#define ALWAYS_DEBUG 0
// - set FOCUSLOGLEVEL to non-zero log level (usually, 5,6, or 7==LOG_DEBUG) to get focus (extensive logging) for this file
// Note: must be before including "logger.hpp" (or anything that includes "logger.hpp")
#define FOCUSLOGLEVEL IFNOTREDUCEDFOOTPRINT(7)
#include "ssdpsearch.hpp"
using namespace p44;
SsdpSearch::SsdpSearch(MainLoop &aMainLoop) :
inherited(aMainLoop)
{
setReceiveHandler(boost::bind(&SsdpSearch::gotData, this, _1));
}
SsdpSearch::~SsdpSearch()
{
stopSearch();
}
void SsdpSearch::startSearch(SsdpSearchCB aSearchResultHandler, const char *aUuidToFind, bool aVerifyUUID)
{
string searchTarget;
bool singleTarget = false;
bool mustMatch = false;
if (!aUuidToFind) {
// find anything
searchTarget = "upnp:rootdevice";
}
else {
// find specific UUID
singleTarget = true;
searchTarget = string_format("uuid:%s",aUuidToFind);
mustMatch = aVerifyUUID;
}
startSearchForTarget(aSearchResultHandler, searchTarget.c_str(), singleTarget, mustMatch);
}
// Search request:
// M-SEARCH * HTTP/1.1
// HOST: 239.255.255.250:1900
// MAN: "ssdp:discover"
// MX: 5
// ST: upnp:rootdevice
#define SSDP_MULTICAST_ADDR "239.255.255.250"
#define SSDP_PORT "1900"
#define SSDP_MX 3 // should be sufficient (5 is max allowed)
void SsdpSearch::startSearchForTarget(SsdpSearchCB aSearchResultHandler, const char *aSearchTarget, bool aSingleTarget, bool aTargetMustMatch)
{
// save params
singleTargetSearch = aSingleTarget;
searchTarget = aSearchTarget;
searchResultHandler = aSearchResultHandler;
targetMustMatch = aTargetMustMatch;
// close current socket
closeConnection();
// setup new UDP socket
// Note: this socket does not need to (and thus should not) enable broadcast because (SSDP Wikipedia):
// "[...] A client that wishes to discover available services on a network, uses the M-SEARCH method.
// Responses to such search requests are sent via unicast addressing to the
// originating address and port number of the multicast request."
setConnectionParams(SSDP_MULTICAST_ADDR, SSDP_PORT, SOCK_DGRAM, AF_INET);
setConnectionStatusHandler(boost::bind(&SsdpSearch::socketStatusHandler, this, _2));
// prepare socket for usage
initiateConnection();
}
void SsdpSearch::socketStatusHandler(ErrorPtr aError)
{
FOCUSLOG("SSDP socket status: %s", Error::text(aError));
if (Error::isOK(aError)) {
FOCUSLOG("### sending UDP M-SEARCH");
// unregister socket status handler (or we'll get called when connection closes)
setConnectionStatusHandler(NoOP);
// send search request
string ssdpSearch = string_format(
"M-SEARCH * HTTP/1.1\r\n"
"HOST: %s:%s\r\n"
"MAN: \"ssdp:discover\"\r\n"
"MX: %d\r\n"
"ST: %s\r\n"
"\r\n",
SSDP_MULTICAST_ADDR,
SSDP_PORT,
SSDP_MX,
searchTarget.c_str()
);
transmitString(ssdpSearch);
// start timer (wait 1.5 the MX for answers)
timeoutTicket.executeOnce(boost::bind(&SsdpSearch::searchTimedOut, this), SSDP_MX*1500*MilliSecond);
}
else {
// error starting search
if (searchResultHandler) {
searchResultHandler(this, aError);
}
}
}
void SsdpSearch::searchTimedOut()
{
stopSearch();
if (searchResultHandler) {
searchResultHandler(this, Error::err<SsdpError>(SsdpError::Timeout, "SSDP search timed out with no (more) results"));
}
}
void SsdpSearch::stopSearch()
{
timeoutTicket.cancel();
closeConnection();
}
// M-SEARCH response
// HTTP/1.1 200 OK
// CACHE-CONTROL: max-age=100
// EXT:
// LOCATION: http://192.168.59.107:80/description.xml
// SERVER: FreeRTOS/6.0.5, UPnP/1.0, IpBridge/0.1
// ST: urn:schemas-upnp-org:device:basic:1
// USN: uuid:2f402f80-da50-11e1-9b23-0017880979ae
void SsdpSearch::gotData(ErrorPtr aError)
{
if (Error::isOK(receiveIntoString(response))) {
// extract uuid and location
const char *p = response.c_str();
FOCUSLOG("### received UDP answer: %s", p);
string line;
bool locFound = false;
bool uuidFound = false;
bool serverFound = false;
bool stFound = false;
while (nextLine(p, line)) {
string key, value;
if (keyAndValue(line, key, value)) {
if (key=="LOCATION") {
locationURL = value;
locFound = true;
FOCUSLOG("Location: %s", locationURL.c_str());
}
else if (key=="ST") {
if (targetMustMatch) {
if (searchTarget!=value) {
// wrong ST, discard
LOG(LOG_INFO, "Received notify from %s, but wrong ST (%s, expected: %s) -> ignored", locationURL.c_str(), value.c_str(), searchTarget.c_str());
// no more action, wait for response with correct ST
return;
}
}
stFound = true;
}
else if (key=="USN") {
FOCUSLOG("USN: %s", value.c_str());
// extract the UUID
string k,v;
if (keyAndValue(value, k, v)) {
if (k=="uuid") {
size_t i = v.find("::");
if (i!=string::npos)
uuid = v.substr(0,i);
else
uuid = v;
uuidFound = true;
}
}
}
else if (key=="CACHE-CONTROL") {
size_t pos = value.find("max-age =");
if (pos!=string::npos) {
sscanf(value.c_str()+9, "%d", &maxAge);
}
}
else if (key=="SERVER") {
server = value;
serverFound = true;
FOCUSLOG("SERVER: %s", server.c_str());
}
}
}
if (locFound && uuidFound && serverFound && stFound) {
// complete response -> call back
if (singleTargetSearch) {
stopSearch();
}
if (searchResultHandler) {
searchResultHandler(this, ErrorPtr());
}
}
else {
// invalid answer, just ignore it
FOCUSLOG("Received invalid SEARCH response (or unrelated SSDP packet) -> ignored");
}
}
else {
// receiving problem, report it
searchResultHandler(this, aError);
}
}