asiohiper.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2012, 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 http://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. /*
  23. * file: asiohiper.cpp
  24. * Example program to demonstrate the use of multi socket interface
  25. * with boost::asio
  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 write
  43. * callback.
  44. */
  45. #include <curl/curl.h>
  46. #include <boost/asio.hpp>
  47. #include <boost/bind.hpp>
  48. #define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */
  49. /* boost::asio related objects
  50. * using global variables for simplicity
  51. */
  52. boost::asio::io_service io_service;
  53. boost::asio::deadline_timer timer(io_service);
  54. std::map<curl_socket_t, boost::asio::ip::tcp::socket *> socket_map;
  55. /* Global information, common to all connections */
  56. typedef struct _GlobalInfo
  57. {
  58. CURLM *multi;
  59. int still_running;
  60. } GlobalInfo;
  61. /* Information associated with a specific easy handle */
  62. typedef struct _ConnInfo
  63. {
  64. CURL *easy;
  65. char *url;
  66. GlobalInfo *global;
  67. char error[CURL_ERROR_SIZE];
  68. } ConnInfo;
  69. static void timer_cb(const boost::system::error_code & error, GlobalInfo *g);
  70. /* Update the event timer after curl_multi library calls */
  71. static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
  72. {
  73. fprintf(MSG_OUT, "\nmulti_timer_cb: timeout_ms %ld", timeout_ms);
  74. /* cancel running timer */
  75. timer.cancel();
  76. if ( timeout_ms > 0 )
  77. {
  78. /* update timer */
  79. timer.expires_from_now(boost::posix_time::millisec(timeout_ms));
  80. timer.async_wait(boost::bind(&timer_cb, _1, g));
  81. }
  82. else
  83. {
  84. /* call timeout function immediately */
  85. boost::system::error_code error; /*success*/
  86. timer_cb(error, g);
  87. }
  88. return 0;
  89. }
  90. /* Die if we get a bad CURLMcode somewhere */
  91. static void mcode_or_die(const char *where, CURLMcode code)
  92. {
  93. if ( CURLM_OK != code )
  94. {
  95. const char *s;
  96. switch ( code )
  97. {
  98. case CURLM_CALL_MULTI_PERFORM: s="CURLM_CALL_MULTI_PERFORM"; break;
  99. case CURLM_BAD_HANDLE: s="CURLM_BAD_HANDLE"; break;
  100. case CURLM_BAD_EASY_HANDLE: s="CURLM_BAD_EASY_HANDLE"; break;
  101. case CURLM_OUT_OF_MEMORY: s="CURLM_OUT_OF_MEMORY"; break;
  102. case CURLM_INTERNAL_ERROR: s="CURLM_INTERNAL_ERROR"; break;
  103. case CURLM_UNKNOWN_OPTION: s="CURLM_UNKNOWN_OPTION"; break;
  104. case CURLM_LAST: s="CURLM_LAST"; break;
  105. default: s="CURLM_unknown";
  106. break;
  107. case CURLM_BAD_SOCKET: s="CURLM_BAD_SOCKET";
  108. fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
  109. /* ignore this error */
  110. return;
  111. }
  112. fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
  113. exit(code);
  114. }
  115. }
  116. /* Check for completed transfers, and remove their easy handles */
  117. static void check_multi_info(GlobalInfo *g)
  118. {
  119. char *eff_url;
  120. CURLMsg *msg;
  121. int msgs_left;
  122. ConnInfo *conn;
  123. CURL *easy;
  124. CURLcode res;
  125. fprintf(MSG_OUT, "\nREMAINING: %d", g->still_running);
  126. while ((msg = curl_multi_info_read(g->multi, &msgs_left)))
  127. {
  128. if (msg->msg == CURLMSG_DONE)
  129. {
  130. easy = msg->easy_handle;
  131. res = msg->data.result;
  132. curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
  133. curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
  134. fprintf(MSG_OUT, "\nDONE: %s => (%d) %s", eff_url, res, conn->error);
  135. curl_multi_remove_handle(g->multi, easy);
  136. free(conn->url);
  137. curl_easy_cleanup(easy);
  138. free(conn);
  139. }
  140. }
  141. }
  142. /* Called by asio when there is an action on a socket */
  143. static void event_cb(GlobalInfo * g, boost::asio::ip::tcp::socket * tcp_socket, int action)
  144. {
  145. fprintf(MSG_OUT, "\nevent_cb: action=%d", action);
  146. CURLMcode rc;
  147. rc = curl_multi_socket_action(g->multi, tcp_socket->native_handle(), action, &g->still_running);
  148. mcode_or_die("event_cb: curl_multi_socket_action", rc);
  149. check_multi_info(g);
  150. if ( g->still_running <= 0 )
  151. {
  152. fprintf(MSG_OUT, "\nlast transfer done, kill timeout");
  153. timer.cancel();
  154. }
  155. }
  156. /* Called by asio when our timeout expires */
  157. static void timer_cb(const boost::system::error_code & error, GlobalInfo *g)
  158. {
  159. if ( !error)
  160. {
  161. fprintf(MSG_OUT, "\ntimer_cb: ");
  162. CURLMcode rc;
  163. rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0, &g->still_running);
  164. mcode_or_die("timer_cb: curl_multi_socket_action", rc);
  165. check_multi_info(g);
  166. }
  167. }
  168. /* Clean up any data */
  169. static void remsock(int *f, GlobalInfo *g)
  170. {
  171. fprintf(MSG_OUT, "\nremsock: ");
  172. if ( f )
  173. {
  174. free(f);
  175. }
  176. }
  177. static void setsock(int *fdp, curl_socket_t s, CURL*e, int act, GlobalInfo*g)
  178. {
  179. fprintf(MSG_OUT, "\nsetsock: socket=%d, act=%d, fdp=%p", s, act, fdp);
  180. std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it = socket_map.find(s);
  181. if ( it == socket_map.end() )
  182. {
  183. fprintf(MSG_OUT, "\nsocket %d is a c-ares socket, ignoring", s);
  184. return;
  185. }
  186. boost::asio::ip::tcp::socket * tcp_socket = it->second;
  187. *fdp = act;
  188. if ( act == CURL_POLL_IN )
  189. {
  190. fprintf(MSG_OUT, "\nwatching for socket to become readable");
  191. tcp_socket->async_read_some(boost::asio::null_buffers(),
  192. boost::bind(&event_cb, g,
  193. tcp_socket,
  194. act));
  195. }
  196. else if ( act == CURL_POLL_OUT )
  197. {
  198. fprintf(MSG_OUT, "\nwatching for socket to become writable");
  199. tcp_socket->async_write_some(boost::asio::null_buffers(),
  200. boost::bind(&event_cb, g,
  201. tcp_socket,
  202. act));
  203. }
  204. else if ( act == CURL_POLL_INOUT )
  205. {
  206. fprintf(MSG_OUT, "\nwatching for socket to become readable & writable");
  207. tcp_socket->async_read_some(boost::asio::null_buffers(),
  208. boost::bind(&event_cb, g,
  209. tcp_socket,
  210. act));
  211. tcp_socket->async_write_some(boost::asio::null_buffers(),
  212. boost::bind(&event_cb, g,
  213. tcp_socket,
  214. act));
  215. }
  216. }
  217. static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
  218. {
  219. int *fdp = (int *)calloc(sizeof(int), 1); /* fdp is used to store current action */
  220. setsock(fdp, s, easy, action, g);
  221. curl_multi_assign(g->multi, s, fdp);
  222. }
  223. /* CURLMOPT_SOCKETFUNCTION */
  224. static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
  225. {
  226. fprintf(MSG_OUT, "\nsock_cb: socket=%d, what=%d, sockp=%p", s, what, sockp);
  227. GlobalInfo *g = (GlobalInfo*) cbp;
  228. int *actionp = (int*) sockp;
  229. const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE"};
  230. fprintf(MSG_OUT,
  231. "\nsocket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
  232. if ( what == CURL_POLL_REMOVE )
  233. {
  234. fprintf(MSG_OUT, "\n");
  235. remsock(actionp, g);
  236. }
  237. else
  238. {
  239. if ( !actionp )
  240. {
  241. fprintf(MSG_OUT, "\nAdding data: %s", whatstr[what]);
  242. addsock(s, e, what, g);
  243. }
  244. else
  245. {
  246. fprintf(MSG_OUT,
  247. "\nChanging action from %s to %s",
  248. whatstr[*actionp], whatstr[what]);
  249. setsock(actionp, s, e, what, g);
  250. }
  251. }
  252. return 0;
  253. }
  254. /* CURLOPT_WRITEFUNCTION */
  255. static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
  256. {
  257. size_t written = size * nmemb;
  258. char* pBuffer = (char*)malloc(written + 1);
  259. strncpy(pBuffer, (const char *)ptr, written);
  260. pBuffer [written] = '\0';
  261. fprintf(MSG_OUT, "%s", pBuffer);
  262. free(pBuffer);
  263. return written;
  264. }
  265. /* CURLOPT_PROGRESSFUNCTION */
  266. static int prog_cb (void *p, double dltotal, double dlnow, double ult,
  267. double uln)
  268. {
  269. ConnInfo *conn = (ConnInfo *)p;
  270. (void)ult;
  271. (void)uln;
  272. fprintf(MSG_OUT, "\nProgress: %s (%g/%g)", conn->url, dlnow, dltotal);
  273. fprintf(MSG_OUT, "\nProgress: %s (%g)", conn->url, ult);
  274. return 0;
  275. }
  276. /* CURLOPT_OPENSOCKETFUNCTION */
  277. static curl_socket_t opensocket(void *clientp,
  278. curlsocktype purpose,
  279. struct curl_sockaddr *address)
  280. {
  281. fprintf(MSG_OUT, "\nopensocket :");
  282. curl_socket_t sockfd = CURL_SOCKET_BAD;
  283. /* restrict to ipv4 */
  284. if (purpose == CURLSOCKTYPE_IPCXN && address->family == AF_INET)
  285. {
  286. /* create a tcp socket object */
  287. boost::asio::ip::tcp::socket *tcp_socket = new boost::asio::ip::tcp::socket(io_service);
  288. /* open it and get the native handle*/
  289. boost::system::error_code ec;
  290. tcp_socket->open(boost::asio::ip::tcp::v4(), ec);
  291. if (ec)
  292. {
  293. //An error occurred
  294. std::cout << std::endl << "Couldn't open socket [" << ec << "][" << ec.message() << "]";
  295. fprintf(MSG_OUT, "\nERROR: Returning CURL_SOCKET_BAD to signal error");
  296. }
  297. else
  298. {
  299. sockfd = tcp_socket->native_handle();
  300. fprintf(MSG_OUT, "\nOpened socket %d", sockfd);
  301. /* save it for monitoring */
  302. socket_map.insert(std::pair<curl_socket_t, boost::asio::ip::tcp::socket *>(sockfd, tcp_socket));
  303. }
  304. }
  305. return sockfd;
  306. }
  307. /* CURLOPT_CLOSESOCKETFUNCTION */
  308. static int closesocket(void *clientp, curl_socket_t item)
  309. {
  310. fprintf(MSG_OUT, "\nclosesocket : %d", item);
  311. std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it = socket_map.find(item);
  312. if ( it != socket_map.end() )
  313. {
  314. delete it->second;
  315. socket_map.erase(it);
  316. }
  317. return 0;
  318. }
  319. /* Create a new easy handle, and add it to the global curl_multi */
  320. static void new_conn(char *url, GlobalInfo *g )
  321. {
  322. ConnInfo *conn;
  323. CURLMcode rc;
  324. conn = (ConnInfo *)calloc(1, sizeof(ConnInfo));
  325. memset(conn, 0, sizeof(ConnInfo));
  326. conn->error[0]='\0';
  327. conn->easy = curl_easy_init();
  328. if ( !conn->easy )
  329. {
  330. fprintf(MSG_OUT, "\ncurl_easy_init() failed, exiting!");
  331. exit(2);
  332. }
  333. conn->global = g;
  334. conn->url = strdup(url);
  335. curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  336. curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  337. curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, &conn);
  338. curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
  339. curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  340. curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  341. curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 1L);
  342. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
  343. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  344. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L);
  345. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L);
  346. /* call this function to get a socket */
  347. curl_easy_setopt(conn->easy, CURLOPT_OPENSOCKETFUNCTION, opensocket);
  348. /* call this function to close a socket */
  349. curl_easy_setopt(conn->easy, CURLOPT_CLOSESOCKETFUNCTION, closesocket);
  350. fprintf(MSG_OUT,
  351. "\nAdding easy %p to multi %p (%s)", conn->easy, g->multi, url);
  352. rc = curl_multi_add_handle(g->multi, conn->easy);
  353. mcode_or_die("new_conn: curl_multi_add_handle", rc);
  354. /* note that the add_handle() will set a time-out to trigger very soon so
  355. that the necessary socket_action() call will be called by this app */
  356. }
  357. int main(int argc, char **argv)
  358. {
  359. GlobalInfo g;
  360. CURLMcode rc;
  361. (void)argc;
  362. (void)argv;
  363. memset(&g, 0, sizeof(GlobalInfo));
  364. g.multi = curl_multi_init();
  365. curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
  366. curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
  367. curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
  368. curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
  369. new_conn((char *)"www.google.com", &g); /* add a URL */
  370. /* enter io_service run loop */
  371. io_service.run();
  372. curl_multi_cleanup(g.multi);
  373. fprintf(MSG_OUT, "\ndone.\n");
  374. return 0;
  375. }