ephiperfifo.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 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. #ifdef __GNUC__
  64. #define _Unused __attribute__((unused))
  65. #else
  66. #define _Unused
  67. #endif
  68. #define MSG_OUT stdout /* Send info to stdout, change to stderr if you want */
  69. /* Global information, common to all connections */
  70. typedef struct _GlobalInfo
  71. {
  72. int epfd; /* epoll filedescriptor */
  73. int tfd; /* timer filedescriptor */
  74. int fifofd; /* fifo filedescriptor */
  75. CURLM *multi;
  76. int still_running;
  77. FILE *input;
  78. } GlobalInfo;
  79. /* Information associated with a specific easy handle */
  80. typedef struct _ConnInfo
  81. {
  82. CURL *easy;
  83. char *url;
  84. GlobalInfo *global;
  85. char error[CURL_ERROR_SIZE];
  86. } ConnInfo;
  87. /* Information associated with a specific socket */
  88. typedef struct _SockInfo
  89. {
  90. curl_socket_t sockfd;
  91. CURL *easy;
  92. int action;
  93. long timeout;
  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. static void timer_cb(GlobalInfo* g, int revents);
  121. /* Update the timer after curl_multi library does it's thing. Curl will
  122. * inform us through this callback what it wants the new timeout to be,
  123. * after it does some work. */
  124. static int multi_timer_cb(CURLM *multi, long timeout_ms, GlobalInfo *g)
  125. {
  126. struct itimerspec its;
  127. CURLMcode rc;
  128. fprintf(MSG_OUT, "multi_timer_cb: Setting timeout to %ld ms\n", timeout_ms);
  129. if(timeout_ms > 0) {
  130. its.it_interval.tv_sec = 1;
  131. its.it_interval.tv_nsec = 0;
  132. its.it_value.tv_sec = timeout_ms / 1000;
  133. its.it_value.tv_nsec = (timeout_ms % 1000) * 1000 * 1000;
  134. }
  135. else if(timeout_ms == 0) {
  136. /* libcurl wants us to timeout now, however setting both fields of
  137. * new_value.it_value to zero disarms the timer. The closest we can
  138. * do is to schedule the timer to fire in 1 ns. */
  139. its.it_interval.tv_sec = 1;
  140. its.it_interval.tv_nsec = 0;
  141. its.it_value.tv_sec = 0;
  142. its.it_value.tv_nsec = 1;
  143. }
  144. else {
  145. memset(&its, 0, sizeof(struct itimerspec));
  146. }
  147. timerfd_settime(g->tfd, /*flags=*/0, &its, NULL);
  148. return 0;
  149. }
  150. /* Check for completed transfers, and remove their easy handles */
  151. static void check_multi_info(GlobalInfo *g)
  152. {
  153. char *eff_url;
  154. CURLMsg *msg;
  155. int msgs_left;
  156. ConnInfo *conn;
  157. CURL *easy;
  158. CURLcode res;
  159. fprintf(MSG_OUT, "REMAINING: %d\n", g->still_running);
  160. while((msg = curl_multi_info_read(g->multi, &msgs_left))) {
  161. if(msg->msg == CURLMSG_DONE) {
  162. easy = msg->easy_handle;
  163. res = msg->data.result;
  164. curl_easy_getinfo(easy, CURLINFO_PRIVATE, &conn);
  165. curl_easy_getinfo(easy, CURLINFO_EFFECTIVE_URL, &eff_url);
  166. fprintf(MSG_OUT, "DONE: %s => (%d) %s\n", eff_url, res, conn->error);
  167. curl_multi_remove_handle(g->multi, easy);
  168. free(conn->url);
  169. curl_easy_cleanup(easy);
  170. free(conn);
  171. }
  172. }
  173. }
  174. /* Called by libevent when we get action on a multi socket filedescriptor*/
  175. static void event_cb(GlobalInfo *g, int fd, int revents)
  176. {
  177. CURLMcode rc;
  178. struct itimerspec its;
  179. int action = (revents & EPOLLIN ? CURL_CSELECT_IN : 0) |
  180. (revents & EPOLLOUT ? CURL_CSELECT_OUT : 0);
  181. rc = curl_multi_socket_action(g->multi, fd, action, &g->still_running);
  182. mcode_or_die("event_cb: curl_multi_socket_action", rc);
  183. check_multi_info(g);
  184. if(g->still_running <= 0) {
  185. fprintf(MSG_OUT, "last transfer done, kill timeout\n");
  186. memset(&its, 0, sizeof(struct itimerspec));
  187. timerfd_settime(g->tfd, 0, &its, NULL);
  188. }
  189. }
  190. /* Called by main loop when our timeout expires */
  191. static void timer_cb(GlobalInfo* g, int revents)
  192. {
  193. CURLMcode rc;
  194. uint64_t count = 0;
  195. ssize_t err = 0;
  196. err = read(g->tfd, &count, sizeof(uint64_t));
  197. if(err == -1) {
  198. /* Note that we may call the timer callback even if the timerfd isn't
  199. * readable. It's possible that there are multiple events stored in the
  200. * epoll buffer (i.e. the timer may have fired multiple times). The
  201. * event count is cleared after the first call so future events in the
  202. * epoll buffer will fail to read from the timer. */
  203. if(errno == EAGAIN) {
  204. fprintf(MSG_OUT, "EAGAIN on tfd %d\n", g->tfd);
  205. return;
  206. }
  207. }
  208. if(err != sizeof(uint64_t)) {
  209. fprintf(stderr, "read(tfd) == %ld", err);
  210. perror("read(tfd)");
  211. }
  212. rc = curl_multi_socket_action(g->multi,
  213. CURL_SOCKET_TIMEOUT, 0, &g->still_running);
  214. mcode_or_die("timer_cb: curl_multi_socket_action", rc);
  215. check_multi_info(g);
  216. }
  217. /* Clean up the SockInfo structure */
  218. static void remsock(SockInfo *f, GlobalInfo* g)
  219. {
  220. if(f) {
  221. if(f->sockfd) {
  222. if(epoll_ctl(g->epfd, EPOLL_CTL_DEL, f->sockfd, NULL))
  223. fprintf(stderr, "EPOLL_CTL_DEL failed for fd: %d : %s\n",
  224. f->sockfd, strerror(errno));
  225. }
  226. free(f);
  227. }
  228. }
  229. /* Assign information to a SockInfo structure */
  230. static void setsock(SockInfo *f, curl_socket_t s, CURL *e, int act,
  231. GlobalInfo *g)
  232. {
  233. struct epoll_event ev;
  234. int kind = (act & CURL_POLL_IN ? EPOLLIN : 0) |
  235. (act & CURL_POLL_OUT ? EPOLLOUT : 0);
  236. if(f->sockfd) {
  237. if(epoll_ctl(g->epfd, EPOLL_CTL_DEL, f->sockfd, NULL))
  238. fprintf(stderr, "EPOLL_CTL_DEL failed for fd: %d : %s\n",
  239. f->sockfd, strerror(errno));
  240. }
  241. f->sockfd = s;
  242. f->action = act;
  243. f->easy = e;
  244. ev.events = kind;
  245. ev.data.fd = s;
  246. if(epoll_ctl(g->epfd, EPOLL_CTL_ADD, s, &ev))
  247. fprintf(stderr, "EPOLL_CTL_ADD failed for fd: %d : %s\n",
  248. s, strerror(errno));
  249. }
  250. /* Initialize a new SockInfo structure */
  251. static void addsock(curl_socket_t s, CURL *easy, int action, GlobalInfo *g)
  252. {
  253. SockInfo *fdp = (SockInfo*)calloc(sizeof(SockInfo), 1);
  254. fdp->global = g;
  255. setsock(fdp, s, easy, action, g);
  256. curl_multi_assign(g->multi, s, fdp);
  257. }
  258. /* CURLMOPT_SOCKETFUNCTION */
  259. static int sock_cb(CURL *e, curl_socket_t s, int what, void *cbp, void *sockp)
  260. {
  261. GlobalInfo *g = (GlobalInfo*) cbp;
  262. SockInfo *fdp = (SockInfo*) sockp;
  263. const char *whatstr[]={ "none", "IN", "OUT", "INOUT", "REMOVE" };
  264. fprintf(MSG_OUT,
  265. "socket callback: s=%d e=%p what=%s ", s, e, whatstr[what]);
  266. if(what == CURL_POLL_REMOVE) {
  267. fprintf(MSG_OUT, "\n");
  268. remsock(fdp, g);
  269. }
  270. else {
  271. if(!fdp) {
  272. fprintf(MSG_OUT, "Adding data: %s\n", whatstr[what]);
  273. addsock(s, e, what, g);
  274. }
  275. else {
  276. fprintf(MSG_OUT,
  277. "Changing action from %s to %s\n",
  278. whatstr[fdp->action], whatstr[what]);
  279. setsock(fdp, s, e, what, g);
  280. }
  281. }
  282. return 0;
  283. }
  284. /* CURLOPT_WRITEFUNCTION */
  285. static size_t write_cb(void *ptr _Unused, size_t size, size_t nmemb,
  286. void *data)
  287. {
  288. size_t realsize = size * nmemb;
  289. ConnInfo *conn _Unused = (ConnInfo*) data;
  290. return realsize;
  291. }
  292. /* CURLOPT_PROGRESSFUNCTION */
  293. static int prog_cb(void *p, double dltotal, double dlnow, double ult _Unused,
  294. double uln _Unused)
  295. {
  296. ConnInfo *conn = (ConnInfo *)p;
  297. fprintf(MSG_OUT, "Progress: %s (%g/%g)\n", conn->url, dlnow, dltotal);
  298. return 0;
  299. }
  300. /* Create a new easy handle, and add it to the global curl_multi */
  301. static void new_conn(char *url, GlobalInfo *g)
  302. {
  303. ConnInfo *conn;
  304. CURLMcode rc;
  305. conn = (ConnInfo*)calloc(1, sizeof(ConnInfo));
  306. conn->error[0]='\0';
  307. conn->easy = curl_easy_init();
  308. if(!conn->easy) {
  309. fprintf(MSG_OUT, "curl_easy_init() failed, exiting!\n");
  310. exit(2);
  311. }
  312. conn->global = g;
  313. conn->url = strdup(url);
  314. curl_easy_setopt(conn->easy, CURLOPT_URL, conn->url);
  315. curl_easy_setopt(conn->easy, CURLOPT_WRITEFUNCTION, write_cb);
  316. curl_easy_setopt(conn->easy, CURLOPT_WRITEDATA, conn);
  317. curl_easy_setopt(conn->easy, CURLOPT_VERBOSE, 1L);
  318. curl_easy_setopt(conn->easy, CURLOPT_ERRORBUFFER, conn->error);
  319. curl_easy_setopt(conn->easy, CURLOPT_PRIVATE, conn);
  320. curl_easy_setopt(conn->easy, CURLOPT_NOPROGRESS, 0L);
  321. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSFUNCTION, prog_cb);
  322. curl_easy_setopt(conn->easy, CURLOPT_PROGRESSDATA, conn);
  323. curl_easy_setopt(conn->easy, CURLOPT_FOLLOWLOCATION, 1L);
  324. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_TIME, 3L);
  325. curl_easy_setopt(conn->easy, CURLOPT_LOW_SPEED_LIMIT, 10L);
  326. fprintf(MSG_OUT,
  327. "Adding easy %p to multi %p (%s)\n", conn->easy, g->multi, url);
  328. rc = curl_multi_add_handle(g->multi, conn->easy);
  329. mcode_or_die("new_conn: curl_multi_add_handle", rc);
  330. /* note that the add_handle() will set a time-out to trigger very soon so
  331. that the necessary socket_action() call will be called by this app */
  332. }
  333. /* This gets called whenever data is received from the fifo */
  334. static void fifo_cb(GlobalInfo* g, int revents)
  335. {
  336. char s[1024];
  337. long int rv = 0;
  338. int n = 0;
  339. do {
  340. s[0]='\0';
  341. rv = fscanf(g->input, "%1023s%n", s, &n);
  342. s[n]='\0';
  343. if(n && s[0]) {
  344. new_conn(s, g); /* if we read a URL, go get it! */
  345. }
  346. else
  347. break;
  348. } while(rv != EOF);
  349. }
  350. /* Create a named pipe and tell libevent to monitor it */
  351. static const char *fifo = "hiper.fifo";
  352. static int init_fifo(GlobalInfo *g)
  353. {
  354. struct stat st;
  355. curl_socket_t sockfd;
  356. struct epoll_event epev;
  357. fprintf(MSG_OUT, "Creating named pipe \"%s\"\n", fifo);
  358. if(lstat (fifo, &st) == 0) {
  359. if((st.st_mode & S_IFMT) == S_IFREG) {
  360. errno = EEXIST;
  361. perror("lstat");
  362. exit(1);
  363. }
  364. }
  365. unlink(fifo);
  366. if(mkfifo (fifo, 0600) == -1) {
  367. perror("mkfifo");
  368. exit(1);
  369. }
  370. sockfd = open(fifo, O_RDWR | O_NONBLOCK, 0);
  371. if(sockfd == -1) {
  372. perror("open");
  373. exit(1);
  374. }
  375. g->fifofd = sockfd;
  376. g->input = fdopen(sockfd, "r");
  377. epev.events = EPOLLIN;
  378. epev.data.fd = sockfd;
  379. epoll_ctl(g->epfd, EPOLL_CTL_ADD, sockfd, &epev);
  380. fprintf(MSG_OUT, "Now, pipe some URL's into > %s\n", fifo);
  381. return 0;
  382. }
  383. static void clean_fifo(GlobalInfo *g)
  384. {
  385. epoll_ctl(g->epfd, EPOLL_CTL_DEL, g->fifofd, NULL);
  386. fclose(g->input);
  387. unlink(fifo);
  388. }
  389. int g_should_exit_ = 0;
  390. void SignalHandler(int signo)
  391. {
  392. if(signo == SIGINT) {
  393. g_should_exit_ = 1;
  394. }
  395. }
  396. int main(int argc _Unused, char **argv _Unused)
  397. {
  398. GlobalInfo g;
  399. int err;
  400. int idx;
  401. struct itimerspec its;
  402. struct epoll_event ev;
  403. struct epoll_event events[10];
  404. g_should_exit_ = 0;
  405. signal(SIGINT, SignalHandler);
  406. memset(&g, 0, sizeof(GlobalInfo));
  407. g.epfd = epoll_create1(EPOLL_CLOEXEC);
  408. if(g.epfd == -1) {
  409. perror("epoll_create1 failed");
  410. exit(1);
  411. }
  412. g.tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
  413. if(g.tfd == -1) {
  414. perror("timerfd_create failed");
  415. exit(1);
  416. }
  417. memset(&its, 0, sizeof(struct itimerspec));
  418. its.it_interval.tv_sec = 1;
  419. its.it_value.tv_sec = 1;
  420. timerfd_settime(g.tfd, 0, &its, NULL);
  421. ev.events = EPOLLIN;
  422. ev.data.fd = g.tfd;
  423. epoll_ctl(g.epfd, EPOLL_CTL_ADD, g.tfd, &ev);
  424. init_fifo(&g);
  425. g.multi = curl_multi_init();
  426. /* setup the generic multi interface options we want */
  427. curl_multi_setopt(g.multi, CURLMOPT_SOCKETFUNCTION, sock_cb);
  428. curl_multi_setopt(g.multi, CURLMOPT_SOCKETDATA, &g);
  429. curl_multi_setopt(g.multi, CURLMOPT_TIMERFUNCTION, multi_timer_cb);
  430. curl_multi_setopt(g.multi, CURLMOPT_TIMERDATA, &g);
  431. /* we don't call any curl_multi_socket*() function yet as we have no handles
  432. added! */
  433. fprintf(MSG_OUT, "Entering wait loop\n");
  434. fflush(MSG_OUT);
  435. while(!g_should_exit_) {
  436. /* TODO(josh): use epoll_pwait to avoid a race on the signal. Mask the
  437. * signal before the while loop, and then re-enable the signal during
  438. * epoll wait. Mask at the end of the loop. */
  439. err = epoll_wait(g.epfd, events, sizeof(events)/sizeof(struct epoll_event),
  440. 10000);
  441. if(err == -1) {
  442. if(errno == EINTR) {
  443. fprintf(MSG_OUT, "note: wait interrupted\n");
  444. continue;
  445. }
  446. else {
  447. perror("epoll_wait");
  448. exit(1);
  449. }
  450. }
  451. for(idx = 0; idx < err; ++idx) {
  452. if(events[idx].data.fd == g.fifofd) {
  453. fifo_cb(&g, events[idx].events);
  454. }
  455. else if(events[idx].data.fd == g.tfd) {
  456. timer_cb(&g, events[idx].events);
  457. }
  458. else {
  459. event_cb(&g, events[idx].data.fd, events[idx].events);
  460. }
  461. }
  462. }
  463. fprintf(MSG_OUT, "Exiting normally.\n");
  464. fflush(MSG_OUT);
  465. curl_multi_cleanup(g.multi);
  466. return 0;
  467. }