client.cpp 15 KB

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