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