ephiperfifo.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2018, 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 epoll and timerfd
  24. * </DESC>
  25. */
  26. /* Example application source code using the multi socket interface to
  27. * download many files at once.
  28. *
  29. * This example features the same basic functionality as hiperfifo.c does,
  30. * but this uses epoll and timerfd instead of libevent.
  31. *
  32. * Written by Jeff Pohlmeyer, converted to use epoll by Josh Bialkowski
  33. Requires a linux system with epoll
  34. When running, the program creates the named pipe "hiper.fifo"
  35. Whenever there is input into the fifo, the program reads the input as a list
  36. of URL's and creates some new easy handles to fetch each URL via the
  37. curl_multi "hiper" API.
  38. Thus, you can try a single URL:
  39. % echo http://www.yahoo.com > hiper.fifo
  40. Or a whole bunch of them:
  41. % cat my-url-list > hiper.fifo
  42. The fifo buffer is handled almost instantly, so you can even add more URL's
  43. while the previous requests are still being downloaded.
  44. Note:
  45. For the sake of simplicity, URL length is limited to 1023 char's !
  46. This is purely a demo app, all retrieved data is simply discarded by the write
  47. callback.
  48. */
  49. #include <errno.h>
  50. #include <fcntl.h>
  51. #include <signal.h>
  52. #include <stdio.h>
  53. #include <stdlib.h>
  54. #include <string.h>
  55. #include <sys/epoll.h>
  56. #include <sys/stat.h>
  57. #include <sys/time.h>
  58. #include <sys/timerfd.h>
  59. #include <sys/types.h>
  60. #include <time.h>
  61. #include <unistd.h>
  62. #include <curl/curl.h>
  63. #include <curl/multi.h>
  64. #ifdef __GNUC__
  65. #define _Unused __attribute__((unused))
  66. #else
  67. #define _Unused
  68. #endif
  69. #define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */
  70. /* Global information, common to all connections */
  71. typedef struct _GlobalInfo
  72. {
  73. int epfd; /* epoll filedescriptor */
  74. int tfd; /* timer filedescriptor */
  75. int fifofd; /* fifo filedescriptor */
  76. CURLM *multi;
  77. int still_running;
  78. FILE *input;
  79. } GlobalInfo;
  80. /* Information associated with a specific easy handle */
  81. typedef struct _ConnInfo
  82. {
  83. CURL *easy;
  84. char *url;
  85. GlobalInfo *global;
  86. char error[CURL_ERROR_SIZE];
  87. } ConnInfo;
  88. /* Information associated with a specific socket */
  89. typedef struct _SockInfo
  90. {
  91. curl_socket_t sockfd;
  92. CURL *easy;
  93. int action;
  94. long timeout;
  95. GlobalInfo *global;
  96. } SockInfo;
  97. #define __case(code) \
  98. case code: s = __STRING(code)
  99. /* Die if we get a bad CURLMcode somewhere */
  100. static void mcode_or_die(const char *where, CURLMcode code)
  101. {
  102. if(CURLM_OK != code) {
  103. const char *s;
  104. switch(code) {
  105. __case(CURLM_BAD_HANDLE); break;
  106. __case(CURLM_BAD_EASY_HANDLE); break;
  107. __case(CURLM_OUT_OF_MEMORY); break;
  108. __case(CURLM_INTERNAL_ERROR); break;
  109. __case(CURLM_UNKNOWN_OPTION); break;
  110. __case(CURLM_LAST); break;
  111. default: s = "CURLM_unknown"; break;
  112. __case(CURLM_BAD_SOCKET);
  113. fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s);
  114. /* ignore this error */
  115. return;
  116. }
  117. fprintf(MSG_OUT, "ERROR: %s returns %s\n", where, s);
  118. exit(code);
  119. }
  120. }
  121. static void timer_cb(GlobalInfo* g, int revents);
  122. /* Update the timer after curl_multi library does it's thing. Curl will
  123. * inform us through this callback what it wants the new timeout to be,
  124. * after it does some work. */
  125. static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
  126. {
  127. struct itimerspec its;
  128. CURLMcode rc;
  129. fprintf(MSG_OUT, "multi_timer_cb: Setting timeout to %ld ms\n", timeout_ms);
  130. timerfd_settime(g->tfd, /*flags=*/0, &its, NULL);
  131. if(timeout_ms > 0) {
  132. its.it_interval.tv_sec = 1;
  133. its.it_interval.tv_nsec = 0;
  134. its.it_value.tv_sec = timeout_ms / 1000;
  135. its.it_value.tv_nsec = (timeout_ms % 1000) * 1000;
  136. timerfd_settime(g->tfd, /*flags=*/0, &its, NULL);
  137. }
  138. else if(timeout_ms == 0) {
  139. rc = curl_multi_socket_action(g->multi,
  140. CURL_SOCKET_TIMEOUT, 0, &g->still_running);
  141. mcode_or_die("multi_timer_cb: curl_multi_socket_action", rc);
  142. }
  143. else {
  144. memset(&its, 0, sizeof(struct itimerspec));
  145. timerfd_settime(g->tfd, /*flags=*/0, &its, NULL);
  146. }
  147. return 0;
  148. }
  149. /* Check for completed transfers, and remove their easy handles */
  150. static void check_multi_info(GlobalInfo *g)
  151. {
  152. char *eff_url;
  153. CURLMsg *msg;
  154. int msgs_left;
  155. ConnInfo *conn;
  156. CURL *easy;
  157. CURLcode res;
  158. fprintf(MSG_OUT, "REMAINING: %d\n", g->still_running);
  159. while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
  160. if(msg->msg == CURLMSG_DONE) {
  161. easy = msg->easy_handle;
  162. res = msg->data.result;
  163. curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
  164. curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
  165. fprintf(MSG_OUT, "DONE: %s => (%d) %s\n", eff_url, res, conn->error);
  166. curl_multi_remove_handle(g->multi, easy);
  167. free(conn->url);
  168. curl_easy_cleanup(easy);
  169. free(conn);
  170. }
  171. }
  172. }
  173. /* Called by libevent when we get action on a multi socket filedescriptor*/
  174. static void event_cb(GlobalInfo *g, int fd, int revents)
  175. {
  176. CURLMcode rc;
  177. struct itimerspec its;
  178. int action = (revents & EPOLLIN ? CURL_POLL_IN : 0) |
  179. (revents & EPOLLOUT ? CURL_POLL_OUT : 0);
  180. rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running);
  181. mcode_or_die("event_cb: curl_multi_socket_action", rc);
  182. check_multi_info(g);
  183. if(g->still_running <= 0) {
  184. fprintf(MSG_OUT, "last transfer done, kill timeout\n");
  185. memset(&its, 0, sizeof(struct itimerspec));
  186. timerfd_settime(g->tfd, 0, &its, NULL);
  187. }
  188. }
  189. /* Called by main loop when our timeout expires */
  190. static void timer_cb(GlobalInfo* g, int revents)
  191. {
  192. CURLMcode rc;
  193. uint64_t count = 0;
  194. ssize_t err = 0;
  195. err = read(g->tfd, &count, sizeof(uint64_t));
  196. if(err == -1) {
  197. /* Note that we may call the timer callback even if the timerfd isn't
  198. * readable. It's possible that there are multiple events stored in the
  199. * epoll buffer (i.e. the timer may have fired multiple times). The
  200. * event count is cleared after the first call so future events in the
  201. * epoll buffer will fail to read from the timer. */
  202. if(errno == EAGAIN) {
  203. fprintf(MSG_OUT, "EAGAIN on tfd %d\n", g->tfd);
  204. return;
  205. }
  206. }
  207. if(err != sizeof(uint64_t)) {
  208. fprintf(stderr, "read(tfd) == %ld", err);
  209. perror("read(tfd)");
  210. }
  211. rc = curl_multi_socket_action(g->multi,
  212. CURL_SOCKET_TIMEOUT, 0, &g->still_running);
  213. mcode_or_die("timer_cb: curl_multi_socket_action", rc);
  214. check_multi_info(g);
  215. }
  216. /* Clean up the SockInfo structure */
  217. static void remsock(SockInfo *f, GlobalInfo* g)
  218. {
  219. if(f) {
  220. if(f->sockfd) {
  221. epoll_ctl(g->epfd, EPOLL_CTL_DEL, f->sockfd, NULL);
  222. }
  223. free(f);
  224. }
  225. }
  226. /* Assign information to a SockInfo structure */
  227. static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act,
  228. GlobalInfo *g)
  229. {
  230. struct epoll_event ev;
  231. int kind = (act & CURL_POLL_IN ? EPOLLIN : 0) |
  232. (act & CURL_POLL_OUT ? EPOLLOUT : 0);
  233. if(f->sockfd) {
  234. epoll_ctl(g->epfd, EPOLL_CTL_DEL, f->sockfd, NULL);
  235. }
  236. f->sockfd = s;
  237. f->action = act;
  238. f->easy = e;
  239. ev.events = kind;
  240. ev.data.fd = s;
  241. epoll_ctl(g->epfd, EPOLL_CTL_ADD, s, &ev);
  242. }
  243. /* Initialize a new SockInfo structure */
  244. static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
  245. {
  246. SockInfo *fdp = (SockInfo*)calloc(sizeof(SockInfo), 1);
  247. fdp->global = g;
  248. setsock(fdp, s, easy, action, g);
  249. curl_multi_assign(g->multi, s, fdp);
  250. }
  251. /* CURLMOPT_SOCKETFUNCTION */
  252. static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
  253. {
  254. GlobalInfo *g = (GlobalInfo*) cbp;
  255. SockInfo *fdp = (SockInfo*) sockp;
  256. const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" };
  257. fprintf(MSG_OUT,
  258. "socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
  259. if(what == CURL_POLL_REMOVE) {
  260. fprintf(MSG_OUT, "\n");
  261. remsock(fdp, g);
  262. }
  263. else {
  264. if(!fdp) {
  265. fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]);
  266. addsock(s, e, what, g);
  267. }
  268. else {
  269. fprintf(MSG_OUT,
  270. "Changing action from %s to %s\n",
  271. whatstr[fdp->action], whatstr[what]);
  272. setsock(fdp, s, e, what, g);
  273. }
  274. }
  275. return 0;
  276. }
  277. /* CURLOPT_WRITEFUNCTION */
  278. static size_t write_cb(void *ptr _Unused, size_t size, size_t nmemb,
  279. void *data)
  280. {
  281. size_t realsize = size * nmemb;
  282. ConnInfo *conn _Unused = (ConnInfo*) data;
  283. return realsize;
  284. }
  285. /* CURLOPT_PROGRESSFUNCTION */
  286. static int prog_cb(void *p, double dltotal, double dlnow, double ult _Unused,
  287. double uln _Unused)
  288. {
  289. ConnInfo *conn = (ConnInfo *)p;
  290. fprintf(MSG_OUT, "Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal);
  291. return 0;
  292. }
  293. /* Create a new easy handle, and add it to the global curl_multi */
  294. static void new_conn(char *url, GlobalInfo *g)
  295. {
  296. ConnInfo *conn;
  297. CURLMcode rc;
  298. conn = (ConnInfo*)calloc(1, sizeof(ConnInfo));
  299. conn->error[0]='\0';
  300. conn->easy = curl_easy_init();
  301. if(!conn->easy) {
  302. fprintf(MSG_OUT, "curl_easy_init() failed, exiting!\n");
  303. exit(2);
  304. }
  305. conn->global = g;
  306. conn->url = strdup(url);
  307. curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  308. curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  309. curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn);
  310. curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
  311. curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  312. curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  313. curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L);
  314. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
  315. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  316. curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
  317. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L);
  318. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L);
  319. fprintf(MSG_OUT,
  320. "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
  321. rc = curl_multi_add_handle(g->multi, conn->easy);
  322. mcode_or_die("new_conn: curl_multi_add_handle", rc);
  323. /* note that the add_handle() will set a time-out to trigger very soon so
  324. that the necessary socket_action() call will be called by this app */
  325. }
  326. /* This gets called whenever data is received from the fifo */
  327. static void fifo_cb(GlobalInfo* g, int revents)
  328. {
  329. char s[1024];
  330. long int rv = 0;
  331. int n = 0;
  332. do {
  333. s[0]='\0';
  334. rv = fscanf(g->input, "%1023s%n", s, &n);
  335. s[n]='\0';
  336. if(n && s[0]) {
  337. new_conn(s, g); /* if we read a URL, go get it! */
  338. }
  339. else
  340. break;
  341. } while(rv != EOF);
  342. }
  343. /* Create a named pipe and tell libevent to monitor it */
  344. static const char *fifo = "hiper.fifo";
  345. static int init_fifo(GlobalInfo *g)
  346. {
  347. struct stat st;
  348. curl_socket_t sockfd;
  349. struct epoll_event epev;
  350. fprintf(MSG_OUT, "Creating named pipe \"%s\"\n", fifo);
  351. if(lstat (fifo, &st) == 0) {
  352. if((st.st_mode & S_IFMT) == S_IFREG) {
  353. errno = EEXIST;
  354. perror("lstat");
  355. exit(1);
  356. }
  357. }
  358. unlink(fifo);
  359. if(mkfifo (fifo, 0600) == -1) {
  360. perror("mkfifo");
  361. exit(1);
  362. }
  363. sockfd = open(fifo, O_RDWR | O_NONBLOCK, 0);
  364. if(sockfd == -1) {
  365. perror("open");
  366. exit(1);
  367. }
  368. g->fifofd = sockfd;
  369. g->input = fdopen(sockfd, "r");
  370. epev.events = EPOLLIN;
  371. epev.data.fd = sockfd;
  372. epoll_ctl(g->epfd, EPOLL_CTL_ADD, sockfd, &epev);
  373. fprintf(MSG_OUT, "Now, pipe some URL's into > %s\n", fifo);
  374. return 0;
  375. }
  376. static void clean_fifo(GlobalInfo *g)
  377. {
  378. epoll_ctl(g->epfd, EPOLL_CTL_DEL, g->fifofd, NULL);
  379. fclose(g->input);
  380. unlink(fifo);
  381. }
  382. int g_should_exit_ = 0;
  383. void SignalHandler(int signo)
  384. {
  385. if(signo == SIGINT) {
  386. g_should_exit_ = 1;
  387. }
  388. }
  389. int main(int argc _Unused, char **argv _Unused)
  390. {
  391. GlobalInfo g;
  392. int err;
  393. int idx;
  394. struct itimerspec its;
  395. struct epoll_event ev;
  396. struct epoll_event events[10];
  397. g_should_exit_ = 0;
  398. signal(SIGINT, SignalHandler);
  399. memset(&g, 0, sizeof(GlobalInfo));
  400. g.epfd = epoll_create1(EPOLL_CLOEXEC);
  401. if(g.epfd == -1) {
  402. perror("epoll_create1 failed");
  403. exit(1);
  404. }
  405. g.tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
  406. if(g.tfd == -1) {
  407. perror("timerfd_create failed");
  408. exit(1);
  409. }
  410. memset(&its, 0, sizeof(struct itimerspec));
  411. its.it_interval.tv_sec = 1;
  412. its.it_value.tv_sec = 1;
  413. timerfd_settime(g.tfd, 0, &its, NULL);
  414. ev.events = EPOLLIN;
  415. ev.data.fd = g.tfd;
  416. epoll_ctl(g.epfd, EPOLL_CTL_ADD, g.tfd, &ev);
  417. init_fifo(&g);
  418. g.multi = curl_multi_init();
  419. /* setup the generic multi interface options we want */
  420. curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
  421. curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
  422. curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
  423. curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
  424. /* we don't call any curl_multi_socket*() function yet as we have no handles
  425. added! */
  426. fprintf(MSG_OUT, "Entering wait loop\n");
  427. fflush(MSG_OUT);
  428. while(!g_should_exit_) {
  429. /* TODO(josh): use epoll_pwait to avoid a race on the signal. Mask the
  430. * signal before the while loop, and then re-enable the signal during
  431. * epoll wait. Mask at the end of the loop. */
  432. err = epoll_wait(g.epfd, events, sizeof(events)/sizeof(struct epoll_event),
  433. 10000);
  434. if(err == -1) {
  435. if(errno == EINTR) {
  436. fprintf(MSG_OUT, "note: wait interrupted\n");
  437. continue;
  438. }
  439. else {
  440. perror("epoll_wait");
  441. exit(1);
  442. }
  443. }
  444. for(idx = 0; idx < err; ++idx) {
  445. if(events[idx].data.fd == g.fifofd) {
  446. fifo_cb(&g, events[idx].events);
  447. }
  448. else if(events[idx].data.fd == g.tfd) {
  449. timer_cb(&g, events[idx].events);
  450. }
  451. else {
  452. event_cb(&g, events[idx].data.fd, events[idx].events);
  453. }
  454. }
  455. }
  456. fprintf(MSG_OUT, "Exiting normally.\n");
  457. fflush(MSG_OUT);
  458. curl_multi_cleanup(g.multi);
  459. return 0;
  460. }