tcpudp.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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. /* 3+ args, -i at most once, -p implies -h, -v is counter, -b N, -c N */
  248. opt_complementary = "-3:i--i:ph:vv";
  249. #ifdef SSLSVD
  250. opts = getopt32(argv, "+c:+C:i:x:u:l:Eb:+hpt:vU:/:Z:K:",
  251. &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
  252. &backlog, &str_t, &ssluser, &root, &cert, &key, &verbose
  253. );
  254. #else
  255. /* "+": stop on first non-option */
  256. opts = getopt32(argv, "+c:+C:i:x:u:l:Eb:hpt:v",
  257. &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
  258. &backlog, &str_t, &verbose
  259. );
  260. #endif
  261. if (opts & OPT_C) { /* -C n[:message] */
  262. max_per_host = bb_strtou(str_C, &str_C, 10);
  263. if (str_C[0]) {
  264. if (str_C[0] != ':')
  265. bb_show_usage();
  266. msg_per_host = str_C + 1;
  267. len_per_host = strlen(msg_per_host);
  268. }
  269. }
  270. if (max_per_host > cmax)
  271. max_per_host = cmax;
  272. if (opts & OPT_u) {
  273. xget_uidgid(&ugid, user);
  274. }
  275. #ifdef SSLSVD
  276. if (opts & OPT_U) ssluser = optarg;
  277. if (opts & OPT_slash) root = optarg;
  278. if (opts & OPT_Z) cert = optarg;
  279. if (opts & OPT_K) key = optarg;
  280. #endif
  281. argv += optind;
  282. if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
  283. argv[0] = (char*)"0.0.0.0";
  284. /* Per-IP flood protection is not thought-out for UDP */
  285. if (!tcp)
  286. max_per_host = 0;
  287. bb_sanitize_stdio(); /* fd# 0,1,2 must be opened */
  288. #ifdef SSLSVD
  289. sslser = user;
  290. client = 0;
  291. if ((getuid() == 0) && !(opts & OPT_u)) {
  292. xfunc_exitcode = 100;
  293. bb_error_msg_and_die(bb_msg_you_must_be_root);
  294. }
  295. if (opts & OPT_u)
  296. if (!uidgid_get(&sslugid, ssluser, 1)) {
  297. if (errno) {
  298. bb_perror_msg_and_die("can't get user/group: %s", ssluser);
  299. }
  300. bb_error_msg_and_die("unknown user/group %s", ssluser);
  301. }
  302. if (!cert) cert = "./cert.pem";
  303. if (!key) key = cert;
  304. if (matrixSslOpen() < 0)
  305. fatal("can't initialize ssl");
  306. if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
  307. if (client)
  308. fatal("can't read cert, key, or ca file");
  309. fatal("can't read cert or key file");
  310. }
  311. if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
  312. fatal("can't create ssl session");
  313. #endif
  314. sig_block(SIGCHLD);
  315. signal(SIGCHLD, sig_child_handler);
  316. bb_signals(BB_FATAL_SIGS, sig_term_handler);
  317. signal(SIGPIPE, SIG_IGN);
  318. if (max_per_host)
  319. ipsvd_perhost_init(cmax);
  320. local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
  321. lsa = xhost2sockaddr(argv[0], local_port);
  322. argv += 2;
  323. sock = xsocket(lsa->u.sa.sa_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
  324. setsockopt_reuseaddr(sock);
  325. sa_len = lsa->len; /* I presume sockaddr len stays the same */
  326. xbind(sock, &lsa->u.sa, sa_len);
  327. if (tcp) {
  328. xlisten(sock, backlog);
  329. close_on_exec_on(sock);
  330. } else { /* udp: needed for recv_from_to to work: */
  331. socket_want_pktinfo(sock);
  332. }
  333. /* ndelay_off(sock); - it is the default I think? */
  334. #ifndef SSLSVD
  335. if (opts & OPT_u) {
  336. /* drop permissions */
  337. xsetgid(ugid.gid);
  338. xsetuid(ugid.uid);
  339. }
  340. #endif
  341. if (verbose) {
  342. char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
  343. if (opts & OPT_u)
  344. bb_error_msg("listening on %s, starting, uid %u, gid %u", addr,
  345. (unsigned)ugid.uid, (unsigned)ugid.gid);
  346. else
  347. bb_error_msg("listening on %s, starting", addr);
  348. free(addr);
  349. }
  350. /* Main accept() loop */
  351. again:
  352. hccp = NULL;
  353. again1:
  354. close(0);
  355. /* It's important to close(0) _before_ wait loop:
  356. * fd#0 can be a shared connection fd.
  357. * If kept open by us, peer can't detect PROG closing it.
  358. */
  359. while (cnum >= cmax)
  360. wait_for_any_sig(); /* expecting SIGCHLD */
  361. again2:
  362. sig_unblock(SIGCHLD);
  363. local.len = remote.len = sa_len;
  364. if (tcp) {
  365. /* Accept a connection to fd #0 */
  366. conn = accept(sock, &remote.u.sa, &remote.len);
  367. } else {
  368. /* In case recv_from_to won't be able to recover local addr.
  369. * Also sets port - recv_from_to is unable to do it. */
  370. local = *lsa;
  371. conn = recv_from_to(sock, NULL, 0, MSG_PEEK,
  372. &remote.u.sa, &local.u.sa, sa_len);
  373. }
  374. sig_block(SIGCHLD);
  375. if (conn < 0) {
  376. if (errno != EINTR)
  377. bb_perror_msg(tcp ? "accept" : "recv");
  378. goto again2;
  379. }
  380. xmove_fd(tcp ? conn : sock, 0);
  381. if (max_per_host) {
  382. /* Drop connection immediately if cur_per_host > max_per_host
  383. * (minimizing load under SYN flood) */
  384. remote_addr = xmalloc_sockaddr2dotted_noport(&remote.u.sa);
  385. cur_per_host = ipsvd_perhost_add(remote_addr, max_per_host, &hccp);
  386. if (cur_per_host > max_per_host) {
  387. /* ipsvd_perhost_add detected that max is exceeded
  388. * (and did not store ip in connection table) */
  389. free(remote_addr);
  390. if (msg_per_host) {
  391. /* don't block or test for errors */
  392. send(0, msg_per_host, len_per_host, MSG_DONTWAIT);
  393. }
  394. goto again1;
  395. }
  396. /* NB: remote_addr is not leaked, it is stored in conn table */
  397. }
  398. if (!tcp) {
  399. /* Voodoo magic: making udp sockets each receive its own
  400. * packets is not trivial, and I still not sure
  401. * I do it 100% right.
  402. * 1) we have to do it before fork()
  403. * 2) order is important - is it right now? */
  404. /* Open new non-connected UDP socket for further clients... */
  405. sock = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
  406. setsockopt_reuseaddr(sock);
  407. /* Make plain write/send work for old socket by supplying default
  408. * destination address. This also restricts incoming packets
  409. * to ones coming from this remote IP. */
  410. xconnect(0, &remote.u.sa, sa_len);
  411. /* hole? at this point we have no wildcard udp socket...
  412. * can this cause clients to get "port unreachable" icmp?
  413. * Yup, time window is very small, but it exists (is it?) */
  414. /* ..."open new socket", continued */
  415. xbind(sock, &lsa->u.sa, sa_len);
  416. socket_want_pktinfo(sock);
  417. /* Doesn't work:
  418. * we cannot replace fd #0 - we will lose pending packet
  419. * which is already buffered for us! And we cannot use fd #1
  420. * instead - it will "intercept" all following packets, but child
  421. * does not expect data coming *from fd #1*! */
  422. #if 0
  423. /* Make it so that local addr is fixed to localp->u.sa
  424. * and we don't accidentally accept packets to other local IPs. */
  425. /* NB: we possibly bind to the _very_ same_ address & port as the one
  426. * already bound in parent! This seems to work in Linux.
  427. * (otherwise we can move socket to fd #0 only if bind succeeds) */
  428. close(0);
  429. set_nport(&localp->u.sa, htons(local_port));
  430. xmove_fd(xsocket(localp->u.sa.sa_family, SOCK_DGRAM, 0), 0);
  431. setsockopt_reuseaddr(0); /* crucial */
  432. xbind(0, &localp->u.sa, localp->len);
  433. #endif
  434. }
  435. pid = vfork();
  436. if (pid == -1) {
  437. bb_perror_msg("vfork");
  438. goto again;
  439. }
  440. if (pid != 0) {
  441. /* Parent */
  442. cnum++;
  443. if (verbose)
  444. connection_status();
  445. if (hccp)
  446. hccp->pid = pid;
  447. /* clean up changes done by vforked child */
  448. undo_xsetenv();
  449. goto again;
  450. }
  451. /* Child: prepare env, log, and exec prog */
  452. { /* vfork alert! every xmalloc in this block should be freed! */
  453. char *local_hostname = local_hostname; /* for compiler */
  454. char *local_addr = NULL;
  455. char *free_me0 = NULL;
  456. char *free_me1 = NULL;
  457. char *free_me2 = NULL;
  458. if (verbose || !(opts & OPT_E)) {
  459. if (!max_per_host) /* remote_addr is not yet known */
  460. free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
  461. if (opts & OPT_h) {
  462. free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
  463. if (!remote_hostname) {
  464. bb_error_msg("can't look up hostname for %s", remote_addr);
  465. remote_hostname = remote_addr;
  466. }
  467. }
  468. /* Find out local IP peer connected to.
  469. * Errors ignored (I'm not paranoid enough to imagine kernel
  470. * which doesn't know local IP). */
  471. if (tcp)
  472. getsockname(0, &local.u.sa, &local.len);
  473. /* else: for UDP it is done earlier by parent */
  474. local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
  475. if (opts & OPT_h) {
  476. local_hostname = preset_local_hostname;
  477. if (!local_hostname) {
  478. free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
  479. if (!local_hostname)
  480. bb_error_msg_and_die("can't look up hostname for %s", local_addr);
  481. }
  482. /* else: local_hostname is not NULL, but is NOT malloced! */
  483. }
  484. }
  485. if (verbose) {
  486. pid = getpid();
  487. if (max_per_host) {
  488. bb_error_msg("concurrency %s %u/%u",
  489. remote_addr,
  490. cur_per_host, max_per_host);
  491. }
  492. bb_error_msg((opts & OPT_h)
  493. ? "start %u %s-%s (%s-%s)"
  494. : "start %u %s-%s",
  495. pid,
  496. local_addr, remote_addr,
  497. local_hostname, remote_hostname);
  498. }
  499. if (!(opts & OPT_E)) {
  500. /* setup ucspi env */
  501. const char *proto = tcp ? "TCP" : "UDP";
  502. #ifdef SO_ORIGINAL_DST
  503. /* Extract "original" destination addr:port
  504. * from Linux firewall. Useful when you redirect
  505. * an outbond connection to local handler, and it needs
  506. * to know where it originally tried to connect */
  507. if (tcp && getsockopt(0, SOL_IP, SO_ORIGINAL_DST, &local.u.sa, &local.len) == 0) {
  508. char *addr = xmalloc_sockaddr2dotted(&local.u.sa);
  509. xsetenv_plain("TCPORIGDSTADDR", addr);
  510. free(addr);
  511. }
  512. #endif
  513. xsetenv_plain("PROTO", proto);
  514. xsetenv_proto(proto, "LOCALADDR", local_addr);
  515. xsetenv_proto(proto, "REMOTEADDR", remote_addr);
  516. if (opts & OPT_h) {
  517. xsetenv_proto(proto, "LOCALHOST", local_hostname);
  518. xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
  519. }
  520. //compat? xsetenv_proto(proto, "REMOTEINFO", "");
  521. /* additional */
  522. if (cur_per_host > 0) /* can not be true for udp */
  523. xsetenv_plain("TCPCONCURRENCY", utoa(cur_per_host));
  524. }
  525. free(local_addr);
  526. free(free_me0);
  527. free(free_me1);
  528. free(free_me2);
  529. }
  530. xdup2(0, 1);
  531. signal(SIGPIPE, SIG_DFL); /* this one was SIG_IGNed */
  532. /* Non-ignored signals revert to SIG_DFL on exec anyway */
  533. /*signal(SIGCHLD, SIG_DFL);*/
  534. sig_unblock(SIGCHLD);
  535. #ifdef SSLSVD
  536. strcpy(id, utoa(pid));
  537. ssl_io(0, argv);
  538. bb_perror_msg_and_die("can't execute '%s'", argv[0]);
  539. #else
  540. BB_EXECVP_or_die(argv);
  541. #endif
  542. }
  543. /*
  544. tcpsvd [-hpEvv] [-c n] [-C n:msg] [-b n] [-u user] [-l name]
  545. [-i dir|-x cdb] [ -t sec] host port prog
  546. tcpsvd creates a TCP/IP socket, binds it to the address host:port,
  547. and listens on the socket for incoming connections.
  548. On each incoming connection, tcpsvd conditionally runs a program,
  549. with standard input reading from the socket, and standard output
  550. writing to the socket, to handle this connection. tcpsvd keeps
  551. listening on the socket for new connections, and can handle
  552. multiple connections simultaneously.
  553. tcpsvd optionally checks for special instructions depending
  554. on the IP address or hostname of the client that initiated
  555. the connection, see ipsvd-instruct(5).
  556. host
  557. host either is a hostname, or a dotted-decimal IP address,
  558. or 0. If host is 0, tcpsvd accepts connections to any local
  559. IP address.
  560. * busybox accepts IPv6 addresses and host:port pairs too
  561. In this case second parameter is ignored
  562. port
  563. tcpsvd accepts connections to host:port. port may be a name
  564. from /etc/services or a number.
  565. prog
  566. prog consists of one or more arguments. For each connection,
  567. tcpsvd normally runs prog, with file descriptor 0 reading from
  568. the network, and file descriptor 1 writing to the network.
  569. By default it also sets up TCP-related environment variables,
  570. see tcp-environ(5)
  571. -i dir
  572. read instructions for handling new connections from the instructions
  573. directory dir. See ipsvd-instruct(5) for details.
  574. * ignored by busyboxed version
  575. -x cdb
  576. read instructions for handling new connections from the constant database
  577. cdb. The constant database normally is created from an instructions
  578. directory by running ipsvd-cdb(8).
  579. * ignored by busyboxed version
  580. -t sec
  581. timeout. This option only takes effect if the -i option is given.
  582. While checking the instructions directory, check the time of last access
  583. of the file that matches the clients address or hostname if any, discard
  584. and remove the file if it wasn't accessed within the last sec seconds;
  585. tcpsvd does not discard or remove a file if the user's write permission
  586. is not set, for those files the timeout is disabled. Default is 0,
  587. which means that the timeout is disabled.
  588. * ignored by busyboxed version
  589. -l name
  590. local hostname. Do not look up the local hostname in DNS, but use name
  591. as hostname. This option must be set if tcpsvd listens on port 53
  592. to avoid loops.
  593. -u user[:group]
  594. drop permissions. Switch user ID to user's UID, and group ID to user's
  595. primary GID after creating and binding to the socket. If user is followed
  596. by a colon and a group name, the group ID is switched to the GID of group
  597. instead. All supplementary groups are removed.
  598. -c n
  599. concurrency. Handle up to n connections simultaneously. Default is 30.
  600. If there are n connections active, tcpsvd defers acceptance of a new
  601. connection until an active connection is closed.
  602. -C n[:msg]
  603. per host concurrency. Allow only up to n connections from the same IP
  604. address simultaneously. If there are n active connections from one IP
  605. address, new incoming connections from this IP address are closed
  606. immediately. If n is followed by :msg, the message msg is written
  607. to the client if possible, before closing the connection. By default
  608. msg is empty. See ipsvd-instruct(5) for supported escape sequences in msg.
  609. For each accepted connection, the current per host concurrency is
  610. available through the environment variable TCPCONCURRENCY. n and msg
  611. can be overwritten by ipsvd(7) instructions, see ipsvd-instruct(5).
  612. By default tcpsvd doesn't keep track of connections.
  613. -h
  614. Look up the client's hostname in DNS.
  615. -p
  616. paranoid. After looking up the client's hostname in DNS, look up the IP
  617. addresses in DNS for that hostname, and forget about the hostname
  618. if none of the addresses match the client's IP address. You should
  619. set this option if you use hostname based instructions. The -p option
  620. implies the -h option.
  621. * ignored by busyboxed version
  622. -b n
  623. backlog. Allow a backlog of approximately n TCP SYNs. On some systems n
  624. is silently limited. Default is 20.
  625. -E
  626. no special environment. Do not set up TCP-related environment variables.
  627. -v
  628. verbose. Print verbose messages to standard output.
  629. -vv
  630. more verbose. Print more verbose messages to standard output.
  631. * no difference between -v and -vv in busyboxed version
  632. */