2
0

proxy.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. * Portions created by SGI are Copyright (C) 2000 Silicon Graphics, Inc.
  3. * All Rights Reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of Silicon Graphics, Inc. nor the names of its
  15. * contributors may be used to endorse or promote products derived from
  16. * this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  24. * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  25. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  26. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  27. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #include <signal.h>
  34. #include <unistd.h>
  35. #include <fcntl.h>
  36. #include <sys/types.h>
  37. #include <sys/stat.h>
  38. #include <sys/socket.h>
  39. #include <netinet/in.h>
  40. #include <arpa/inet.h>
  41. #include <netdb.h>
  42. #include "st.h"
  43. #define IOBUFSIZE (16*1024)
  44. #define IOV_LEN 256
  45. #define IOV_COUNT (IOBUFSIZE / IOV_LEN)
  46. #ifndef INADDR_NONE
  47. #define INADDR_NONE 0xffffffff
  48. #endif
  49. static char *prog; /* Program name */
  50. static struct sockaddr_in rmt_addr; /* Remote address */
  51. static unsigned long testing;
  52. #define TESTING_VERBOSE 0x1
  53. #define TESTING_READV 0x2
  54. #define TESTING_READ_RESID 0x4
  55. #define TESTING_WRITEV 0x8
  56. #define TESTING_WRITE_RESID 0x10
  57. static void read_address(const char *str, struct sockaddr_in *sin);
  58. static void start_daemon(void);
  59. static int cpu_count(void);
  60. static void set_concurrency(int nproc);
  61. static void *handle_request(void *arg);
  62. static void print_sys_error(const char *msg);
  63. /*
  64. * This program acts as a generic gateway. It listens for connections
  65. * to a local address ('-l' option). Upon accepting a client connection,
  66. * it connects to the specified remote address ('-r' option) and then
  67. * just pumps the data through without any modification.
  68. */
  69. int main(int argc, char *argv[])
  70. {
  71. extern char *optarg;
  72. int opt, sock, n;
  73. int laddr, raddr, num_procs, alt_ev, one_process;
  74. int serialize_accept = 0;
  75. struct sockaddr_in lcl_addr, cli_addr;
  76. st_netfd_t cli_nfd, srv_nfd;
  77. prog = argv[0];
  78. num_procs = laddr = raddr = alt_ev = one_process = 0;
  79. /* Parse arguments */
  80. while((opt = getopt(argc, argv, "l:r:p:Saht:X")) != EOF) {
  81. switch (opt) {
  82. case 'a':
  83. alt_ev = 1;
  84. break;
  85. case 'l':
  86. read_address(optarg, &lcl_addr);
  87. laddr = 1;
  88. break;
  89. case 'r':
  90. read_address(optarg, &rmt_addr);
  91. if (rmt_addr.sin_addr.s_addr == INADDR_ANY) {
  92. fprintf(stderr, "%s: invalid remote address: %s\n", prog, optarg);
  93. exit(1);
  94. }
  95. raddr = 1;
  96. break;
  97. case 'p':
  98. num_procs = atoi(optarg);
  99. if (num_procs < 1) {
  100. fprintf(stderr, "%s: invalid number of processes: %s\n", prog, optarg);
  101. exit(1);
  102. }
  103. break;
  104. case 'S':
  105. /*
  106. * Serialization decision is tricky on some platforms. For example,
  107. * Solaris 2.6 and above has kernel sockets implementation, so supposedly
  108. * there is no need for serialization. The ST library may be compiled
  109. * on one OS version, but used on another, so the need for serialization
  110. * should be determined at run time by the application. Since it's just
  111. * an example, the serialization decision is left up to user.
  112. * Only on platforms where the serialization is never needed on any OS
  113. * version st_netfd_serialize_accept() is a no-op.
  114. */
  115. serialize_accept = 1;
  116. break;
  117. case 't':
  118. testing = strtoul(optarg, NULL, 0);
  119. break;
  120. case 'X':
  121. one_process = 1;
  122. break;
  123. case 'h':
  124. case '?':
  125. fprintf(stderr, "Usage: %s [options] -l <[host]:port> -r <host:port>\n",
  126. prog);
  127. fprintf(stderr, "options are:\n");
  128. fprintf(stderr, " -p <num_processes> number of parallel processes\n");
  129. fprintf(stderr, " -S serialize accepts\n");
  130. fprintf(stderr, " -a use alternate event system\n");
  131. #ifdef DEBUG
  132. fprintf(stderr, " -t mask testing/debugging mode\n");
  133. fprintf(stderr, " -X one process, don't daemonize\n");
  134. #endif
  135. exit(1);
  136. }
  137. }
  138. if (!laddr) {
  139. fprintf(stderr, "%s: local address required\n", prog);
  140. exit(1);
  141. }
  142. if (!raddr) {
  143. fprintf(stderr, "%s: remote address required\n", prog);
  144. exit(1);
  145. }
  146. if (num_procs == 0)
  147. num_procs = cpu_count();
  148. fprintf(stderr, "%s: starting proxy daemon on %s:%d\n", prog,
  149. inet_ntoa(lcl_addr.sin_addr), ntohs(lcl_addr.sin_port));
  150. /* Start the daemon */
  151. if (one_process)
  152. num_procs = 1;
  153. else
  154. start_daemon();
  155. if (alt_ev)
  156. st_set_eventsys(ST_EVENTSYS_ALT);
  157. /* Initialize the ST library */
  158. if (st_init() < 0) {
  159. print_sys_error("st_init");
  160. exit(1);
  161. }
  162. /* Create and bind listening socket */
  163. if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  164. print_sys_error("socket");
  165. exit(1);
  166. }
  167. n = 1;
  168. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof(n)) < 0) {
  169. print_sys_error("setsockopt");
  170. exit(1);
  171. }
  172. if (bind(sock, (struct sockaddr *)&lcl_addr, sizeof(lcl_addr)) < 0) {
  173. print_sys_error("bind");
  174. exit(1);
  175. }
  176. listen(sock, 128);
  177. if ((srv_nfd = st_netfd_open_socket(sock)) == NULL) {
  178. print_sys_error("st_netfd_open");
  179. exit(1);
  180. }
  181. /* See the comment regarding serialization decision above */
  182. if (num_procs > 1 && serialize_accept && st_netfd_serialize_accept(srv_nfd)
  183. < 0) {
  184. print_sys_error("st_netfd_serialize_accept");
  185. exit(1);
  186. }
  187. /* Start server processes */
  188. if (!one_process)
  189. set_concurrency(num_procs);
  190. for ( ; ; ) {
  191. n = sizeof(cli_addr);
  192. cli_nfd = st_accept(srv_nfd, (struct sockaddr *)&cli_addr, &n,
  193. ST_UTIME_NO_TIMEOUT);
  194. if (cli_nfd == NULL) {
  195. print_sys_error("st_accept");
  196. exit(1);
  197. }
  198. if (st_thread_create(handle_request, cli_nfd, 0, 0) == NULL) {
  199. print_sys_error("st_thread_create");
  200. exit(1);
  201. }
  202. }
  203. /* NOTREACHED */
  204. return 1;
  205. }
  206. static void read_address(const char *str, struct sockaddr_in *sin)
  207. {
  208. char host[128], *p;
  209. struct hostent *hp;
  210. unsigned short port;
  211. strcpy(host, str);
  212. if ((p = strchr(host, ':')) == NULL) {
  213. fprintf(stderr, "%s: invalid address: %s\n", prog, host);
  214. exit(1);
  215. }
  216. *p++ = '\0';
  217. port = (unsigned short) atoi(p);
  218. if (port < 1) {
  219. fprintf(stderr, "%s: invalid port: %s\n", prog, p);
  220. exit(1);
  221. }
  222. memset(sin, 0, sizeof(struct sockaddr_in));
  223. sin->sin_family = AF_INET;
  224. sin->sin_port = htons(port);
  225. if (host[0] == '\0') {
  226. sin->sin_addr.s_addr = INADDR_ANY;
  227. return;
  228. }
  229. sin->sin_addr.s_addr = inet_addr(host);
  230. if (sin->sin_addr.s_addr == INADDR_NONE) {
  231. /* not dotted-decimal */
  232. if ((hp = gethostbyname(host)) == NULL) {
  233. fprintf(stderr, "%s: can't resolve address: %s\n", prog, host);
  234. exit(1);
  235. }
  236. memcpy(&sin->sin_addr, hp->h_addr, hp->h_length);
  237. }
  238. }
  239. #ifdef DEBUG
  240. static void show_iov(const struct iovec *iov, int niov)
  241. {
  242. int i;
  243. size_t total;
  244. printf("iov %p has %d entries:\n", iov, niov);
  245. total = 0;
  246. for (i = 0; i < niov; i++) {
  247. printf("iov[%3d] iov_base=%p iov_len=0x%lx(%lu)\n",
  248. i, iov[i].iov_base, (unsigned long) iov[i].iov_len,
  249. (unsigned long) iov[i].iov_len);
  250. total += iov[i].iov_len;
  251. }
  252. printf("total 0x%lx(%ld)\n", (unsigned long) total, (unsigned long) total);
  253. }
  254. /*
  255. * This version is tricked out to test all the
  256. * st_(read|write)v?(_resid)? variants. Use the non-DEBUG version for
  257. * anything serious. st_(read|write) are all this function really
  258. * needs.
  259. */
  260. static int pass(st_netfd_t in, st_netfd_t out)
  261. {
  262. char buf[IOBUFSIZE];
  263. struct iovec iov[IOV_COUNT];
  264. int ioviter, nw, nr;
  265. if (testing & TESTING_READV) {
  266. for (ioviter = 0; ioviter < IOV_COUNT; ioviter++) {
  267. iov[ioviter].iov_base = &buf[ioviter * IOV_LEN];
  268. iov[ioviter].iov_len = IOV_LEN;
  269. }
  270. if (testing & TESTING_VERBOSE) {
  271. printf("readv(%p)...\n", in);
  272. show_iov(iov, IOV_COUNT);
  273. }
  274. if (testing & TESTING_READ_RESID) {
  275. struct iovec *riov = iov;
  276. int riov_cnt = IOV_COUNT;
  277. if (st_readv_resid(in, &riov, &riov_cnt, ST_UTIME_NO_TIMEOUT) == 0) {
  278. if (testing & TESTING_VERBOSE) {
  279. printf("resid\n");
  280. show_iov(riov, riov_cnt);
  281. printf("full\n");
  282. show_iov(iov, IOV_COUNT);
  283. }
  284. nr = 0;
  285. for (ioviter = 0; ioviter < IOV_COUNT; ioviter++)
  286. nr += iov[ioviter].iov_len;
  287. nr = IOBUFSIZE - nr;
  288. } else
  289. nr = -1;
  290. } else
  291. nr = (int) st_readv(in, iov, IOV_COUNT, ST_UTIME_NO_TIMEOUT);
  292. } else {
  293. if (testing & TESTING_READ_RESID) {
  294. size_t resid = IOBUFSIZE;
  295. if (st_read_resid(in, buf, &resid, ST_UTIME_NO_TIMEOUT) == 0)
  296. nr = IOBUFSIZE - resid;
  297. else
  298. nr = -1;
  299. } else
  300. nr = (int) st_read(in, buf, IOBUFSIZE, ST_UTIME_NO_TIMEOUT);
  301. }
  302. if (testing & TESTING_VERBOSE)
  303. printf("got 0x%x(%d) E=%d\n", nr, nr, errno);
  304. if (nr <= 0)
  305. return 0;
  306. if (testing & TESTING_WRITEV) {
  307. for (nw = 0, ioviter = 0; nw < nr;
  308. nw += iov[ioviter].iov_len, ioviter++) {
  309. iov[ioviter].iov_base = &buf[nw];
  310. iov[ioviter].iov_len = nr - nw;
  311. if (iov[ioviter].iov_len > IOV_LEN)
  312. iov[ioviter].iov_len = IOV_LEN;
  313. }
  314. if (testing & TESTING_VERBOSE) {
  315. printf("writev(%p)...\n", out);
  316. show_iov(iov, ioviter);
  317. }
  318. if (testing & TESTING_WRITE_RESID) {
  319. struct iovec *riov = iov;
  320. int riov_cnt = ioviter;
  321. if (st_writev_resid(out, &riov, &riov_cnt, ST_UTIME_NO_TIMEOUT) == 0) {
  322. if (testing & TESTING_VERBOSE) {
  323. printf("resid\n");
  324. show_iov(riov, riov_cnt);
  325. printf("full\n");
  326. show_iov(iov, ioviter);
  327. }
  328. nw = 0;
  329. while (--ioviter >= 0)
  330. nw += iov[ioviter].iov_len;
  331. nw = nr - nw;
  332. } else
  333. nw = -1;
  334. } else
  335. nw = st_writev(out, iov, ioviter, ST_UTIME_NO_TIMEOUT);
  336. } else {
  337. if (testing & TESTING_WRITE_RESID) {
  338. size_t resid = nr;
  339. if (st_write_resid(out, buf, &resid, ST_UTIME_NO_TIMEOUT) == 0)
  340. nw = nr - resid;
  341. else
  342. nw = -1;
  343. } else
  344. nw = st_write(out, buf, nr, ST_UTIME_NO_TIMEOUT);
  345. }
  346. if (testing & TESTING_VERBOSE)
  347. printf("put 0x%x(%d) E=%d\n", nw, nw, errno);
  348. if (nw != nr)
  349. return 0;
  350. return 1;
  351. }
  352. #else /* DEBUG */
  353. /*
  354. * This version is the simple one suitable for serious use.
  355. */
  356. static int pass(st_netfd_t in, st_netfd_t out)
  357. {
  358. char buf[IOBUFSIZE];
  359. int nw, nr;
  360. nr = (int) st_read(in, buf, IOBUFSIZE, ST_UTIME_NO_TIMEOUT);
  361. if (nr <= 0)
  362. return 0;
  363. nw = st_write(out, buf, nr, ST_UTIME_NO_TIMEOUT);
  364. if (nw != nr)
  365. return 0;
  366. return 1;
  367. }
  368. #endif
  369. static void *handle_request(void *arg)
  370. {
  371. struct pollfd pds[2];
  372. st_netfd_t cli_nfd, rmt_nfd;
  373. int sock;
  374. cli_nfd = (st_netfd_t) arg;
  375. pds[0].fd = st_netfd_fileno(cli_nfd);
  376. pds[0].events = POLLIN;
  377. /* Connect to remote host */
  378. if ((sock = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  379. print_sys_error("socket");
  380. goto done;
  381. }
  382. if ((rmt_nfd = st_netfd_open_socket(sock)) == NULL) {
  383. print_sys_error("st_netfd_open_socket");
  384. close(sock);
  385. goto done;
  386. }
  387. if (st_connect(rmt_nfd, (struct sockaddr *)&rmt_addr,
  388. sizeof(rmt_addr), ST_UTIME_NO_TIMEOUT) < 0) {
  389. print_sys_error("st_connect");
  390. st_netfd_close(rmt_nfd);
  391. goto done;
  392. }
  393. pds[1].fd = sock;
  394. pds[1].events = POLLIN;
  395. /*
  396. * Now just pump the data through.
  397. * XXX This should use one thread for each direction for true full-duplex.
  398. */
  399. for ( ; ; ) {
  400. pds[0].revents = 0;
  401. pds[1].revents = 0;
  402. if (st_poll(pds, 2, ST_UTIME_NO_TIMEOUT) <= 0) {
  403. print_sys_error("st_poll");
  404. break;
  405. }
  406. if (pds[0].revents & POLLIN) {
  407. if (!pass(cli_nfd, rmt_nfd))
  408. break;
  409. }
  410. if (pds[1].revents & POLLIN) {
  411. if (!pass(rmt_nfd, cli_nfd))
  412. break;
  413. }
  414. }
  415. st_netfd_close(rmt_nfd);
  416. done:
  417. st_netfd_close(cli_nfd);
  418. return NULL;
  419. }
  420. static void start_daemon(void)
  421. {
  422. pid_t pid;
  423. /* Start forking */
  424. if ((pid = fork()) < 0) {
  425. print_sys_error("fork");
  426. exit(1);
  427. }
  428. if (pid > 0)
  429. exit(0); /* parent */
  430. /* First child process */
  431. setsid(); /* become session leader */
  432. if ((pid = fork()) < 0) {
  433. print_sys_error("fork");
  434. exit(1);
  435. }
  436. if (pid > 0) /* first child */
  437. exit(0);
  438. chdir("/");
  439. umask(022);
  440. }
  441. /*
  442. * Create separate processes ("virtual processors"). Since it's just an
  443. * example, there is no watchdog - the parent just exits leaving children
  444. * on their own.
  445. */
  446. static void set_concurrency(int nproc)
  447. {
  448. pid_t pid;
  449. int i;
  450. if (nproc < 1)
  451. nproc = 1;
  452. for (i = 0; i < nproc; i++) {
  453. if ((pid = fork()) < 0) {
  454. print_sys_error("fork");
  455. exit(1);
  456. }
  457. /* Child returns */
  458. if (pid == 0)
  459. return;
  460. }
  461. /* Parent just exits */
  462. exit(0);
  463. }
  464. static int cpu_count(void)
  465. {
  466. int n;
  467. #if defined (_SC_NPROCESSORS_ONLN)
  468. n = (int) sysconf(_SC_NPROCESSORS_ONLN);
  469. #elif defined (_SC_NPROC_ONLN)
  470. n = (int) sysconf(_SC_NPROC_ONLN);
  471. #elif defined (HPUX)
  472. #include <sys/mpctl.h>
  473. n = mpctl(MPC_GETNUMSPUS, 0, 0);
  474. #else
  475. n = -1;
  476. errno = ENOSYS;
  477. #endif
  478. return n;
  479. }
  480. static void print_sys_error(const char *msg)
  481. {
  482. fprintf(stderr, "%s: %s: %s\n", prog, msg, strerror(errno));
  483. }