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