asiohiper.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2012 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. /* <DESC>
  23. * demonstrate the use of multi socket interface with boost::asio
  24. * </DESC>
  25. */
  26. /*
  27. * This program is in c++ and uses boost::asio instead of libevent/libev.
  28. * Requires boost::asio, boost::bind and boost::system
  29. *
  30. * This is an adaptation of libcurl's "hiperfifo.c" and "evhiperfifo.c"
  31. * sample programs. This example implements a subset of the functionality from
  32. * hiperfifo.c, for full functionality refer hiperfifo.c or evhiperfifo.c
  33. *
  34. * Written by Lijo Antony based on hiperfifo.c by Jeff Pohlmeyer
  35. *
  36. * When running, the program creates an easy handle for a URL and
  37. * uses the curl_multi API to fetch it.
  38. *
  39. * Note:
  40. * For the sake of simplicity, URL is hard coded to "www.google.com"
  41. *
  42. * This is purely a demo app, all retrieved data is simply discarded by the
  43. * write callback.
  44. *
  45. * ===========================================================================
  46. * WARNING: This example program is known to have flaws:
  47. * https://github.com/curl/curl/issues/2407
  48. *
  49. * It still kept in the example repository with the hope that it might be
  50. * useful, and maybe some day someone who knows enough about boost::asio will
  51. * read this text, accept the challenge and make the example code work
  52. * correctly. Until then: expect this example program to fail occasionally.
  53. * ===========================================================================
  54. */
  55. #include <curl/curl.h>
  56. #include <boost/asio.hpp>
  57. #include <boost/bind.hpp>
  58. #include <iostream>
  59. #define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */
  60. /* boost::asio related objects
  61. * using global variables for simplicity
  62. */
  63. boost::asio::io_service io_service;
  64. boost::asio::deadline_timer timer(io_service);
  65. std::map<curl_socket_t, boost::asio::ip::tcp::socket *> socket_map;
  66. /* Global information, common to all connections */
  67. typedef struct _GlobalInfo
  68. {
  69. CURLM *multi;
  70. int still_running;
  71. } GlobalInfo;
  72. /* Information associated with a specific easy handle */
  73. typedef struct _ConnInfo
  74. {
  75. CURL *easy;
  76. char *url;
  77. GlobalInfo *global;
  78. char error[CURL_ERROR_SIZE];
  79. } ConnInfo;
  80. static void timer_cb(const boost::system::error_code & error, GlobalInfo *g);
  81. /* Update the event timer after curl_multi library calls */
  82. static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
  83. {
  84. fprintf(MSG_OUT, "\nmulti_timer_cb: timeout_ms %ld", timeout_ms);
  85. /* cancel running timer */
  86. timer.cancel();
  87. if(timeout_ms > 0) {
  88. /* update timer */
  89. timer.expires_from_now(boost::posix_time::millisec(timeout_ms));
  90. timer.async_wait(boost::bind(&timer_cb, _1, g));
  91. }
  92. else if(timeout_ms == 0) {
  93. /* call timeout function immediately */
  94. boost::system::error_code error; /*success*/
  95. timer_cb(error, g);
  96. }
  97. return 0;
  98. }
  99. /* Die if we get a bad CURLMcode somewhere */
  100. static void mcode_or_die(const char *where, CURLMcode code)
  101. {
  102. if(CURLM_OK != code) {
  103. const char *s;
  104. switch(code) {
  105. case CURLM_CALL_MULTI_PERFORM:
  106. s = "CURLM_CALL_MULTI_PERFORM";
  107. break;
  108. case CURLM_BAD_HANDLE:
  109. s = "CURLM_BAD_HANDLE";
  110. break;
  111. case CURLM_BAD_EASY_HANDLE:
  112. s = "CURLM_BAD_EASY_HANDLE";
  113. break;
  114. case CURLM_OUT_OF_MEMORY:
  115. s = "CURLM_OUT_OF_MEMORY";
  116. break;
  117. case CURLM_INTERNAL_ERROR:
  118. s = "CURLM_INTERNAL_ERROR";
  119. break;
  120. case CURLM_UNKNOWN_OPTION:
  121. s = "CURLM_UNKNOWN_OPTION";
  122. break;
  123. case CURLM_LAST:
  124. s = "CURLM_LAST";
  125. break;
  126. default:
  127. s = "CURLM_unknown";
  128. break;
  129. case CURLM_BAD_SOCKET:
  130. s = "CURLM_BAD_SOCKET";
  131. fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
  132. /* ignore this error */
  133. return;
  134. }
  135. fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
  136. exit(code);
  137. }
  138. }
  139. /* Check for completed transfers, and remove their easy handles */
  140. static void check_multi_info(GlobalInfo *g)
  141. {
  142. char *eff_url;
  143. CURLMsg *msg;
  144. int msgs_left;
  145. ConnInfo *conn;
  146. CURL *easy;
  147. CURLcode res;
  148. fprintf(MSG_OUT, "\nREMAINING: %d", g->still_running);
  149. while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
  150. if(msg->msg == CURLMSG_DONE) {
  151. easy = msg->easy_handle;
  152. res = msg->data.result;
  153. curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
  154. curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
  155. fprintf(MSG_OUT, "\nDONE: %s => (%d) %s", eff_url, res, conn->error);
  156. curl_multi_remove_handle(g->multi, easy);
  157. free(conn->url);
  158. curl_easy_cleanup(easy);
  159. free(conn);
  160. }
  161. }
  162. }
  163. /* Called by asio when there is an action on a socket */
  164. static void event_cb(GlobalInfo *g, curl_socket_t s,
  165. int action, const boost::system::error_code & error,
  166. int *fdp)
  167. {
  168. fprintf(MSG_OUT, "\nevent_cb: action=%d", action);
  169. if(socket_map.find(s) == socket_map.end()) {
  170. fprintf(MSG_OUT, "\nevent_cb: socket already closed");
  171. return;
  172. }
  173. /* make sure the event matches what are wanted */
  174. if(*fdp == action || *fdp == CURL_POLL_INOUT) {
  175. CURLMcode rc;
  176. if(error)
  177. action = CURL_CSELECT_ERR;
  178. rc = curl_multi_socket_action(g->multi, s, action, &g->still_running);
  179. mcode_or_die("event_cb: curl_multi_socket_action", rc);
  180. check_multi_info(g);
  181. if(g->still_running <= 0) {
  182. fprintf(MSG_OUT, "\nlast transfer done, kill timeout");
  183. timer.cancel();
  184. }
  185. /* keep on watching.
  186. * the socket may have been closed and/or fdp may have been changed
  187. * in curl_multi_socket_action(), so check them both */
  188. if(!error && socket_map.find(s) != socket_map.end() &&
  189. (*fdp == action || *fdp == CURL_POLL_INOUT)) {
  190. boost::asio::ip::tcp::socket *tcp_socket = socket_map.find(s)->second;
  191. if(action == CURL_POLL_IN) {
  192. tcp_socket->async_read_some(boost::asio::null_buffers(),
  193. boost::bind(&event_cb, g, s,
  194. action, _1, fdp));
  195. }
  196. if(action == CURL_POLL_OUT) {
  197. tcp_socket->async_write_some(boost::asio::null_buffers(),
  198. boost::bind(&event_cb, g, s,
  199. action, _1, fdp));
  200. }
  201. }
  202. }
  203. }
  204. /* Called by asio when our timeout expires */
  205. static void timer_cb(const boost::system::error_code & error, GlobalInfo *g)
  206. {
  207. if(!error) {
  208. fprintf(MSG_OUT, "\ntimer_cb: ");
  209. CURLMcode rc;
  210. rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0,
  211. &g->still_running);
  212. mcode_or_die("timer_cb: curl_multi_socket_action", rc);
  213. check_multi_info(g);
  214. }
  215. }
  216. /* Clean up any data */
  217. static void remsock(int *f, GlobalInfo *g)
  218. {
  219. fprintf(MSG_OUT, "\nremsock: ");
  220. if(f) {
  221. free(f);
  222. }
  223. }
  224. static void setsock(int *fdp, curl_socket_t s, CURL *e, int act, int oldact,
  225. GlobalInfo *g)
  226. {
  227. fprintf(MSG_OUT, "\nsetsock: socket=%d, act=%d, fdp=%p", s, act, fdp);
  228. std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it =
  229. socket_map.find(s);
  230. if(it == socket_map.end()) {
  231. fprintf(MSG_OUT, "\nsocket %d is a c-ares socket, ignoring", s);
  232. return;
  233. }
  234. boost::asio::ip::tcp::socket * tcp_socket = it->second;
  235. *fdp = act;
  236. if(act == CURL_POLL_IN) {
  237. fprintf(MSG_OUT, "\nwatching for socket to become readable");
  238. if(oldact != CURL_POLL_IN && oldact != CURL_POLL_INOUT) {
  239. tcp_socket->async_read_some(boost::asio::null_buffers(),
  240. boost::bind(&event_cb, g, s,
  241. CURL_POLL_IN, _1, fdp));
  242. }
  243. }
  244. else if(act == CURL_POLL_OUT) {
  245. fprintf(MSG_OUT, "\nwatching for socket to become writable");
  246. if(oldact != CURL_POLL_OUT && oldact != CURL_POLL_INOUT) {
  247. tcp_socket->async_write_some(boost::asio::null_buffers(),
  248. boost::bind(&event_cb, g, s,
  249. CURL_POLL_OUT, _1, fdp));
  250. }
  251. }
  252. else if(act == CURL_POLL_INOUT) {
  253. fprintf(MSG_OUT, "\nwatching for socket to become readable & writable");
  254. if(oldact != CURL_POLL_IN && oldact != CURL_POLL_INOUT) {
  255. tcp_socket->async_read_some(boost::asio::null_buffers(),
  256. boost::bind(&event_cb, g, s,
  257. CURL_POLL_IN, _1, fdp));
  258. }
  259. if(oldact != CURL_POLL_OUT && oldact != CURL_POLL_INOUT) {
  260. tcp_socket->async_write_some(boost::asio::null_buffers(),
  261. boost::bind(&event_cb, g, s,
  262. CURL_POLL_OUT, _1, fdp));
  263. }
  264. }
  265. }
  266. static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
  267. {
  268. /* fdp is used to store current action */
  269. int *fdp = (int *) calloc(sizeof(int), 1);
  270. setsock(fdp, s, easy, action, 0, g);
  271. curl_multi_assign(g->multi, s, fdp);
  272. }
  273. /* CURLMOPT_SOCKETFUNCTION */
  274. static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
  275. {
  276. fprintf(MSG_OUT, "\nsock_cb: socket=%d, what=%d, sockp=%p", s, what, sockp);
  277. GlobalInfo *g = (GlobalInfo*) cbp;
  278. int *actionp = (int *) sockp;
  279. const char *whatstr[] = { "none", "IN", "OUT", "INOUT", "REMOVE"};
  280. fprintf(MSG_OUT,
  281. "\nsocket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
  282. if(what == CURL_POLL_REMOVE) {
  283. fprintf(MSG_OUT, "\n");
  284. remsock(actionp, g);
  285. }
  286. else {
  287. if(!actionp) {
  288. fprintf(MSG_OUT, "\nAdding data: %s", whatstr[what]);
  289. addsock(s, e, what, g);
  290. }
  291. else {
  292. fprintf(MSG_OUT,
  293. "\nChanging action from %s to %s",
  294. whatstr[*actionp], whatstr[what]);
  295. setsock(actionp, s, e, what, *actionp, g);
  296. }
  297. }
  298. return 0;
  299. }
  300. /* CURLOPT_WRITEFUNCTION */
  301. static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
  302. {
  303. size_t written = size * nmemb;
  304. char *pBuffer = (char *)malloc(written + 1);
  305. strncpy(pBuffer, (const char *)ptr, written);
  306. pBuffer[written] = '\0';
  307. fprintf(MSG_OUT, "%s", pBuffer);
  308. free(pBuffer);
  309. return written;
  310. }
  311. /* CURLOPT_PROGRESSFUNCTION */
  312. static int prog_cb(void *p, double dltotal, double dlnow, double ult,
  313. double uln)
  314. {
  315. ConnInfo *conn = (ConnInfo *)p;
  316. (void)ult;
  317. (void)uln;
  318. fprintf(MSG_OUT, "\nProgress: %s (%g/%g)", conn->url, dlnow, dltotal);
  319. fprintf(MSG_OUT, "\nProgress: %s (%g)", conn->url, ult);
  320. return 0;
  321. }
  322. /* CURLOPT_OPENSOCKETFUNCTION */
  323. static curl_socket_t opensocket(void *clientp, curlsocktype purpose,
  324. struct curl_sockaddr *address)
  325. {
  326. fprintf(MSG_OUT, "\nopensocket :");
  327. curl_socket_t sockfd = CURL_SOCKET_BAD;
  328. /* restrict to IPv4 */
  329. if(purpose == CURLSOCKTYPE_IPCXN && address->family == AF_INET) {
  330. /* create a tcp socket object */
  331. boost::asio::ip::tcp::socket *tcp_socket =
  332. new boost::asio::ip::tcp::socket(io_service);
  333. /* open it and get the native handle*/
  334. boost::system::error_code ec;
  335. tcp_socket->open(boost::asio::ip::tcp::v4(), ec);
  336. if(ec) {
  337. /* An error occurred */
  338. std::cout << std::endl << "Couldn't open socket [" << ec << "][" <<
  339. ec.message() << "]";
  340. fprintf(MSG_OUT, "\nERROR: Returning CURL_SOCKET_BAD to signal error");
  341. }
  342. else {
  343. sockfd = tcp_socket->native_handle();
  344. fprintf(MSG_OUT, "\nOpened socket %d", sockfd);
  345. /* save it for monitoring */
  346. socket_map.insert(std::pair<curl_socket_t,
  347. boost::asio::ip::tcp::socket *>(sockfd, tcp_socket));
  348. }
  349. }
  350. return sockfd;
  351. }
  352. /* CURLOPT_CLOSESOCKETFUNCTION */
  353. static int close_socket(void *clientp, curl_socket_t item)
  354. {
  355. fprintf(MSG_OUT, "\nclose_socket : %d", item);
  356. std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it =
  357. socket_map.find(item);
  358. if(it != socket_map.end()) {
  359. delete it->second;
  360. socket_map.erase(it);
  361. }
  362. return 0;
  363. }
  364. /* Create a new easy handle, and add it to the global curl_multi */
  365. static void new_conn(char *url, GlobalInfo *g)
  366. {
  367. ConnInfo *conn;
  368. CURLMcode rc;
  369. conn = (ConnInfo *) calloc(1, sizeof(ConnInfo));
  370. conn->easy = curl_easy_init();
  371. if(!conn->easy) {
  372. fprintf(MSG_OUT, "\ncurl_easy_init() failed, exiting!");
  373. exit(2);
  374. }
  375. conn->global = g;
  376. conn->url = strdup(url);
  377. curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  378. curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  379. curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, &conn);
  380. curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
  381. curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  382. curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  383. curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 1L);
  384. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
  385. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  386. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L);
  387. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L);
  388. /* call this function to get a socket */
  389. curl_easy_setopt(conn->easy, CURLOPT_OPENSOCKETFUNCTION, opensocket);
  390. /* call this function to close a socket */
  391. curl_easy_setopt(conn->easy, CURLOPT_CLOSESOCKETFUNCTION, close_socket);
  392. fprintf(MSG_OUT,
  393. "\nAdding easy %p to multi %p (%s)", conn->easy, g->multi, url);
  394. rc = curl_multi_add_handle(g->multi, conn->easy);
  395. mcode_or_die("new_conn: curl_multi_add_handle", rc);
  396. /* note that the add_handle() will set a time-out to trigger very soon so
  397. that the necessary socket_action() call will be called by this app */
  398. }
  399. int main(int argc, char **argv)
  400. {
  401. GlobalInfo g;
  402. (void)argc;
  403. (void)argv;
  404. memset(&g, 0, sizeof(GlobalInfo));
  405. g.multi = curl_multi_init();
  406. curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
  407. curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
  408. curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
  409. curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
  410. new_conn((char *)"www.google.com", &g); /* add a URL */
  411. /* enter io_service run loop */
  412. io_service.run();
  413. curl_multi_cleanup(g.multi);
  414. fprintf(MSG_OUT, "\ndone.\n");
  415. return 0;
  416. }