ghiper.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*****************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * $Id$
  9. *
  10. * Example application source code using the multi socket interface to
  11. * download many files at once.
  12. *
  13. * Written by Jeff Pohlmeyer
  14. Requires glib-2.x and a (POSIX?) system that has mkfifo().
  15. This is an adaptation of libcurl's "hipev.c" and libevent's "event-test.c"
  16. sample programs, adapted to use glib's g_io_channel in place of libevent.
  17. When running, the program creates the named pipe "hiper.fifo"
  18. Whenever there is input into the fifo, the program reads the input as a list
  19. of URL's and creates some new easy handles to fetch each URL via the
  20. curl_multi "hiper" API.
  21. Thus, you can try a single URL:
  22. % echo http://www.yahoo.com > hiper.fifo
  23. Or a whole bunch of them:
  24. % cat my-url-list > hiper.fifo
  25. The fifo buffer is handled almost instantly, so you can even add more URL's
  26. while the previous requests are still being downloaded.
  27. This is purely a demo app, all retrieved data is simply discarded by the write
  28. callback.
  29. */
  30. #include <glib.h>
  31. #include <sys/stat.h>
  32. #include <unistd.h>
  33. #include <fcntl.h>
  34. #include <stdlib.h>
  35. #include <stdio.h>
  36. #include <errno.h>
  37. #include <curl/curl.h>
  38. #define MSG_OUT g_print /* Change to "g_error" to write to stderr */
  39. #define SHOW_VERBOSE 0 /* Set to non-zero for libcurl messages */
  40. #define SHOW_PROGRESS 0 /* Set to non-zero to enable progress callback */
  41. /* Global information, common to all connections */
  42. typedef struct _GlobalInfo {
  43. CURLM *multi;
  44. guint timer_event;
  45. int prev_running;
  46. int still_running;
  47. int requested; /* count: curl_easy_init() */
  48. int completed; /* count: curl_easy_cleanup() */
  49. } GlobalInfo;
  50. /* Information associated with a specific easy handle */
  51. typedef struct _ConnInfo {
  52. CURL *easy;
  53. char *url;
  54. GlobalInfo *global;
  55. char error[CURL_ERROR_SIZE];
  56. } ConnInfo;
  57. /* Information associated with a specific socket */
  58. typedef struct _SockInfo {
  59. curl_socket_t sockfd;
  60. CURL *easy;
  61. int action;
  62. long timeout;
  63. GIOChannel *ch;
  64. guint ev;
  65. GlobalInfo *global;
  66. } SockInfo;
  67. /* Die if we get a bad CURLMcode somewhere */
  68. static void mcode_or_die(const char *where, CURLMcode code) {
  69. if ( CURLM_OK != code ) {
  70. const char *s;
  71. switch (code) {
  72. case CURLM_CALL_MULTI_PERFORM: s="CURLM_CALL_MULTI_PERFORM"; break;
  73. case CURLM_OK: s="CURLM_OK"; break;
  74. case CURLM_BAD_HANDLE: s="CURLM_BAD_HANDLE"; break;
  75. case CURLM_BAD_EASY_HANDLE: s="CURLM_BAD_EASY_HANDLE"; break;
  76. case CURLM_OUT_OF_MEMORY: s="CURLM_OUT_OF_MEMORY"; break;
  77. case CURLM_INTERNAL_ERROR: s="CURLM_INTERNAL_ERROR"; break;
  78. case CURLM_BAD_SOCKET: s="CURLM_BAD_SOCKET"; break;
  79. case CURLM_UNKNOWN_OPTION: s="CURLM_UNKNOWN_OPTION"; break;
  80. case CURLM_LAST: s="CURLM_LAST"; break;
  81. default: s="CURLM_unknown";
  82. }
  83. MSG_OUT("ERROR: %s returns %s\n", where, s);
  84. exit(code);
  85. }
  86. }
  87. /* Check for completed transfers, and remove their easy handles */
  88. static void check_run_count(GlobalInfo *g)
  89. {
  90. if (g->prev_running > g->still_running) {
  91. char *eff_url=NULL;
  92. CURLMsg *msg;
  93. int msgs_left;
  94. ConnInfo *conn=NULL;
  95. CURL*easy;
  96. CURLcode res;
  97. MSG_OUT("REMAINING: %d\n", g->still_running);
  98. /*
  99. I am still uncertain whether it is safe to remove an easy handle
  100. from inside the curl_multi_info_read loop, so here I will search
  101. for completed transfers in the inner "while" loop, and then remove
  102. them in the outer "do-while" loop...
  103. */
  104. do {
  105. easy=NULL;
  106. while ((msg = curl_multi_info_read(g->multi, &msgs_left))) {
  107. if (msg->msg == CURLMSG_DONE) {
  108. easy=msg->easy_handle;
  109. res=msg->data.result;
  110. break;
  111. }
  112. }
  113. if (easy) {
  114. curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
  115. curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
  116. MSG_OUT("DONE: %s => (%d) %s\n", eff_url, res, conn->error);
  117. curl_multi_remove_handle(g->multi, easy);
  118. g_free(conn->url);
  119. curl_easy_cleanup(easy);
  120. g_free(conn);
  121. g->completed++;
  122. }
  123. } while ( easy );
  124. MSG_OUT("Requested: %d Completed:%d\n", g->requested, g->completed);
  125. }
  126. g->prev_running = g->still_running;
  127. }
  128. /* Called by glib when our timeout expires */
  129. static gboolean timer_cb(gpointer data)
  130. {
  131. GlobalInfo *g = (GlobalInfo *)data;
  132. CURLMcode rc;
  133. do {
  134. rc = curl_multi_socket(g->multi, CURL_SOCKET_TIMEOUT, &g->still_running);
  135. } while (rc == CURLM_CALL_MULTI_PERFORM);
  136. mcode_or_die("timer_cb: curl_multi_socket", rc);
  137. check_run_count(g);
  138. return FALSE;
  139. }
  140. /* Update the event timer after curl_multi library calls */
  141. static int update_timeout_cb(CURLM *multi, long timeout_ms, void *userp)
  142. {
  143. struct timeval timeout;
  144. GlobalInfo *g=(GlobalInfo *)userp;
  145. timeout.tv_sec = timeout_ms/1000;
  146. timeout.tv_usec = (timeout_ms%1000)*1000;
  147. MSG_OUT("*** update_timeout_cb %ld => %ld:%ld ***\n",
  148. timeout_ms, timeout.tv_sec, timeout.tv_usec);
  149. g->timer_event = g_timeout_add(timeout_ms, timer_cb, g);
  150. return 0;
  151. }
  152. /* Called by glib when we get action on a multi socket */
  153. static gboolean event_cb(GIOChannel *ch, GIOCondition condition, gpointer data)
  154. {
  155. GlobalInfo *g = (GlobalInfo*) data;
  156. CURLMcode rc;
  157. int fd=g_io_channel_unix_get_fd(ch);
  158. do {
  159. rc = curl_multi_socket(g->multi, fd, &g->still_running);
  160. } while (rc == CURLM_CALL_MULTI_PERFORM);
  161. mcode_or_die("event_cb: curl_multi_socket", rc);
  162. check_run_count(g);
  163. if(g->still_running) {
  164. return TRUE;
  165. } else {
  166. MSG_OUT("last transfer done, kill timeout\n");
  167. if (g->timer_event) { g_source_remove(g->timer_event); }
  168. return FALSE;
  169. }
  170. }
  171. /* Clean up the SockInfo structure */
  172. static void remsock(SockInfo *f)
  173. {
  174. if (!f) { return; }
  175. if (f->ev) { g_source_remove(f->ev); }
  176. g_free(f);
  177. }
  178. /* Assign information to a SockInfo structure */
  179. static void setsock(SockInfo*f, curl_socket_t s, CURL*e, int act, GlobalInfo*g)
  180. {
  181. GIOCondition kind =
  182. (act&CURL_POLL_IN?G_IO_IN:0)|(act&CURL_POLL_OUT?G_IO_OUT:0);
  183. f->sockfd = s;
  184. f->action = act;
  185. f->easy = e;
  186. if (f->ev) { g_source_remove(f->ev); }
  187. f->ev=g_io_add_watch(f->ch, kind, event_cb,g);
  188. }
  189. /* Initialize a new SockInfo structure */
  190. static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
  191. {
  192. SockInfo *fdp = g_malloc0(sizeof(SockInfo));
  193. fdp->global = g;
  194. fdp->ch=g_io_channel_unix_new(s);
  195. setsock(fdp, s, easy, action, g);
  196. curl_multi_assign(g->multi, s, fdp);
  197. }
  198. /* CURLMOPT_SOCKETFUNCTION */
  199. static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
  200. {
  201. GlobalInfo *g = (GlobalInfo*) cbp;
  202. SockInfo *fdp = (SockInfo*) sockp;
  203. static const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" };
  204. MSG_OUT("socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
  205. if (what == CURL_POLL_REMOVE) {
  206. MSG_OUT("\n");
  207. remsock(fdp);
  208. } else {
  209. if (!fdp) {
  210. MSG_OUT("Adding data: %s%s\n",
  211. what&CURL_POLL_IN?"READ":"",
  212. what&CURL_POLL_OUT?"WRITE":"" );
  213. addsock(s, e, what, g);
  214. }
  215. else {
  216. MSG_OUT(
  217. "Changing action from %d to %d\n", fdp->action, what);
  218. setsock(fdp, s, e, what, g);
  219. }
  220. }
  221. return 0;
  222. }
  223. /* CURLOPT_WRITEFUNCTION */
  224. static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
  225. {
  226. size_t realsize = size * nmemb;
  227. ConnInfo *conn = (ConnInfo*) data;
  228. (void)ptr;
  229. (void)conn;
  230. return realsize;
  231. }
  232. /* CURLOPT_PROGRESSFUNCTION */
  233. static int prog_cb (void *p, double dltotal, double dlnow, double ult, double uln)
  234. {
  235. ConnInfo *conn = (ConnInfo *)p;
  236. MSG_OUT("Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal);
  237. return 0;
  238. }
  239. /* Create a new easy handle, and add it to the global curl_multi */
  240. static void new_conn(char *url, GlobalInfo *g )
  241. {
  242. ConnInfo *conn;
  243. CURLMcode rc;
  244. conn = g_malloc0(sizeof(ConnInfo));
  245. conn->error[0]='\0';
  246. conn->easy = curl_easy_init();
  247. if (!conn->easy) {
  248. MSG_OUT("curl_easy_init() failed, exiting!\n");
  249. exit(2);
  250. }
  251. conn->global = g;
  252. conn->url = g_strdup(url);
  253. curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  254. curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  255. curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, &conn);
  256. curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, (long)SHOW_VERBOSE);
  257. curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  258. curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  259. curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, SHOW_PROGRESS?0L:1L);
  260. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
  261. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  262. curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
  263. curl_easy_setopt(conn->easy, CURLOPT_CONNECTTIMEOUT, 30L);
  264. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 1L);
  265. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 30L);
  266. MSG_OUT("Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
  267. rc =curl_multi_add_handle(g->multi, conn->easy);
  268. mcode_or_die("new_conn: curl_multi_add_handle", rc);
  269. g->requested++;
  270. do {
  271. rc = curl_multi_socket_all(g->multi, &g->still_running);
  272. } while (CURLM_CALL_MULTI_PERFORM == rc);
  273. mcode_or_die("new_conn: curl_multi_socket_all", rc);
  274. check_run_count(g);
  275. }
  276. /* This gets called by glib whenever data is received from the fifo */
  277. static gboolean fifo_cb (GIOChannel *ch, GIOCondition condition, gpointer data)
  278. {
  279. #define BUF_SIZE 1024
  280. gsize len, tp;
  281. gchar *buf, *tmp, *all=NULL;
  282. GIOStatus rv;
  283. do {
  284. GError *err=NULL;
  285. rv = g_io_channel_read_line (ch,&buf,&len,&tp,&err);
  286. if ( buf ) {
  287. if (tp) { buf[tp]='\0'; }
  288. new_conn(buf,(GlobalInfo*)data);
  289. g_free(buf);
  290. } else {
  291. buf = g_malloc(BUF_SIZE+1);
  292. while (TRUE) {
  293. buf[BUF_SIZE]='\0';
  294. g_io_channel_read_chars(ch,buf,BUF_SIZE,&len,&err);
  295. if (len) {
  296. buf[len]='\0';
  297. if (all) {
  298. tmp=all;
  299. all=g_strdup_printf("%s%s", tmp, buf);
  300. g_free(tmp);
  301. } else {
  302. all = g_strdup(buf);
  303. }
  304. } else {
  305. break;
  306. }
  307. }
  308. if (all) {
  309. new_conn(all,(GlobalInfo*)data);
  310. g_free(all);
  311. }
  312. g_free(buf);
  313. }
  314. if ( err ) {
  315. g_error("fifo_cb: %s", err->message);
  316. g_free(err);
  317. break;
  318. }
  319. } while ( (len) && (rv == G_IO_STATUS_NORMAL) );
  320. return TRUE;
  321. }
  322. int init_fifo(void)
  323. {
  324. struct stat st;
  325. const char *fifo = "hiper.fifo";
  326. int socket;
  327. if (lstat (fifo, &st) == 0) {
  328. if ((st.st_mode & S_IFMT) == S_IFREG) {
  329. errno = EEXIST;
  330. perror("lstat");
  331. exit (1);
  332. }
  333. }
  334. unlink (fifo);
  335. if (mkfifo (fifo, 0600) == -1) {
  336. perror("mkfifo");
  337. exit (1);
  338. }
  339. socket = open (fifo, O_RDWR | O_NONBLOCK, 0);
  340. if (socket == -1) {
  341. perror("open");
  342. exit (1);
  343. }
  344. MSG_OUT("Now, pipe some URL's into > %s\n", fifo);
  345. return socket;
  346. }
  347. int main(int argc, char **argv)
  348. {
  349. GlobalInfo *g;
  350. CURLMcode rc;
  351. GMainLoop*gmain;
  352. int fd;
  353. GIOChannel* ch;
  354. g=g_malloc0(sizeof(GlobalInfo));
  355. fd=init_fifo();
  356. ch=g_io_channel_unix_new(fd);
  357. g_io_add_watch(ch,G_IO_IN,fifo_cb,g);
  358. gmain=g_main_loop_new(NULL,FALSE);
  359. g->multi = curl_multi_init();
  360. curl_multi_setopt(g->multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
  361. curl_multi_setopt(g->multi, CURLMOPT_SOCKETDATA, g);
  362. curl_multi_setopt(g->multi, CURLMOPT_TIMERFUNCTION, update_timeout_cb);
  363. curl_multi_setopt(g->multi, CURLMOPT_TIMERDATA, g);
  364. do {
  365. rc = curl_multi_socket_all(g->multi, &g->still_running);
  366. } while (CURLM_CALL_MULTI_PERFORM == rc);
  367. g_main_loop_run(gmain);
  368. curl_multi_cleanup(g->multi);
  369. return 0;
  370. }