Discovery.cxx 7.76 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * Copyright (C) 2003-2014 The Music Player Daemon Project
 * 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 27 28 29 30 31

#include <upnp/upnptools.h>

#include <string.h>

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

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

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

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

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

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

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

	directories.emplace_back(std::move(d));
86 87 88

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

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

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

102 103 104 105
			directories.erase(i);
			break;
		}
	}
106 107
}

108 109
inline void
UPnPDeviceDirectory::discoExplorer()
110 111 112
{
	for (;;) {
		DiscoveredTask *tsk = 0;
113
		if (!discoveredQueue.take(tsk)) {
114
			discoveredQueue.workerExit();
115
			return;
116 117
		}

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

		// Update or insert the device
130 131
		ContentDirectoryDescriptor d(std::move(tsk->deviceId),
					     MonotonicClockS(), tsk->expires);
132 133 134 135 136 137 138 139 140 141

		{
			Error error2;
			bool success = d.Parse(tsk->url, buf, error2);
			free(buf);
			if (!success) {
				delete tsk;
				LogError(error2);
				continue;
			}
142
		}
143

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

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

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

	return UPNP_E_SUCCESS;
}

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

	return UPNP_E_SUCCESS;
}

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

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

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

	return UPNP_E_SUCCESS;
}

211 212
bool
UPnPDeviceDirectory::expireDevices(Error &error)
213
{
214
	const ScopeLock protect(mutex);
215
	const unsigned now = MonotonicClockS();
216 217
	bool didsomething = false;

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

	if (didsomething)
229 230 231
		return search(error);

	return true;
232 233
}

234
UPnPDeviceDirectory::UPnPDeviceDirectory(UpnpClient_Handle _handle,
235
					 UPnPDiscoveryListener *_listener)
236
	:handle(_handle),
237
	 listener(_listener),
238 239
	 discoveredQueue("DiscoveredQueue"),
	 m_searchTimeout(2), m_lastSearch(0)
240 241 242
{
}

243 244 245 246 247
UPnPDeviceDirectory::~UPnPDeviceDirectory()
{
	/* this destructor exists here just so it won't get inlined */
}

248 249
bool
UPnPDeviceDirectory::Start(Error &error)
250
{
251
	if (!discoveredQueue.start(1, discoExplorer, this)) {
252
		error.Set(upnp_domain, "Discover work queue start failed");
253
		return false;
254 255
	}

256
	return search(error);
257 258 259
}

bool
260
UPnPDeviceDirectory::search(Error &error)
261
{
262
	const unsigned now = MonotonicClockS();
263 264 265 266 267
	if (now - m_lastSearch < 10)
		return true;
	m_lastSearch = now;

	// We search both for device and service just in case.
268
	int code = UpnpSearchAsync(handle, m_searchTimeout,
269
				   ContentDirectorySType, GetUpnpCookie());
270 271 272 273 274 275 276
	if (code != UPNP_E_SUCCESS) {
		error.Format(upnp_domain, code,
			     "UpnpSearchAsync() failed: %s",
			     UpnpGetErrorMessage(code));
		return false;
	}

277
	code = UpnpSearchAsync(handle, m_searchTimeout,
278
			       MediaServerDType, GetUpnpCookie());
279 280 281 282 283 284 285 286 287 288 289
	if (code != UPNP_E_SUCCESS) {
		error.Format(upnp_domain, code,
			     "UpnpSearchAsync() failed: %s",
			     UpnpGetErrorMessage(code));
		return false;
	}

	return true;
}

bool
290 291
UPnPDeviceDirectory::getDirServices(std::vector<ContentDirectoryService> &out,
				    Error &error)
292 293
{
	// Has locking, do it before our own lock
294 295
	if (!expireDevices(error))
		return false;
296

297
	const ScopeLock protect(mutex);
298

299 300
	for (auto dit = directories.begin();
	     dit != directories.end(); dit++) {
301
		for (const auto &service : dit->device.services) {
302
			if (isCDService(service.serviceType.c_str())) {
303
				out.emplace_back(dit->device, service);
304 305 306 307 308 309 310 311 312
			}
		}
	}

	return true;
}

bool
UPnPDeviceDirectory::getServer(const char *friendlyName,
313 314
			       ContentDirectoryService &server,
			       Error &error)
315
{
316 317
	// Has locking, do it before our own lock
	if (!expireDevices(error))
318 319
		return false;

320 321 322
	const ScopeLock protect(mutex);

	for (const auto &i : directories) {
323
		const auto &device = i.device;
324 325 326 327 328 329 330 331 332 333

		if (device.friendlyName != friendlyName)
			continue;

		for (const auto &service : device.services) {
			if (isCDService(service.serviceType.c_str())) {
				server = ContentDirectoryService(device,
								 service);
				return true;
			}
334 335 336
		}
	}

337
	error.Set(upnp_domain, "Server not found");
338 339
	return false;
}