Request.cxx 5.28 KB
Newer Older
1
/*
2
 * Copyright 2008-2018 Max Kellermann <max.kellermann@gmail.com>
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "Request.hxx"
#include "Global.hxx"
#include "Handler.hxx"
34
#include "event/Call.hxx"
35
#include "util/RuntimeError.hxx"
36
#include "util/StringStrip.hxx"
37 38
#include "util/StringView.hxx"
#include "util/CharUtil.hxx"
39
#include "Version.h"
40 41 42 43

#include <curl/curl.h>

#include <algorithm>
44
#include <cassert>
45 46 47

#include <string.h>

48
CurlRequest::CurlRequest(CurlGlobal &_global,
49
			 CurlResponseHandler &_handler)
50
	:global(_global), handler(_handler)
51 52 53
{
	error_buffer[0] = 0;

54 55 56 57
	easy.SetPrivate((void *)this);
	easy.SetUserAgent("Music Player Daemon " VERSION);
	easy.SetHeaderFunction(_HeaderFunction, this);
	easy.SetWriteFunction(WriteFunction, this);
58
#if !defined(ANDROID) && !defined(_WIN32)
59
	easy.SetOption(CURLOPT_NETRC, 1L);
60
#endif
61 62 63 64
	easy.SetErrorBuffer(error_buffer);
	easy.SetNoProgress();
	easy.SetNoSignal();
	easy.SetConnectTimeout(10);
65
	easy.SetOption(CURLOPT_HTTPAUTH, (long) CURLAUTH_ANY);
66 67
}

68
CurlRequest::~CurlRequest() noexcept
69 70 71 72
{
	FreeEasy();
}

73
void
74
CurlRequest::Start()
75 76 77
{
	assert(!registered);

78
	global.Add(*this);
79 80 81
	registered = true;
}

82 83 84 85 86 87 88 89
void
CurlRequest::StartIndirect()
{
	BlockingCall(global.GetEventLoop(), [this](){
			Start();
		});
}

90
void
91
CurlRequest::Stop() noexcept
92
{
93 94
	if (!registered)
		return;
95

96
	global.Remove(*this);
97 98 99
	registered = false;
}

100 101 102 103 104 105 106 107
void
CurlRequest::StopIndirect()
{
	BlockingCall(global.GetEventLoop(), [this](){
			Stop();
		});
}

108
void
109
CurlRequest::FreeEasy() noexcept
110 111 112 113
{
	if (!easy)
		return;

114
	Stop();
115 116 117 118
	easy = nullptr;
}

void
119
CurlRequest::Resume() noexcept
120
{
121 122
	assert(registered);

123
	easy.Unpause();
124 125 126 127

	global.InvalidateSockets();
}

128
void
129 130 131
CurlRequest::FinishHeaders()
{
	if (state != State::HEADERS)
132
		return;
133 134 135 136

	state = State::BODY;

	long status = 0;
137
	easy.GetInfo(CURLINFO_RESPONSE_CODE, &status);
138

139
	handler.OnHeaders(status, std::move(headers));
140 141 142 143 144
}

void
CurlRequest::FinishBody()
{
145
	FinishHeaders();
146 147 148 149 150 151 152 153 154

	if (state != State::BODY)
		return;

	state = State::CLOSED;
	handler.OnEnd();
}

void
155
CurlRequest::Done(CURLcode result) noexcept
156
{
157
	Stop();
158 159 160 161 162 163 164 165 166 167

	try {
		if (result != CURLE_OK) {
			StripRight(error_buffer);
			const char *msg = error_buffer;
			if (*msg == 0)
				msg = curl_easy_strerror(result);
			throw FormatRuntimeError("CURL failed: %s", msg);
		}

168 169 170 171 172
		FinishBody();
	} catch (...) {
		state = State::CLOSED;
		handler.OnError(std::current_exception());
	}
173 174
}

175
[[gnu::pure]]
176
static bool
177
IsResponseBoundaryHeader(StringView s) noexcept
178
{
179
	return s.size > 5 && (s.StartsWith("HTTP/") ||
180 181
			      /* the proprietary "ICY 200 OK" is
				 emitted by Shoutcast */
182
			      s.StartsWith("ICY 2"));
183 184
}

185
inline void
186
CurlRequest::HeaderFunction(StringView s) noexcept
187 188 189 190
{
	if (state > State::HEADERS)
		return;

191
	if (IsResponseBoundaryHeader(s)) {
192 193 194 195 196 197 198 199 200 201 202 203 204 205
		/* this is the boundary to a new response, for example
		   after a redirect */
		headers.clear();
		return;
	}

	const char *header = s.data;
	const char *end = StripRight(header, header + s.size);

	const char *value = s.Find(':');
	if (value == nullptr)
		return;

	std::string name(header, value);
206 207
	std::transform(name.begin(), name.end(), name.begin(),
		       static_cast<char(*)(char)>(ToLowerASCII));
208 209 210 211 212 213 214 215 216 217 218 219 220 221

	/* skip the colon */

	++value;

	/* strip the value */

	value = StripLeft(value, end);
	end = StripRight(value, end);

	headers.emplace(std::move(name), std::string(value, end));
}

size_t
222
CurlRequest::_HeaderFunction(char *ptr, size_t size, size_t nmemb,
223
			     void *stream) noexcept
224 225 226 227 228
{
	CurlRequest &c = *(CurlRequest *)stream;

	size *= nmemb;

229
	c.HeaderFunction({ptr, size});
230 231 232 233
	return size;
}

inline size_t
234
CurlRequest::DataReceived(const void *ptr, size_t received_size) noexcept
235 236 237 238
{
	assert(received_size > 0);

	try {
239
		FinishHeaders();
240 241
		handler.OnData({ptr, received_size});
		return received_size;
242
	} catch (CurlResponseHandler::Pause) {
243 244 245 246 247 248
		return CURL_WRITEFUNC_PAUSE;
	}

}

size_t
249
CurlRequest::WriteFunction(char *ptr, size_t size, size_t nmemb,
250
			   void *stream) noexcept
251 252 253 254 255 256 257 258 259
{
	CurlRequest &c = *(CurlRequest *)stream;

	size *= nmemb;
	if (size == 0)
		return 0;

	return c.DataReceived(ptr, size);
}