Global.cxx 6.09 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
#include "util/Compiler.h"
35

36
#include <cassert>
37

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

44 45
	SocketEvent socket_event;

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

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

61 62 63
	CurlSocket(const CurlSocket &) = delete;
	CurlSocket &operator=(const CurlSocket &) = delete;

Rosen Penev's avatar
Rosen Penev committed
64
	[[nodiscard]] auto &GetEventLoop() const noexcept {
65 66 67
		return socket_event.GetEventLoop();
	}

68 69 70 71 72
	/**
	 * Callback function for CURLMOPT_SOCKETFUNCTION.
	 */
	static int SocketFunction(CURL *easy,
				  curl_socket_t s, int action,
73
				  void *userp, void *socketp) noexcept;
74 75

private:
Rosen Penev's avatar
Rosen Penev committed
76
	[[nodiscard]] SocketDescriptor GetSocket() const noexcept {
77 78 79
		return socket_event.GetSocket();
	}

80
	void OnSocketReady(unsigned events) noexcept;
81

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

88
	[[gnu::const]]
89
	static unsigned CurlPollToFlags(int action) noexcept {
90 91 92 93 94
		switch (action) {
		case CURL_POLL_NONE:
			return 0;

		case CURL_POLL_IN:
95
			return SocketEvent::READ;
96 97

		case CURL_POLL_OUT:
98
			return SocketEvent::WRITE;
99 100

		case CURL_POLL_INOUT:
101
			return SocketEvent::READ|SocketEvent::WRITE;
102 103 104 105 106 107 108 109
		}

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

CurlGlobal::CurlGlobal(EventLoop &_loop)
110
	:defer_read_info(_loop, BIND_THIS_METHOD(ReadInfo)),
111
	 timeout_event(_loop, BIND_THIS_METHOD(OnTimeout))
112 113 114 115 116 117 118 119 120
{
	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
121
CurlSocket::SocketFunction([[maybe_unused]] CURL *easy,
122
			   curl_socket_t s, int action,
123 124
			   void *userp, void *socketp) noexcept
{
125
	auto &global = *(CurlGlobal *)userp;
126
	auto *cs = (CurlSocket *)socketp;
127

128
	assert(global.GetEventLoop().IsInside());
129 130 131 132 133 134 135

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

	if (cs == nullptr) {
136 137
		cs = new CurlSocket(global, global.GetEventLoop(),
				    SocketDescriptor(s));
138 139 140 141 142
		global.Assign(s, *cs);
	}

	unsigned flags = CurlPollToFlags(action);
	if (flags != 0)
143
		cs->socket_event.Schedule(flags);
144 145 146
	return 0;
}

147
void
148
CurlSocket::OnSocketReady(unsigned flags) noexcept
149
{
150
	assert(GetEventLoop().IsInside());
151

152
	global.SocketAction(GetSocket().Get(), FlagsToCurlCSelect(flags));
153 154 155
}

void
156
CurlGlobal::Add(CurlRequest &r)
157
{
158
	assert(GetEventLoop().IsInside());
159

160
	multi.Add(r.Get());
161 162 163 164 165

	InvalidateSockets();
}

void
166
CurlGlobal::Remove(CurlRequest &r) noexcept
167
{
168
	assert(GetEventLoop().IsInside());
169

170
	multi.Remove(r.Get());
171 172
}

173 174 175
/**
 * Find a request by its CURL "easy" handle.
 */
176
[[gnu::pure]]
177
static CurlRequest *
178
ToRequest(CURL *easy) noexcept
179 180 181 182 183 184 185 186 187 188
{
	void *p;
	CURLcode code = curl_easy_getinfo(easy, CURLINFO_PRIVATE, &p);
	if (code != CURLE_OK)
		return nullptr;

	return (CurlRequest *)p;
}

inline void
189
CurlGlobal::ReadInfo() noexcept
190
{
191
	assert(GetEventLoop().IsInside());
192 193 194

	CURLMsg *msg;

195
	while ((msg = multi.InfoRead()) != nullptr) {
196 197 198 199 200 201 202 203
		if (msg->msg == CURLMSG_DONE) {
			auto *request = ToRequest(msg->easy_handle);
			if (request != nullptr)
				request->Done(msg->data.result);
		}
	}
}

204 205 206 207 208 209
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);
210
	(void)mcode;
211 212 213 214

	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 224
	if (timeout_ms < 1)
		/* CURL's threaded resolver sets a timeout of 0ms, which
225 226
		   means we're running in a busy loop.  Quite a bad
		   idea to waste so much CPU.  Let's use a lower limit
227 228
		   of 1ms. */
		timeout_ms = 1;
229

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

int
Rosen Penev's avatar
Rosen Penev committed
234
CurlGlobal::TimerFunction([[maybe_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);
}