CurlInputPlugin.cxx 11.1 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/Error.hxx"
23
#include "lib/curl/Easy.hxx"
24
#include "lib/curl/Global.hxx"
25
#include "lib/curl/Init.hxx"
26
#include "lib/curl/Request.hxx"
27
#include "lib/curl/Handler.hxx"
28
#include "lib/curl/Slist.hxx"
29
#include "../MaybeBufferedInputStream.hxx"
30
#include "../AsyncInputStream.hxx"
31
#include "../IcyInputStream.hxx"
32
#include "IcyMetaDataParser.hxx"
Max Kellermann's avatar
Max Kellermann committed
33
#include "../InputPlugin.hxx"
34
#include "config/Block.hxx"
35
#include "tag/Builder.hxx"
36
#include "tag/Tag.hxx"
37
#include "event/Call.hxx"
38
#include "event/Loop.hxx"
39
#include "util/ASCII.hxx"
40
#include "util/StringUtil.hxx"
41
#include "util/StringFormat.hxx"
42
#include "util/NumberParser.hxx"
43
#include "util/RuntimeError.hxx"
44
#include "util/Domain.hxx"
45
#include "Log.hxx"
46
#include "PluginUnavailable.hxx"
Max Kellermann's avatar
Max Kellermann committed
47

48 49
#include <cinttypes>

Max Kellermann's avatar
Max Kellermann committed
50 51
#include <assert.h>
#include <string.h>
52

Max Kellermann's avatar
Max Kellermann committed
53 54
#include <curl/curl.h>

55 56 57 58
#if LIBCURL_VERSION_NUM < 0x071200
#error libcurl is too old
#endif

59 60 61 62 63 64 65
/**
 * 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;

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

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

76
	CurlRequest *request = nullptr;
77

78
	/** parser for icy-metadata */
79
	std::shared_ptr<IcyMetaDataParser> icy;
80

81
public:
82
	template<typename I>
83
	CurlInputStream(EventLoop &event_loop, const char *_url,
84
			const std::multimap<std::string, std::string> &headers,
85
			I &&_icy,
86
			Mutex &_mutex);
87

88
	~CurlInputStream() noexcept;
89

90 91
	CurlInputStream(const CurlInputStream &) = delete;
	CurlInputStream &operator=(const CurlInputStream &) = delete;
92

93 94
	static InputStreamPtr Open(const char *url,
				   const std::multimap<std::string, std::string> &headers,
95
				   Mutex &mutex);
96

97
private:
98 99 100 101 102
	/**
	 * 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().
	 */
103
	void InitEasy();
104

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

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

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

127 128 129 130 131
	/**
	 * The DoSeek() implementation invoked in the IOThread.
	 */
	void SeekInternal(offset_type new_offset);

132 133 134 135 136
	/* 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;
137
	void OnError(std::exception_ptr e) noexcept override;
138

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

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

147 148 149 150
/** HTTP proxy settings */
static const char *proxy, *proxy_user, *proxy_password;
static unsigned proxy_port;

151 152
static bool verify_peer, verify_host;

153
static CurlInit *curl_init;
154

155
static constexpr Domain curl_domain("curl");
156

157 158
void
CurlInputStream::DoResume()
159
{
160
	assert(GetEventLoop().IsInside());
161

162
	mutex.unlock();
163
	request->Resume();
164
	mutex.lock();
165 166
}

167
void
168
CurlInputStream::FreeEasy() noexcept
169
{
170
	assert(GetEventLoop().IsInside());
171

172
	if (request == nullptr)
173 174
		return;

175 176
	delete request;
	request = nullptr;
177 178
}

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

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

196
	if (status < 200 || status >= 300)
197 198 199
		throw HttpStatusError(status,
				      StringFormat<40>("got HTTP status %u",
						       status).c_str());
200

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

203 204 205 206 207 208
	if (IsSeekPending()) {
		/* don't update metadata while seeking */
		SeekDone();
		return;
	}

209
	if (headers.find("accept-ranges") != headers.end())
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
		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());

231
		SetTag(tag_builder.CommitNew());
232
	}
233

234
	if (icy) {
235 236 237 238
		i = headers.find("icy-metaint");

		if (i != headers.end()) {
			size_t icy_metaint = ParseUint64(i->second.c_str());
239
#ifndef _WIN32
240 241 242 243 244
			/* Windows doesn't know "%z" */
			FormatDebug(curl_domain, "icy-metaint=%zu", icy_metaint);
#endif

			if (icy_metaint > 0) {
245
				icy->Start(icy_metaint);
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

				/* 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);

264 265
	if (IsSeekPending())
		SeekDone();
266 267 268 269 270 271 272

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

	AppendToBuffer(data.data, data.size);
273 274
}

275
void
276
CurlInputStream::OnEnd()
277
{
278
	const std::lock_guard<Mutex> protect(mutex);
279
	InvokeOnAvailable();
280 281 282 283 284

	AsyncInputStream::SetClosed();
}

void
285
CurlInputStream::OnError(std::exception_ptr e) noexcept
286
{
287
	const std::lock_guard<Mutex> protect(mutex);
288 289 290 291 292 293 294
	postponed_exception = std::move(e);

	if (IsSeekPending())
		SeekDone();
	else if (!IsReady())
		SetReady();
	else
295
		InvokeOnAvailable();
296

297
	AsyncInputStream::SetClosed();
298 299 300
}

/*
301
 * InputPlugin methods
302 303 304
 *
 */

305
static void
306
input_curl_init(EventLoop &event_loop, const ConfigBlock &block)
Max Kellermann's avatar
Max Kellermann committed
307
{
308 309 310 311 312 313
	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
314

315 316 317 318 319 320 321 322
	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
323
	http_200_aliases = curl_slist_append(http_200_aliases, "ICY 200 OK");
324

325 326 327 328
	proxy = block.GetBlockValue("proxy");
	proxy_port = block.GetBlockValue("proxy_port", 0u);
	proxy_user = block.GetBlockValue("proxy_user");
	proxy_password = block.GetBlockValue("proxy_password");
329

330 331
	verify_peer = block.GetBlockValue("verify_peer", true);
	verify_host = block.GetBlockValue("verify_host", true);
Max Kellermann's avatar
Max Kellermann committed
332 333
}

334
static void
335
input_curl_finish() noexcept
Max Kellermann's avatar
Max Kellermann committed
336
{
337
	delete curl_init;
338

Max Kellermann's avatar
Max Kellermann committed
339
	curl_slist_free_all(http_200_aliases);
340
	http_200_aliases = nullptr;
Max Kellermann's avatar
Max Kellermann committed
341 342
}

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

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

360
CurlInputStream::~CurlInputStream() noexcept
Max Kellermann's avatar
Max Kellermann committed
361
{
362
	FreeEasyIndirect();
Max Kellermann's avatar
Max Kellermann committed
363 364
}

365 366
void
CurlInputStream::InitEasy()
Max Kellermann's avatar
Max Kellermann committed
367
{
368
	request = new CurlRequest(**curl_init, GetURI(), *this);
369 370 371 372 373

	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
374

375
	if (proxy != nullptr)
376
		request->SetOption(CURLOPT_PROXY, proxy);
377

378
	if (proxy_port > 0)
379
		request->SetOption(CURLOPT_PROXYPORT, (long)proxy_port);
380

381 382 383 384
	if (proxy_user != nullptr && proxy_password != nullptr)
		request->SetOption(CURLOPT_PROXYUSERPWD,
				   StringFormat<1024>("%s:%s", proxy_user,
						      proxy_password).c_str());
385

386 387
	request->SetOption(CURLOPT_SSL_VERIFYPEER, verify_peer ? 1l : 0l);
	request->SetOption(CURLOPT_SSL_VERIFYHOST, verify_host ? 2l : 0l);
388
	request->SetOption(CURLOPT_HTTPHEADER, request_headers.Get());
389 390 391 392 393
}

void
CurlInputStream::StartRequest()
{
394
	request->Start();
Max Kellermann's avatar
Max Kellermann committed
395 396
}

397
void
398
CurlInputStream::SeekInternal(offset_type new_offset)
Max Kellermann's avatar
Max Kellermann committed
399 400 401
{
	/* close the old connection and open a new one */

402
	FreeEasy();
Max Kellermann's avatar
Max Kellermann committed
403

404
	offset = new_offset;
405
	if (offset == size) {
406 407 408
		/* seek to EOF: simulate empty result; avoid
		   triggering a "416 Requested Range Not Satisfiable"
		   response */
409
		SeekDone();
410
		return;
411
	}
412

413
	InitEasy();
Max Kellermann's avatar
Max Kellermann committed
414 415 416

	/* send the "Range" header */

417 418 419 420
	if (offset > 0)
		request->SetOption(CURLOPT_RANGE,
				   StringFormat<40>("%" PRIoffset "-",
						    offset).c_str());
421 422

	StartRequest();
423
}
424

425 426 427 428
void
CurlInputStream::DoSeek(offset_type new_offset)
{
	assert(IsReady());
429
	assert(seekable);
430 431 432

	const ScopeUnlock unlock(mutex);

433
	BlockingCall(GetEventLoop(), [this, new_offset](){
434 435
			SeekInternal(new_offset);
		});
Max Kellermann's avatar
Max Kellermann committed
436 437
}

438
inline InputStreamPtr
439 440
CurlInputStream::Open(const char *url,
		      const std::multimap<std::string, std::string> &headers,
441
		      Mutex &mutex)
Max Kellermann's avatar
Max Kellermann committed
442
{
443 444
	auto icy = std::make_shared<IcyMetaDataParser>();

445
	auto c = std::make_unique<CurlInputStream>((*curl_init)->GetEventLoop(),
446
						   url, headers,
447
						   icy,
448
						   mutex);
449

450 451 452 453
	BlockingCall(c->GetEventLoop(), [&c](){
			c->InitEasy();
			c->StartRequest();
		});
Max Kellermann's avatar
Max Kellermann committed
454

455
	return std::make_unique<MaybeBufferedInputStream>(std::make_unique<IcyInputStream>(std::move(c), std::move(icy)));
456 457
}

458 459 460
InputStreamPtr
OpenCurlInputStream(const char *uri,
		    const std::multimap<std::string, std::string> &headers,
461
		    Mutex &mutex)
462
{
463
	return CurlInputStream::Open(uri, headers, mutex);
464 465
}

466
static InputStreamPtr
467
input_curl_open(const char *url, Mutex &mutex)
468
{
469 470
	if (!StringStartsWithCaseASCII(url, "http://") &&
	    !StringStartsWithCaseASCII(url, "https://"))
471
		return nullptr;
472

473
	return CurlInputStream::Open(url, {}, mutex);
Max Kellermann's avatar
Max Kellermann committed
474
}
475

476
const struct InputPlugin input_plugin_curl = {
477 478 479 480
	"curl",
	input_curl_init,
	input_curl_finish,
	input_curl_open,
481
};