2
0

ephiperfifo.c 15 KB

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