Debian Codegraph @

coeurl/lib/client.cpp

raw symbols SCIP
1 #include "coeurl/client.hpp"
2
3 #include <event2/thread.h>
4 #include <spdlog/sinks/null_sink.h>
5
6 #include <thread>
7
8 #include "coeurl/request.hpp"
9 #include "coeurl/errors.hpp"
10
11 namespace coeurl {
12 std::shared_ptr<spdlog::logger> Client::log = spdlog::null_logger_mt("coeurl_null");
13
14 /* Die if we get a bad CURLMcode somewhere */
15 void Client::mcode_or_die(const char *where, CURLMcode code) {
16 if (CURLM_OK != code) {
17 const char *s = curl_multi_strerror(code);
18 switch (code) {
19 case CURLM_BAD_SOCKET:
20 Client::log->error("{} returns {}", where, s);
21 /* ignore this error */
22 return;
23 case CURLM_BAD_HANDLE:
24 case CURLM_BAD_EASY_HANDLE:
25 case CURLM_OUT_OF_MEMORY:
26 case CURLM_INTERNAL_ERROR:
27 case CURLM_UNKNOWN_OPTION:
28 case CURLM_LAST:
29 break;
30 default:
31 s = "CURLM_unknown";
32 break;
33 }
34 Client::log->critical("{} returns {}", where, s);
35 throw std::runtime_error(s);
36 }
37 }
38
39 /* Information associated with a specific socket */
40 struct SockInfo {
41 curl_socket_t sockfd;
42 struct event ev;
43 };
44
45 /* Update the event timer after curl_multi library calls */
46 int Client::multi_timer_cb(CURLM *multi, long timeout_ms, Client *g) {
47 struct timeval timeout;
48 (void)multi;
49
50 timeout.tv_sec = timeout_ms / 1000;
51 timeout.tv_usec = (timeout_ms % 1000) * 1000;
52 Client::log->trace("multi_timer_cb: Setting timeout to {} ms", timeout_ms);
53
54 /*
55 * if timeout_ms is -1, just delete the timer
56 *
57 * For all other values of timeout_ms, this should set or *update* the timer
58 * to the new value
59 */
60 if (timeout_ms == -1)
61 event_del(&g->timer_event);
62 else /* includes timeout zero */ {
63 event_add(&g->timer_event, &timeout);
64 }
65 return 0;
66 }
67
68 /* Called by libevent when we get action on a multi socket */
69 void Client::event_cb(evutil_socket_t fd, short kind, void *userp) {
70 Client *g = (Client *)userp;
71
72 int action = ((kind & EV_READ) ? CURL_CSELECT_IN : 0) | ((kind & EV_WRITE) ? CURL_CSELECT_OUT : 0);
73
74 CURLMcode rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running);
75 mcode_or_die("event_cb: curl_multi_socket_action", rc);
76
77 g->check_multi_info();
78 if (g->still_running <= 0 && g->running_requests.empty()) {
79 Client::log->trace("last transfer done, kill timeout");
80 if (evtimer_pending(&g->timer_event, NULL)) {
81 evtimer_del(&g->timer_event);
82 }
83 }
84 }
85
86 /* Called by libevent when our timeout expires */
87 void Client::timer_cb(evutil_socket_t, short, void *userp) {
88 Client::log->trace("timer_cb");
89
90 Client *g = (Client *)userp;
91
92 CURLMcode rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0, &g->still_running);
93 mcode_or_die("timer_cb: curl_multi_socket_action", rc);
94 g->check_multi_info();
95 }
96
97 // Invoked when we were told to shut down.
98 void Client::stop_ev_loop_cb(evutil_socket_t, short, void *userp) {
99 Client::log->trace("stop_ev_loop_cb");
100
101 Client *g = (Client *)userp;
102
103 CURLMcode rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0, &g->still_running);
104 mcode_or_die("stop_ev_loop_cb: curl_multi_socket_action", rc);
105 g->check_multi_info();
106 }
107
108 /* Called by libevent when our timeout expires */
109 void Client::add_pending_requests_cb(evutil_socket_t, short, void *userp) {
110 Client::log->trace("add_pending_requests_cb");
111
112 Client *g = (Client *)userp;
113
114 {
115 const std::scoped_lock lock(g->pending_requests_mutex, g->running_requests_mutex);
116
117 for (size_t i = 0; i < g->pending_requests.size(); i++) {
118 const auto &conn = g->pending_requests[i];
119
120 Client::log->trace("Adding easy {} to multi {} ({})", conn->easy, g->multi, conn->url_.c_str());
121 auto rc = curl_multi_add_handle(g->multi, conn->easy);
122 mcode_or_die("new_conn: curl_multi_add_handle", rc);
123
124 g->running_requests.push_back(std::move(g->pending_requests[i]));
125 }
126
127 g->pending_requests.clear();
128 }
129 }
130
131 /* Called by libevent when our timeout expires */
132 void Client::cancel_requests_cb(evutil_socket_t, short, void *userp) {
133 Client::log->trace("cancel_requests_cb");
134
135 Client *g = (Client *)userp;
136
137 // prevent new requests from being added
138 { g->prevent_new_requests = true; }
139
140 // safe to access now, since we are running on the worker thread and only
141 // there running_requests is modified
142 while (!g->running_requests.empty())
143 g->remove_request(g->running_requests.back().get());
144
145 // Allow for new requests
146 { g->prevent_new_requests = false; }
147
148 CURLMcode rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0, &g->still_running);
149 mcode_or_die("timer_cb: curl_multi_socket_action", rc);
150 g->check_multi_info();
151 }
152
153 /* Clean up the SockInfo structure */
154 void Client::remsock(SockInfo *f) {
155 if (f) {
156 if (event_initialized(&f->ev)) {
157 event_del(&f->ev);
158 }
159 delete f;
160 }
161 }
162
163 /* Assign information to a SockInfo structure */
164 void Client::setsock(SockInfo *f, curl_socket_t s, int act) {
165 short kind = ((act & CURL_POLL_IN) ? EV_READ : 0) | ((act & CURL_POLL_OUT) ? EV_WRITE : 0) | EV_PERSIST;
166
167 f->sockfd = s;
168 if (event_initialized(&f->ev)) {
169 event_del(&f->ev);
170 }
171 event_assign(&f->ev, this->evbase, f->sockfd, kind, event_cb, this);
172 event_add(&f->ev, NULL);
173 }
174
175 /* Initialize a new SockInfo structure */
176 void Client::addsock(curl_socket_t s, int action) {
177 SockInfo *fdp = new SockInfo();
178
179 setsock(fdp, s, action);
180 curl_multi_assign(this->multi, s, fdp);
181 }
182
183 /* CURLMOPT_SOCKETFUNCTION */
184 int Client::sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp) {
185 Client *g = (Client *)cbp;
186 SockInfo *fdp = (SockInfo *)sockp;
187 const char *whatstr[] = {"none", "IN", "OUT", "INOUT", "REMOVE"};
188
189 Client::log->trace("socket callback: s={} e={} what={} ", s, e, whatstr[what]);
190 if (what == CURL_POLL_REMOVE) {
191 g->remsock(fdp);
192 } else {
193 if (!fdp) {
194 Client::log->trace("Adding data: {}", whatstr[what]);
195 g->addsock(s, what);
196 } else {
197 Client::log->trace("Changing action to: {}", whatstr[what]);
198 g->setsock(fdp, s, what);
199 }
200 }
201 return 0;
202 }
203
204 Client::Client() {
205 std::once_flag threads_once;
206 #ifdef WIN32
207 std::call_once(threads_once, evthread_use_windows_threads);
208 #elif defined(EVENT__HAVE_PTHREADS)
209 std::call_once(threads_once, evthread_use_pthreads);
210 #else
211 #error "No supported threading backend!"
212 #endif
213
214 /* Make sure the SSL or WinSock backends are initialized */
215 std::once_flag curl_once;
216 std::call_once(curl_once, curl_global_init, CURL_GLOBAL_DEFAULT);
217
218 this->evbase = event_base_new();
219 this->multi = curl_multi_init();
220 event_assign(&this->timer_event, this->evbase, -1, 0, timer_cb, this);
221 event_assign(&this->add_request_timer, this->evbase, -1, 0, add_pending_requests_cb, this);
222 event_assign(&this->stop_event, this->evbase, -1, 0, stop_ev_loop_cb, this);
223 event_assign(&this->cancel_requests_timer, this->evbase, -1, 0, cancel_requests_cb, this);
224
225 /* setup the generic multi interface options we want */
226 curl_multi_setopt(this->multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
227 curl_multi_setopt(this->multi, CURLMOPT_SOCKETDATA, this);
228 curl_multi_setopt(this->multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
229 curl_multi_setopt(this->multi, CURLMOPT_TIMERDATA, this);
230
231 maximum_total_connections(64);
232 maximum_connections_per_host(8);
233
234 bg_thread = std::thread([this]() { this->run(); });
235 }
236
237 void Client::maximum_total_connections(long count) {
238 curl_multi_setopt(this->multi, CURLMOPT_MAX_TOTAL_CONNECTIONS, count);
239 }
240
241 void Client::maximum_connections_per_host(long count) {
242 curl_multi_setopt(this->multi, CURLMOPT_MAX_HOST_CONNECTIONS, count);
243 }
244
245 Client::~Client() {
246 close();
247
248 event_del(&this->timer_event);
249 event_del(&this->add_request_timer);
250 event_del(&this->stop_event);
251 event_del(&this->cancel_requests_timer);
252
253 curl_multi_cleanup(this->multi);
254
255 event_base_free(this->evbase);
256 }
257
258 void Client::close(bool force) {
259 std::unique_lock l{stopped_mutex};
260 if (stopped)
261 return;
262
263 Client::log->trace("STOP");
264
265 if (force)
266 shutdown();
267
268 stopped = true;
269 event_active(&this->stop_event, 0, 0);
270
271 Client::log->trace("WAITING");
272 if (bg_thread.get_id() != std::this_thread::get_id())
273 bg_thread.join();
274 else
275 bg_thread.detach();
276 Client::log->trace("CLOSED");
277 }
278
279 void Client::shutdown() { event_active(&this->cancel_requests_timer, 0, 0); }
280
281 void Client::run() { event_base_loop(this->evbase, EVLOOP_NO_EXIT_ON_EMPTY); }
282
283 /* Check for completed transfers, and remove their easy handles */
284 void Client::check_multi_info() {
285 CURLMsg *msg;
286 int msgs_left;
287
288 Client::log->trace("REMAINING: {}", this->still_running);
289 while ((msg = curl_multi_info_read(this->multi, &msgs_left))) {
290 if (msg->msg == CURLMSG_DONE) {
291 CURL *easy = msg->easy_handle;
292
293 Request *conn;
294 curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
295 conn->status = Request::Status::Done;
296 conn->curl_error = msg->data.result;
297
298 remove_request(conn);
299 }
300 }
301
302 if (this->still_running == 0)
303 add_pending_requests_cb(0, 0, this);
304
305 if (this->still_running == 0 && this->running_requests.empty() && this->stopped) {
306 event_base_loopbreak(this->evbase);
307 Client::log->trace("BREAK");
308 }
309 Client::log->trace("after check_multi_info: {}", this->still_running);
310 }
311
312 void Client::submit_request(std::shared_ptr<Request> conn) {
313 Client::log->trace("SUBMIT");
314
315 if (this->prevent_new_requests) {
316 conn->curl_error = CURLE_ABORTED_BY_CALLBACK;
317 conn->status = Request::Status::Canceled;
318 if (conn->on_complete_)
319 conn->on_complete_(*conn.get());
320 return;
321 }
322
323 {
324 const std::scoped_lock lock(pending_requests_mutex);
325
326 pending_requests.push_back(conn);
327 }
328
329 event_active(&add_request_timer, 0, 0);
330 }
331 void Client::remove_request(Request *r) {
332 Client::log->trace("REMOVE");
333
334 std::shared_ptr<Request> req;
335
336 {
337 std::scoped_lock lock(this->running_requests_mutex);
338 curl_multi_remove_handle(this->multi, r->easy);
339
340 for (auto it = this->running_requests.begin(); this->running_requests.end() != it; ++it) {
341 if (it->get() == r) {
342 req = std::move(*it);
343 this->running_requests.erase(it);
344 break;
345 }
346 }
347 }
348
349 if (req) {
350 long http_code;
351 curl_easy_getinfo(req->easy, CURLINFO_RESPONSE_CODE, &http_code);
352
353 Client::log->trace("DONE: {} => {} ({}) http: {}", req->url_, coeurl::to_string(req->curl_error), req->error, http_code);
354
355 if (req->on_complete_)
356 req->on_complete_(*req.get());
357 }
358 }
359
360 void Client::get(std::string url, std::function<void(const Request &)> callback, const Headers &headers,
361 long max_redirects) {
362 auto req = std::make_shared<Request>(this, Request::Method::Get, std::move(url));
363
364 req->on_complete(std::move(callback));
365
366 if (!headers.empty())
367 req->request_headers(headers);
368
369 if (max_redirects > 0)
370 req->max_redirects(max_redirects);
371
372 req->connection_timeout(connection_timeout_);
373
374 this->submit_request(std::move(req));
375 }
376
377 void Client::delete_(std::string url, std::function<void(const Request &)> callback, const Headers &headers,
378 long max_redirects) {
379 auto req = std::make_shared<Request>(this, Request::Method::Delete, std::move(url));
380
381 req->on_complete(std::move(callback));
382
383 if (!headers.empty())
384 req->request_headers(headers);
385
386 if (max_redirects > 0)
387 req->max_redirects(max_redirects);
388
389 req->connection_timeout(connection_timeout_);
390
391 this->submit_request(std::move(req));
392 }
393
394 void Client::delete_(std::string url, std::string request_body, std::string mimetype,
395 std::function<void(const Request &)> callback, const Headers &headers, long max_redirects) {
396 auto req = std::make_shared<Request>(this, Request::Method::Delete, std::move(url));
397
398 req->request(request_body, mimetype);
399 req->on_complete(std::move(callback));
400
401 if (!headers.empty())
402 req->request_headers(headers);
403
404 if (max_redirects > 0)
405 req->max_redirects(max_redirects);
406
407 req->connection_timeout(connection_timeout_);
408
409 this->submit_request(std::move(req));
410 }
411
412 void Client::head(std::string url, std::function<void(const Request &)> callback, const Headers &headers,
413 long max_redirects) {
414 auto req = std::make_shared<Request>(this, Request::Method::Head, std::move(url));
415
416 req->on_complete(std::move(callback));
417
418 if (!headers.empty())
419 req->request_headers(headers);
420
421 if (max_redirects > 0)
422 req->max_redirects(max_redirects);
423
424 req->connection_timeout(connection_timeout_);
425
426 this->submit_request(std::move(req));
427 }
428
429 void Client::options(std::string url, std::function<void(const Request &)> callback, const Headers &headers,
430 long max_redirects) {
431 auto req = std::make_shared<Request>(this, Request::Method::Options, std::move(url));
432
433 req->on_complete(std::move(callback));
434
435 if (!headers.empty())
436 req->request_headers(headers);
437
438 if (max_redirects > 0)
439 req->max_redirects(max_redirects);
440
441 req->connection_timeout(connection_timeout_);
442
443 this->submit_request(std::move(req));
444 }
445
446 void Client::put(std::string url, std::string request_body, std::string mimetype,
447 std::function<void(const Request &)> callback, const Headers &headers, long max_redirects) {
448 auto req = std::make_shared<Request>(this, Request::Method::Put, std::move(url));
449
450 req->request(request_body, mimetype);
451 req->on_complete(std::move(callback));
452
453 if (!headers.empty())
454 req->request_headers(headers);
455
456 if (max_redirects > 0)
457 req->max_redirects(max_redirects);
458
459 req->connection_timeout(connection_timeout_);
460
461 this->submit_request(std::move(req));
462 }
463
464 void Client::post(std::string url, std::string request_body, std::string mimetype,
465 std::function<void(const Request &)> callback, const Headers &headers, long max_redirects) {
466 auto req = std::make_shared<Request>(this, Request::Method::Post, std::move(url));
467
468 req->request(request_body, mimetype);
469 req->on_complete(std::move(callback));
470
471 if (!headers.empty())
472 req->request_headers(headers);
473
474 if (max_redirects > 0)
475 req->max_redirects(max_redirects);
476
477 req->connection_timeout(connection_timeout_);
478
479 this->submit_request(std::move(req));
480 }
481 } // namespace coeurl