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