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