CurlInputPlugin.cxx 11.6 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3
 * http://www.musicpd.org
Max Kellermann's avatar
Max Kellermann committed
4 5 6 7 8 9 10 11 12 13
 *
 * 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.
14 15 16 17
 *
 * 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.
Max Kellermann's avatar
Max Kellermann committed
18 19
 */

20
#include "config.h"
21
#include "CurlInputPlugin.hxx"
22
#include "lib/curl/Easy.hxx"
23
#include "lib/curl/Global.hxx"
24
#include "lib/curl/Init.hxx"
25
#include "lib/curl/Request.hxx"
26
#include "lib/curl/Handler.hxx"
27
#include "lib/curl/Slist.hxx"
28
#include "../AsyncInputStream.hxx"
29
#include "../IcyInputStream.hxx"
30
#include "IcyMetaDataParser.hxx"
Max Kellermann's avatar
Max Kellermann committed
31
#include "../InputPlugin.hxx"
32
#include "config/ConfigGlobal.hxx"
33
#include "config/Block.hxx"
34
#include "tag/Builder.hxx"
35
#include "tag/Tag.hxx"
36
#include "event/Call.hxx"
37
#include "event/Loop.hxx"
38
#include "thread/Cond.hxx"
39
#include "util/ASCII.hxx"
40
#include "util/StringUtil.hxx"
41
#include "util/NumberParser.hxx"
42
#include "util/RuntimeError.hxx"
43
#include "util/Domain.hxx"
44
#include "Log.hxx"
45
#include "PluginUnavailable.hxx"
Max Kellermann's avatar
Max Kellermann committed
46 47 48

#include <assert.h>
#include <string.h>
49

Max Kellermann's avatar
Max Kellermann committed
50 51
#include <curl/curl.h>

52 53 54 55
#if LIBCURL_VERSION_NUM < 0x071200
#error libcurl is too old
#endif

56 57 58 59 60 61 62
/**
 * Do not buffer more than this number of bytes.  It should be a
 * reasonable limit that doesn't make low-end machines suffer too
 * much, but doesn't cause stuttering on high-latency lines.
 */
static const size_t CURL_MAX_BUFFERED = 512 * 1024;

63 64 65 66 67
/**
 * Resume the stream at this number of bytes after it has been paused.
 */
static const size_t CURL_RESUME_AT = 384 * 1024;

68
class CurlInputStream final : public AsyncInputStream, CurlResponseHandler {
Max Kellermann's avatar
Max Kellermann committed
69 70
	/* some buffers which were passed to libcurl, which we have
	   too free */
71
	CurlSlist request_headers;
Max Kellermann's avatar
Max Kellermann committed
72

73
	CurlRequest *request = nullptr;
74

75
	/** parser for icy-metadata */
76
	std::shared_ptr<IcyMetaDataParser> icy;
77

78
public:
79
	template<typename I>
80
	CurlInputStream(EventLoop &event_loop, const char *_url,
81
			const std::multimap<std::string, std::string> &headers,
82
			I &&_icy,
83
			Mutex &_mutex, Cond &_cond);
84

85
	~CurlInputStream() noexcept;
86

87 88
	CurlInputStream(const CurlInputStream &) = delete;
	CurlInputStream &operator=(const CurlInputStream &) = delete;
89

90 91 92
	static InputStreamPtr Open(const char *url,
				   const std::multimap<std::string, std::string> &headers,
				   Mutex &mutex, Cond &cond);
93

94
private:
95 96 97 98 99
	/**
	 * Create and initialize a new #CurlRequest instance.  After
	 * this, you may add more request headers and set options.  To
	 * actually start the request, call StartRequest().
	 */
100
	void InitEasy();
101

102 103 104 105 106 107
	/**
	 * Start the request after having called InitEasy().  After
	 * this, you must not set any CURL options.
	 */
	void StartRequest();

108 109 110 111 112 113
	/**
	 * Frees the current "libcurl easy" handle, and everything
	 * associated with it.
	 *
	 * Runs in the I/O thread.
	 */
114
	void FreeEasy() noexcept;
115 116 117 118 119 120 121

	/**
	 * Frees the current "libcurl easy" handle, and everything associated
	 * with it.
	 *
	 * The mutex must not be locked.
	 */
122
	void FreeEasyIndirect() noexcept;
123

124 125 126 127 128
	/**
	 * The DoSeek() implementation invoked in the IOThread.
	 */
	void SeekInternal(offset_type new_offset);

129 130 131 132 133
	/* virtual methods from CurlResponseHandler */
	void OnHeaders(unsigned status,
		       std::multimap<std::string, std::string> &&headers) override;
	void OnData(ConstBuffer<void> data) override;
	void OnEnd() override;
134
	void OnError(std::exception_ptr e) noexcept override;
135

136 137 138
	/* virtual methods from AsyncInputStream */
	virtual void DoResume() override;
	virtual void DoSeek(offset_type new_offset) override;
Max Kellermann's avatar
Max Kellermann committed
139 140 141 142 143
};

/** libcurl should accept "ICY 200 OK" */
static struct curl_slist *http_200_aliases;

144 145 146 147
/** HTTP proxy settings */
static const char *proxy, *proxy_user, *proxy_password;
static unsigned proxy_port;

148 149
static bool verify_peer, verify_host;

150
static CurlInit *curl_init;
151

152
static constexpr Domain curl_domain("curl");
153

154 155
void
CurlInputStream::DoResume()
156
{
157
	assert(GetEventLoop().IsInside());
158

159
	mutex.unlock();
160
	request->Resume();
161
	mutex.lock();
162 163
}

164
void
165
CurlInputStream::FreeEasy() noexcept
166
{
167
	assert(GetEventLoop().IsInside());
168

169
	if (request == nullptr)
170 171
		return;

172 173
	delete request;
	request = nullptr;
174 175
}

176
void
177
CurlInputStream::FreeEasyIndirect() noexcept
178
{
179
	BlockingCall(GetEventLoop(), [this](){
180
			FreeEasy();
181
			(*curl_init)->InvalidateSockets();
182
		});
183 184
}

185 186 187
void
CurlInputStream::OnHeaders(unsigned status,
			   std::multimap<std::string, std::string> &&headers)
188
{
189
	assert(GetEventLoop().IsInside());
190
	assert(!postponed_exception);
191
	assert(!icy || !icy->IsDefined());
192

193 194
	if (status < 200 || status >= 300)
		throw FormatRuntimeError("got HTTP status %ld", status);
195

196
	const std::lock_guard<Mutex> protect(mutex);
197

198 199 200 201 202 203
	if (IsSeekPending()) {
		/* don't update metadata while seeking */
		SeekDone();
		return;
	}

204
	if (headers.find("accept-ranges") != headers.end())
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
		seekable = true;

	auto i = headers.find("content-length");
	if (i != headers.end())
		size = offset + ParseUint64(i->second.c_str());

	i = headers.find("content-type");
	if (i != headers.end())
		SetMimeType(std::move(i->second));

	i = headers.find("icy-name");
	if (i == headers.end()) {
		i = headers.find("ice-name");
		if (i == headers.end())
			i = headers.find("x-audiocast-name");
	}

	if (i != headers.end()) {
		TagBuilder tag_builder;
		tag_builder.AddItem(TAG_NAME, i->second.c_str());

226
		SetTag(tag_builder.CommitNew());
227
	}
228

229
	if (icy) {
230 231 232 233
		i = headers.find("icy-metaint");

		if (i != headers.end()) {
			size_t icy_metaint = ParseUint64(i->second.c_str());
234
#ifndef _WIN32
235 236 237 238 239
			/* Windows doesn't know "%z" */
			FormatDebug(curl_domain, "icy-metaint=%zu", icy_metaint);
#endif

			if (icy_metaint > 0) {
240
				icy->Start(icy_metaint);
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

				/* a stream with icy-metadata is not
				   seekable */
				seekable = false;
			}
		}
	}

	SetReady();
}

void
CurlInputStream::OnData(ConstBuffer<void> data)
{
	assert(data.size > 0);

	const std::lock_guard<Mutex> protect(mutex);

259 260
	if (IsSeekPending())
		SeekDone();
261 262 263 264 265 266 267

	if (data.size > GetBufferSpace()) {
		AsyncInputStream::Pause();
		throw CurlRequest::Pause();
	}

	AppendToBuffer(data.data, data.size);
268 269
}

270
void
271
CurlInputStream::OnEnd()
272
{
273
	const std::lock_guard<Mutex> protect(mutex);
274 275 276 277 278 279
	cond.broadcast();

	AsyncInputStream::SetClosed();
}

void
280
CurlInputStream::OnError(std::exception_ptr e) noexcept
281
{
282
	const std::lock_guard<Mutex> protect(mutex);
283 284 285 286 287 288 289 290
	postponed_exception = std::move(e);

	if (IsSeekPending())
		SeekDone();
	else if (!IsReady())
		SetReady();
	else
		cond.broadcast();
291

292
	AsyncInputStream::SetClosed();
293 294 295
}

/*
296
 * InputPlugin methods
297 298 299
 *
 */

300
static void
301
input_curl_init(EventLoop &event_loop, const ConfigBlock &block)
Max Kellermann's avatar
Max Kellermann committed
302
{
303 304 305 306 307 308
	try {
		curl_init = new CurlInit(event_loop);
	} catch (const std::runtime_error &e) {
		LogError(e);
		throw PluginUnavailable(e.what());
	}
Max Kellermann's avatar
Max Kellermann committed
309

310 311 312 313 314 315 316 317
	const auto version_info = curl_version_info(CURLVERSION_FIRST);
	if (version_info != nullptr) {
		FormatDebug(curl_domain, "version %s", version_info->version);
		if (version_info->features & CURL_VERSION_SSL)
			FormatDebug(curl_domain, "with %s",
				    version_info->ssl_version);
	}

Max Kellermann's avatar
Max Kellermann committed
318
	http_200_aliases = curl_slist_append(http_200_aliases, "ICY 200 OK");
319

320 321 322 323
	proxy = block.GetBlockValue("proxy");
	proxy_port = block.GetBlockValue("proxy_port", 0u);
	proxy_user = block.GetBlockValue("proxy_user");
	proxy_password = block.GetBlockValue("proxy_password");
324

325
	if (proxy == nullptr) {
326
		/* deprecated proxy configuration */
327
		proxy = config_get_string(ConfigOption::HTTP_PROXY_HOST);
328
		proxy_port = config_get_positive(ConfigOption::HTTP_PROXY_PORT, 0);
329
		proxy_user = config_get_string(ConfigOption::HTTP_PROXY_USER);
330
		proxy_password = config_get_string(ConfigOption::HTTP_PROXY_PASSWORD,
331 332 333
						   "");
	}

334 335
	verify_peer = block.GetBlockValue("verify_peer", true);
	verify_host = block.GetBlockValue("verify_host", true);
Max Kellermann's avatar
Max Kellermann committed
336 337
}

338
static void
339
input_curl_finish() noexcept
Max Kellermann's avatar
Max Kellermann committed
340
{
341
	delete curl_init;
342

Max Kellermann's avatar
Max Kellermann committed
343
	curl_slist_free_all(http_200_aliases);
344
	http_200_aliases = nullptr;
Max Kellermann's avatar
Max Kellermann committed
345 346
}

347
template<typename I>
348 349
inline
CurlInputStream::CurlInputStream(EventLoop &event_loop, const char *_url,
350
				 const std::multimap<std::string, std::string> &headers,
351
				 I &&_icy,
352 353 354 355
				 Mutex &_mutex, Cond &_cond)
	:AsyncInputStream(event_loop, _url, _mutex, _cond,
			  CURL_MAX_BUFFERED,
			  CURL_RESUME_AT),
356
	 icy(std::forward<I>(_icy))
357
{
358
	request_headers.Append("Icy-Metadata: 1");
359 360 361

	for (const auto &i : headers)
		request_headers.Append((i.first + ":" + i.second).c_str());
362 363
}

364
CurlInputStream::~CurlInputStream() noexcept
Max Kellermann's avatar
Max Kellermann committed
365
{
366
	FreeEasyIndirect();
Max Kellermann's avatar
Max Kellermann committed
367 368
}

369 370
void
CurlInputStream::InitEasy()
Max Kellermann's avatar
Max Kellermann committed
371
{
372
	request = new CurlRequest(**curl_init, GetURI(), *this);
373 374 375 376 377

	request->SetOption(CURLOPT_HTTP200ALIASES, http_200_aliases);
	request->SetOption(CURLOPT_FOLLOWLOCATION, 1l);
	request->SetOption(CURLOPT_MAXREDIRS, 5l);
	request->SetOption(CURLOPT_FAILONERROR, 1l);
Max Kellermann's avatar
Max Kellermann committed
378

379
	if (proxy != nullptr)
380
		request->SetOption(CURLOPT_PROXY, proxy);
381

382
	if (proxy_port > 0)
383
		request->SetOption(CURLOPT_PROXYPORT, (long)proxy_port);
384

385
	if (proxy_user != nullptr && proxy_password != nullptr) {
386 387 388 389
		char proxy_auth_str[1024];
		snprintf(proxy_auth_str, sizeof(proxy_auth_str),
			 "%s:%s",
			 proxy_user, proxy_password);
390
		request->SetOption(CURLOPT_PROXYUSERPWD, proxy_auth_str);
391 392
	}

393 394
	request->SetOption(CURLOPT_SSL_VERIFYPEER, verify_peer ? 1l : 0l);
	request->SetOption(CURLOPT_SSL_VERIFYHOST, verify_host ? 2l : 0l);
395
	request->SetOption(CURLOPT_HTTPHEADER, request_headers.Get());
396 397 398 399 400
}

void
CurlInputStream::StartRequest()
{
401
	request->Start();
Max Kellermann's avatar
Max Kellermann committed
402 403
}

404
void
405
CurlInputStream::SeekInternal(offset_type new_offset)
Max Kellermann's avatar
Max Kellermann committed
406 407 408
{
	/* close the old connection and open a new one */

409
	FreeEasy();
Max Kellermann's avatar
Max Kellermann committed
410

411
	offset = new_offset;
412
	if (offset == size) {
413 414 415
		/* seek to EOF: simulate empty result; avoid
		   triggering a "416 Requested Range Not Satisfiable"
		   response */
416
		SeekDone();
417
		return;
418
	}
419

420
	InitEasy();
Max Kellermann's avatar
Max Kellermann committed
421 422 423

	/* send the "Range" header */

424
	if (offset > 0) {
425
		char range[32];
426
#ifdef _WIN32
427 428 429
		// TODO: what can we use on Windows to format 64 bit?
		sprintf(range, "%lu-", (long)offset);
#else
430
		sprintf(range, "%llu-", (unsigned long long)offset);
431
#endif
432
		request->SetOption(CURLOPT_RANGE, range);
Max Kellermann's avatar
Max Kellermann committed
433
	}
434 435

	StartRequest();
436
}
437

438 439 440 441
void
CurlInputStream::DoSeek(offset_type new_offset)
{
	assert(IsReady());
442
	assert(seekable);
443 444 445

	const ScopeUnlock unlock(mutex);

446
	BlockingCall(GetEventLoop(), [this, new_offset](){
447 448
			SeekInternal(new_offset);
		});
Max Kellermann's avatar
Max Kellermann committed
449 450
}

451
inline InputStreamPtr
452 453 454
CurlInputStream::Open(const char *url,
		      const std::multimap<std::string, std::string> &headers,
		      Mutex &mutex, Cond &cond)
Max Kellermann's avatar
Max Kellermann committed
455
{
456 457
	auto icy = std::make_shared<IcyMetaDataParser>();

458
	auto c = std::make_unique<CurlInputStream>((*curl_init)->GetEventLoop(),
459
						   url, headers,
460 461
						   icy,
						   mutex, cond);
462

463 464 465 466
	BlockingCall(c->GetEventLoop(), [&c](){
			c->InitEasy();
			c->StartRequest();
		});
Max Kellermann's avatar
Max Kellermann committed
467

468
	return std::make_unique<IcyInputStream>(std::move(c), std::move(icy));
469 470
}

471 472 473 474 475 476 477 478
InputStreamPtr
OpenCurlInputStream(const char *uri,
		    const std::multimap<std::string, std::string> &headers,
		    Mutex &mutex, Cond &cond)
{
	return CurlInputStream::Open(uri, headers, mutex, cond);
}

479
static InputStreamPtr
480
input_curl_open(const char *url, Mutex &mutex, Cond &cond)
481
{
482 483
	if (strncmp(url, "http://", 7) != 0 &&
	    strncmp(url, "https://", 8) != 0)
484
		return nullptr;
485

486
	return CurlInputStream::Open(url, {}, mutex, cond);
Max Kellermann's avatar
Max Kellermann committed
487
}
488

489
const struct InputPlugin input_plugin_curl = {
490 491 492 493
	"curl",
	input_curl_init,
	input_curl_finish,
	input_curl_open,
494
};