Discovery.cxx 8.32 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 * 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 "Discovery.hxx"
#include "ContentDirectoryService.hxx"
22
#include "Log.hxx"
23
#include "lib/curl/Global.hxx"
24
#include "event/Call.hxx"
25
#include "util/DeleteDisposer.hxx"
26
#include "util/ScopeExit.hxx"
27
#include "util/RuntimeError.hxx"
28

29
#include <upnptools.h>
30

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

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

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

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 {
82
		d.Parse(url, data.c_str());
83 84
	} catch (...) {
		LogError(std::current_exception());
85 86 87 88 89 90
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return UPNP_E_SUCCESS;
}

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

	return UPNP_E_SUCCESS;
}

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

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

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

	return UPNP_E_SUCCESS;
}

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

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

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

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

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

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

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

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

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

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

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

313
	ExpireDevices();
314

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

324
	return out;
325 326
}

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

332
	ExpireDevices();
333

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

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

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

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