PageRenderTime 27ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/examples/ghiper.c

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