Discovery.cxx 8.32 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 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 "Log.hxx"
24
#include "lib/curl/Global.hxx"
25
#include "event/Call.hxx"
26
#include "util/DeleteDisposer.hxx"
27
#include "util/ScopeExit.hxx"
28
#include "util/RuntimeError.hxx"
29

30
#include <upnptools.h>
31

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

35
UPnPDeviceDirectory::Downloader::Downloader(UPnPDeviceDirectory &_parent,
Max Kellermann's avatar
Max Kellermann committed
36
					    const UpnpDiscovery &disco)
37 38 39
	:defer_start_event(_parent.GetEventLoop(),
			   BIND_THIS_METHOD(OnDeferredStart)),
	 parent(_parent),
Max Kellermann's avatar
Max Kellermann committed
40 41 42
	 id(UpnpDiscovery_get_DeviceID_cstr(&disco)),
	 url(UpnpDiscovery_get_Location_cstr(&disco)),
	 expires(std::chrono::seconds(UpnpDiscovery_get_Expires(&disco))),
43 44
	 request(*parent.curl, url.c_str(), *this)
{
45
	const std::lock_guard<Mutex> protect(parent.mutex);
46 47 48 49
	parent.downloaders.push_back(*this);
}

void
50
UPnPDeviceDirectory::Downloader::Destroy() noexcept
51
{
52
	const std::lock_guard<Mutex> protect(parent.mutex);
53 54
	parent.downloaders.erase_and_dispose(parent.downloaders.iterator_to(*this),
					     DeleteDisposer());
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
}

void
UPnPDeviceDirectory::Downloader::OnHeaders(unsigned status,
					   std::multimap<std::string, std::string> &&)
{
	if (status != 200) {
		Destroy();
		return;
	}
}

void
UPnPDeviceDirectory::Downloader::OnData(ConstBuffer<void> _data)
{
	data.append((const char *)_data.data, _data.size);
}

void
UPnPDeviceDirectory::Downloader::OnEnd()
{
	AtScopeExit(this) { Destroy(); };

	ContentDirectoryDescriptor d(std::move(id),
				     std::chrono::steady_clock::now(),
				     expires);

	try {
83
		d.Parse(url, data.c_str());
84 85 86 87 88 89 90 91
	} catch (const std::exception &e) {
		LogError(e);
	}

	parent.LockAdd(std::move(d));
}

void
92
UPnPDeviceDirectory::Downloader::OnError(std::exception_ptr e) noexcept
93 94 95 96 97
{
	LogError(e);
	Destroy();
}

98
// The service type string we are looking for.
99
static constexpr char ContentDirectorySType[] = "urn:schemas-upnp-org:service:ContentDirectory:1";
100 101 102

// We don't include a version in comparisons, as we are satisfied with
// version 1
103
gcc_pure
104
static bool
105
isCDService(const char *st) noexcept
106
{
107
	constexpr size_t sz = sizeof(ContentDirectorySType) - 3;
108
	return strncmp(ContentDirectorySType, st, sz) == 0;
109 110 111
}

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

114
gcc_pure
115
static bool
116
isMSDevice(const char *st) noexcept
117
{
118
	constexpr size_t sz = sizeof(MediaServerDType) - 3;
119
	return strncmp(MediaServerDType, st, sz) == 0;
120 121
}

122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
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));
}

140
inline void
141
UPnPDeviceDirectory::LockAdd(ContentDirectoryDescriptor &&d)
142
{
143
	const std::lock_guard<Mutex> protect(mutex);
144 145 146 147 148 149 150 151 152

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

	directories.emplace_back(std::move(d));
153 154 155

	if (listener != nullptr)
		AnnounceFoundUPnP(*listener, directories.back().device);
156 157 158 159 160
}

inline void
UPnPDeviceDirectory::LockRemove(const std::string &id)
{
161
	const std::lock_guard<Mutex> protect(mutex);
162 163 164 165

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

169 170 171 172
			directories.erase(i);
			break;
		}
	}
173 174
}

175
inline int
Max Kellermann's avatar
Max Kellermann committed
176
UPnPDeviceDirectory::OnAlive(const UpnpDiscovery *disco) noexcept
177
{
178 179
	if (isMSDevice(UpnpDiscovery_get_DeviceType_cstr(disco)) ||
	    isCDService(UpnpDiscovery_get_ServiceType_cstr(disco))) {
180
		try {
181
			auto *downloader = new Downloader(*this, *disco);
182

183 184 185 186 187 188 189 190 191 192
			try {
				downloader->Start();
			} catch (...) {
				BlockingCall(GetEventLoop(), [downloader](){
						downloader->Destroy();
					});

				throw;
			}
		} catch (...) {
193 194 195
			LogError(std::current_exception());
			return UPNP_E_SUCCESS;
		}
196 197 198 199 200
	}

	return UPNP_E_SUCCESS;
}

201
inline int
Max Kellermann's avatar
Max Kellermann committed
202
UPnPDeviceDirectory::OnByeBye(const UpnpDiscovery *disco) noexcept
203
{
204 205
	if (isMSDevice(UpnpDiscovery_get_DeviceType_cstr(disco)) ||
	    isCDService(UpnpDiscovery_get_ServiceType_cstr(disco))) {
206
		// Device signals it is going off.
207
		LockRemove(UpnpDiscovery_get_DeviceID_cstr(disco));
208 209 210 211 212
	}

	return UPNP_E_SUCCESS;
}

213 214 215 216
// 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)
217
int
Max Kellermann's avatar
Max Kellermann committed
218
UPnPDeviceDirectory::Invoke(Upnp_EventType et, const void *evp) noexcept
219 220 221 222 223
{
	switch (et) {
	case UPNP_DISCOVERY_SEARCH_RESULT:
	case UPNP_DISCOVERY_ADVERTISEMENT_ALIVE:
		{
224
			auto *disco = (const UpnpDiscovery *)evp;
225
			return OnAlive(disco);
226 227 228 229
		}

	case UPNP_DISCOVERY_ADVERTISEMENT_BYEBYE:
		{
230
			auto *disco = (const UpnpDiscovery *)evp;
231
			return OnByeBye(disco);
232 233 234 235 236 237 238 239 240 241
		}

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

	return UPNP_E_SUCCESS;
}

242 243
void
UPnPDeviceDirectory::ExpireDevices()
244
{
245
	const auto now = std::chrono::steady_clock::now();
246 247
	bool didsomething = false;

248 249 250 251 252 253
	directories.remove_if([now, &didsomething](const ContentDirectoryDescriptor &d){
			bool expired = now > d.expires;
			if (expired)
				didsomething = true;
			return expired;
		});
254 255

	if (didsomething)
256
		Search();
257 258
}

259 260
UPnPDeviceDirectory::UPnPDeviceDirectory(EventLoop &event_loop,
					 UpnpClient_Handle _handle,
261
					 UPnPDiscoveryListener *_listener)
262 263
	:curl(event_loop), handle(_handle),
	 listener(_listener)
264 265 266
{
}

267
UPnPDeviceDirectory::~UPnPDeviceDirectory() noexcept
268
{
269
	BlockingCall(GetEventLoop(), [this](){
270
			const std::lock_guard<Mutex> protect(mutex);
271 272
			downloaders.clear_and_dispose(DeleteDisposer());
		});
273 274
}

275
inline EventLoop &
276
UPnPDeviceDirectory::GetEventLoop() noexcept
277 278 279 280
{
	return curl->GetEventLoop();
}

281 282
void
UPnPDeviceDirectory::Start()
283
{
284
	Search();
285 286
}

287 288
void
UPnPDeviceDirectory::Search()
289
{
290 291
	const auto now = std::chrono::steady_clock::now();
	if (now - last_search < std::chrono::seconds(10))
292
		return;
293
	last_search = now;
294 295

	// We search both for device and service just in case.
296
	int code = UpnpSearchAsync(handle, search_timeout,
297
				   ContentDirectorySType, GetUpnpCookie());
298 299 300
	if (code != UPNP_E_SUCCESS)
		throw FormatRuntimeError("UpnpSearchAsync() failed: %s",
					 UpnpGetErrorMessage(code));
301

302
	code = UpnpSearchAsync(handle, search_timeout,
303
			       MediaServerDType, GetUpnpCookie());
304 305 306
	if (code != UPNP_E_SUCCESS)
		throw FormatRuntimeError("UpnpSearchAsync() failed: %s",
					 UpnpGetErrorMessage(code));
307 308
}

309 310
std::vector<ContentDirectoryService>
UPnPDeviceDirectory::GetDirectories()
311
{
312
	const std::lock_guard<Mutex> protect(mutex);
313

314
	ExpireDevices();
315

316
	std::vector<ContentDirectoryService> out;
317 318
	for (const auto &descriptor : directories) {
		for (const auto &service : descriptor.device.services) {
319
			if (isCDService(service.serviceType.c_str())) {
320
				out.emplace_back(descriptor.device, service);
321 322 323 324
			}
		}
	}

325
	return out;
326 327
}

328 329
ContentDirectoryService
UPnPDeviceDirectory::GetServer(const char *friendly_name)
330
{
331
	const std::lock_guard<Mutex> protect(mutex);
332

333
	ExpireDevices();
334

335
	for (const auto &i : directories) {
336
		const auto &device = i.device;
337

338
		if (device.friendlyName != friendly_name)
339 340
			continue;

341 342 343 344
		for (const auto &service : device.services)
			if (isCDService(service.serviceType.c_str()))
				return ContentDirectoryService(device,
							       service);
345 346
	}

347
	throw std::runtime_error("Server not found");
348
}