tcpudp.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. /* Based on ipsvd utilities written by Gerrit Pape <pape@smarden.org>
  2. * which are released into public domain by the author.
  3. * Homepage: http://smarden.sunsite.dk/ipsvd/
  4. *
  5. * Copyright (C) 2007 Denys Vlasenko.
  6. *
  7. * Licensed under GPLv2, see file LICENSE in this source tree.
  8. */
  9. /* Based on ipsvd-0.12.1. This tcpsvd accepts all options
  10. * which are supported by one from ipsvd-0.12.1, but not all are
  11. * functional. See help text at the end of this file for details.
  12. *
  13. * Code inside "#ifdef SSLSVD" is for sslsvd and is currently unused.
  14. *
  15. * Busybox version exports TCPLOCALADDR instead of
  16. * TCPLOCALIP + TCPLOCALPORT pair. ADDR more closely matches reality
  17. * (which is "struct sockaddr_XXX". Port is not a separate entity,
  18. * it's just a part of (AF_INET[6]) sockaddr!).
  19. *
  20. * TCPORIGDSTADDR is Busybox-specific addition.
  21. *
  22. * udp server is hacked up by reusing TCP code. It has the following
  23. * limitation inherent in Unix DGRAM sockets implementation:
  24. * - local IP address is retrieved (using recvmsg voodoo) but
  25. * child's socket is not bound to it (bind cannot be called on
  26. * already bound socket). Thus it still can emit outgoing packets
  27. * with wrong source IP...
  28. * - don't know how to retrieve ORIGDST for udp.
  29. */
  30. //config:config TCPSVD
  31. //config: bool "tcpsvd (13 kb)"
  32. //config: default y
  33. //config: help
  34. //config: tcpsvd listens on a TCP port and runs a program for each new
  35. //config: connection.
  36. //config:
  37. //config:config UDPSVD
  38. //config: bool "udpsvd (13 kb)"
  39. //config: default y
  40. //config: help
  41. //config: udpsvd listens on an UDP port and runs a program for each new
  42. //config: connection.
  43. //applet:IF_TCPSVD(APPLET_ODDNAME(tcpsvd, tcpudpsvd, BB_DIR_USR_BIN, BB_SUID_DROP, tcpsvd))
  44. //applet:IF_UDPSVD(APPLET_ODDNAME(udpsvd, tcpudpsvd, BB_DIR_USR_BIN, BB_SUID_DROP, udpsvd))
  45. //kbuild:lib-$(CONFIG_TCPSVD) += tcpudp.o tcpudp_perhost.o
  46. //kbuild:lib-$(CONFIG_UDPSVD) += tcpudp.o tcpudp_perhost.o
  47. //usage:#define tcpsvd_trivial_usage
  48. //usage: "[-hEv] [-c N] [-C N[:MSG]] [-b N] [-u USER] [-l NAME] IP PORT PROG"
  49. /* with not-implemented options: */
  50. /* //usage: "[-hpEvv] [-c N] [-C N[:MSG]] [-b N] [-u USER] [-l NAME] [-i DIR|-x CDB] [-t SEC] IP PORT PROG" */
  51. //usage:#define tcpsvd_full_usage "\n\n"
  52. //usage: "Create TCP socket, bind to IP:PORT and listen for incoming connections.\n"
  53. //usage: "Run PROG for each connection.\n"
  54. //usage: "\n IP PORT IP:PORT to listen on"
  55. //usage: "\n PROG ARGS Program to run"
  56. //usage: "\n -u USER[:GRP] Change to user/group after bind"
  57. //usage: "\n -c N Up to N connections simultaneously (default 30)"
  58. //usage: "\n -b N Allow backlog of approximately N TCP SYNs (default 20)"
  59. //usage: "\n -C N[:MSG] Allow only up to N connections from the same IP:"
  60. //usage: "\n new connections from this IP address are closed"
  61. //usage: "\n immediately, MSG is written to the peer before close"
  62. //usage: "\n -E Don't set up environment"
  63. //usage: "\n -h Look up peer's hostname"
  64. //usage: "\n -l NAME Local hostname (else look up local hostname in DNS)"
  65. //usage: "\n -v Verbose"
  66. //usage: "\n"
  67. //usage: "\nEnvironment if no -E:"
  68. //usage: "\nPROTO='TCP'"
  69. //usage: "\nTCPREMOTEADDR='ip:port'" IF_FEATURE_IPV6(" ('[ip]:port' for IPv6)")
  70. //usage: "\nTCPLOCALADDR='ip:port'"
  71. //usage: "\nTCPORIGDSTADDR='ip:port' of destination before firewall"
  72. //usage: "\n Useful for REDIRECTed-to-local connections:"
  73. //usage: "\n iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to 8080"
  74. //usage: "\nTCPCONCURRENCY=num_of_connects_from_this_ip"
  75. //usage: "\nIf -h:"
  76. //usage: "\nTCPLOCALHOST='hostname' (-l NAME is used if specified)"
  77. //usage: "\nTCPREMOTEHOST='hostname'"
  78. //usage:
  79. //usage:#define udpsvd_trivial_usage
  80. //usage: "[-hEv] [-c N] [-u USER] [-l NAME] IP PORT PROG"
  81. //usage:#define udpsvd_full_usage "\n\n"
  82. //usage: "Create UDP socket, bind to IP:PORT and wait for incoming packets.\n"
  83. //usage: "Run PROG for each packet, redirecting all further packets with same\n"
  84. //usage: "peer ip:port to it.\n"
  85. //usage: "\n IP PORT IP:PORT to listen on"
  86. //usage: "\n PROG ARGS Program to run"
  87. //usage: "\n -u USER[:GRP] Change to user/group after bind"
  88. //usage: "\n -c N Up to N connections simultaneously (default 30)"
  89. //usage: "\n -E Don't set up environment"
  90. //usage: "\n -h Look up peer's hostname"
  91. //usage: "\n -l NAME Local hostname (else look up local hostname in DNS)"
  92. //usage: "\n -v Verbose"
  93. //usage: "\n"
  94. //usage: "\nEnvironment if no -E:"
  95. //usage: "\nPROTO='UDP'"
  96. //usage: "\nUDPREMOTEADDR='ip:port'" IF_FEATURE_IPV6(" ('[ip]:port' for IPv6)")
  97. //usage: "\nUDPLOCALADDR='ip:port'"
  98. //usage: "\nIf -h:"
  99. //usage: "\nUDPLOCALHOST='hostname' (-l NAME is used if specified)"
  100. //usage: "\nUDPREMOTEHOST='hostname'"
  101. #include "libbb.h"
  102. #include "common_bufsiz.h"
  103. #ifdef __linux__
  104. /* from linux/netfilter_ipv4.h: */
  105. # undef SO_ORIGINAL_DST
  106. # define SO_ORIGINAL_DST 80
  107. #endif
  108. // TODO: move into this file:
  109. #include "tcpudp_perhost.h"
  110. #ifdef SSLSVD
  111. #include "matrixSsl.h"
  112. #include "ssl_io.h"
  113. #endif
  114. struct globals {
  115. unsigned verbose;
  116. unsigned max_per_host;
  117. unsigned cur_per_host;
  118. unsigned cnum;
  119. unsigned cmax;
  120. char **env_cur;
  121. char *env_var[1]; /* actually bigger */
  122. } FIX_ALIASING;
  123. #define G (*(struct globals*)bb_common_bufsiz1)
  124. #define verbose (G.verbose )
  125. #define max_per_host (G.max_per_host)
  126. #define cur_per_host (G.cur_per_host)
  127. #define cnum (G.cnum )
  128. #define cmax (G.cmax )
  129. #define env_cur (G.env_cur )
  130. #define env_var (G.env_var )
  131. #define INIT_G() do { \
  132. setup_common_bufsiz(); \
  133. cmax = 30; \
  134. env_cur = &env_var[0]; \
  135. } while (0)
  136. /* We have to be careful about leaking memory in repeated setenv's */
  137. static void xsetenv_plain(const char *n, const char *v)
  138. {
  139. char *var = xasprintf("%s=%s", n, v);
  140. *env_cur++ = var;
  141. putenv(var);
  142. }
  143. static void xsetenv_proto(const char *proto, const char *n, const char *v)
  144. {
  145. char *var = xasprintf("%s%s=%s", proto, n, v);
  146. *env_cur++ = var;
  147. putenv(var);
  148. }
  149. static void undo_xsetenv(void)
  150. {
  151. char **pp = env_cur = &env_var[0];
  152. while (*pp) {
  153. char *var = *pp;
  154. bb_unsetenv_and_free(var);
  155. *pp++ = NULL;
  156. }
  157. }
  158. static void sig_term_handler(int sig)
  159. {
  160. if (verbose)
  161. bb_error_msg("got signal %u, exit", sig);
  162. kill_myself_with_sig(sig);
  163. }
  164. /* Little bloated, but tries to give accurate info how child exited.
  165. * Makes easier to spot segfaulting children etc... */
  166. static void print_waitstat(unsigned pid, int wstat)
  167. {
  168. unsigned e = 0;
  169. const char *cause = "?exit";
  170. if (WIFEXITED(wstat)) {
  171. cause++;
  172. e = WEXITSTATUS(wstat);
  173. } else if (WIFSIGNALED(wstat)) {
  174. cause = "signal";
  175. e = WTERMSIG(wstat);
  176. }
  177. bb_error_msg("end %d %s %d", pid, cause, e);
  178. }
  179. /* Must match getopt32 in main! */
  180. enum {
  181. OPT_c = (1 << 0),
  182. OPT_C = (1 << 1),
  183. OPT_i = (1 << 2),
  184. OPT_x = (1 << 3),
  185. OPT_u = (1 << 4),
  186. OPT_l = (1 << 5),
  187. OPT_E = (1 << 6),
  188. OPT_b = (1 << 7),
  189. OPT_h = (1 << 8),
  190. OPT_p = (1 << 9),
  191. OPT_t = (1 << 10),
  192. OPT_v = (1 << 11),
  193. OPT_V = (1 << 12),
  194. OPT_U = (1 << 13), /* from here: sslsvd only */
  195. OPT_slash = (1 << 14),
  196. OPT_Z = (1 << 15),
  197. OPT_K = (1 << 16),
  198. };
  199. static void connection_status(void)
  200. {
  201. /* "only 1 client max" desn't need this */
  202. if (cmax > 1)
  203. bb_error_msg("status %u/%u", cnum, cmax);
  204. }
  205. static void sig_child_handler(int sig UNUSED_PARAM)
  206. {
  207. int wstat;
  208. pid_t pid;
  209. while ((pid = wait_any_nohang(&wstat)) > 0) {
  210. if (max_per_host)
  211. ipsvd_perhost_remove(pid);
  212. if (cnum)
  213. cnum--;
  214. if (verbose)
  215. print_waitstat(pid, wstat);
  216. }
  217. if (verbose)
  218. connection_status();
  219. }
  220. int tcpudpsvd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  221. int tcpudpsvd_main(int argc UNUSED_PARAM, char **argv)
  222. {
  223. char *str_C, *str_t;
  224. char *user;
  225. struct hcc *hccp;
  226. const char *instructs;
  227. char *msg_per_host = NULL;
  228. unsigned len_per_host = len_per_host; /* gcc */
  229. #ifndef SSLSVD
  230. struct bb_uidgid_t ugid;
  231. #endif
  232. bool tcp;
  233. uint16_t local_port;
  234. char *preset_local_hostname = NULL;
  235. char *remote_hostname = remote_hostname; /* for compiler */
  236. char *remote_addr = remote_addr; /* for compiler */
  237. len_and_sockaddr *lsa;
  238. len_and_sockaddr local, remote;
  239. socklen_t sa_len;
  240. int pid;
  241. int sock;
  242. int conn;
  243. unsigned backlog = 20;
  244. unsigned opts;
  245. INIT_G();
  246. tcp = (applet_name[0] == 't');
  247. #ifdef SSLSVD
  248. opts = getopt32(argv, "^+"
  249. "c:+C:i:x:u:l:Eb:+hpt:vU:/:Z:K:" /* -c NUM, -b NUM */
  250. /* 3+ args, -i at most once, -p implies -h, -v is a counter */
  251. "\0" "-3:i--i:ph:vv",
  252. &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
  253. &backlog, &str_t, &ssluser, &root, &cert, &key, &verbose
  254. );
  255. #else
  256. /* "+": stop on first non-option */
  257. opts = getopt32(argv, "+c:+C:i:x:u:l:Eb:hpt:v",
  258. &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
  259. &backlog, &str_t, &verbose
  260. );
  261. #endif
  262. if (opts & OPT_C) { /* -C n[:message] */
  263. max_per_host = bb_strtou(str_C, &str_C, 10);
  264. if (str_C[0]) {
  265. if (str_C[0] != ':')
  266. bb_show_usage();
  267. msg_per_host = str_C + 1;
  268. len_per_host = strlen(msg_per_host);
  269. }
  270. }
  271. if (max_per_host > cmax)
  272. max_per_host = cmax;
  273. if (opts & OPT_u) {
  274. xget_uidgid(&ugid, user);
  275. }
  276. #ifdef SSLSVD
  277. if (opts & OPT_U) ssluser = optarg;
  278. if (opts & OPT_slash) root = optarg;
  279. if (opts & OPT_Z) cert = optarg;
  280. if (opts & OPT_K) key = optarg;
  281. #endif
  282. argv += optind;
  283. if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
  284. argv[0] = (char*)"0.0.0.0";
  285. /* Per-IP flood protection is not thought-out for UDP */
  286. if (!tcp)
  287. max_per_host = 0;
  288. bb_sanitize_stdio(); /* fd# 0,1,2 must be opened */
  289. #ifdef SSLSVD
  290. sslser = user;
  291. client = 0;
  292. if ((getuid() == 0) && !(opts & OPT_u)) {
  293. xfunc_exitcode = 100;
  294. bb_error_msg_and_die(bb_msg_you_must_be_root);
  295. }
  296. if (opts & OPT_u)
  297. if (!uidgid_get(&sslugid, ssluser, 1)) {
  298. if (errno) {
  299. bb_perror_msg_and_die("can't get user/group: %s", ssluser);
  300. }
  301. bb_error_msg_and_die("unknown user/group %s", ssluser);
  302. }
  303. if (!cert) cert = "./cert.pem";
  304. if (!key) key = cert;
  305. if (matrixSslOpen() < 0)
  306. fatal("can't initialize ssl");
  307. if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
  308. if (client)
  309. fatal("can't read cert, key, or ca file");
  310. fatal("can't read cert or key file");
  311. }
  312. if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
  313. fatal("can't create ssl session");
  314. #endif
  315. sig_block(SIGCHLD);
  316. signal(SIGCHLD, sig_child_handler);
  317. bb_signals(BB_FATAL_SIGS, sig_term_handler);
  318. signal(SIGPIPE, SIG_IGN);
  319. if (max_per_host)
  320. ipsvd_perhost_init(cmax);
  321. local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
  322. lsa = xhost2sockaddr(argv[0], local_port);
  323. argv += 2;
  324. sock = xsocket(lsa->u.sa.sa_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
  325. setsockopt_reuseaddr(sock);
  326. sa_len = lsa->len; /* I presume sockaddr len stays the same */
  327. xbind(sock, &lsa->u.sa, sa_len);
  328. if (tcp) {
  329. xlisten(sock, backlog);
  330. close_on_exec_on(sock);
  331. } else { /* udp: needed for recv_from_to to work: */
  332. socket_want_pktinfo(sock);
  333. }
  334. /* ndelay_off(sock); - it is the default I think? */
  335. #ifndef SSLSVD
  336. if (opts & OPT_u) {
  337. /* drop permissions */
  338. xsetgid(ugid.gid);
  339. xsetuid(ugid.uid);
  340. }
  341. #endif
  342. if (verbose) {
  343. char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
  344. if (opts & OPT_u)
  345. bb_error_msg("listening on %s, starting, uid %u, gid %u", addr,
  346. (unsigned)ugid.uid, (unsigned)ugid.gid);
  347. else
  348. bb_error_msg("listening on %s, starting", addr);
  349. free(addr);
  350. }
  351. /* Main accept() loop */
  352. again:
  353. hccp = NULL;
  354. again1:
  355. close(0);
  356. /* It's important to close(0) _before_ wait loop:
  357. * fd#0 can be a shared connection fd.
  358. * If kept open by us, peer can't detect PROG closing it.
  359. */
  360. while (cnum >= cmax)
  361. wait_for_any_sig(); /* expecting SIGCHLD */
  362. again2:
  363. sig_unblock(SIGCHLD);
  364. local.len = remote.len = sa_len;
  365. if (tcp) {
  366. /* Accept a connection to fd #0 */
  367. conn = accept(sock, &remote.u.sa, &remote.len);
  368. } else {
  369. /* In case recv_from_to won't be able to recover local addr.
  370. * Also sets port - recv_from_to is unable to do it. */
  371. local = *lsa;
  372. conn = recv_from_to(sock, NULL, 0, MSG_PEEK,
  373. &remote.u.sa, &local.u.sa, sa_len);
  374. }
  375. sig_block(SIGCHLD);
  376. if (conn < 0) {
  377. if (errno != EINTR)
  378. bb_perror_msg(tcp ? "accept" : "recv");
  379. goto again2;
  380. }
  381. xmove_fd(tcp ? conn : sock, 0);
  382. if (max_per_host) {
  383. /* Drop connection immediately if cur_per_host > max_per_host
  384. * (minimizing load under SYN flood) */
  385. remote_addr = xmalloc_sockaddr2dotted_noport(&remote.u.sa);
  386. cur_per_host = ipsvd_perhost_add(remote_addr, max_per_host, &hccp);
  387. if (cur_per_host > max_per_host) {
  388. /* ipsvd_perhost_add detected that max is exceeded
  389. * (and did not store ip in connection table) */
  390. free(remote_addr);
  391. if (msg_per_host) {
  392. /* don't block or test for errors */
  393. send(0, msg_per_host, len_per_host, MSG_DONTWAIT);
  394. }
  395. goto again1;
  396. }
  397. /* NB: remote_addr is not leaked, it is stored in conn table */
  398. }
  399. if (!tcp) {
  400. /* Voodoo magic: making udp sockets each receive its own
  401. * packets is not trivial, and I still not sure
  402. * I do it 100% right.
  403. * 1) we have to do it before fork()
  404. * 2) order is important - is it right now? */
  405. /* Open new non-connected UDP socket for further clients... */
  406. sock = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
  407. setsockopt_reuseaddr(sock);
  408. /* Make plain write/send work for old socket by supplying default
  409. * destination address. This also restricts incoming packets
  410. * to ones coming from this remote IP. */
  411. xconnect(0, &remote.u.sa, sa_len);
  412. /* hole? at this point we have no wildcard udp socket...
  413. * can this cause clients to get "port unreachable" icmp?
  414. * Yup, time window is very small, but it exists (is it?) */
  415. /* ..."open new socket", continued */
  416. xbind(sock, &lsa->u.sa, sa_len);
  417. socket_want_pktinfo(sock);
  418. /* Doesn't work:
  419. * we cannot replace fd #0 - we will lose pending packet
  420. * which is already buffered for us! And we cannot use fd #1
  421. * instead - it will "intercept" all following packets, but child
  422. * does not expect data coming *from fd #1*! */
  423. #if 0
  424. /* Make it so that local addr is fixed to localp->u.sa
  425. * and we don't accidentally accept packets to other local IPs. */
  426. /* NB: we possibly bind to the _very_ same_ address & port as the one
  427. * already bound in parent! This seems to work in Linux.
  428. * (otherwise we can move socket to fd #0 only if bind succeeds) */
  429. close(0);
  430. set_nport(&localp->u.sa, htons(local_port));
  431. xmove_fd(xsocket(localp->u.sa.sa_family, SOCK_DGRAM, 0), 0);
  432. setsockopt_reuseaddr(0); /* crucial */
  433. xbind(0, &localp->u.sa, localp->len);
  434. #endif
  435. }
  436. pid = vfork();
  437. if (pid == -1) {
  438. bb_perror_msg("vfork");
  439. goto again;
  440. }
  441. if (pid != 0) {
  442. /* Parent */
  443. cnum++;
  444. if (verbose)
  445. connection_status();
  446. if (hccp)
  447. hccp->pid = pid;
  448. /* clean up changes done by vforked child */
  449. undo_xsetenv();
  450. goto again;
  451. }
  452. /* Child: prepare env, log, and exec prog */
  453. { /* vfork alert! every xmalloc in this block should be freed! */
  454. char *local_hostname = local_hostname; /* for compiler */
  455. char *local_addr = NULL;
  456. char *free_me0 = NULL;
  457. char *free_me1 = NULL;
  458. char *free_me2 = NULL;
  459. if (verbose || !(opts & OPT_E)) {
  460. if (!max_per_host) /* remote_addr is not yet known */
  461. free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
  462. if (opts & OPT_h) {
  463. free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
  464. if (!remote_hostname) {
  465. bb_error_msg("can't look up hostname for %s", remote_addr);
  466. remote_hostname = remote_addr;
  467. }
  468. }
  469. /* Find out local IP peer connected to.
  470. * Errors ignored (I'm not paranoid enough to imagine kernel
  471. * which doesn't know local IP). */
  472. if (tcp)
  473. getsockname(0, &local.u.sa, &local.len);
  474. /* else: for UDP it is done earlier by parent */
  475. local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
  476. if (opts & OPT_h) {
  477. local_hostname = preset_local_hostname;
  478. if (!local_hostname) {
  479. free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
  480. if (!local_hostname)
  481. bb_error_msg_and_die("can't look up hostname for %s", local_addr);
  482. }
  483. /* else: local_hostname is not NULL, but is NOT malloced! */
  484. }
  485. }
  486. if (verbose) {
  487. pid = getpid();
  488. if (max_per_host) {
  489. bb_error_msg("concurrency %s %u/%u",
  490. remote_addr,
  491. cur_per_host, max_per_host);
  492. }
  493. bb_error_msg((opts & OPT_h)
  494. ? "start %u %s-%s (%s-%s)"
  495. : "start %u %s-%s",
  496. pid,
  497. local_addr, remote_addr,
  498. local_hostname, remote_hostname);
  499. }
  500. if (!(opts & OPT_E)) {
  501. /* setup ucspi env */
  502. const char *proto = tcp ? "TCP" : "UDP";
  503. #ifdef SO_ORIGINAL_DST
  504. /* Extract "original" destination addr:port
  505. * from Linux firewall. Useful when you redirect
  506. * an outbond connection to local handler, and it needs
  507. * to know where it originally tried to connect */
  508. if (tcp && getsockopt(0, SOL_IP, SO_ORIGINAL_DST, &local.u.sa, &local.len) == 0) {
  509. char *addr = xmalloc_sockaddr2dotted(&local.u.sa);
  510. xsetenv_plain("TCPORIGDSTADDR", addr);
  511. free(addr);
  512. }
  513. #endif
  514. xsetenv_plain("PROTO", proto);
  515. xsetenv_proto(proto, "LOCALADDR", local_addr);
  516. xsetenv_proto(proto, "REMOTEADDR", remote_addr);
  517. if (opts & OPT_h) {
  518. xsetenv_proto(proto, "LOCALHOST", local_hostname);
  519. xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
  520. }
  521. //compat? xsetenv_proto(proto, "REMOTEINFO", "");
  522. /* additional */
  523. if (cur_per_host > 0) /* can not be true for udp */
  524. xsetenv_plain("TCPCONCURRENCY", utoa(cur_per_host));
  525. }
  526. free(local_addr);
  527. free(free_me0);
  528. free(free_me1);
  529. free(free_me2);
  530. }
  531. xdup2(0, 1);
  532. signal(SIGPIPE, SIG_DFL); /* this one was SIG_IGNed */
  533. /* Non-ignored signals revert to SIG_DFL on exec anyway */
  534. /*signal(SIGCHLD, SIG_DFL);*/
  535. sig_unblock(SIGCHLD);
  536. #ifdef SSLSVD
  537. strcpy(id, utoa(pid));
  538. ssl_io(0, argv);
  539. bb_perror_msg_and_die("can't execute '%s'", argv[0]);
  540. #else
  541. BB_EXECVP_or_die(argv);
  542. #endif
  543. }
  544. /*
  545. tcpsvd [-hpEvv] [-c n] [-C n:msg] [-b n] [-u user] [-l name]
  546. [-i dir|-x cdb] [ -t sec] host port prog
  547. tcpsvd creates a TCP/IP socket, binds it to the address host:port,
  548. and listens on the socket for incoming connections.
  549. On each incoming connection, tcpsvd conditionally runs a program,
  550. with standard input reading from the socket, and standard output
  551. writing to the socket, to handle this connection. tcpsvd keeps
  552. listening on the socket for new connections, and can handle
  553. multiple connections simultaneously.
  554. tcpsvd optionally checks for special instructions depending
  555. on the IP address or hostname of the client that initiated
  556. the connection, see ipsvd-instruct(5).
  557. host
  558. host either is a hostname, or a dotted-decimal IP address,
  559. or 0. If host is 0, tcpsvd accepts connections to any local
  560. IP address.
  561. * busybox accepts IPv6 addresses and host:port pairs too
  562. In this case second parameter is ignored
  563. port
  564. tcpsvd accepts connections to host:port. port may be a name
  565. from /etc/services or a number.
  566. prog
  567. prog consists of one or more arguments. For each connection,
  568. tcpsvd normally runs prog, with file descriptor 0 reading from
  569. the network, and file descriptor 1 writing to the network.
  570. By default it also sets up TCP-related environment variables,
  571. see tcp-environ(5)
  572. -i dir
  573. read instructions for handling new connections from the instructions
  574. directory dir. See ipsvd-instruct(5) for details.
  575. * ignored by busyboxed version
  576. -x cdb
  577. read instructions for handling new connections from the constant database
  578. cdb. The constant database normally is created from an instructions
  579. directory by running ipsvd-cdb(8).
  580. * ignored by busyboxed version
  581. -t sec
  582. timeout. This option only takes effect if the -i option is given.
  583. While checking the instructions directory, check the time of last access
  584. of the file that matches the clients address or hostname if any, discard
  585. and remove the file if it wasn't accessed within the last sec seconds;
  586. tcpsvd does not discard or remove a file if the user's write permission
  587. is not set, for those files the timeout is disabled. Default is 0,
  588. which means that the timeout is disabled.
  589. * ignored by busyboxed version
  590. -l name
  591. local hostname. Do not look up the local hostname in DNS, but use name
  592. as hostname. This option must be set if tcpsvd listens on port 53
  593. to avoid loops.
  594. -u user[:group]
  595. drop permissions. Switch user ID to user's UID, and group ID to user's
  596. primary GID after creating and binding to the socket. If user is followed
  597. by a colon and a group name, the group ID is switched to the GID of group
  598. instead. All supplementary groups are removed.
  599. -c n
  600. concurrency. Handle up to n connections simultaneously. Default is 30.
  601. If there are n connections active, tcpsvd defers acceptance of a new
  602. connection until an active connection is closed.
  603. -C n[:msg]
  604. per host concurrency. Allow only up to n connections from the same IP
  605. address simultaneously. If there are n active connections from one IP
  606. address, new incoming connections from this IP address are closed
  607. immediately. If n is followed by :msg, the message msg is written
  608. to the client if possible, before closing the connection. By default
  609. msg is empty. See ipsvd-instruct(5) for supported escape sequences in msg.
  610. For each accepted connection, the current per host concurrency is
  611. available through the environment variable TCPCONCURRENCY. n and msg
  612. can be overwritten by ipsvd(7) instructions, see ipsvd-instruct(5).
  613. By default tcpsvd doesn't keep track of connections.
  614. -h
  615. Look up the client's hostname in DNS.
  616. -p
  617. paranoid. After looking up the client's hostname in DNS, look up the IP
  618. addresses in DNS for that hostname, and forget about the hostname
  619. if none of the addresses match the client's IP address. You should
  620. set this option if you use hostname based instructions. The -p option
  621. implies the -h option.
  622. * ignored by busyboxed version
  623. -b n
  624. backlog. Allow a backlog of approximately n TCP SYNs. On some systems n
  625. is silently limited. Default is 20.
  626. -E
  627. no special environment. Do not set up TCP-related environment variables.
  628. -v
  629. verbose. Print verbose messages to standard output.
  630. -vv
  631. more verbose. Print more verbose messages to standard output.
  632. * no difference between -v and -vv in busyboxed version
  633. */