ghiper.c 12 KB

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