Global.cxx 6.13 KB
Newer Older
1
/*
2
 * Copyright 2008-2019 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
 *
 * 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 "Global.hxx"
#include "Request.hxx"
#include "Log.hxx"
33
#include "event/Loop.hxx"
34 35 36 37
#include "event/SocketMonitor.hxx"
#include "util/RuntimeError.hxx"
#include "util/Domain.hxx"

38 39
#include <assert.h>

40 41 42 43 44 45 46 47 48
static constexpr Domain curlm_domain("curlm");

/**
 * Monitor for one socket created by CURL.
 */
class CurlSocket final : SocketMonitor {
	CurlGlobal &global;

public:
49
	CurlSocket(CurlGlobal &_global, EventLoop &_loop, SocketDescriptor _fd)
50 51
		:SocketMonitor(_fd, _loop), global(_global) {}

52
	~CurlSocket() noexcept {
53 54 55 56 57 58 59 60 61 62 63 64 65 66
		/* TODO: sometimes, CURL uses CURL_POLL_REMOVE after
		   closing the socket, and sometimes, it uses
		   CURL_POLL_REMOVE just to move the (still open)
		   connection to the pool; in the first case,
		   Abandon() would be most appropriate, but it breaks
		   the second case - is that a CURL bug?  is there a
		   better solution? */
	}

	/**
	 * Callback function for CURLMOPT_SOCKETFUNCTION.
	 */
	static int SocketFunction(CURL *easy,
				  curl_socket_t s, int action,
67
				  void *userp, void *socketp) noexcept;
68

69
	bool OnSocketReady(unsigned flags) noexcept override;
70 71

private:
72
	static constexpr int FlagsToCurlCSelect(unsigned flags) noexcept {
73 74 75 76 77 78
		return (flags & (READ | HANGUP) ? CURL_CSELECT_IN : 0) |
			(flags & WRITE ? CURL_CSELECT_OUT : 0) |
			(flags & ERROR ? CURL_CSELECT_ERR : 0);
	}

	gcc_const
79
	static unsigned CurlPollToFlags(int action) noexcept {
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
		switch (action) {
		case CURL_POLL_NONE:
			return 0;

		case CURL_POLL_IN:
			return READ;

		case CURL_POLL_OUT:
			return WRITE;

		case CURL_POLL_INOUT:
			return READ|WRITE;
		}

		assert(false);
		gcc_unreachable();
	}
};

CurlGlobal::CurlGlobal(EventLoop &_loop)
100
	:defer_read_info(_loop, BIND_THIS_METHOD(ReadInfo)),
101
	 timeout_event(_loop, BIND_THIS_METHOD(OnTimeout))
102 103 104 105 106 107 108 109 110 111 112
{
	multi.SetOption(CURLMOPT_SOCKETFUNCTION, CurlSocket::SocketFunction);
	multi.SetOption(CURLMOPT_SOCKETDATA, this);

	multi.SetOption(CURLMOPT_TIMERFUNCTION, TimerFunction);
	multi.SetOption(CURLMOPT_TIMERDATA, this);
}

int
CurlSocket::SocketFunction(gcc_unused CURL *easy,
			   curl_socket_t s, int action,
113 114
			   void *userp, void *socketp) noexcept
{
115
	auto &global = *(CurlGlobal *)userp;
116
	auto *cs = (CurlSocket *)socketp;
117

118
	assert(global.GetEventLoop().IsInside());
119 120 121 122 123 124 125

	if (action == CURL_POLL_REMOVE) {
		delete cs;
		return 0;
	}

	if (cs == nullptr) {
126 127
		cs = new CurlSocket(global, global.GetEventLoop(),
				    SocketDescriptor(s));
128 129 130 131 132 133 134 135 136 137
		global.Assign(s, *cs);
	}

	unsigned flags = CurlPollToFlags(action);
	if (flags != 0)
		cs->Schedule(flags);
	return 0;
}

bool
138
CurlSocket::OnSocketReady(unsigned flags) noexcept
139
{
140
	assert(GetEventLoop().IsInside());
141

142
	global.SocketAction(GetSocket().Get(), FlagsToCurlCSelect(flags));
143 144 145 146
	return true;
}

void
147
CurlGlobal::Add(CurlRequest &r)
148
{
149
	assert(GetEventLoop().IsInside());
150

151
	CURLMcode mcode = curl_multi_add_handle(multi.Get(), r.Get());
152 153 154 155 156 157 158 159
	if (mcode != CURLM_OK)
		throw FormatRuntimeError("curl_multi_add_handle() failed: %s",
					 curl_multi_strerror(mcode));

	InvalidateSockets();
}

void
160
CurlGlobal::Remove(CurlRequest &r) noexcept
161
{
162
	assert(GetEventLoop().IsInside());
163

164
	curl_multi_remove_handle(multi.Get(), r.Get());
165
	InvalidateSockets();
166 167
}

168 169 170 171
/**
 * Find a request by its CURL "easy" handle.
 */
gcc_pure
172
static CurlRequest *
173
ToRequest(CURL *easy) noexcept
174 175 176 177 178 179 180 181 182 183
{
	void *p;
	CURLcode code = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p);
	if (code != CURLE_OK)
		return nullptr;

	return (CurlRequest *)p;
}

inline void
184
CurlGlobal::ReadInfo() noexcept
185
{
186
	assert(GetEventLoop().IsInside());
187 188 189 190 191 192 193 194 195 196 197 198 199 200

	CURLMsg *msg;
	int msgs_in_queue;

	while ((msg = curl_multi_info_read(multi.Get(),
					   &msgs_in_queue)) != nullptr) {
		if (msg->msg == CURLMSG_DONE) {
			auto *request = ToRequest(msg->easy_handle);
			if (request != nullptr)
				request->Done(msg->data.result);
		}
	}
}

201 202 203 204 205 206 207 208 209 210 211 212 213 214
void
CurlGlobal::SocketAction(curl_socket_t fd, int ev_bitmask) noexcept
{
	int running_handles;
	CURLMcode mcode = curl_multi_socket_action(multi.Get(), fd, ev_bitmask,
						   &running_handles);
	if (mcode != CURLM_OK)
		FormatError(curlm_domain,
			    "curl_multi_socket_action() failed: %s",
			    curl_multi_strerror(mcode));

	defer_read_info.Schedule();
}

215
inline void
216
CurlGlobal::UpdateTimeout(long timeout_ms) noexcept
217 218
{
	if (timeout_ms < 0) {
219
		timeout_event.Cancel();
220
		return;
221 222
	}

223
	if (timeout_ms < 10)
224 225 226 227 228 229
		/* CURL 7.21.1 likes to report "timeout=0", which
		   means we're running in a busy loop.  Quite a bad
		   idea to waste so much CPU.  Let's use a lower limit
		   of 10ms. */
		timeout_ms = 10;

230
	timeout_event.Schedule(std::chrono::milliseconds(timeout_ms));
231 232 233
}

int
234
CurlGlobal::TimerFunction(gcc_unused CURLM *_multi, long timeout_ms,
235
			  void *userp) noexcept
236 237
{
	auto &global = *(CurlGlobal *)userp;
238
	assert(_multi == global.multi.Get());
239 240

	global.UpdateTimeout(timeout_ms);
241 242 243 244
	return 0;
}

void
245
CurlGlobal::OnTimeout() noexcept
246 247 248
{
	SocketAction(CURL_SOCKET_TIMEOUT, 0);
}