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