Discovery.cxx 7.78 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

#include <upnp/upnptools.h>

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

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

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

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

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

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

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

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

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

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

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

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

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

109 110
inline void
UPnPDeviceDirectory::discoExplorer()
111 112 113
{
	for (;;) {
		DiscoveredTask *tsk = 0;
114
		if (!discoveredQueue.take(tsk)) {
115
			discoveredQueue.workerExit();
116
			return;
117 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;
		}

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

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

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

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

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

	return UPNP_E_SUCCESS;
}

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

	return UPNP_E_SUCCESS;
}

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

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

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

	return UPNP_E_SUCCESS;
}

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

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

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

	return true;
233 234
}

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

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

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

257
	return search(error);
258 259 260
}

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

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

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

	return true;
}

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

298
	const ScopeLock protect(mutex);
299

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

	return true;
}

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

321 322 323
	const ScopeLock protect(mutex);

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

		if (device.friendlyName != friendlyName)
			continue;

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

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