Revert "Update to 7.40.1"
[platform/upstream/curl.git] / docs / examples / asiohiper.cpp
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 /*
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 */
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 */
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: 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";
119       break;
120     case     CURLM_BAD_SOCKET:         s="CURLM_BAD_SOCKET";
121       fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
122       /* ignore this error */
123       return;
124     }
125     fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
126     exit(code);
127   }
128 }
129
130 /* Check for completed transfers, and remove their easy handles */
131 static void check_multi_info(GlobalInfo *g)
132 {
133   char *eff_url;
134   CURLMsg *msg;
135   int msgs_left;
136   ConnInfo *conn;
137   CURL *easy;
138   CURLcode res;
139
140   fprintf(MSG_OUT, "\nREMAINING: %d", g->still_running);
141
142   while ((msg = curl_multi_info_read(g->multi, &msgs_left)))
143   {
144     if (msg->msg == CURLMSG_DONE)
145     {
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);
152       free(conn->url);
153       curl_easy_cleanup(easy);
154       free(conn);
155     }
156   }
157 }
158
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)
161 {
162   fprintf(MSG_OUT, "\nevent_cb: action=%d", action);
163
164   CURLMcode rc;
165   rc = curl_multi_socket_action(g->multi, tcp_socket->native_handle(), action, &g->still_running);
166
167   mcode_or_die("event_cb: curl_multi_socket_action", rc);
168   check_multi_info(g);
169
170   if ( g->still_running <= 0 )
171   {
172     fprintf(MSG_OUT, "\nlast transfer done, kill timeout");
173     timer.cancel();
174   }
175 }
176
177 /* Called by asio when our timeout expires */
178 static void timer_cb(const boost::system::error_code & error, GlobalInfo *g)
179 {
180   if ( !error)
181   {
182     fprintf(MSG_OUT, "\ntimer_cb: ");
183
184     CURLMcode rc;
185     rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0, &g->still_running);
186
187     mcode_or_die("timer_cb: curl_multi_socket_action", rc);
188     check_multi_info(g);
189   }
190 }
191
192 /* Clean up any data */
193 static void remsock(int *f, GlobalInfo *g)
194 {
195   fprintf(MSG_OUT, "\nremsock: ");
196
197   if ( f )
198   {
199     free(f);
200   }
201 }
202
203 static void setsock(int *fdp, curl_socket_t s, CURL*e, int act, GlobalInfo*g)
204 {
205   fprintf(MSG_OUT, "\nsetsock: socket=%d, act=%d, fdp=%p", s, act, fdp);
206
207   std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it = socket_map.find(s);
208
209   if ( it == socket_map.end() )
210   {
211     fprintf(MSG_OUT, "\nsocket %d is a c-ares socket, ignoring", s);
212     return;
213   }
214
215   boost::asio::ip::tcp::socket * tcp_socket = it->second;
216
217   *fdp = act;
218
219   if ( act == CURL_POLL_IN )
220   {
221     fprintf(MSG_OUT, "\nwatching for socket to become readable");
222
223     tcp_socket->async_read_some(boost::asio::null_buffers(),
224                              boost::bind(&event_cb, g,
225                                tcp_socket,
226                                act));
227   }
228   else if ( act == CURL_POLL_OUT )
229   {
230     fprintf(MSG_OUT, "\nwatching for socket to become writable");
231
232     tcp_socket->async_write_some(boost::asio::null_buffers(),
233                               boost::bind(&event_cb, g,
234                                 tcp_socket,
235                                 act));
236   }
237   else if ( act == CURL_POLL_INOUT )
238   {
239     fprintf(MSG_OUT, "\nwatching for socket to become readable & writable");
240
241     tcp_socket->async_read_some(boost::asio::null_buffers(),
242                              boost::bind(&event_cb, g,
243                                tcp_socket,
244                                act));
245
246     tcp_socket->async_write_some(boost::asio::null_buffers(),
247                               boost::bind(&event_cb, g,
248                                 tcp_socket,
249                                 act));
250   }
251 }
252
253
254 static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
255 {
256   int *fdp = (int *)calloc(sizeof(int), 1); /* fdp is used to store current action */
257
258   setsock(fdp, s, easy, action, g);
259   curl_multi_assign(g->multi, s, fdp);
260 }
261
262 /* CURLMOPT_SOCKETFUNCTION */
263 static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
264 {
265   fprintf(MSG_OUT, "\nsock_cb: socket=%d, what=%d, sockp=%p", s, what, sockp);
266
267   GlobalInfo *g = (GlobalInfo*) cbp;
268   int *actionp = (int*) sockp;
269   const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE"};
270
271   fprintf(MSG_OUT,
272           "\nsocket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
273
274   if ( what == CURL_POLL_REMOVE )
275   {
276     fprintf(MSG_OUT, "\n");
277     remsock(actionp, g);
278   }
279   else
280   {
281     if ( !actionp )
282     {
283       fprintf(MSG_OUT, "\nAdding data: %s", whatstr[what]);
284       addsock(s, e, what, g);
285     }
286     else
287     {
288       fprintf(MSG_OUT,
289               "\nChanging action from %s to %s",
290               whatstr[*actionp], whatstr[what]);
291       setsock(actionp, s, e, what, g);
292     }
293   }
294   return 0;
295 }
296
297
298 /* CURLOPT_WRITEFUNCTION */
299 static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
300 {
301
302   size_t written = size * nmemb;
303   char* pBuffer = (char*)malloc(written + 1);
304
305   strncpy(pBuffer, (const char *)ptr, written);
306   pBuffer [written] = '\0';
307
308   fprintf(MSG_OUT, "%s", pBuffer);
309
310   free(pBuffer);
311
312   return written;
313 }
314
315
316 /* CURLOPT_PROGRESSFUNCTION */
317 static int prog_cb (void *p, double dltotal, double dlnow, double ult,
318                     double uln)
319 {
320   ConnInfo *conn = (ConnInfo *)p;
321   (void)ult;
322   (void)uln;
323
324   fprintf(MSG_OUT, "\nProgress: %s (%g/%g)", conn->url, dlnow, dltotal);
325   fprintf(MSG_OUT, "\nProgress: %s (%g)", conn->url, ult);
326
327   return 0;
328 }
329
330 /* CURLOPT_OPENSOCKETFUNCTION */
331 static curl_socket_t opensocket(void *clientp,
332                                 curlsocktype purpose,
333                                 struct curl_sockaddr *address)
334 {
335   fprintf(MSG_OUT, "\nopensocket :");
336
337   curl_socket_t sockfd = CURL_SOCKET_BAD;
338
339   /* restrict to ipv4 */
340   if (purpose == CURLSOCKTYPE_IPCXN && address->family == AF_INET)
341   {
342     /* create a tcp socket object */
343     boost::asio::ip::tcp::socket *tcp_socket = new boost::asio::ip::tcp::socket(io_service);
344
345     /* open it and get the native handle*/
346     boost::system::error_code ec;
347     tcp_socket->open(boost::asio::ip::tcp::v4(), ec);
348
349     if (ec)
350     {
351       //An error occurred
352       std::cout << std::endl << "Couldn't open socket [" << ec << "][" << ec.message() << "]";
353       fprintf(MSG_OUT, "\nERROR: Returning CURL_SOCKET_BAD to signal error");
354     }
355     else
356     {
357       sockfd = tcp_socket->native_handle();
358       fprintf(MSG_OUT, "\nOpened socket %d", sockfd);
359
360       /* save it for monitoring */
361       socket_map.insert(std::pair<curl_socket_t, boost::asio::ip::tcp::socket *>(sockfd, tcp_socket));
362     }
363   }
364
365   return sockfd;
366 }
367
368 /* CURLOPT_CLOSESOCKETFUNCTION */
369 static int closesocket(void *clientp, curl_socket_t item)
370 {
371   fprintf(MSG_OUT, "\nclosesocket : %d", item);
372
373   std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it = socket_map.find(item);
374
375   if ( it != socket_map.end() )
376   {
377     delete it->second;
378     socket_map.erase(it);
379   }
380
381   return 0;
382 }
383
384 /* Create a new easy handle, and add it to the global curl_multi */
385 static void new_conn(char *url, GlobalInfo *g )
386 {
387   ConnInfo *conn;
388   CURLMcode rc;
389
390   conn = (ConnInfo *)calloc(1, sizeof(ConnInfo));
391   memset(conn, 0, sizeof(ConnInfo));
392   conn->error[0]='\0';
393
394   conn->easy = curl_easy_init();
395
396   if ( !conn->easy )
397   {
398     fprintf(MSG_OUT, "\ncurl_easy_init() failed, exiting!");
399     exit(2);
400   }
401   conn->global = g;
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);
414
415   /* call this function to get a socket */
416   curl_easy_setopt(conn->easy, CURLOPT_OPENSOCKETFUNCTION, opensocket);
417
418   /* call this function to close a socket */
419   curl_easy_setopt(conn->easy, CURLOPT_CLOSESOCKETFUNCTION, closesocket);
420
421   fprintf(MSG_OUT,
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);
425
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 */
428 }
429
430 int main(int argc, char **argv)
431 {
432   GlobalInfo g;
433   CURLMcode rc;
434   (void)argc;
435   (void)argv;
436
437   memset(&g, 0, sizeof(GlobalInfo));
438   g.multi = curl_multi_init();
439
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);
444
445   new_conn((char *)"www.google.com", &g);  /* add a URL */
446
447   /* enter io_service run loop */
448   io_service.run();
449
450   curl_multi_cleanup(g.multi);
451
452   fprintf(MSG_OUT, "\ndone.\n");
453   return 0;
454 }