xref: /curl/docs/examples/hiperfifo.c (revision 37fb50a8)
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 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.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  * SPDX-License-Identifier: curl
22  *
23  ***************************************************************************/
24 /* <DESC>
25  * multi socket API usage with libevent 2
26  * </DESC>
27  */
28 /* Example application source code using the multi socket interface to
29    download many files at once.
30 
31 Written by Jeff Pohlmeyer
32 
33 Requires libevent version 2 and a (POSIX?) system that has mkfifo().
34 
35 This is an adaptation of libcurl's "hipev.c" and libevent's "event-test.c"
36 sample programs.
37 
38 When running, the program creates the named pipe "hiper.fifo"
39 
40 Whenever there is input into the fifo, the program reads the input as a list
41 of URL's and creates some new easy handles to fetch each URL via the
42 curl_multi "hiper" API.
43 
44 
45 Thus, you can try a single URL:
46   % echo http://www.yahoo.com > hiper.fifo
47 
48 Or a whole bunch of them:
49   % cat my-url-list > hiper.fifo
50 
51 The fifo buffer is handled almost instantly, so you can even add more URL's
52 while the previous requests are still being downloaded.
53 
54 Note:
55   For the sake of simplicity, URL length is limited to 1023 char's !
56 
57 This is purely a demo app, all retrieved data is simply discarded by the write
58 callback.
59 
60 */
61 
62 #include <stdio.h>
63 #include <string.h>
64 #include <stdlib.h>
65 #include <sys/time.h>
66 #include <time.h>
67 #include <unistd.h>
68 #include <sys/poll.h>
69 #include <curl/curl.h>
70 #include <event2/event.h>
71 #include <event2/event_struct.h>
72 #include <fcntl.h>
73 #include <sys/stat.h>
74 #include <errno.h>
75 #include <sys/cdefs.h>
76 
77 #define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */
78 
79 
80 /* Global information, common to all connections */
81 typedef struct _GlobalInfo
82 {
83   struct event_base *evbase;
84   struct event fifo_event;
85   struct event timer_event;
86   CURLM *multi;
87   int still_running;
88   FILE *input;
89   int stopped;
90 } GlobalInfo;
91 
92 
93 /* Information associated with a specific easy handle */
94 typedef struct _ConnInfo
95 {
96   CURL *easy;
97   char *url;
98   GlobalInfo *global;
99   char error[CURL_ERROR_SIZE];
100 } ConnInfo;
101 
102 
103 /* Information associated with a specific socket */
104 typedef struct _SockInfo
105 {
106   curl_socket_t sockfd;
107   CURL *easy;
108   int action;
109   long timeout;
110   struct event ev;
111   GlobalInfo *global;
112 } SockInfo;
113 
114 #define mycase(code) \
115   case code: s = __STRING(code)
116 
117 /* Die if we get a bad CURLMcode somewhere */
mcode_or_die(const char * where,CURLMcode code)118 static void mcode_or_die(const char *where, CURLMcode code)
119 {
120   if(CURLM_OK != code) {
121     const char *s;
122     switch(code) {
123       mycase(CURLM_BAD_HANDLE); break;
124       mycase(CURLM_BAD_EASY_HANDLE); break;
125       mycase(CURLM_OUT_OF_MEMORY); break;
126       mycase(CURLM_INTERNAL_ERROR); break;
127       mycase(CURLM_UNKNOWN_OPTION); break;
128       mycase(CURLM_LAST); break;
129       default: s = "CURLM_unknown"; break;
130       mycase(CURLM_BAD_SOCKET);
131       fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s);
132       /* ignore this error */
133       return;
134     }
135     fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s);
136     exit(code);
137   }
138 }
139 
140 
141 /* Update the event timer after curl_multi library calls */
multi_timer_cb(CURLM * multi,long timeout_ms,GlobalInfo * g)142 static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
143 {
144   struct timeval timeout;
145   (void)multi;
146 
147   timeout.tv_sec = timeout_ms/1000;
148   timeout.tv_usec = (timeout_ms%1000)*1000;
149   fprintf(MSG_OUT, "multi_timer_cb: Setting timeout to %ld ms\n", timeout_ms);
150 
151   /*
152    * if timeout_ms is -1, just delete the timer
153    *
154    * For all other values of timeout_ms, this should set or *update* the timer
155    * to the new value
156    */
157   if(timeout_ms == -1)
158     evtimer_del(&g->timer_event);
159   else /* includes timeout zero */
160     evtimer_add(&g->timer_event, &timeout);
161   return 0;
162 }
163 
164 
165 /* Check for completed transfers, and remove their easy handles */
check_multi_info(GlobalInfo * g)166 static void check_multi_info(GlobalInfo *g)
167 {
168   char *eff_url;
169   CURLMsg *msg;
170   int msgs_left;
171   ConnInfo *conn;
172   CURL *easy;
173   CURLcode res;
174 
175   fprintf(MSG_OUT, "REMAINING: %d\n", g->still_running);
176   while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
177     if(msg->msg == CURLMSG_DONE) {
178       easy = msg->easy_handle;
179       res = msg->data.result;
180       curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
181       curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
182       fprintf(MSG_OUT, "DONE: %s => (%d) %s\n", eff_url, res, conn->error);
183       curl_multi_remove_handle(g->multi, easy);
184       free(conn->url);
185       curl_easy_cleanup(easy);
186       free(conn);
187     }
188   }
189   if(g->still_running == 0 && g->stopped)
190     event_base_loopbreak(g->evbase);
191 }
192 
193 
194 
195 /* Called by libevent when we get action on a multi socket */
event_cb(int fd,short kind,void * userp)196 static void event_cb(int fd, short kind, void *userp)
197 {
198   GlobalInfo *g = (GlobalInfo*) userp;
199   CURLMcode rc;
200 
201   int action =
202     ((kind & EV_READ) ? CURL_CSELECT_IN : 0) |
203     ((kind & EV_WRITE) ? CURL_CSELECT_OUT : 0);
204 
205   rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running);
206   mcode_or_die("event_cb: curl_multi_socket_action", rc);
207 
208   check_multi_info(g);
209   if(g->still_running <= 0) {
210     fprintf(MSG_OUT, "last transfer done, kill timeout\n");
211     if(evtimer_pending(&g->timer_event, NULL)) {
212       evtimer_del(&g->timer_event);
213     }
214   }
215 }
216 
217 
218 
219 /* Called by libevent when our timeout expires */
timer_cb(int fd,short kind,void * userp)220 static void timer_cb(int fd, short kind, void *userp)
221 {
222   GlobalInfo *g = (GlobalInfo *)userp;
223   CURLMcode rc;
224   (void)fd;
225   (void)kind;
226 
227   rc = curl_multi_socket_action(g->multi,
228                                   CURL_SOCKET_TIMEOUT, 0, &g->still_running);
229   mcode_or_die("timer_cb: curl_multi_socket_action", rc);
230   check_multi_info(g);
231 }
232 
233 
234 
235 /* Clean up the SockInfo structure */
remsock(SockInfo * f)236 static void remsock(SockInfo *f)
237 {
238   if(f) {
239     if(event_initialized(&f->ev)) {
240       event_del(&f->ev);
241     }
242     free(f);
243   }
244 }
245 
246 
247 
248 /* Assign information to a SockInfo structure */
setsock(SockInfo * f,curl_socket_t s,CURL * e,int act,GlobalInfo * g)249 static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act,
250                     GlobalInfo *g)
251 {
252   int kind =
253      ((act & CURL_POLL_IN) ? EV_READ : 0) |
254      ((act & CURL_POLL_OUT) ? EV_WRITE : 0) | EV_PERSIST;
255 
256   f->sockfd = s;
257   f->action = act;
258   f->easy = e;
259   if(event_initialized(&f->ev)) {
260     event_del(&f->ev);
261   }
262   event_assign(&f->ev, g->evbase, f->sockfd, (short)kind, event_cb, g);
263   event_add(&f->ev, NULL);
264 }
265 
266 
267 
268 /* Initialize a new SockInfo structure */
addsock(curl_socket_t s,CURL * easy,int action,GlobalInfo * g)269 static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
270 {
271   SockInfo *fdp = calloc(1, sizeof(SockInfo));
272 
273   fdp->global = g;
274   setsock(fdp, s, easy, action, g);
275   curl_multi_assign(g->multi, s, fdp);
276 }
277 
278 /* CURLMOPT_SOCKETFUNCTION */
sock_cb(CURL * e,curl_socket_t s,int what,void * cbp,void * sockp)279 static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
280 {
281   GlobalInfo *g = (GlobalInfo*) cbp;
282   SockInfo *fdp = (SockInfo*) sockp;
283   const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" };
284 
285   fprintf(MSG_OUT,
286           "socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
287   if(what == CURL_POLL_REMOVE) {
288     fprintf(MSG_OUT, "\n");
289     remsock(fdp);
290   }
291   else {
292     if(!fdp) {
293       fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]);
294       addsock(s, e, what, g);
295     }
296     else {
297       fprintf(MSG_OUT,
298               "Changing action from %s to %s\n",
299               whatstr[fdp->action], whatstr[what]);
300       setsock(fdp, s, e, what, g);
301     }
302   }
303   return 0;
304 }
305 
306 
307 
308 /* CURLOPT_WRITEFUNCTION */
write_cb(void * ptr,size_t size,size_t nmemb,void * data)309 static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
310 {
311   (void)ptr;
312   (void)data;
313   return size * nmemb;
314 }
315 
316 
317 /* CURLOPT_PROGRESSFUNCTION */
xferinfo_cb(void * p,curl_off_t dltotal,curl_off_t dlnow,curl_off_t ult,curl_off_t uln)318 static int xferinfo_cb(void *p, curl_off_t dltotal, curl_off_t dlnow,
319                        curl_off_t ult, curl_off_t uln)
320 {
321   ConnInfo *conn = (ConnInfo *)p;
322   (void)ult;
323   (void)uln;
324 
325   fprintf(MSG_OUT, "Progress: %s (%" CURL_FORMAT_CURL_OFF_T
326           "/%" CURL_FORMAT_CURL_OFF_T ")\n", conn->url, dlnow, dltotal);
327   return 0;
328 }
329 
330 
331 /* Create a new easy handle, and add it to the global curl_multi */
new_conn(const char * url,GlobalInfo * g)332 static void new_conn(const char *url, GlobalInfo *g)
333 {
334   ConnInfo *conn;
335   CURLMcode rc;
336 
337   conn = calloc(1, sizeof(ConnInfo));
338   conn->error[0] = '\0';
339 
340   conn->easy = curl_easy_init();
341   if(!conn->easy) {
342     fprintf(MSG_OUT, "curl_easy_init() failed, exiting!\n");
343     exit(2);
344   }
345   conn->global = g;
346   conn->url = strdup(url);
347   curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
348   curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
349   curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn);
350   curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
351   curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
352   curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
353   curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L);
354   curl_easy_setopt(conn->easy, CURLOPT_XFERINFOFUNCTION, xferinfo_cb);
355   curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
356   curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
357   fprintf(MSG_OUT,
358           "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
359   rc = curl_multi_add_handle(g->multi, conn->easy);
360   mcode_or_die("new_conn: curl_multi_add_handle", rc);
361 
362   /* note that the add_handle() sets a time-out to trigger soon so that
363      the necessary socket_action() gets called */
364 }
365 
366 /* This gets called whenever data is received from the fifo */
fifo_cb(int fd,short event,void * arg)367 static void fifo_cb(int fd, short event, void *arg)
368 {
369   char s[1024];
370   long int rv = 0;
371   int n = 0;
372   GlobalInfo *g = (GlobalInfo *)arg;
373   (void)fd;
374   (void)event;
375 
376   do {
377     s[0]='\0';
378     rv = fscanf(g->input, "%1023s%n", s, &n);
379     s[n]='\0';
380     if(n && s[0]) {
381       if(!strcmp(s, "stop")) {
382         g->stopped = 1;
383         if(g->still_running == 0)
384           event_base_loopbreak(g->evbase);
385       }
386       else
387         new_conn(s, arg);  /* if we read a URL, go get it! */
388     }
389     else
390       break;
391   } while(rv != EOF);
392 }
393 
394 /* Create a named pipe and tell libevent to monitor it */
395 static const char *fifo = "hiper.fifo";
init_fifo(GlobalInfo * g)396 static int init_fifo(GlobalInfo *g)
397 {
398   struct stat st;
399   curl_socket_t sockfd;
400 
401   fprintf(MSG_OUT, "Creating named pipe \"%s\"\n", fifo);
402   if(lstat (fifo, &st) == 0) {
403     if((st.st_mode & S_IFMT) == S_IFREG) {
404       errno = EEXIST;
405       perror("lstat");
406       exit(1);
407     }
408   }
409   unlink(fifo);
410   if(mkfifo (fifo, 0600) == -1) {
411     perror("mkfifo");
412     exit(1);
413   }
414   sockfd = open(fifo, O_RDWR | O_NONBLOCK, 0);
415   if(sockfd == -1) {
416     perror("open");
417     exit(1);
418   }
419   g->input = fdopen(sockfd, "r");
420 
421   fprintf(MSG_OUT, "Now, pipe some URL's into > %s\n", fifo);
422   event_assign(&g->fifo_event, g->evbase, sockfd, EV_READ|EV_PERSIST,
423                fifo_cb, g);
424   event_add(&g->fifo_event, NULL);
425   return (0);
426 }
427 
clean_fifo(GlobalInfo * g)428 static void clean_fifo(GlobalInfo *g)
429 {
430     event_del(&g->fifo_event);
431     fclose(g->input);
432     unlink(fifo);
433 }
434 
main(int argc,char ** argv)435 int main(int argc, char **argv)
436 {
437   GlobalInfo g;
438   (void)argc;
439   (void)argv;
440 
441   memset(&g, 0, sizeof(GlobalInfo));
442   g.evbase = event_base_new();
443   init_fifo(&g);
444   g.multi = curl_multi_init();
445   evtimer_assign(&g.timer_event, g.evbase, timer_cb, &g);
446 
447   /* setup the generic multi interface options we want */
448   curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
449   curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
450   curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
451   curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
452 
453   /* we do not call any curl_multi_socket*() function yet as we have no handles
454      added! */
455 
456   event_base_dispatch(g.evbase);
457 
458   /* this, of course, does not get called since the only way to stop this
459      program is via ctrl-C, but it is here to show how cleanup /would/ be
460      done. */
461   clean_fifo(&g);
462   event_del(&g.timer_event);
463   event_base_free(g.evbase);
464   curl_multi_cleanup(g.multi);
465   return 0;
466 }
467