• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2019, 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 /* <DESC>
23  * multi socket API usage with epoll and timerfd
24  * </DESC>
25  */
26 /* Example application source code using the multi socket interface to
27  * download many files at once.
28  *
29  * This example features the same basic functionality as hiperfifo.c does,
30  * but this uses epoll and timerfd instead of libevent.
31  *
32  * Written by Jeff Pohlmeyer, converted to use epoll by Josh Bialkowski
33 
34 Requires a linux system with epoll
35 
36 When running, the program creates the named pipe "hiper.fifo"
37 
38 Whenever there is input into the fifo, the program reads the input as a list
39 of URL's and creates some new easy handles to fetch each URL via the
40 curl_multi "hiper" API.
41 
42 
43 Thus, you can try a single URL:
44   % echo http://www.yahoo.com > hiper.fifo
45 
46 Or a whole bunch of them:
47   % cat my-url-list > hiper.fifo
48 
49 The fifo buffer is handled almost instantly, so you can even add more URL's
50 while the previous requests are still being downloaded.
51 
52 Note:
53   For the sake of simplicity, URL length is limited to 1023 char's !
54 
55 This is purely a demo app, all retrieved data is simply discarded by the write
56 callback.
57 
58 */
59 
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <signal.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <sys/epoll.h>
67 #include <sys/stat.h>
68 #include <sys/time.h>
69 #include <sys/timerfd.h>
70 #include <sys/types.h>
71 #include <time.h>
72 #include <unistd.h>
73 
74 #include <curl/curl.h>
75 
76 #ifdef __GNUC__
77 #define _Unused __attribute__((unused))
78 #else
79 #define _Unused
80 #endif
81 
82 #define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */
83 
84 
85 /* Global information, common to all connections */
86 typedef struct _GlobalInfo
87 {
88   int epfd;    /* epoll filedescriptor */
89   int tfd;     /* timer filedescriptor */
90   int fifofd;  /* fifo filedescriptor */
91   CURLM *multi;
92   int still_running;
93   FILE *input;
94 } GlobalInfo;
95 
96 
97 /* Information associated with a specific easy handle */
98 typedef struct _ConnInfo
99 {
100   CURL *easy;
101   char *url;
102   GlobalInfo *global;
103   char error[CURL_ERROR_SIZE];
104 } ConnInfo;
105 
106 
107 /* Information associated with a specific socket */
108 typedef struct _SockInfo
109 {
110   curl_socket_t sockfd;
111   CURL *easy;
112   int action;
113   long timeout;
114   GlobalInfo *global;
115 } SockInfo;
116 
117 #define __case(code) \
118   case code: s = __STRING(code)
119 
120 /* Die if we get a bad CURLMcode somewhere */
mcode_or_die(const char * where,CURLMcode code)121 static void mcode_or_die(const char *where, CURLMcode code)
122 {
123   if(CURLM_OK != code) {
124     const char *s;
125     switch(code) {
126       __case(CURLM_BAD_HANDLE); break;
127       __case(CURLM_BAD_EASY_HANDLE); break;
128       __case(CURLM_OUT_OF_MEMORY); break;
129       __case(CURLM_INTERNAL_ERROR); break;
130       __case(CURLM_UNKNOWN_OPTION); break;
131       __case(CURLM_LAST); break;
132       default: s = "CURLM_unknown"; break;
133       __case(CURLM_BAD_SOCKET);
134       fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s);
135       /* ignore this error */
136       return;
137     }
138     fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s);
139     exit(code);
140   }
141 }
142 
143 static void timer_cb(GlobalInfo* g, int revents);
144 
145 /* Update the timer after curl_multi library does it's thing. Curl will
146  * inform us through this callback what it wants the new timeout to be,
147  * after it does some work. */
multi_timer_cb(CURLM * multi,long timeout_ms,GlobalInfo * g)148 static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
149 {
150   struct itimerspec its;
151   CURLMcode rc;
152 
153   fprintf(MSG_OUT, "multi_timer_cb: Setting timeout to %ld ms\n", timeout_ms);
154 
155   if(timeout_ms > 0) {
156     its.it_interval.tv_sec = 1;
157     its.it_interval.tv_nsec = 0;
158     its.it_value.tv_sec = timeout_ms / 1000;
159     its.it_value.tv_nsec = (timeout_ms % 1000) * 1000 * 1000;
160   }
161   else if(timeout_ms == 0) {
162     /* libcurl wants us to timeout now, however setting both fields of
163      * new_value.it_value to zero disarms the timer. The closest we can
164      * do is to schedule the timer to fire in 1 ns. */
165     its.it_interval.tv_sec = 1;
166     its.it_interval.tv_nsec = 0;
167     its.it_value.tv_sec = 0;
168     its.it_value.tv_nsec = 1;
169   }
170   else {
171     memset(&its, 0, sizeof(struct itimerspec));
172   }
173 
174   timerfd_settime(g->tfd, /*flags=*/0, &its, NULL);
175   return 0;
176 }
177 
178 
179 /* Check for completed transfers, and remove their easy handles */
check_multi_info(GlobalInfo * g)180 static void check_multi_info(GlobalInfo *g)
181 {
182   char *eff_url;
183   CURLMsg *msg;
184   int msgs_left;
185   ConnInfo *conn;
186   CURL *easy;
187   CURLcode res;
188 
189   fprintf(MSG_OUT, "REMAINING: %d\n", g->still_running);
190   while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
191     if(msg->msg == CURLMSG_DONE) {
192       easy = msg->easy_handle;
193       res = msg->data.result;
194       curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
195       curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
196       fprintf(MSG_OUT, "DONE: %s => (%d) %s\n", eff_url, res, conn->error);
197       curl_multi_remove_handle(g->multi, easy);
198       free(conn->url);
199       curl_easy_cleanup(easy);
200       free(conn);
201     }
202   }
203 }
204 
205 /* Called by libevent when we get action on a multi socket filedescriptor*/
event_cb(GlobalInfo * g,int fd,int revents)206 static void event_cb(GlobalInfo *g, int fd, int revents)
207 {
208   CURLMcode rc;
209   struct itimerspec its;
210 
211   int action = (revents & EPOLLIN ? CURL_CSELECT_IN : 0) |
212                (revents & EPOLLOUT ? CURL_CSELECT_OUT : 0);
213 
214   rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running);
215   mcode_or_die("event_cb: curl_multi_socket_action", rc);
216 
217   check_multi_info(g);
218   if(g->still_running <= 0) {
219     fprintf(MSG_OUT, "last transfer done, kill timeout\n");
220     memset(&its, 0, sizeof(struct itimerspec));
221     timerfd_settime(g->tfd, 0, &its, NULL);
222   }
223 }
224 
225 /* Called by main loop when our timeout expires */
timer_cb(GlobalInfo * g,int revents)226 static void timer_cb(GlobalInfo* g, int revents)
227 {
228   CURLMcode rc;
229   uint64_t count = 0;
230   ssize_t err = 0;
231 
232   err = read(g->tfd, &count, sizeof(uint64_t));
233   if(err == -1) {
234     /* Note that we may call the timer callback even if the timerfd isn't
235      * readable. It's possible that there are multiple events stored in the
236      * epoll buffer (i.e. the timer may have fired multiple times). The
237      * event count is cleared after the first call so future events in the
238      * epoll buffer will fail to read from the timer. */
239     if(errno == EAGAIN) {
240       fprintf(MSG_OUT, "EAGAIN on tfd %d\n", g->tfd);
241       return;
242     }
243   }
244   if(err != sizeof(uint64_t)) {
245     fprintf(stderr, "read(tfd) == %ld", err);
246     perror("read(tfd)");
247   }
248 
249   rc = curl_multi_socket_action(g->multi,
250                                   CURL_SOCKET_TIMEOUT, 0, &g->still_running);
251   mcode_or_die("timer_cb: curl_multi_socket_action", rc);
252   check_multi_info(g);
253 }
254 
255 
256 
257 /* Clean up the SockInfo structure */
remsock(SockInfo * f,GlobalInfo * g)258 static void remsock(SockInfo *f, GlobalInfo* g)
259 {
260   if(f) {
261     if(f->sockfd) {
262       if(epoll_ctl(g->epfd, EPOLL_CTL_DEL, f->sockfd, NULL))
263         fprintf(stderr, "EPOLL_CTL_DEL failed for fd: %d : %s\n",
264                 f->sockfd, strerror(errno));
265     }
266     free(f);
267   }
268 }
269 
270 
271 
272 /* Assign information to a SockInfo structure */
setsock(SockInfo * f,curl_socket_t s,CURL * e,int act,GlobalInfo * g)273 static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act,
274                     GlobalInfo *g)
275 {
276   struct epoll_event ev;
277   int kind = (act & CURL_POLL_IN ? EPOLLIN : 0) |
278              (act & CURL_POLL_OUT ? EPOLLOUT : 0);
279 
280   if(f->sockfd) {
281     if(epoll_ctl(g->epfd, EPOLL_CTL_DEL, f->sockfd, NULL))
282       fprintf(stderr, "EPOLL_CTL_DEL failed for fd: %d : %s\n",
283               f->sockfd, strerror(errno));
284   }
285 
286   f->sockfd = s;
287   f->action = act;
288   f->easy = e;
289 
290   ev.events = kind;
291   ev.data.fd = s;
292   if(epoll_ctl(g->epfd, EPOLL_CTL_ADD, s, &ev))
293     fprintf(stderr, "EPOLL_CTL_ADD failed for fd: %d : %s\n",
294             s, strerror(errno));
295 }
296 
297 
298 
299 /* Initialize a new SockInfo structure */
addsock(curl_socket_t s,CURL * easy,int action,GlobalInfo * g)300 static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
301 {
302   SockInfo *fdp = (SockInfo*)calloc(sizeof(SockInfo), 1);
303 
304   fdp->global = g;
305   setsock(fdp, s, easy, action, g);
306   curl_multi_assign(g->multi, s, fdp);
307 }
308 
309 /* CURLMOPT_SOCKETFUNCTION */
sock_cb(CURL * e,curl_socket_t s,int what,void * cbp,void * sockp)310 static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
311 {
312   GlobalInfo *g = (GlobalInfo*) cbp;
313   SockInfo *fdp = (SockInfo*) sockp;
314   const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" };
315 
316   fprintf(MSG_OUT,
317           "socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
318   if(what == CURL_POLL_REMOVE) {
319     fprintf(MSG_OUT, "\n");
320     remsock(fdp, g);
321   }
322   else {
323     if(!fdp) {
324       fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]);
325       addsock(s, e, what, g);
326     }
327     else {
328       fprintf(MSG_OUT,
329               "Changing action from %s to %s\n",
330               whatstr[fdp->action], whatstr[what]);
331       setsock(fdp, s, e, what, g);
332     }
333   }
334   return 0;
335 }
336 
337 
338 
339 /* CURLOPT_WRITEFUNCTION */
write_cb(void * ptr _Unused,size_t size,size_t nmemb,void * data)340 static size_t write_cb(void *ptr _Unused, size_t size, size_t nmemb,
341                        void *data)
342 {
343   size_t realsize = size * nmemb;
344   ConnInfo *conn _Unused = (ConnInfo*) data;
345 
346   return realsize;
347 }
348 
349 
350 /* CURLOPT_PROGRESSFUNCTION */
prog_cb(void * p,double dltotal,double dlnow,double ult _Unused,double uln _Unused)351 static int prog_cb(void *p, double dltotal, double dlnow, double ult _Unused,
352                    double uln _Unused)
353 {
354   ConnInfo *conn = (ConnInfo *)p;
355 
356   fprintf(MSG_OUT, "Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal);
357   return 0;
358 }
359 
360 
361 /* Create a new easy handle, and add it to the global curl_multi */
new_conn(char * url,GlobalInfo * g)362 static void new_conn(char *url, GlobalInfo *g)
363 {
364   ConnInfo *conn;
365   CURLMcode rc;
366 
367   conn = (ConnInfo*)calloc(1, sizeof(ConnInfo));
368   conn->error[0]='\0';
369 
370   conn->easy = curl_easy_init();
371   if(!conn->easy) {
372     fprintf(MSG_OUT, "curl_easy_init() failed, exiting!\n");
373     exit(2);
374   }
375   conn->global = g;
376   conn->url = strdup(url);
377   curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
378   curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
379   curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn);
380   curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
381   curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
382   curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
383   curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L);
384   curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
385   curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
386   curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
387   curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L);
388   curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L);
389   fprintf(MSG_OUT,
390           "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
391   rc = curl_multi_add_handle(g->multi, conn->easy);
392   mcode_or_die("new_conn: curl_multi_add_handle", rc);
393 
394   /* note that the add_handle() will set a time-out to trigger very soon so
395      that the necessary socket_action() call will be called by this app */
396 }
397 
398 /* This gets called whenever data is received from the fifo */
fifo_cb(GlobalInfo * g,int revents)399 static void fifo_cb(GlobalInfo* g, int revents)
400 {
401   char s[1024];
402   long int rv = 0;
403   int n = 0;
404 
405   do {
406     s[0]='\0';
407     rv = fscanf(g->input, "%1023s%n", s, &n);
408     s[n]='\0';
409     if(n && s[0]) {
410       new_conn(s, g); /* if we read a URL, go get it! */
411     }
412     else
413       break;
414   } while(rv != EOF);
415 }
416 
417 /* Create a named pipe and tell libevent to monitor it */
418 static const char *fifo = "hiper.fifo";
init_fifo(GlobalInfo * g)419 static int init_fifo(GlobalInfo *g)
420 {
421   struct stat st;
422   curl_socket_t sockfd;
423   struct epoll_event epev;
424 
425   fprintf(MSG_OUT, "Creating named pipe \"%s\"\n", fifo);
426   if(lstat (fifo, &st) == 0) {
427     if((st.st_mode & S_IFMT) == S_IFREG) {
428       errno = EEXIST;
429       perror("lstat");
430       exit(1);
431     }
432   }
433   unlink(fifo);
434   if(mkfifo (fifo, 0600) == -1) {
435     perror("mkfifo");
436     exit(1);
437   }
438   sockfd = open(fifo, O_RDWR | O_NONBLOCK, 0);
439   if(sockfd == -1) {
440     perror("open");
441     exit(1);
442   }
443 
444   g->fifofd = sockfd;
445   g->input = fdopen(sockfd, "r");
446 
447   epev.events = EPOLLIN;
448   epev.data.fd = sockfd;
449   epoll_ctl(g->epfd, EPOLL_CTL_ADD, sockfd, &epev);
450 
451   fprintf(MSG_OUT, "Now, pipe some URL's into > %s\n", fifo);
452   return 0;
453 }
454 
clean_fifo(GlobalInfo * g)455 static void clean_fifo(GlobalInfo *g)
456 {
457     epoll_ctl(g->epfd, EPOLL_CTL_DEL, g->fifofd, NULL);
458     fclose(g->input);
459     unlink(fifo);
460 }
461 
462 
463 int g_should_exit_ = 0;
464 
SignalHandler(int signo)465 void SignalHandler(int signo)
466 {
467   if(signo == SIGINT) {
468     g_should_exit_ = 1;
469   }
470 }
471 
main(int argc _Unused,char ** argv _Unused)472 int main(int argc _Unused, char **argv _Unused)
473 {
474   GlobalInfo g;
475   int err;
476   int idx;
477   struct itimerspec its;
478   struct epoll_event ev;
479   struct epoll_event events[10];
480 
481   g_should_exit_ = 0;
482   signal(SIGINT, SignalHandler);
483 
484   memset(&g, 0, sizeof(GlobalInfo));
485   g.epfd = epoll_create1(EPOLL_CLOEXEC);
486   if(g.epfd == -1) {
487     perror("epoll_create1 failed");
488     exit(1);
489   }
490 
491   g.tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
492   if(g.tfd == -1) {
493     perror("timerfd_create failed");
494     exit(1);
495   }
496 
497   memset(&its, 0, sizeof(struct itimerspec));
498   its.it_interval.tv_sec = 1;
499   its.it_value.tv_sec = 1;
500   timerfd_settime(g.tfd, 0, &its, NULL);
501 
502   ev.events = EPOLLIN;
503   ev.data.fd = g.tfd;
504   epoll_ctl(g.epfd, EPOLL_CTL_ADD, g.tfd, &ev);
505 
506   init_fifo(&g);
507   g.multi = curl_multi_init();
508 
509   /* setup the generic multi interface options we want */
510   curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
511   curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
512   curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
513   curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
514 
515   /* we don't call any curl_multi_socket*() function yet as we have no handles
516      added! */
517 
518   fprintf(MSG_OUT, "Entering wait loop\n");
519   fflush(MSG_OUT);
520   while(!g_should_exit_) {
521     /* TODO(josh): use epoll_pwait to avoid a race on the signal. Mask the
522      * signal before the while loop, and then re-enable the signal during
523      * epoll wait. Mask at the end of the loop. */
524     err = epoll_wait(g.epfd, events, sizeof(events)/sizeof(struct epoll_event),
525                      10000);
526     if(err == -1) {
527       if(errno == EINTR) {
528         fprintf(MSG_OUT, "note: wait interrupted\n");
529         continue;
530       }
531       else {
532         perror("epoll_wait");
533         exit(1);
534       }
535     }
536 
537     for(idx = 0; idx < err; ++idx) {
538       if(events[idx].data.fd == g.fifofd) {
539         fifo_cb(&g, events[idx].events);
540       }
541       else if(events[idx].data.fd == g.tfd) {
542         timer_cb(&g, events[idx].events);
543       }
544       else {
545         event_cb(&g, events[idx].data.fd, events[idx].events);
546       }
547     }
548   }
549 
550   fprintf(MSG_OUT, "Exiting normally.\n");
551   fflush(MSG_OUT);
552 
553   curl_multi_cleanup(g.multi);
554   return 0;
555 }
556