Discovery.cxx 7.3 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * http://www.musicpd.org
 *
 * This program 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 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"
#include "Discovery.hxx"
#include "Domain.hxx"
#include "ContentDirectoryService.hxx"
24
#include "system/Clock.hxx"
25
#include "Log.hxx"
26
#include "util/ScopeExit.hxx"
27
#include "util/RuntimeError.hxx"
28 29 30

#include <upnp/upnptools.h>

31
#include <stdlib.h>
32 33 34
#include <string.h>

// The service type string we are looking for.
35
static constexpr char ContentDirectorySType[] = "urn:schemas-upnp-org:service:ContentDirectory:1";
36 37 38

// We don't include a version in comparisons, as we are satisfied with
// version 1
39
gcc_pure
40
static bool
41
isCDService(const char *st)
42
{
43
	constexpr size_t sz = sizeof(ContentDirectorySType) - 3;
44
	return memcmp(ContentDirectorySType, st, sz) == 0;
45 46 47
}

// The type of device we're asking for in search
48
static constexpr char MediaServerDType[] = "urn:schemas-upnp-org:device:MediaServer:1";
49

50
gcc_pure
51
static bool
52
isMSDevice(const char *st)
53
{
54
	constexpr size_t sz = sizeof(MediaServerDType) - 3;
55
	return memcmp(MediaServerDType, st, sz) == 0;
56 57
}

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
static void
AnnounceFoundUPnP(UPnPDiscoveryListener &listener, const UPnPDevice &device)
{
	for (const auto &service : device.services)
		if (isCDService(service.serviceType.c_str()))
			listener.FoundUPnP(ContentDirectoryService(device,
								   service));
}

static void
AnnounceLostUPnP(UPnPDiscoveryListener &listener, const UPnPDevice &device)
{
	for (const auto &service : device.services)
		if (isCDService(service.serviceType.c_str()))
			listener.LostUPnP(ContentDirectoryService(device,
								  service));
}

76
inline void
77
UPnPDeviceDirectory::LockAdd(ContentDirectoryDescriptor &&d)
78 79
{
	const ScopeLock protect(mutex);
80 81 82 83 84 85 86 87 88

	for (auto &i : directories) {
		if (i.id == d.id) {
			i = std::move(d);
			return;
		}
	}

	directories.emplace_back(std::move(d));
89 90 91

	if (listener != nullptr)
		AnnounceFoundUPnP(*listener, directories.back().device);
92 93 94 95 96 97
}

inline void
UPnPDeviceDirectory::LockRemove(const std::string &id)
{
	const ScopeLock protect(mutex);
98 99 100 101

	for (auto i = directories.begin(), end = directories.end();
	     i != end; ++i) {
		if (i->id == id) {
102 103 104
			if (listener != nullptr)
				AnnounceLostUPnP(*listener, i->device);

105 106 107 108
			directories.erase(i);
			break;
		}
	}
109 110
}

111
inline void
112
UPnPDeviceDirectory::Explore()
113 114
{
	for (;;) {
115
		std::unique_ptr<DiscoveredTask> tsk;
116 117
		if (!queue.take(tsk)) {
			queue.workerExit();
118
			return;
119 120
		}

121 122 123 124 125 126 127 128 129 130 131
		// Device signals its existence and well-being. Perform the
		// UPnP "description" phase by downloading and decoding the
		// description document.
		char *buf;
		// LINE_SIZE is defined by libupnp's upnp.h...
		char contentType[LINE_SIZE];
		int code = UpnpDownloadUrlItem(tsk->url.c_str(), &buf, contentType);
		if (code != UPNP_E_SUCCESS) {
			continue;
		}

132 133
		AtScopeExit(buf){ free(buf); };

134
		// Update or insert the device
135
		ContentDirectoryDescriptor d(std::move(tsk->device_id),
136
					     MonotonicClockS(), tsk->expires);
137

138 139 140 141
		try {
			d.Parse(tsk->url, buf);
		} catch (const std::exception &e) {
			LogError(e);
142
		}
143

144
		LockAdd(std::move(d));
145 146 147
	}
}

148
void *
149
UPnPDeviceDirectory::Explore(void *ctx)
150 151
{
	UPnPDeviceDirectory &directory = *(UPnPDeviceDirectory *)ctx;
152
	directory.Explore();
153 154 155 156 157
	return (void*)1;
}

inline int
UPnPDeviceDirectory::OnAlive(Upnp_Discovery *disco)
158 159 160
{
	if (isMSDevice(disco->DeviceType) ||
	    isCDService(disco->ServiceType)) {
161
		DiscoveredTask *tp = new DiscoveredTask(disco);
162
		if (queue.put(tp))
163 164 165 166 167 168
			return UPNP_E_FINISH;
	}

	return UPNP_E_SUCCESS;
}

169 170
inline int
UPnPDeviceDirectory::OnByeBye(Upnp_Discovery *disco)
171 172 173
{
	if (isMSDevice(disco->DeviceType) ||
	    isCDService(disco->ServiceType)) {
174
		// Device signals it is going off.
175
		LockRemove(disco->DeviceId);
176 177 178 179 180
	}

	return UPNP_E_SUCCESS;
}

181 182 183 184
// This gets called for all libupnp asynchronous events, in a libupnp
// thread context.
// Example: ContentDirectories appearing and disappearing from the network
// We queue a task for our worker thread(s)
185 186
int
UPnPDeviceDirectory::Invoke(Upnp_EventType et, void *evp)
187 188 189 190 191 192
{
	switch (et) {
	case UPNP_DISCOVERY_SEARCH_RESULT:
	case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
		{
			Upnp_Discovery *disco = (Upnp_Discovery *)evp;
193
			return OnAlive(disco);
194 195 196 197 198
		}

	case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE:
		{
			Upnp_Discovery *disco = (Upnp_Discovery *)evp;
199
			return OnByeBye(disco);
200 201 202 203 204 205 206 207 208 209
		}

	default:
		// Ignore other events for now
		break;
	}

	return UPNP_E_SUCCESS;
}

210 211
void
UPnPDeviceDirectory::ExpireDevices()
212
{
213
	const unsigned now = MonotonicClockS();
214 215
	bool didsomething = false;

216 217
	for (auto it = directories.begin();
	     it != directories.end();) {
218
		if (now > it->expires) {
219
			it = directories.erase(it);
220 221 222 223 224 225 226
			didsomething = true;
		} else {
			it++;
		}
	}

	if (didsomething)
227
		Search();
228 229
}

230
UPnPDeviceDirectory::UPnPDeviceDirectory(UpnpClient_Handle _handle,
231
					 UPnPDiscoveryListener *_listener)
232
	:handle(_handle),
233
	 listener(_listener),
234 235
	 queue("DiscoveredQueue"),
	 search_timeout(2), last_search(0)
236 237 238
{
}

239 240 241 242 243
UPnPDeviceDirectory::~UPnPDeviceDirectory()
{
	/* this destructor exists here just so it won't get inlined */
}

244 245
void
UPnPDeviceDirectory::Start()
246
{
247 248
	if (!queue.start(1, Explore, this))
		throw std::runtime_error("Discover work queue start failed");
249

250
	Search();
251 252
}

253 254
void
UPnPDeviceDirectory::Search()
255
{
256
	const unsigned now = MonotonicClockS();
257
	if (now - last_search < 10)
258
		return;
259
	last_search = now;
260 261

	// We search both for device and service just in case.
262
	int code = UpnpSearchAsync(handle, search_timeout,
263
				   ContentDirectorySType, GetUpnpCookie());
264 265 266
	if (code != UPNP_E_SUCCESS)
		throw FormatRuntimeError("UpnpSearchAsync() failed: %s",
					 UpnpGetErrorMessage(code));
267

268
	code = UpnpSearchAsync(handle, search_timeout,
269
			       MediaServerDType, GetUpnpCookie());
270 271 272
	if (code != UPNP_E_SUCCESS)
		throw FormatRuntimeError("UpnpSearchAsync() failed: %s",
					 UpnpGetErrorMessage(code));
273 274
}

275 276
std::vector<ContentDirectoryService>
UPnPDeviceDirectory::GetDirectories()
277
{
278 279
	const ScopeLock protect(mutex);

280
	ExpireDevices();
281

282
	std::vector<ContentDirectoryService> out;
283 284
	for (auto dit = directories.begin();
	     dit != directories.end(); dit++) {
285
		for (const auto &service : dit->device.services) {
286
			if (isCDService(service.serviceType.c_str())) {
287
				out.emplace_back(dit->device, service);
288 289 290 291
			}
		}
	}

292
	return out;
293 294
}

295 296
ContentDirectoryService
UPnPDeviceDirectory::GetServer(const char *friendly_name)
297
{
298 299
	const ScopeLock protect(mutex);

300
	ExpireDevices();
301

302
	for (const auto &i : directories) {
303
		const auto &device = i.device;
304

305
		if (device.friendlyName != friendly_name)
306 307
			continue;

308 309 310 311
		for (const auto &service : device.services)
			if (isCDService(service.serviceType.c_str()))
				return ContentDirectoryService(device,
							       service);
312 313
	}

314
	throw std::runtime_error("Server not found");
315
}