2
0

ephiperfifo.c 15 KB

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