ced4ef419aaa1e757a7f4a94c4ce81533bfa9eb6
[platform/upstream/curl.git] / docs / examples / asiohiper.cpp
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 2012 - 2017, 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
44  * write 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     /* 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     /* call timeout function immediately */
95     boost::system::error_code error; /*success*/
96     timer_cb(error, g);
97   }
98
99   return 0;
100 }
101
102 /* Die if we get a bad CURLMcode somewhere */
103 static void mcode_or_die(const char *where, CURLMcode code)
104 {
105   if(CURLM_OK != code) {
106     const char *s;
107     switch(code) {
108     case CURLM_CALL_MULTI_PERFORM:
109       s = "CURLM_CALL_MULTI_PERFORM";
110       break;
111     case CURLM_BAD_HANDLE:
112       s = "CURLM_BAD_HANDLE";
113       break;
114     case CURLM_BAD_EASY_HANDLE:
115       s = "CURLM_BAD_EASY_HANDLE";
116       break;
117     case CURLM_OUT_OF_MEMORY:
118       s = "CURLM_OUT_OF_MEMORY";
119       break;
120     case CURLM_INTERNAL_ERROR:
121       s = "CURLM_INTERNAL_ERROR";
122       break;
123     case CURLM_UNKNOWN_OPTION:
124       s = "CURLM_UNKNOWN_OPTION";
125       break;
126     case CURLM_LAST:
127       s = "CURLM_LAST";
128       break;
129     default:
130       s = "CURLM_unknown";
131       break;
132     case CURLM_BAD_SOCKET:
133       s = "CURLM_BAD_SOCKET";
134       fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
135       /* ignore this error */
136       return;
137     }
138
139     fprintf(MSG_OUT, "\nERROR: %s returns %s", where, s);
140
141     exit(code);
142   }
143 }
144
145 /* Check for completed transfers, and remove their easy handles */
146 static void check_multi_info(GlobalInfo *g)
147 {
148   char *eff_url;
149   CURLMsg *msg;
150   int msgs_left;
151   ConnInfo *conn;
152   CURL *easy;
153   CURLcode res;
154
155   fprintf(MSG_OUT, "\nREMAINING: %d", g->still_running);
156
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);
165       free(conn->url);
166       curl_easy_cleanup(easy);
167       free(conn);
168     }
169   }
170 }
171
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,
175                      int *fdp)
176 {
177   fprintf(MSG_OUT, "\nevent_cb: action=%d", action);
178
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();
182     CURLMcode rc;
183     if(error)
184       action = CURL_CSELECT_ERR;
185     rc = curl_multi_socket_action(g->multi, s, action, &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       fprintf(MSG_OUT, "\nlast transfer done, kill timeout");
192       timer.cancel();
193     }
194
195     /* keep on watching.
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,
203                                                 action, _1, fdp));
204       }
205       if(action == CURL_POLL_OUT) {
206         tcp_socket->async_write_some(boost::asio::null_buffers(),
207                                      boost::bind(&event_cb, g, tcp_socket,
208                                                  action, _1, fdp));
209       }
210     }
211   }
212 }
213
214 /* Called by asio when our timeout expires */
215 static void timer_cb(const boost::system::error_code & error, GlobalInfo *g)
216 {
217   if(!error) {
218     fprintf(MSG_OUT, "\ntimer_cb: ");
219
220     CURLMcode rc;
221     rc = curl_multi_socket_action(g->multi, CURL_SOCKET_TIMEOUT, 0,
222                                   &g->still_running);
223
224     mcode_or_die("timer_cb: curl_multi_socket_action", rc);
225     check_multi_info(g);
226   }
227 }
228
229 /* Clean up any data */
230 static void remsock(int *f, GlobalInfo *g)
231 {
232   fprintf(MSG_OUT, "\nremsock: ");
233
234   if(f) {
235     free(f);
236   }
237 }
238
239 static void setsock(int *fdp, curl_socket_t s, CURL *e, int act, int oldact,
240                     GlobalInfo *g)
241 {
242   fprintf(MSG_OUT, "\nsetsock: socket=%d, act=%d, fdp=%p", s, act, fdp);
243
244   std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it =
245     socket_map.find(s);
246
247   if(it == socket_map.end()) {
248     fprintf(MSG_OUT, "\nsocket %d is a c-ares socket, ignoring", s);
249     return;
250   }
251
252   boost::asio::ip::tcp::socket * tcp_socket = it->second;
253
254   *fdp = act;
255
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));
262     }
263   }
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));
270     }
271   }
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));
278     }
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));
283     }
284   }
285 }
286
287 static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
288 {
289   /* fdp is used to store current action */
290   int *fdp = (int *) calloc(sizeof(int), 1);
291
292   setsock(fdp, s, easy, action, 0, g);
293   curl_multi_assign(g->multi, s, fdp);
294 }
295
296 /* CURLMOPT_SOCKETFUNCTION */
297 static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
298 {
299   fprintf(MSG_OUT, "\nsock_cb: socket=%d, what=%d, sockp=%p", s, what, sockp);
300
301   GlobalInfo *g = (GlobalInfo*) cbp;
302   int *actionp = (int *) sockp;
303   const char *whatstr[] = { "none", "IN", "OUT", "INOUT", "REMOVE"};
304
305   fprintf(MSG_OUT,
306           "\nsocket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
307
308   if(what == CURL_POLL_REMOVE) {
309     fprintf(MSG_OUT, "\n");
310     remsock(actionp, g);
311   }
312   else {
313     if(!actionp) {
314       fprintf(MSG_OUT, "\nAdding data: %s", whatstr[what]);
315       addsock(s, e, what, g);
316     }
317     else {
318       fprintf(MSG_OUT,
319               "\nChanging action from %s to %s",
320               whatstr[*actionp], whatstr[what]);
321       setsock(actionp, s, e, what, *actionp, g);
322     }
323   }
324
325   return 0;
326 }
327
328 /* CURLOPT_WRITEFUNCTION */
329 static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
330 {
331   size_t written = size * nmemb;
332   char *pBuffer = (char *)malloc(written + 1);
333
334   strncpy(pBuffer, (const char *)ptr, written);
335   pBuffer[written] = '\0';
336
337   fprintf(MSG_OUT, "%s", pBuffer);
338
339   free(pBuffer);
340
341   return written;
342 }
343
344 /* CURLOPT_PROGRESSFUNCTION */
345 static int prog_cb(void *p, double dltotal, double dlnow, double ult,
346                    double uln)
347 {
348   ConnInfo *conn = (ConnInfo *)p;
349
350   (void)ult;
351   (void)uln;
352
353   fprintf(MSG_OUT, "\nProgress: %s (%g/%g)", conn->url, dlnow, dltotal);
354   fprintf(MSG_OUT, "\nProgress: %s (%g)", conn->url, ult);
355
356   return 0;
357 }
358
359 /* CURLOPT_OPENSOCKETFUNCTION */
360 static curl_socket_t opensocket(void *clientp, curlsocktype purpose,
361                                 struct curl_sockaddr *address)
362 {
363   fprintf(MSG_OUT, "\nopensocket :");
364
365   curl_socket_t sockfd = CURL_SOCKET_BAD;
366
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);
372
373     /* open it and get the native handle*/
374     boost::system::error_code ec;
375     tcp_socket->open(boost::asio::ip::tcp::v4(), ec);
376
377     if(ec) {
378       /* An error occurred */
379       std::cout << std::endl << "Couldn't open socket [" << ec << "][" <<
380         ec.message() << "]";
381       fprintf(MSG_OUT, "\nERROR: Returning CURL_SOCKET_BAD to signal error");
382     }
383     else {
384       sockfd = tcp_socket->native_handle();
385       fprintf(MSG_OUT, "\nOpened socket %d", sockfd);
386
387       /* save it for monitoring */
388       socket_map.insert(std::pair<curl_socket_t,
389                         boost::asio::ip::tcp::socket *>(sockfd, tcp_socket));
390     }
391   }
392
393   return sockfd;
394 }
395
396 /* CURLOPT_CLOSESOCKETFUNCTION */
397 static int close_socket(void *clientp, curl_socket_t item)
398 {
399   fprintf(MSG_OUT, "\nclose_socket : %d", item);
400
401   std::map<curl_socket_t, boost::asio::ip::tcp::socket *>::iterator it =
402     socket_map.find(item);
403
404   if(it != socket_map.end()) {
405     delete it->second;
406     socket_map.erase(it);
407   }
408
409   return 0;
410 }
411
412 /* Create a new easy handle, and add it to the global curl_multi */
413 static void new_conn(char *url, GlobalInfo *g)
414 {
415   ConnInfo *conn;
416   CURLMcode rc;
417
418   conn = (ConnInfo *) calloc(1, sizeof(ConnInfo));
419
420   conn->easy = curl_easy_init();
421   if(!conn->easy) {
422     fprintf(MSG_OUT, "\ncurl_easy_init() failed, exiting!");
423     exit(2);
424   }
425
426   conn->global = g;
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);
439
440   /* call this function to get a socket */
441   curl_easy_setopt(conn->easy, CURLOPT_OPENSOCKETFUNCTION, opensocket);
442
443   /* call this function to close a socket */
444   curl_easy_setopt(conn->easy, CURLOPT_CLOSESOCKETFUNCTION, close_socket);
445
446   fprintf(MSG_OUT,
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);
450
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 */
453 }
454
455 int main(int argc, char **argv)
456 {
457   GlobalInfo g;
458
459   (void)argc;
460   (void)argv;
461
462   memset(&g, 0, sizeof(GlobalInfo));
463   g.multi = curl_multi_init();
464
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);
469
470   new_conn((char *)"www.google.com", &g);  /* add a URL */
471
472   /* enter io_service run loop */
473   io_service.run();
474
475   curl_multi_cleanup(g.multi);
476
477   fprintf(MSG_OUT, "\ndone.\n");
478
479   return 0;
480 }