client.cpp 14 KB

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