Discovery.cxx 7.28 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 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
 * 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 "ContentDirectoryService.hxx"
23
#include "system/Clock.hxx"
24
#include "Log.hxx"
25
#include "util/ScopeExit.hxx"
26
#include "util/RuntimeError.hxx"
27 28 29

#include <upnp/upnptools.h>

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

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

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

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

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

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
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));
}

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

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

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

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

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

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

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

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

120 121 122 123 124 125 126 127 128 129 130
		// 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;
		}

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

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

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

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

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

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

	return UPNP_E_SUCCESS;
}

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

	return UPNP_E_SUCCESS;
}

180 181 182 183
// 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)
184 185
int
UPnPDeviceDirectory::Invoke(Upnp_EventType et, void *evp)
186 187 188 189 190 191
{
	switch (et) {
	case UPNP_DISCOVERY_SEARCH_RESULT:
	case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
		{
			Upnp_Discovery *disco = (Upnp_Discovery *)evp;
192
			return OnAlive(disco);
193 194 195 196 197
		}

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

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

	return UPNP_E_SUCCESS;
}

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

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

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

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

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

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

249
	Search();
250 251
}

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

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

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

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

279
	ExpireDevices();
280

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

291
	return out;
292 293
}

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

299
	ExpireDevices();
300

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

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

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

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