1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 2012 - 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
24 * demonstrate the use of multi socket interface with boost::asio
28 * This program is in c++ and uses boost::asio instead of libevent/libev.
29 * Requires boost::asio, boost::bind and boost::system
31 * This is an adaptation of libcurl's "hiperfifo.c" and "evhiperfifo.c"
32 * sample programs. This example implements a subset of the functionality from
33 * hiperfifo.c, for full functionality refer hiperfifo.c or evhiperfifo.c
35 * Written by Lijo Antony based on hiperfifo.c by Jeff Pohlmeyer
37 * When running, the program creates an easy handle for a URL and
38 * uses the curl_multi API to fetch it.
41 * For the sake of simplicity, URL is hard coded to "www.google.com"
43 * This is purely a demo app, all retrieved data is simply discarded by the
48 #include <curl/curl.h>
49 #include <boost/asio.hpp>
50 #include <boost/bind.hpp>
53 #define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */
55 /* boost::asio related objects
56 * using global variables for simplicity
58 boost::asio::io_service io_service;
59 boost::asio::deadline_timer timer(io_service);
60 std::map<curl_socket_t, boost::asio::ip::tcp::socket *> socket_map;
62 /* Global information, common to all connections */
63 typedef struct _GlobalInfo
69 /* Information associated with a specific easy handle */
70 typedef struct _ConnInfo
75 char error[CURL_ERROR_SIZE];
78 static void timer_cb(const boost::system::error_code & error, GlobalInfo *g);
80 /* Update the event timer after curl_multi library calls */
81 static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
83 fprintf(MSG_OUT, "\nmulti_timer_cb: timeout_ms %ld", timeout_ms);
85 /* cancel running timer */
90 timer.expires_from_now(boost::posix_time::millisec(timeout_ms));
91 timer.async_wait(boost::bind(&timer_cb, _1, g));
94 /* call timeout function immediately */
95 boost::system::error_code error; /*success*/
102 /* Die if we get a bad CURLMcode somewhere */
103 static void mcode_or_die(const char *where, CURLMcode code)
105 if(CURLM_OK != code) {
108 case CURLM_CALL_MULTI_PERFORM:
109 s = "CURLM_CALL_MULTI_PERFORM";
111 case CURLM_BAD_HANDLE:
112 s = "CURLM_BAD_HANDLE";
114 case CURLM_BAD_EASY_HANDLE:
115 s = "CURLM_BAD_EASY_HANDLE";
117 case CURLM_OUT_OF_MEMORY:
118 s = "CURLM_OUT_OF_MEMORY";
120 case CURLM_INTERNAL_ERROR:
121 s = "CURLM_INTERNAL_ERROR";
123 case CURLM_UNKNOWN_OPTION:
124 s = "CURLM_UNKNOWN_OPTION";
132 case CURLM_BAD_SOCKET:
133 s = "CURLM_BAD_SOCKET";
134 fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
135 /* ignore this error */
139 fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
145 /* Check for completed transfers, and remove their easy handles */
146 static void check_multi_info(GlobalInfo *g)
155 fprintf(MSG_OUT, "\nREMAINING: %d", g->still_running);
157 while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
158 if(msg->msg == CURLMSG_DONE) {
159 easy = msg->easy_handle;
160 res = msg->data.result;
161 curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
162 curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
163 fprintf(MSG_OUT, "\nDONE: %s => (%d) %s", eff_url, res, conn->error);
164 curl_multi_remove_handle(g->multi, easy);
166 curl_easy_cleanup(easy);
172 /* Called by asio when there is an action on a socket */
173 static void event_cb(GlobalInfo *g, boost::asio::ip::tcp::socket *tcp_socket,
174 int action, const boost::system::error_code & error,
177 fprintf(MSG_OUT, "\nevent_cb: action=%d", action);
179 /* make sure the event matches what are wanted */
180 if(*fdp == action || *fdp == CURL_POLL_INOUT) {
181 curl_socket_t s = tcp_socket->native_handle();
184 action = CURL_CSELECT_ERR;
185 rc = curl_multi_socket_action(g->multi, s, action, &g->still_running);
187 mcode_or_die("event_cb: curl_multi_socket_action", rc);
190 if(g->still_running <= 0) {
191 fprintf(MSG_OUT, "\nlast transfer done, kill timeout");
196 * the socket may have been closed and/or fdp may have been changed
197 * in curl_multi_socket_action(), so check them both */
198 if(!error && socket_map.find(s) != socket_map.end() &&
199 (*fdp == action || *fdp == CURL_POLL_INOUT)) {
200 if(action == CURL_POLL_IN) {
201 tcp_socket->async_read_some(boost::asio::null_buffers(),
202 boost::bind(&event_cb, g, tcp_socket,
205 if(action == CURL_POLL_OUT) {
206 tcp_socket->async_write_some(boost::asio::null_buffers(),
207 boost::bind(&event_cb, g, tcp_socket,
214 /* Called by asio when our timeout expires */
215 static void timer_cb(const boost::system::error_code & error, GlobalInfo *g)
218 fprintf(MSG_OUT, "\ntimer_cb: ");
221 rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0,
224 mcode_or_die("timer_cb: curl_multi_socket_action", rc);
229 /* Clean up any data */
230 static void remsock(int *f, GlobalInfo *g)
232 fprintf(MSG_OUT, "\nremsock: ");
239 static void setsock(int *fdp, curl_socket_t s, CURL *e, int act, int oldact,
242 fprintf(MSG_OUT, "\nsetsock: socket=%d, act=%d, fdp=%p", s, act, fdp);
244 std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it =
247 if(it == socket_map.end()) {
248 fprintf(MSG_OUT, "\nsocket %d is a c-ares socket, ignoring", s);
252 boost::asio::ip::tcp::socket * tcp_socket = it->second;
256 if(act == CURL_POLL_IN) {
257 fprintf(MSG_OUT, "\nwatching for socket to become readable");
258 if(oldact != CURL_POLL_IN && oldact != CURL_POLL_INOUT) {
259 tcp_socket->async_read_some(boost::asio::null_buffers(),
260 boost::bind(&event_cb, g, tcp_socket,
261 CURL_POLL_IN, _1, fdp));
264 else if(act == CURL_POLL_OUT) {
265 fprintf(MSG_OUT, "\nwatching for socket to become writable");
266 if(oldact != CURL_POLL_OUT && oldact != CURL_POLL_INOUT) {
267 tcp_socket->async_write_some(boost::asio::null_buffers(),
268 boost::bind(&event_cb, g, tcp_socket,
269 CURL_POLL_OUT, _1, fdp));
272 else if(act == CURL_POLL_INOUT) {
273 fprintf(MSG_OUT, "\nwatching for socket to become readable & writable");
274 if(oldact != CURL_POLL_IN && oldact != CURL_POLL_INOUT) {
275 tcp_socket->async_read_some(boost::asio::null_buffers(),
276 boost::bind(&event_cb, g, tcp_socket,
277 CURL_POLL_IN, _1, fdp));
279 if(oldact != CURL_POLL_OUT && oldact != CURL_POLL_INOUT) {
280 tcp_socket->async_write_some(boost::asio::null_buffers(),
281 boost::bind(&event_cb, g, tcp_socket,
282 CURL_POLL_OUT, _1, fdp));
287 static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
289 /* fdp is used to store current action */
290 int *fdp = (int *) calloc(sizeof(int), 1);
292 setsock(fdp, s, easy, action, 0, g);
293 curl_multi_assign(g->multi, s, fdp);
296 /* CURLMOPT_SOCKETFUNCTION */
297 static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
299 fprintf(MSG_OUT, "\nsock_cb: socket=%d, what=%d, sockp=%p", s, what, sockp);
301 GlobalInfo *g = (GlobalInfo*) cbp;
302 int *actionp = (int *) sockp;
303 const char *whatstr[] = { "none", "IN", "OUT", "INOUT", "REMOVE"};
306 "\nsocket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
308 if(what == CURL_POLL_REMOVE) {
309 fprintf(MSG_OUT, "\n");
314 fprintf(MSG_OUT, "\nAdding data: %s", whatstr[what]);
315 addsock(s, e, what, g);
319 "\nChanging action from %s to %s",
320 whatstr[*actionp], whatstr[what]);
321 setsock(actionp, s, e, what, *actionp, g);
328 /* CURLOPT_WRITEFUNCTION */
329 static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
331 size_t written = size * nmemb;
332 char *pBuffer = (char *)malloc(written + 1);
334 strncpy(pBuffer, (const char *)ptr, written);
335 pBuffer[written] = '\0';
337 fprintf(MSG_OUT, "%s", pBuffer);
344 /* CURLOPT_PROGRESSFUNCTION */
345 static int prog_cb(void *p, double dltotal, double dlnow, double ult,
348 ConnInfo *conn = (ConnInfo *)p;
353 fprintf(MSG_OUT, "\nProgress: %s (%g/%g)", conn->url, dlnow, dltotal);
354 fprintf(MSG_OUT, "\nProgress: %s (%g)", conn->url, ult);
359 /* CURLOPT_OPENSOCKETFUNCTION */
360 static curl_socket_t opensocket(void *clientp, curlsocktype purpose,
361 struct curl_sockaddr *address)
363 fprintf(MSG_OUT, "\nopensocket :");
365 curl_socket_t sockfd = CURL_SOCKET_BAD;
367 /* restrict to IPv4 */
368 if(purpose == CURLSOCKTYPE_IPCXN && address->family == AF_INET) {
369 /* create a tcp socket object */
370 boost::asio::ip::tcp::socket *tcp_socket =
371 new boost::asio::ip::tcp::socket(io_service);
373 /* open it and get the native handle*/
374 boost::system::error_code ec;
375 tcp_socket->open(boost::asio::ip::tcp::v4(), ec);
378 /* An error occurred */
379 std::cout << std::endl << "Couldn't open socket [" << ec << "][" <<
381 fprintf(MSG_OUT, "\nERROR: Returning CURL_SOCKET_BAD to signal error");
384 sockfd = tcp_socket->native_handle();
385 fprintf(MSG_OUT, "\nOpened socket %d", sockfd);
387 /* save it for monitoring */
388 socket_map.insert(std::pair<curl_socket_t,
389 boost::asio::ip::tcp::socket *>(sockfd, tcp_socket));
396 /* CURLOPT_CLOSESOCKETFUNCTION */
397 static int close_socket(void *clientp, curl_socket_t item)
399 fprintf(MSG_OUT, "\nclose_socket : %d", item);
401 std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it =
402 socket_map.find(item);
404 if(it != socket_map.end()) {
406 socket_map.erase(it);
412 /* Create a new easy handle, and add it to the global curl_multi */
413 static void new_conn(char *url, GlobalInfo *g)
418 conn = (ConnInfo *) calloc(1, sizeof(ConnInfo));
420 conn->easy = curl_easy_init();
422 fprintf(MSG_OUT, "\ncurl_easy_init() failed, exiting!");
427 conn->url = strdup(url);
428 curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
429 curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
430 curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, &conn);
431 curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
432 curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
433 curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
434 curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 1L);
435 curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
436 curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
437 curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L);
438 curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L);
440 /* call this function to get a socket */
441 curl_easy_setopt(conn->easy, CURLOPT_OPENSOCKETFUNCTION, opensocket);
443 /* call this function to close a socket */
444 curl_easy_setopt(conn->easy, CURLOPT_CLOSESOCKETFUNCTION, close_socket);
447 "\nAdding easy %p to multi %p (%s)", conn->easy, g->multi, url);
448 rc = curl_multi_add_handle(g->multi, conn->easy);
449 mcode_or_die("new_conn: curl_multi_add_handle", rc);
451 /* note that the add_handle() will set a time-out to trigger very soon so
452 that the necessary socket_action() call will be called by this app */
455 int main(int argc, char **argv)
462 memset(&g, 0, sizeof(GlobalInfo));
463 g.multi = curl_multi_init();
465 curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
466 curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
467 curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
468 curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
470 new_conn((char *)"www.google.com", &g); /* add a URL */
472 /* enter io_service run loop */
475 curl_multi_cleanup(g.multi);
477 fprintf(MSG_OUT, "\ndone.\n");