ghiper.c 12 KB

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