hiperfifo.c 12 KB

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