tcpudp.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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 (14 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. struct hcc *cc;
  121. char **env_cur;
  122. char *env_var[1]; /* actually bigger */
  123. } FIX_ALIASING;
  124. #define G (*(struct globals*)bb_common_bufsiz1)
  125. #define verbose (G.verbose )
  126. #define max_per_host (G.max_per_host)
  127. #define cur_per_host (G.cur_per_host)
  128. #define cnum (G.cnum )
  129. #define cmax (G.cmax )
  130. #define env_cur (G.env_cur )
  131. #define env_var (G.env_var )
  132. #define INIT_G() do { \
  133. setup_common_bufsiz(); \
  134. cmax = 30; \
  135. env_cur = &env_var[0]; \
  136. } while (0)
  137. /* We have to be careful about leaking memory in repeated setenv's */
  138. static void xsetenv_plain(const char *n, const char *v)
  139. {
  140. char *var = xasprintf("%s=%s", n, v);
  141. *env_cur++ = var;
  142. putenv(var);
  143. }
  144. static void xsetenv_proto(const char *proto, const char *n, const char *v)
  145. {
  146. char *var = xasprintf("%s%s=%s", proto, n, v);
  147. *env_cur++ = var;
  148. putenv(var);
  149. }
  150. static void undo_xsetenv(void)
  151. {
  152. char **pp = env_cur = &env_var[0];
  153. while (*pp) {
  154. char *var = *pp;
  155. bb_unsetenv_and_free(var);
  156. *pp++ = NULL;
  157. }
  158. }
  159. static void sig_term_handler(int sig)
  160. {
  161. if (verbose)
  162. bb_error_msg("got signal %u, exit", sig);
  163. kill_myself_with_sig(sig);
  164. }
  165. /* Little bloated, but tries to give accurate info how child exited.
  166. * Makes easier to spot segfaulting children etc... */
  167. static void print_waitstat(unsigned pid, int wstat)
  168. {
  169. unsigned e = 0;
  170. const char *cause = "?exit";
  171. if (WIFEXITED(wstat)) {
  172. cause++;
  173. e = WEXITSTATUS(wstat);
  174. } else if (WIFSIGNALED(wstat)) {
  175. cause = "signal";
  176. e = WTERMSIG(wstat);
  177. }
  178. bb_error_msg("end %d %s %d", pid, cause, e);
  179. }
  180. /* Must match getopt32 in main! */
  181. enum {
  182. OPT_c = (1 << 0),
  183. OPT_C = (1 << 1),
  184. OPT_i = (1 << 2),
  185. OPT_x = (1 << 3),
  186. OPT_u = (1 << 4),
  187. OPT_l = (1 << 5),
  188. OPT_E = (1 << 6),
  189. OPT_b = (1 << 7),
  190. OPT_h = (1 << 8),
  191. OPT_p = (1 << 9),
  192. OPT_t = (1 << 10),
  193. OPT_v = (1 << 11),
  194. OPT_V = (1 << 12),
  195. OPT_U = (1 << 13), /* from here: sslsvd only */
  196. OPT_slash = (1 << 14),
  197. OPT_Z = (1 << 15),
  198. OPT_K = (1 << 16),
  199. };
  200. static void if_verbose_print_connection_status(void)
  201. {
  202. if (verbose) {
  203. /* "only 1 client max" desn't need this */
  204. if (cmax > 1)
  205. bb_error_msg("status %u/%u", cnum, cmax);
  206. }
  207. }
  208. /* SIGCHLD handler is reentrancy-safe because SIGCHLD is unmasked
  209. * only over accept() or recvfrom() calls, not over memory allocations
  210. * or printouts. Do need to save/restore errno in order not to mangle
  211. * these syscalls' error code, if any.
  212. */
  213. static void sig_child_handler(int sig UNUSED_PARAM)
  214. {
  215. int wstat;
  216. pid_t pid;
  217. int sv_errno = errno;
  218. while ((pid = wait_any_nohang(&wstat)) > 0) {
  219. if (max_per_host)
  220. ipsvd_perhost_remove(G.cc, pid);
  221. if (cnum)
  222. cnum--;
  223. if (verbose)
  224. print_waitstat(pid, wstat);
  225. }
  226. if_verbose_print_connection_status();
  227. errno = sv_errno;
  228. }
  229. int tcpudpsvd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  230. int tcpudpsvd_main(int argc UNUSED_PARAM, char **argv)
  231. {
  232. char *str_C, *str_t;
  233. char *user;
  234. struct hcc *hccp;
  235. const char *instructs;
  236. char *msg_per_host = NULL;
  237. unsigned len_per_host = len_per_host; /* gcc */
  238. #ifndef SSLSVD
  239. struct bb_uidgid_t ugid;
  240. #endif
  241. bool tcp;
  242. uint16_t local_port;
  243. char *preset_local_hostname = NULL;
  244. char *remote_hostname = remote_hostname; /* for compiler */
  245. char *remote_addr = remote_addr; /* for compiler */
  246. len_and_sockaddr *lsa;
  247. len_and_sockaddr local, remote;
  248. socklen_t sa_len;
  249. int pid;
  250. int sock;
  251. int conn;
  252. unsigned backlog = 20;
  253. unsigned opts;
  254. INIT_G();
  255. tcp = (applet_name[0] == 't');
  256. /* "+": stop on first non-option */
  257. #ifdef SSLSVD
  258. opts = getopt32(argv, "^+"
  259. "c:+C:i:x:u:l:Eb:+hpt:vU:/:Z:K:" /* -c NUM, -b NUM */
  260. "\0"
  261. /* 3+ args, -i at most once, -p implies -h, -v is a counter */
  262. "-3:i--i:ph:vv",
  263. &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
  264. &backlog, &str_t, &ssluser, &root, &cert, &key, &verbose
  265. );
  266. #else
  267. opts = getopt32(argv, "^+"
  268. "c:+C:i:x:u:l:Eb:+hpt:v" /* -c NUM, -b NUM */
  269. "\0"
  270. /* 3+ args, -i at most once, -p implies -h, -v is a counter */
  271. "-3:i--i:ph:vv",
  272. &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
  273. &backlog, &str_t, &verbose
  274. );
  275. #endif
  276. if (opts & OPT_C) { /* -C n[:message] */
  277. max_per_host = bb_strtou(str_C, &str_C, 10);
  278. if (str_C[0]) {
  279. if (str_C[0] != ':')
  280. bb_show_usage();
  281. msg_per_host = str_C + 1;
  282. len_per_host = strlen(msg_per_host);
  283. }
  284. }
  285. if (max_per_host > cmax)
  286. max_per_host = cmax;
  287. if (opts & OPT_u) {
  288. xget_uidgid(&ugid, user);
  289. }
  290. #ifdef SSLSVD
  291. if (opts & OPT_U) ssluser = optarg;
  292. if (opts & OPT_slash) root = optarg;
  293. if (opts & OPT_Z) cert = optarg;
  294. if (opts & OPT_K) key = optarg;
  295. #endif
  296. argv += optind;
  297. if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
  298. argv[0] = (char*)"0.0.0.0";
  299. /* Per-IP flood protection is not thought-out for UDP */
  300. if (!tcp)
  301. max_per_host = 0;
  302. bb_sanitize_stdio(); /* fd# 0,1,2 must be opened */
  303. #ifdef SSLSVD
  304. sslser = user;
  305. client = 0;
  306. if ((getuid() == 0) && !(opts & OPT_u)) {
  307. xfunc_error_retval = 100;
  308. bb_simple_error_msg_and_die(bb_msg_you_must_be_root);
  309. }
  310. if (opts & OPT_u)
  311. if (!uidgid_get(&sslugid, ssluser, 1)) {
  312. if (errno) {
  313. bb_perror_msg_and_die("can't get user/group: %s", ssluser);
  314. }
  315. bb_error_msg_and_die("unknown user/group %s", ssluser);
  316. }
  317. if (!cert) cert = "./cert.pem";
  318. if (!key) key = cert;
  319. if (matrixSslOpen() < 0)
  320. fatal("can't initialize ssl");
  321. if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
  322. if (client)
  323. fatal("can't read cert, key, or ca file");
  324. fatal("can't read cert or key file");
  325. }
  326. if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
  327. fatal("can't create ssl session");
  328. #endif
  329. sig_block(SIGCHLD);
  330. signal(SIGCHLD, sig_child_handler);
  331. bb_signals(BB_FATAL_SIGS, sig_term_handler);
  332. signal(SIGPIPE, SIG_IGN);
  333. if (max_per_host)
  334. G.cc = ipsvd_perhost_init(cmax);
  335. local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
  336. lsa = xhost2sockaddr(argv[0], local_port);
  337. argv += 2;
  338. sock = xsocket(lsa->u.sa.sa_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
  339. setsockopt_reuseaddr(sock);
  340. sa_len = lsa->len; /* I presume sockaddr len stays the same */
  341. xbind(sock, &lsa->u.sa, sa_len);
  342. if (tcp) {
  343. xlisten(sock, backlog);
  344. close_on_exec_on(sock);
  345. } else { /* udp: needed for recv_from_to to work: */
  346. socket_want_pktinfo(sock);
  347. }
  348. /* ndelay_off(sock); - it is the default I think? */
  349. #ifndef SSLSVD
  350. if (opts & OPT_u) {
  351. /* drop permissions */
  352. xsetgid(ugid.gid);
  353. xsetuid(ugid.uid);
  354. }
  355. #endif
  356. if (verbose) {
  357. char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
  358. if (opts & OPT_u)
  359. bb_error_msg("listening on %s, starting, uid %u, gid %u", addr,
  360. (unsigned)ugid.uid, (unsigned)ugid.gid);
  361. else
  362. bb_error_msg("listening on %s, starting", addr);
  363. free(addr);
  364. }
  365. /* Main accept() loop */
  366. again:
  367. hccp = NULL;
  368. again1:
  369. close(0);
  370. /* It's important to close(0) _before_ wait loop:
  371. * fd#0 can be a shared connection fd.
  372. * If kept open by us, peer can't detect PROG closing it.
  373. */
  374. while (cnum >= cmax)
  375. wait_for_any_sig(); /* expecting SIGCHLD */
  376. again2:
  377. sig_unblock(SIGCHLD);
  378. local.len = remote.len = sa_len;
  379. if (tcp) {
  380. /* Accept a connection to fd #0 */
  381. conn = accept(sock, &remote.u.sa, &remote.len);
  382. } else {
  383. /* In case recv_from_to won't be able to recover local addr.
  384. * Also sets port - recv_from_to is unable to do it. */
  385. local = *lsa;
  386. conn = recv_from_to(sock, NULL, 0, MSG_PEEK,
  387. &remote.u.sa, &local.u.sa, sa_len);
  388. }
  389. sig_block(SIGCHLD);
  390. if (conn < 0) {
  391. if (errno != EINTR)
  392. bb_simple_perror_msg(tcp ? "accept" : "recv");
  393. goto again2;
  394. }
  395. xmove_fd(tcp ? conn : sock, 0);
  396. if (max_per_host) {
  397. /* Drop connection immediately if cur_per_host > max_per_host
  398. * (minimizing load under SYN flood) */
  399. remote_addr = xmalloc_sockaddr2dotted_noport(&remote.u.sa);
  400. cur_per_host = ipsvd_perhost_add(G.cc, remote_addr, max_per_host, &hccp);
  401. if (cur_per_host > max_per_host) {
  402. /* ipsvd_perhost_add detected that max is exceeded
  403. * (and did not store ip in connection table) */
  404. free(remote_addr);
  405. if (msg_per_host) {
  406. /* don't block or test for errors */
  407. send(0, msg_per_host, len_per_host, MSG_DONTWAIT);
  408. }
  409. goto again1;
  410. }
  411. /* NB: remote_addr is not leaked, it is stored in conn table */
  412. }
  413. if (!tcp) {
  414. /* Voodoo magic: making udp sockets each receive its own
  415. * packets is not trivial, and I still not sure
  416. * I do it 100% right.
  417. * 1) we have to do it before fork()
  418. * 2) order is important - is it right now? */
  419. /* Open new non-connected UDP socket for further clients... */
  420. sock = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
  421. setsockopt_reuseaddr(sock);
  422. /* Make plain write/send work for old socket by supplying default
  423. * destination address. This also restricts incoming packets
  424. * to ones coming from this remote IP. */
  425. xconnect(0, &remote.u.sa, sa_len);
  426. /* hole? at this point we have no wildcard udp socket...
  427. * can this cause clients to get "port unreachable" icmp?
  428. * Yup, time window is very small, but it exists (does it?) */
  429. /* ..."open new socket", continued */
  430. xbind(sock, &lsa->u.sa, sa_len);
  431. socket_want_pktinfo(sock);
  432. /* Doesn't work:
  433. * we cannot replace fd #0 - we will lose pending packet
  434. * which is already buffered for us! And we cannot use fd #1
  435. * instead - it will "intercept" all following packets, but child
  436. * does not expect data coming *from fd #1*! */
  437. #if 0
  438. /* Make it so that local addr is fixed to localp->u.sa
  439. * and we don't accidentally accept packets to other local IPs. */
  440. /* NB: we possibly bind to the _very_ same_ address & port as the one
  441. * already bound in parent! This seems to work in Linux.
  442. * (otherwise we can move socket to fd #0 only if bind succeeds) */
  443. close(0);
  444. set_nport(&localp->u.sa, htons(local_port));
  445. xmove_fd(xsocket(localp->u.sa.sa_family, SOCK_DGRAM, 0), 0);
  446. setsockopt_reuseaddr(0); /* crucial */
  447. xbind(0, &localp->u.sa, localp->len);
  448. #endif
  449. }
  450. pid = vfork();
  451. if (pid == -1) {
  452. bb_simple_perror_msg("vfork");
  453. goto again;
  454. }
  455. if (pid != 0) {
  456. /* Parent */
  457. cnum++;
  458. if_verbose_print_connection_status();
  459. if (hccp)
  460. hccp->pid = pid;
  461. /* clean up changes done by vforked child */
  462. undo_xsetenv();
  463. goto again;
  464. }
  465. /* Child: prepare env, log, and exec prog */
  466. { /* vfork alert! every xmalloc in this block should be freed! */
  467. char *local_hostname = local_hostname; /* for compiler */
  468. char *local_addr = NULL;
  469. char *free_me0 = NULL;
  470. char *free_me1 = NULL;
  471. char *free_me2 = NULL;
  472. if (verbose || !(opts & OPT_E)) {
  473. if (!max_per_host) /* remote_addr is not yet known */
  474. free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
  475. if (opts & OPT_h) {
  476. free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
  477. if (!remote_hostname) {
  478. bb_error_msg("can't look up hostname for %s", remote_addr);
  479. remote_hostname = remote_addr;
  480. }
  481. }
  482. /* Find out local IP peer connected to.
  483. * Errors ignored (I'm not paranoid enough to imagine kernel
  484. * which doesn't know local IP). */
  485. if (tcp)
  486. getsockname(0, &local.u.sa, &local.len);
  487. /* else: for UDP it is done earlier by parent */
  488. local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
  489. if (opts & OPT_h) {
  490. local_hostname = preset_local_hostname;
  491. if (!local_hostname) {
  492. free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
  493. if (!local_hostname)
  494. bb_error_msg_and_die("can't look up hostname for %s", local_addr);
  495. }
  496. /* else: local_hostname is not NULL, but is NOT malloced! */
  497. }
  498. }
  499. if (verbose) {
  500. pid = getpid();
  501. if (max_per_host) {
  502. bb_error_msg("concurrency %s %u/%u",
  503. remote_addr,
  504. cur_per_host, max_per_host);
  505. }
  506. bb_error_msg((opts & OPT_h)
  507. ? "start %u %s-%s (%s-%s)"
  508. : "start %u %s-%s",
  509. pid,
  510. local_addr, remote_addr,
  511. local_hostname, remote_hostname);
  512. }
  513. if (!(opts & OPT_E)) {
  514. /* setup ucspi env */
  515. const char *proto = tcp ? "TCP" : "UDP";
  516. #ifdef SO_ORIGINAL_DST
  517. /* Extract "original" destination addr:port
  518. * from Linux firewall. Useful when you redirect
  519. * an outbond connection to local handler, and it needs
  520. * to know where it originally tried to connect */
  521. if (tcp && getsockopt(0, SOL_IP, SO_ORIGINAL_DST, &local.u.sa, &local.len) == 0) {
  522. char *addr = xmalloc_sockaddr2dotted(&local.u.sa);
  523. xsetenv_plain("TCPORIGDSTADDR", addr);
  524. free(addr);
  525. }
  526. #endif
  527. xsetenv_plain("PROTO", proto);
  528. xsetenv_proto(proto, "LOCALADDR", local_addr);
  529. xsetenv_proto(proto, "REMOTEADDR", remote_addr);
  530. if (opts & OPT_h) {
  531. xsetenv_proto(proto, "LOCALHOST", local_hostname);
  532. xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
  533. }
  534. //compat? xsetenv_proto(proto, "REMOTEINFO", "");
  535. /* additional */
  536. if (cur_per_host > 0) /* can not be true for udp */
  537. xsetenv_plain("TCPCONCURRENCY", utoa(cur_per_host));
  538. }
  539. free(local_addr);
  540. free(free_me0);
  541. free(free_me1);
  542. free(free_me2);
  543. }
  544. xdup2(0, 1);
  545. /* Restore signal handling for the to-be-execed process */
  546. signal(SIGPIPE, SIG_DFL); /* this one was SIG_IGNed */
  547. /* Non-ignored signals revert to SIG_DFL on exec anyway
  548. * But we can get signals BEFORE execvp(), this is unlikely
  549. * but it would invoke sig_child_handler(), which would
  550. * check waitpid(WNOHANG), then print "status N/M" if verbose.
  551. * I guess we can live with that possibility.
  552. */
  553. /*signal(SIGCHLD, SIG_DFL);*/
  554. sig_unblock(SIGCHLD);
  555. #ifdef SSLSVD
  556. strcpy(id, utoa(pid));
  557. ssl_io(0, argv);
  558. bb_perror_msg_and_die("can't execute '%s'", argv[0]);
  559. #else
  560. BB_EXECVP_or_die(argv);
  561. #endif
  562. }
  563. /*
  564. tcpsvd [-hpEvv] [-c n] [-C n:msg] [-b n] [-u user] [-l name]
  565. [-i dir|-x cdb] [ -t sec] host port prog
  566. tcpsvd creates a TCP/IP socket, binds it to the address host:port,
  567. and listens on the socket for incoming connections.
  568. On each incoming connection, tcpsvd conditionally runs a program,
  569. with standard input reading from the socket, and standard output
  570. writing to the socket, to handle this connection. tcpsvd keeps
  571. listening on the socket for new connections, and can handle
  572. multiple connections simultaneously.
  573. tcpsvd optionally checks for special instructions depending
  574. on the IP address or hostname of the client that initiated
  575. the connection, see ipsvd-instruct(5).
  576. host
  577. host either is a hostname, or a dotted-decimal IP address,
  578. or 0. If host is 0, tcpsvd accepts connections to any local
  579. IP address.
  580. * busybox accepts IPv6 addresses and host:port pairs too
  581. In this case second parameter is ignored
  582. port
  583. tcpsvd accepts connections to host:port. port may be a name
  584. from /etc/services or a number.
  585. prog
  586. prog consists of one or more arguments. For each connection,
  587. tcpsvd normally runs prog, with file descriptor 0 reading from
  588. the network, and file descriptor 1 writing to the network.
  589. By default it also sets up TCP-related environment variables,
  590. see tcp-environ(5)
  591. -i dir
  592. read instructions for handling new connections from the instructions
  593. directory dir. See ipsvd-instruct(5) for details.
  594. * ignored by busyboxed version
  595. -x cdb
  596. read instructions for handling new connections from the constant database
  597. cdb. The constant database normally is created from an instructions
  598. directory by running ipsvd-cdb(8).
  599. * ignored by busyboxed version
  600. -t sec
  601. timeout. This option only takes effect if the -i option is given.
  602. While checking the instructions directory, check the time of last access
  603. of the file that matches the clients address or hostname if any, discard
  604. and remove the file if it wasn't accessed within the last sec seconds;
  605. tcpsvd does not discard or remove a file if the user's write permission
  606. is not set, for those files the timeout is disabled. Default is 0,
  607. which means that the timeout is disabled.
  608. * ignored by busyboxed version
  609. -l name
  610. local hostname. Do not look up the local hostname in DNS, but use name
  611. as hostname. This option must be set if tcpsvd listens on port 53
  612. to avoid loops.
  613. -u user[:group]
  614. drop permissions. Switch user ID to user's UID, and group ID to user's
  615. primary GID after creating and binding to the socket. If user is followed
  616. by a colon and a group name, the group ID is switched to the GID of group
  617. instead. All supplementary groups are removed.
  618. -c n
  619. concurrency. Handle up to n connections simultaneously. Default is 30.
  620. If there are n connections active, tcpsvd defers acceptance of a new
  621. connection until an active connection is closed.
  622. -C n[:msg]
  623. per host concurrency. Allow only up to n connections from the same IP
  624. address simultaneously. If there are n active connections from one IP
  625. address, new incoming connections from this IP address are closed
  626. immediately. If n is followed by :msg, the message msg is written
  627. to the client if possible, before closing the connection. By default
  628. msg is empty. See ipsvd-instruct(5) for supported escape sequences in msg.
  629. For each accepted connection, the current per host concurrency is
  630. available through the environment variable TCPCONCURRENCY. n and msg
  631. can be overwritten by ipsvd(7) instructions, see ipsvd-instruct(5).
  632. By default tcpsvd doesn't keep track of connections.
  633. -h
  634. Look up the client's hostname in DNS.
  635. -p
  636. paranoid. After looking up the client's hostname in DNS, look up the IP
  637. addresses in DNS for that hostname, and forget about the hostname
  638. if none of the addresses match the client's IP address. You should
  639. set this option if you use hostname based instructions. The -p option
  640. implies the -h option.
  641. * ignored by busyboxed version
  642. -b n
  643. backlog. Allow a backlog of approximately n TCP SYNs. On some systems n
  644. is silently limited. Default is 20.
  645. -E
  646. no special environment. Do not set up TCP-related environment variables.
  647. -v
  648. verbose. Print verbose messages to standard output.
  649. -vv
  650. more verbose. Print more verbose messages to standard output.
  651. * no difference between -v and -vv in busyboxed version
  652. */