ghiper.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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)|(act&CURL_POLL_OUT?G_IO_OUT:0);
  193. f->sockfd = s;
  194. f->action = act;
  195. f->easy = e;
  196. if(f->ev) {
  197. g_source_remove(f->ev);
  198. }
  199. f->ev = g_io_add_watch(f->ch, kind, event_cb, g);
  200. }
  201. /* Initialize a new SockInfo structure */
  202. static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
  203. {
  204. SockInfo *fdp = g_malloc0(sizeof(SockInfo));
  205. fdp->global = g;
  206. fdp->ch = g_io_channel_unix_new(s);
  207. setsock(fdp, s, easy, action, g);
  208. curl_multi_assign(g->multi, s, fdp);
  209. }
  210. /* CURLMOPT_SOCKETFUNCTION */
  211. static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
  212. {
  213. GlobalInfo *g = (GlobalInfo*) cbp;
  214. SockInfo *fdp = (SockInfo*) sockp;
  215. static const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" };
  216. MSG_OUT("socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
  217. if(what == CURL_POLL_REMOVE) {
  218. MSG_OUT("\n");
  219. remsock(fdp);
  220. }
  221. else {
  222. if(!fdp) {
  223. MSG_OUT("Adding data: %s%s\n",
  224. what&CURL_POLL_IN?"READ":"",
  225. what&CURL_POLL_OUT?"WRITE":"");
  226. addsock(s, e, what, g);
  227. }
  228. else {
  229. MSG_OUT(
  230. "Changing action from %d to %d\n", fdp->action, what);
  231. setsock(fdp, s, e, what, g);
  232. }
  233. }
  234. return 0;
  235. }
  236. /* CURLOPT_WRITEFUNCTION */
  237. static size_t write_cb(void *ptr, size_t size, size_t nmemb, void *data)
  238. {
  239. size_t realsize = size * nmemb;
  240. ConnInfo *conn = (ConnInfo*) data;
  241. (void)ptr;
  242. (void)conn;
  243. return realsize;
  244. }
  245. /* CURLOPT_PROGRESSFUNCTION */
  246. static int prog_cb(void *p, double dltotal, double dlnow, double ult,
  247. double uln)
  248. {
  249. ConnInfo *conn = (ConnInfo *)p;
  250. MSG_OUT("Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal);
  251. return 0;
  252. }
  253. /* Create a new easy handle, and add it to the global curl_multi */
  254. static void new_conn(char *url, GlobalInfo *g)
  255. {
  256. ConnInfo *conn;
  257. CURLMcode rc;
  258. conn = g_malloc0(sizeof(ConnInfo));
  259. conn->error[0]='\0';
  260. conn->easy = curl_easy_init();
  261. if(!conn->easy) {
  262. MSG_OUT("curl_easy_init() failed, exiting!\n");
  263. exit(2);
  264. }
  265. conn->global = g;
  266. conn->url = g_strdup(url);
  267. curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  268. curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  269. curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, &conn);
  270. curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, (long)SHOW_VERBOSE);
  271. curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  272. curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  273. curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, SHOW_PROGRESS?0L:1L);
  274. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
  275. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  276. curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
  277. curl_easy_setopt(conn->easy, CURLOPT_CONNECTTIMEOUT, 30L);
  278. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 1L);
  279. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 30L);
  280. MSG_OUT("Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
  281. rc = curl_multi_add_handle(g->multi, conn->easy);
  282. mcode_or_die("new_conn: curl_multi_add_handle", rc);
  283. /* note that the add_handle() will set a time-out to trigger very soon so
  284. that the necessary socket_action() call will be called by this app */
  285. }
  286. /* This gets called by glib whenever data is received from the fifo */
  287. static gboolean fifo_cb(GIOChannel *ch, GIOCondition condition, gpointer data)
  288. {
  289. #define BUF_SIZE 1024
  290. gsize len, tp;
  291. gchar *buf, *tmp, *all = NULL;
  292. GIOStatus rv;
  293. do {
  294. GError *err = NULL;
  295. rv = g_io_channel_read_line(ch, &buf, &len, &tp, &err);
  296. if(buf) {
  297. if(tp) {
  298. buf[tp]='\0';
  299. }
  300. new_conn(buf, (GlobalInfo*)data);
  301. g_free(buf);
  302. }
  303. else {
  304. buf = g_malloc(BUF_SIZE + 1);
  305. while(TRUE) {
  306. buf[BUF_SIZE]='\0';
  307. g_io_channel_read_chars(ch, buf, BUF_SIZE, &len, &err);
  308. if(len) {
  309. buf[len]='\0';
  310. if(all) {
  311. tmp = all;
  312. all = g_strdup_printf("%s%s", tmp, buf);
  313. g_free(tmp);
  314. }
  315. else {
  316. all = g_strdup(buf);
  317. }
  318. }
  319. else {
  320. break;
  321. }
  322. }
  323. if(all) {
  324. new_conn(all, (GlobalInfo*)data);
  325. g_free(all);
  326. }
  327. g_free(buf);
  328. }
  329. if(err) {
  330. g_error("fifo_cb: %s", err->message);
  331. g_free(err);
  332. break;
  333. }
  334. } while((len) && (rv == G_IO_STATUS_NORMAL));
  335. return TRUE;
  336. }
  337. int init_fifo(void)
  338. {
  339. struct stat st;
  340. const char *fifo = "hiper.fifo";
  341. int socket;
  342. if(lstat (fifo, &st) == 0) {
  343. if((st.st_mode & S_IFMT) == S_IFREG) {
  344. errno = EEXIST;
  345. perror("lstat");
  346. exit(1);
  347. }
  348. }
  349. unlink(fifo);
  350. if(mkfifo (fifo, 0600) == -1) {
  351. perror("mkfifo");
  352. exit(1);
  353. }
  354. socket = open(fifo, O_RDWR | O_NONBLOCK, 0);
  355. if(socket == -1) {
  356. perror("open");
  357. exit(1);
  358. }
  359. MSG_OUT("Now, pipe some URL's into > %s\n", fifo);
  360. return socket;
  361. }
  362. int main(int argc, char **argv)
  363. {
  364. GlobalInfo *g;
  365. CURLMcode rc;
  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. }