2
0

ghiper.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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 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. CURLMsg *msg;
  105. int msgs_left;
  106. MSG_OUT("REMAINING: %d\n", g->still_running);
  107. while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
  108. if(msg->msg == CURLMSG_DONE) {
  109. CURL *easy = msg->easy_handle;
  110. CURLcode res = msg->data.result;
  111. char *eff_url;
  112. ConnInfo *conn;
  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_XFERINFOFUNCTION */
  247. static int xferinfo_cb(void *p, curl_off_t dltotal, curl_off_t dlnow,
  248. curl_off_t ult, curl_off_t uln)
  249. {
  250. ConnInfo *conn = (ConnInfo *)p;
  251. (void)ult;
  252. (void)uln;
  253. fprintf(MSG_OUT, "Progress: %s (%" CURL_FORMAT_CURL_OFF_T
  254. "/%" CURL_FORMAT_CURL_OFF_T ")\n", conn->url, dlnow, dltotal);
  255. return 0;
  256. }
  257. /* Create a new easy handle, and add it to the global curl_multi */
  258. static void new_conn(const char *url, GlobalInfo *g)
  259. {
  260. ConnInfo *conn;
  261. CURLMcode rc;
  262. conn = g_malloc0(sizeof(ConnInfo));
  263. conn->error[0] = '\0';
  264. conn->easy = curl_easy_init();
  265. if(!conn->easy) {
  266. MSG_OUT("curl_easy_init() failed, exiting!\n");
  267. exit(2);
  268. }
  269. conn->global = g;
  270. conn->url = g_strdup(url);
  271. curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  272. curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  273. curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, &conn);
  274. curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, (long)SHOW_VERBOSE);
  275. curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  276. curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  277. curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, SHOW_PROGRESS ? 0L : 1L);
  278. curl_easy_setopt(conn->easy, CURLOPT_XFERINFOFUNCTION, xferinfo_cb);
  279. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  280. curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
  281. curl_easy_setopt(conn->easy, CURLOPT_CONNECTTIMEOUT, 30L);
  282. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 1L);
  283. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 30L);
  284. MSG_OUT("Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
  285. rc = curl_multi_add_handle(g->multi, conn->easy);
  286. mcode_or_die("new_conn: curl_multi_add_handle", rc);
  287. /* note that add_handle() sets a timeout to trigger soon so that the
  288. necessary socket_action() gets called */
  289. }
  290. /* This gets called by glib whenever data is received from the fifo */
  291. static gboolean fifo_cb(GIOChannel *ch, GIOCondition condition, gpointer data)
  292. {
  293. #define BUF_SIZE 1024
  294. gsize len, tp;
  295. gchar *buf, *tmp, *all = NULL;
  296. GIOStatus rv;
  297. do {
  298. GError *err = NULL;
  299. rv = g_io_channel_read_line(ch, &buf, &len, &tp, &err);
  300. if(buf) {
  301. if(tp) {
  302. buf[tp]='\0';
  303. }
  304. new_conn(buf, (GlobalInfo*)data);
  305. g_free(buf);
  306. }
  307. else {
  308. buf = g_malloc(BUF_SIZE + 1);
  309. while(TRUE) {
  310. buf[BUF_SIZE]='\0';
  311. g_io_channel_read_chars(ch, buf, BUF_SIZE, &len, &err);
  312. if(len) {
  313. buf[len]='\0';
  314. if(all) {
  315. tmp = all;
  316. all = g_strdup_printf("%s%s", tmp, buf);
  317. g_free(tmp);
  318. }
  319. else {
  320. all = g_strdup(buf);
  321. }
  322. }
  323. else {
  324. break;
  325. }
  326. }
  327. if(all) {
  328. new_conn(all, (GlobalInfo*)data);
  329. g_free(all);
  330. }
  331. g_free(buf);
  332. }
  333. if(err) {
  334. g_error("fifo_cb: %s", err->message);
  335. g_free(err);
  336. break;
  337. }
  338. } while((len) && (rv == G_IO_STATUS_NORMAL));
  339. return TRUE;
  340. }
  341. int init_fifo(void)
  342. {
  343. struct stat st;
  344. const char *fifo = "hiper.fifo";
  345. int socket;
  346. if(lstat(fifo, &st) == 0) {
  347. if((st.st_mode & S_IFMT) == S_IFREG) {
  348. errno = EEXIST;
  349. perror("lstat");
  350. exit(1);
  351. }
  352. }
  353. unlink(fifo);
  354. if(mkfifo (fifo, 0600) == -1) {
  355. perror("mkfifo");
  356. exit(1);
  357. }
  358. socket = open(fifo, O_RDWR | O_NONBLOCK, 0);
  359. if(socket == -1) {
  360. perror("open");
  361. exit(1);
  362. }
  363. MSG_OUT("Now, pipe some URL's into > %s\n", fifo);
  364. return socket;
  365. }
  366. int main(void)
  367. {
  368. GlobalInfo *g = g_malloc0(sizeof(GlobalInfo));
  369. GMainLoop*gmain;
  370. int fd;
  371. GIOChannel* ch;
  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. }