Request.cxx 5.7 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 39 40 41 42 43 44 45 46
#include "util/StringView.hxx"
#include "util/CharUtil.hxx"

#include <curl/curl.h>

#include <algorithm>

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

47
CurlRequest::CurlRequest(CurlGlobal &_global,
48
			 CurlResponseHandler &_handler)
49 50 51
	:global(_global), handler(_handler),
	 postpone_error_event(global.GetEventLoop(),
			      BIND_THIS_METHOD(OnPostponeError))
52 53 54
{
	error_buffer[0] = 0;

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

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

74
void
75
CurlRequest::Start()
76 77 78 79 80 81 82
{
	assert(!registered);

	global.Add(easy.Get(), *this);
	registered = true;
}

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

91
void
92
CurlRequest::Stop() noexcept
93
{
94 95
	if (!registered)
		return;
96 97 98 99 100

	global.Remove(easy.Get());
	registered = false;
}

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

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

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

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

124
	easy.Unpause();
125 126 127 128

	global.InvalidateSockets();
}

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

	state = State::BODY;

	long status = 0;
	curl_easy_getinfo(easy.Get(), CURLINFO_RESPONSE_CODE, &status);

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

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

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

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

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

	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);
		}

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

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

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

192
	if (IsResponseBoundaryHeader(s)) {
193 194 195 196 197 198 199 200 201 202 203 204 205 206
		/* 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);
207 208
	std::transform(name.begin(), name.end(), name.begin(),
		       static_cast<char(*)(char)>(ToLowerASCII));
209 210 211 212 213 214 215 216 217 218 219 220 221 222

	/* 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
223
CurlRequest::_HeaderFunction(char *ptr, size_t size, size_t nmemb,
224
			     void *stream) noexcept
225 226 227 228 229
{
	CurlRequest &c = *(CurlRequest *)stream;

	size *= nmemb;

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

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

	try {
240
		FinishHeaders();
241 242 243 244 245 246
		handler.OnData({ptr, received_size});
		return received_size;
	} catch (Pause) {
		return CURL_WRITEFUNC_PAUSE;
	} catch (...) {
		state = State::CLOSED;
247 248 249
		/* move the CurlResponseHandler::OnError() call into a
		   "safe" stack frame */
		postponed_error = std::current_exception();
250
		postpone_error_event.Schedule();
251
		return CURL_WRITEFUNC_PAUSE;
252 253 254 255 256
	}

}

size_t
257
CurlRequest::WriteFunction(char *ptr, size_t size, size_t nmemb,
258
			   void *stream) noexcept
259 260 261 262 263 264 265 266 267
{
	CurlRequest &c = *(CurlRequest *)stream;

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

	return c.DataReceived(ptr, size);
}
268 269

void
270
CurlRequest::OnPostponeError() noexcept
271 272 273 274 275
{
	assert(postponed_error);

	handler.OnError(postponed_error);
}