1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 2012, 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 http://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 ***************************************************************************/
25 * Example program to demonstrate the use of multi socket interface
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 write
48 #include <curl/curl.h>
49 #include <boost/asio.hpp>
50 #include <boost/bind.hpp>
52 #define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */
54 /* boost::asio related objects
55 * using global variables for simplicity
57 boost::asio::io_service io_service;
58 boost::asio::deadline_timer timer(io_service);
59 std::map<curl_socket_t, boost::asio::ip::tcp::socket *> socket_map;
61 /* Global information, common to all connections */
62 typedef struct _GlobalInfo
68 /* Information associated with a specific easy handle */
69 typedef struct _ConnInfo
74 char error[CURL_ERROR_SIZE];
77 static void timer_cb(const boost::system::error_code & error, GlobalInfo *g);
79 /* Update the event timer after curl_multi library calls */
80 static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
82 fprintf(MSG_OUT, "\nmulti_timer_cb: timeout_ms %ld", timeout_ms);
84 /* cancel running timer */
90 timer.expires_from_now(boost::posix_time::millisec(timeout_ms));
91 timer.async_wait(boost::bind(&timer_cb, _1, g));
95 /* call timeout function immediately */
96 boost::system::error_code error; /*success*/
103 /* Die if we get a bad CURLMcode somewhere */
104 static void mcode_or_die(const char *where, CURLMcode code)
106 if ( CURLM_OK != code )
111 case CURLM_CALL_MULTI_PERFORM: s="CURLM_CALL_MULTI_PERFORM"; break;
112 case CURLM_BAD_HANDLE: s="CURLM_BAD_HANDLE"; break;
113 case CURLM_BAD_EASY_HANDLE: s="CURLM_BAD_EASY_HANDLE"; break;
114 case CURLM_OUT_OF_MEMORY: s="CURLM_OUT_OF_MEMORY"; break;
115 case CURLM_INTERNAL_ERROR: s="CURLM_INTERNAL_ERROR"; break;
116 case CURLM_UNKNOWN_OPTION: s="CURLM_UNKNOWN_OPTION"; break;
117 case CURLM_LAST: s="CURLM_LAST"; break;
118 default: s="CURLM_unknown";
120 case CURLM_BAD_SOCKET: s="CURLM_BAD_SOCKET";
121 fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
122 /* ignore this error */
125 fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
130 /* Check for completed transfers, and remove their easy handles */
131 static void check_multi_info(GlobalInfo *g)
140 fprintf(MSG_OUT, "\nREMAINING: %d", g->still_running);
142 while ((msg = curl_multi_info_read(g->multi, &msgs_left)))
144 if (msg->msg == CURLMSG_DONE)
146 easy = msg->easy_handle;
147 res = msg->data.result;
148 curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
149 curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
150 fprintf(MSG_OUT, "\nDONE: %s => (%d) %s", eff_url, res, conn->error);
151 curl_multi_remove_handle(g->multi, easy);
153 curl_easy_cleanup(easy);
159 /* Called by asio when there is an action on a socket */
160 static void event_cb(GlobalInfo * g, boost::asio::ip::tcp::socket * tcp_socket, int action)
162 fprintf(MSG_OUT, "\nevent_cb: action=%d", action);
165 rc = curl_multi_socket_action(g->multi, tcp_socket->native_handle(), action, &g->still_running);
167 mcode_or_die("event_cb: curl_multi_socket_action", rc);
170 if ( g->still_running <= 0 )
172 fprintf(MSG_OUT, "\nlast transfer done, kill timeout");
177 /* Called by asio when our timeout expires */
178 static void timer_cb(const boost::system::error_code & error, GlobalInfo *g)
182 fprintf(MSG_OUT, "\ntimer_cb: ");
185 rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0, &g->still_running);
187 mcode_or_die("timer_cb: curl_multi_socket_action", rc);
192 /* Clean up any data */
193 static void remsock(int *f, GlobalInfo *g)
195 fprintf(MSG_OUT, "\nremsock: ");
203 static void setsock(int *fdp, curl_socket_t s, CURL*e, int act, GlobalInfo*g)
205 fprintf(MSG_OUT, "\nsetsock: socket=%d, act=%d, fdp=%p", s, act, fdp);
207 std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it = socket_map.find(s);
209 if ( it == socket_map.end() )
211 fprintf(MSG_OUT, "\nsocket %d is a c-ares socket, ignoring", s);
215 boost::asio::ip::tcp::socket * tcp_socket = it->second;
219 if ( act == CURL_POLL_IN )
221 fprintf(MSG_OUT, "\nwatching for socket to become readable");
223 tcp_socket->async_read_some(boost::asio::null_buffers(),
224 boost::bind(&event_cb, g,
228 else if ( act == CURL_POLL_OUT )
230 fprintf(MSG_OUT, "\nwatching for socket to become writable");
232 tcp_socket->async_write_some(boost::asio::null_buffers(),
233 boost::bind(&event_cb, g,
237 else if ( act == CURL_POLL_INOUT )
239 fprintf(MSG_OUT, "\nwatching for socket to become readable & writable");
241 tcp_socket->async_read_some(boost::asio::null_buffers(),
242 boost::bind(&event_cb, g,
246 tcp_socket->async_write_some(boost::asio::null_buffers(),
247 boost::bind(&event_cb, g,
254 static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
256 int *fdp = (int *)calloc(sizeof(int), 1); /* fdp is used to store current action */
258 setsock(fdp, s, easy, action, g);
259 curl_multi_assign(g->multi, s, fdp);
262 /* CURLMOPT_SOCKETFUNCTION */
263 static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
265 fprintf(MSG_OUT, "\nsock_cb: socket=%d, what=%d, sockp=%p", s, what, sockp);
267 GlobalInfo *g = (GlobalInfo*) cbp;
268 int *actionp = (int*) sockp;
269 const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE"};
272 "\nsocket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
274 if ( what == CURL_POLL_REMOVE )
276 fprintf(MSG_OUT, "\n");
283 fprintf(MSG_OUT, "\nAdding data: %s", whatstr[what]);
284 addsock(s, e, what, g);
289 "\nChanging action from %s to %s",
290 whatstr[*actionp], whatstr[what]);
291 setsock(actionp, s, e, what, g);
298 /* CURLOPT_WRITEFUNCTION */
299 static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
302 size_t written = size * nmemb;
303 char* pBuffer = (char*)malloc(written + 1);
305 strncpy(pBuffer, (const char *)ptr, written);
306 pBuffer [written] = '\0';
308 fprintf(MSG_OUT, "%s", pBuffer);
316 /* CURLOPT_PROGRESSFUNCTION */
317 static int prog_cb (void *p, double dltotal, double dlnow, double ult,
320 ConnInfo *conn = (ConnInfo *)p;
324 fprintf(MSG_OUT, "\nProgress: %s (%g/%g)", conn->url, dlnow, dltotal);
325 fprintf(MSG_OUT, "\nProgress: %s (%g)", conn->url, ult);
330 /* CURLOPT_OPENSOCKETFUNCTION */
331 static curl_socket_t opensocket(void *clientp,
332 curlsocktype purpose,
333 struct curl_sockaddr *address)
335 fprintf(MSG_OUT, "\nopensocket :");
337 curl_socket_t sockfd = CURL_SOCKET_BAD;
339 /* restrict to ipv4 */
340 if (purpose == CURLSOCKTYPE_IPCXN && address->family == AF_INET)
342 /* create a tcp socket object */
343 boost::asio::ip::tcp::socket *tcp_socket = new boost::asio::ip::tcp::socket(io_service);
345 /* open it and get the native handle*/
346 boost::system::error_code ec;
347 tcp_socket->open(boost::asio::ip::tcp::v4(), ec);
352 std::cout << std::endl << "Couldn't open socket [" << ec << "][" << ec.message() << "]";
353 fprintf(MSG_OUT, "\nERROR: Returning CURL_SOCKET_BAD to signal error");
357 sockfd = tcp_socket->native_handle();
358 fprintf(MSG_OUT, "\nOpened socket %d", sockfd);
360 /* save it for monitoring */
361 socket_map.insert(std::pair<curl_socket_t, boost::asio::ip::tcp::socket *>(sockfd, tcp_socket));
368 /* CURLOPT_CLOSESOCKETFUNCTION */
369 static int closesocket(void *clientp, curl_socket_t item)
371 fprintf(MSG_OUT, "\nclosesocket : %d", item);
373 std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it = socket_map.find(item);
375 if ( it != socket_map.end() )
378 socket_map.erase(it);
384 /* Create a new easy handle, and add it to the global curl_multi */
385 static void new_conn(char *url, GlobalInfo *g )
390 conn = (ConnInfo *)calloc(1, sizeof(ConnInfo));
391 memset(conn, 0, sizeof(ConnInfo));
394 conn->easy = curl_easy_init();
398 fprintf(MSG_OUT, "\ncurl_easy_init() failed, exiting!");
402 conn->url = strdup(url);
403 curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
404 curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
405 curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, &conn);
406 curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
407 curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
408 curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
409 curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 1L);
410 curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
411 curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
412 curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L);
413 curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L);
415 /* call this function to get a socket */
416 curl_easy_setopt(conn->easy, CURLOPT_OPENSOCKETFUNCTION, opensocket);
418 /* call this function to close a socket */
419 curl_easy_setopt(conn->easy, CURLOPT_CLOSESOCKETFUNCTION, closesocket);
422 "\nAdding easy %p to multi %p (%s)", conn->easy, g->multi, url);
423 rc = curl_multi_add_handle(g->multi, conn->easy);
424 mcode_or_die("new_conn: curl_multi_add_handle", rc);
426 /* note that the add_handle() will set a time-out to trigger very soon so
427 that the necessary socket_action() call will be called by this app */
430 int main(int argc, char **argv)
437 memset(&g, 0, sizeof(GlobalInfo));
438 g.multi = curl_multi_init();
440 curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
441 curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
442 curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
443 curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
445 new_conn((char *)"www.google.com", &g); /* add a URL */
447 /* enter io_service run loop */
450 curl_multi_cleanup(g.multi);
452 fprintf(MSG_OUT, "\ndone.\n");