blob: ea0cdb18533335f22149414419a2719e90f09f76 [file] [log] [blame]
xf.li6c8fc1e2023-08-12 00:11:09 -07001/***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
7 *
8 * Copyright (C) 1998 - 2022, 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
31Written by Jeff Pohlmeyer
32
33Requires libevent version 2 and a (POSIX?) system that has mkfifo().
34
35This is an adaptation of libcurl's "hipev.c" and libevent's "event-test.c"
36sample programs.
37
38When running, the program creates the named pipe "hiper.fifo"
39
40Whenever there is input into the fifo, the program reads the input as a list
41of URL's and creates some new easy handles to fetch each URL via the
42curl_multi "hiper" API.
43
44
45Thus, you can try a single URL:
46 % echo http://www.yahoo.com > hiper.fifo
47
48Or a whole bunch of them:
49 % cat my-url-list > hiper.fifo
50
51The fifo buffer is handled almost instantly, so you can even add more URL's
52while the previous requests are still being downloaded.
53
54Note:
55 For the sake of simplicity, URL length is limited to 1023 char's !
56
57This is purely a demo app, all retrieved data is simply discarded by the write
58callback.
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 */
81typedef 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 */
94typedef 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 */
104typedef 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 */
118static 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 */
142static 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 */
166static 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 */
196static 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 */
220static 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 */
236static 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 */
249static 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, kind, event_cb, g);
263 event_add(&f->ev, NULL);
264}
265
266
267
268/* Initialize a new SockInfo structure */
269static 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 */
279static 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 */
309static 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 */
318static int prog_cb(void *p, double dltotal, double dlnow, double ult,
319 double uln)
320{
321 ConnInfo *conn = (ConnInfo *)p;
322 (void)ult;
323 (void)uln;
324
325 fprintf(MSG_OUT, "Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal);
326 return 0;
327}
328
329
330/* Create a new easy handle, and add it to the global curl_multi */
331static void new_conn(char *url, GlobalInfo *g)
332{
333 ConnInfo *conn;
334 CURLMcode rc;
335
336 conn = calloc(1, sizeof(ConnInfo));
337 conn->error[0]='\0';
338
339 conn->easy = curl_easy_init();
340 if(!conn->easy) {
341 fprintf(MSG_OUT, "curl_easy_init() failed, exiting!\n");
342 exit(2);
343 }
344 conn->global = g;
345 conn->url = strdup(url);
346 curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
347 curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
348 curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn);
349 curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
350 curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
351 curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
352 curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L);
353 curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
354 curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
355 curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
356 fprintf(MSG_OUT,
357 "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
358 rc = curl_multi_add_handle(g->multi, conn->easy);
359 mcode_or_die("new_conn: curl_multi_add_handle", rc);
360
361 /* note that the add_handle() will set a time-out to trigger very soon so
362 that the necessary socket_action() call will be called by this app */
363}
364
365/* This gets called whenever data is received from the fifo */
366static void fifo_cb(int fd, short event, void *arg)
367{
368 char s[1024];
369 long int rv = 0;
370 int n = 0;
371 GlobalInfo *g = (GlobalInfo *)arg;
372 (void)fd;
373 (void)event;
374
375 do {
376 s[0]='\0';
377 rv = fscanf(g->input, "%1023s%n", s, &n);
378 s[n]='\0';
379 if(n && s[0]) {
380 if(!strcmp(s, "stop")) {
381 g->stopped = 1;
382 if(g->still_running == 0)
383 event_base_loopbreak(g->evbase);
384 }
385 else
386 new_conn(s, arg); /* if we read a URL, go get it! */
387 }
388 else
389 break;
390 } while(rv != EOF);
391}
392
393/* Create a named pipe and tell libevent to monitor it */
394static const char *fifo = "hiper.fifo";
395static int init_fifo(GlobalInfo *g)
396{
397 struct stat st;
398 curl_socket_t sockfd;
399
400 fprintf(MSG_OUT, "Creating named pipe \"%s\"\n", fifo);
401 if(lstat (fifo, &st) == 0) {
402 if((st.st_mode & S_IFMT) == S_IFREG) {
403 errno = EEXIST;
404 perror("lstat");
405 exit(1);
406 }
407 }
408 unlink(fifo);
409 if(mkfifo (fifo, 0600) == -1) {
410 perror("mkfifo");
411 exit(1);
412 }
413 sockfd = open(fifo, O_RDWR | O_NONBLOCK, 0);
414 if(sockfd == -1) {
415 perror("open");
416 exit(1);
417 }
418 g->input = fdopen(sockfd, "r");
419
420 fprintf(MSG_OUT, "Now, pipe some URL's into > %s\n", fifo);
421 event_assign(&g->fifo_event, g->evbase, sockfd, EV_READ|EV_PERSIST,
422 fifo_cb, g);
423 event_add(&g->fifo_event, NULL);
424 return (0);
425}
426
427static void clean_fifo(GlobalInfo *g)
428{
429 event_del(&g->fifo_event);
430 fclose(g->input);
431 unlink(fifo);
432}
433
434int main(int argc, char **argv)
435{
436 GlobalInfo g;
437 (void)argc;
438 (void)argv;
439
440 memset(&g, 0, sizeof(GlobalInfo));
441 g.evbase = event_base_new();
442 init_fifo(&g);
443 g.multi = curl_multi_init();
444 evtimer_assign(&g.timer_event, g.evbase, timer_cb, &g);
445
446 /* setup the generic multi interface options we want */
447 curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
448 curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
449 curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
450 curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
451
452 /* we do not call any curl_multi_socket*() function yet as we have no handles
453 added! */
454
455 event_base_dispatch(g.evbase);
456
457 /* this, of course, will not get called since only way to stop this program
458 is via ctrl-C, but it is here to show how cleanup /would/ be done. */
459 clean_fifo(&g);
460 event_del(&g.timer_event);
461 event_base_free(g.evbase);
462 curl_multi_cleanup(g.multi);
463 return 0;
464}