Global.cxx 5.93 KB
Newer Older
1
/*
2
 * Copyright 2008-2020 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
 *
 * 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"
32
#include "event/Loop.hxx"
33
#include "event/SocketEvent.hxx"
34

35
#include <cassert>
36

37 38 39
/**
 * Monitor for one socket created by CURL.
 */
40
class CurlSocket final {
41 42
	CurlGlobal &global;

43 44
	SocketEvent socket_event;

45
public:
46
	CurlSocket(CurlGlobal &_global, EventLoop &_loop, SocketDescriptor _fd)
47 48
		:global(_global),
		 socket_event(_loop, BIND_THIS_METHOD(OnSocketReady), _fd) {}
49

50
	~CurlSocket() noexcept {
51 52 53 54 55 56 57 58 59
		/* 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? */
	}

60 61 62 63
	auto &GetEventLoop() const noexcept {
		return socket_event.GetEventLoop();
	}

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

private:
72 73 74 75
	SocketDescriptor GetSocket() const noexcept {
		return socket_event.GetSocket();
	}

76
	void OnSocketReady(unsigned events) noexcept;
77

78
	static constexpr int FlagsToCurlCSelect(unsigned flags) noexcept {
79 80 81
		return (flags & (SocketEvent::READ | SocketEvent::HANGUP) ? CURL_CSELECT_IN : 0) |
			(flags & SocketEvent::WRITE ? CURL_CSELECT_OUT : 0) |
			(flags & SocketEvent::ERROR ? CURL_CSELECT_ERR : 0);
82 83 84
	}

	gcc_const
85
	static unsigned CurlPollToFlags(int action) noexcept {
86 87 88 89 90
		switch (action) {
		case CURL_POLL_NONE:
			return 0;

		case CURL_POLL_IN:
91
			return SocketEvent::READ;
92 93

		case CURL_POLL_OUT:
94
			return SocketEvent::WRITE;
95 96

		case CURL_POLL_INOUT:
97
			return SocketEvent::READ|SocketEvent::WRITE;
98 99 100 101 102 103 104 105
		}

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

CurlGlobal::CurlGlobal(EventLoop &_loop)
106
	:defer_read_info(_loop, BIND_THIS_METHOD(ReadInfo)),
107
	 timeout_event(_loop, BIND_THIS_METHOD(OnTimeout))
108 109 110 111 112 113 114 115 116
{
	multi.SetOption(CURLMOPT_SOCKETFUNCTION, CurlSocket::SocketFunction);
	multi.SetOption(CURLMOPT_SOCKETDATA, this);

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

int
Rosen Penev's avatar
Rosen Penev committed
117
CurlSocket::SocketFunction([[maybe_unused]] CURL *easy,
118
			   curl_socket_t s, int action,
119 120
			   void *userp, void *socketp) noexcept
{
121
	auto &global = *(CurlGlobal *)userp;
122
	auto *cs = (CurlSocket *)socketp;
123

124
	assert(global.GetEventLoop().IsInside());
125 126 127 128 129 130 131

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

	if (cs == nullptr) {
132 133
		cs = new CurlSocket(global, global.GetEventLoop(),
				    SocketDescriptor(s));
134 135 136 137 138
		global.Assign(s, *cs);
	}

	unsigned flags = CurlPollToFlags(action);
	if (flags != 0)
139
		cs->socket_event.Schedule(flags);
140 141 142
	return 0;
}

143
void
144
CurlSocket::OnSocketReady(unsigned flags) noexcept
145
{
146
	assert(GetEventLoop().IsInside());
147

148
	global.SocketAction(GetSocket().Get(), FlagsToCurlCSelect(flags));
149 150 151
}

void
152
CurlGlobal::Add(CurlRequest &r)
153
{
154
	assert(GetEventLoop().IsInside());
155

156
	multi.Add(r.Get());
157 158 159 160 161

	InvalidateSockets();
}

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

166
	multi.Remove(r.Get());
167 168
}

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

	return (CurlRequest *)p;
}

inline void
185
CurlGlobal::ReadInfo() noexcept
186
{
187
	assert(GetEventLoop().IsInside());
188 189 190

	CURLMsg *msg;

191
	while ((msg = multi.InfoRead()) != nullptr) {
192 193 194 195 196 197 198 199
		if (msg->msg == CURLMSG_DONE) {
			auto *request = ToRequest(msg->easy_handle);
			if (request != nullptr)
				request->Done(msg->data.result);
		}
	}
}

200 201 202 203 204 205
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);
206
	(void)mcode;
207 208 209 210

	defer_read_info.Schedule();
}

211
inline void
212
CurlGlobal::UpdateTimeout(long timeout_ms) noexcept
213 214
{
	if (timeout_ms < 0) {
215
		timeout_event.Cancel();
216
		return;
217 218
	}

219 220
	if (timeout_ms < 1)
		/* CURL's threaded resolver sets a timeout of 0ms, which
221 222
		   means we're running in a busy loop.  Quite a bad
		   idea to waste so much CPU.  Let's use a lower limit
223 224
		   of 1ms. */
		timeout_ms = 1;
225

226
	timeout_event.Schedule(std::chrono::milliseconds(timeout_ms));
227 228 229
}

int
Rosen Penev's avatar
Rosen Penev committed
230
CurlGlobal::TimerFunction([[maybe_unused]] CURLM *_multi, long timeout_ms,
231
			  void *userp) noexcept
232 233
{
	auto &global = *(CurlGlobal *)userp;
234
	assert(_multi == global.multi.Get());
235 236

	global.UpdateTimeout(timeout_ms);
237 238 239 240
	return 0;
}

void
241
CurlGlobal::OnTimeout() noexcept
242 243 244
{
	SocketAction(CURL_SOCKET_TIMEOUT, 0);
}