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/
5 * Copyright (C) 2007 Denys Vlasenko.
7 * Licensed under GPLv2, see file LICENSE in this source tree.
10 /* Based on ipsvd-0.12.1. This tcpsvd accepts all options
11 * which are supported by one from ipsvd-0.12.1, but not all are
12 * functional. See help text at the end of this file for details.
14 * Code inside "#ifdef SSLSVD" is for sslsvd and is currently unused.
16 * Busybox version exports TCPLOCALADDR instead of
17 * TCPLOCALIP + TCPLOCALPORT pair. ADDR more closely matches reality
18 * (which is "struct sockaddr_XXX". Port is not a separate entity,
19 * it's just a part of (AF_INET[6]) sockaddr!).
21 * TCPORIGDSTADDR is Busybox-specific addition.
23 * udp server is hacked up by reusing TCP code. It has the following
24 * limitation inherent in Unix DGRAM sockets implementation:
25 * - local IP address is retrieved (using recvmsg voodoo) but
26 * child's socket is not bound to it (bind cannot be called on
27 * already bound socket). Thus it still can emit outgoing packets
28 * with wrong source IP...
29 * - don't know how to retrieve ORIGDST for udp.
31 //config:config TCPSVD
32 //config: bool "tcpsvd (13 kb)"
35 //config: tcpsvd listens on a TCP port and runs a program for each new
38 //config:config UDPSVD
39 //config: bool "udpsvd (13 kb)"
42 //config: udpsvd listens on an UDP port and runs a program for each new
45 //applet:IF_TCPSVD(APPLET_ODDNAME(tcpsvd, tcpudpsvd, BB_DIR_USR_BIN, BB_SUID_DROP, tcpsvd))
46 //applet:IF_UDPSVD(APPLET_ODDNAME(udpsvd, tcpudpsvd, BB_DIR_USR_BIN, BB_SUID_DROP, udpsvd))
48 //kbuild:lib-$(CONFIG_TCPSVD) += tcpudp.o tcpudp_perhost.o
49 //kbuild:lib-$(CONFIG_UDPSVD) += tcpudp.o tcpudp_perhost.o
51 //usage:#define tcpsvd_trivial_usage
52 //usage: "[-hEv] [-c N] [-C N[:MSG]] [-b N] [-u USER] [-l NAME] IP PORT PROG"
53 /* with not-implemented options: */
54 /* //usage: "[-hpEvv] [-c N] [-C N[:MSG]] [-b N] [-u USER] [-l NAME] [-i DIR|-x CDB] [-t SEC] IP PORT PROG" */
55 //usage:#define tcpsvd_full_usage "\n\n"
56 //usage: "Create TCP socket, bind to IP:PORT and listen for incoming connections.\n"
57 //usage: "Run PROG for each connection.\n"
58 //usage: "\n IP PORT IP:PORT to listen on"
59 //usage: "\n PROG ARGS Program to run"
60 //usage: "\n -u USER[:GRP] Change to user/group after bind"
61 //usage: "\n -c N Up to N connections simultaneously (default 30)"
62 //usage: "\n -b N Allow backlog of approximately N TCP SYNs (default 20)"
63 //usage: "\n -C N[:MSG] Allow only up to N connections from the same IP:"
64 //usage: "\n new connections from this IP address are closed"
65 //usage: "\n immediately, MSG is written to the peer before close"
66 //usage: "\n -E Don't set up environment"
67 //usage: "\n -h Look up peer's hostname"
68 //usage: "\n -l NAME Local hostname (else look up local hostname in DNS)"
69 //usage: "\n -v Verbose"
71 //usage: "\nEnvironment if no -E:"
72 //usage: "\nPROTO='TCP'"
73 //usage: "\nTCPREMOTEADDR='ip:port'" IF_FEATURE_IPV6(" ('[ip]:port' for IPv6)")
74 //usage: "\nTCPLOCALADDR='ip:port'"
75 //usage: "\nTCPORIGDSTADDR='ip:port' of destination before firewall"
76 //usage: "\n Useful for REDIRECTed-to-local connections:"
77 //usage: "\n iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to 8080"
78 //usage: "\nTCPCONCURRENCY=num_of_connects_from_this_ip"
80 //usage: "\nTCPLOCALHOST='hostname' (-l NAME is used if specified)"
81 //usage: "\nTCPREMOTEHOST='hostname'"
84 //usage:#define udpsvd_trivial_usage
85 //usage: "[-hEv] [-c N] [-u USER] [-l NAME] IP PORT PROG"
86 //usage:#define udpsvd_full_usage "\n\n"
87 //usage: "Create UDP socket, bind to IP:PORT and wait for incoming packets.\n"
88 //usage: "Run PROG for each packet, redirecting all further packets with same\n"
89 //usage: "peer ip:port to it.\n"
90 //usage: "\n IP PORT IP:PORT to listen on"
91 //usage: "\n PROG ARGS Program to run"
92 //usage: "\n -u USER[:GRP] Change to user/group after bind"
93 //usage: "\n -c N Up to N connections simultaneously (default 30)"
94 //usage: "\n -E Don't set up environment"
95 //usage: "\n -h Look up peer's hostname"
96 //usage: "\n -l NAME Local hostname (else look up local hostname in DNS)"
97 //usage: "\n -v Verbose"
99 //usage: "\nEnvironment if no -E:"
100 //usage: "\nPROTO='UDP'"
101 //usage: "\nUDPREMOTEADDR='ip:port'" IF_FEATURE_IPV6(" ('[ip]:port' for IPv6)")
102 //usage: "\nUDPLOCALADDR='ip:port'"
104 //usage: "\nUDPLOCALHOST='hostname' (-l NAME is used if specified)"
105 //usage: "\nUDPREMOTEHOST='hostname'"
108 #include "common_bufsiz.h"
111 /* from linux/netfilter_ipv4.h: */
112 # undef SO_ORIGINAL_DST
113 # define SO_ORIGINAL_DST 80
116 // TODO: move into this file:
117 #include "tcpudp_perhost.h"
120 #include "matrixSsl.h"
126 unsigned max_per_host;
127 unsigned cur_per_host;
131 char *env_var[1]; /* actually bigger */
133 #define G (*(struct globals*)bb_common_bufsiz1)
134 #define verbose (G.verbose )
135 #define max_per_host (G.max_per_host)
136 #define cur_per_host (G.cur_per_host)
137 #define cnum (G.cnum )
138 #define cmax (G.cmax )
139 #define env_cur (G.env_cur )
140 #define env_var (G.env_var )
141 #define INIT_G() do { \
142 setup_common_bufsiz(); \
144 env_cur = &env_var[0]; \
148 /* We have to be careful about leaking memory in repeated setenv's */
149 static void xsetenv_plain(const char *n, const char *v)
151 char *var = xasprintf("%s=%s", n, v);
156 static void xsetenv_proto(const char *proto, const char *n, const char *v)
158 char *var = xasprintf("%s%s=%s", proto, n, v);
163 static void undo_xsetenv(void)
165 char **pp = env_cur = &env_var[0];
168 bb_unsetenv_and_free(var);
173 static void sig_term_handler(int sig)
176 bb_error_msg("got signal %u, exit", sig);
177 kill_myself_with_sig(sig);
180 /* Little bloated, but tries to give accurate info how child exited.
181 * Makes easier to spot segfaulting children etc... */
182 static void print_waitstat(unsigned pid, int wstat)
185 const char *cause = "?exit";
187 if (WIFEXITED(wstat)) {
189 e = WEXITSTATUS(wstat);
190 } else if (WIFSIGNALED(wstat)) {
194 bb_error_msg("end %d %s %d", pid, cause, e);
197 /* Must match getopt32 in main! */
212 OPT_U = (1 << 13), /* from here: sslsvd only */
213 OPT_slash = (1 << 14),
218 static void connection_status(void)
220 /* "only 1 client max" desn't need this */
222 bb_error_msg("status %u/%u", cnum, cmax);
225 static void sig_child_handler(int sig UNUSED_PARAM)
230 while ((pid = wait_any_nohang(&wstat)) > 0) {
232 ipsvd_perhost_remove(pid);
236 print_waitstat(pid, wstat);
242 int tcpudpsvd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
243 int tcpudpsvd_main(int argc UNUSED_PARAM, char **argv)
248 const char *instructs;
249 char *msg_per_host = NULL;
250 unsigned len_per_host = len_per_host; /* gcc */
252 struct bb_uidgid_t ugid;
256 char *preset_local_hostname = NULL;
257 char *remote_hostname = remote_hostname; /* for compiler */
258 char *remote_addr = remote_addr; /* for compiler */
259 len_and_sockaddr *lsa;
260 len_and_sockaddr local, remote;
265 unsigned backlog = 20;
270 tcp = (applet_name[0] == 't');
273 opts = getopt32(argv, "^+"
274 "c:+C:i:x:u:l:Eb:+hpt:vU:/:Z:K:" /* -c NUM, -b NUM */
275 /* 3+ args, -i at most once, -p implies -h, -v is a counter */
276 "\0" "-3:i--i:ph:vv",
277 &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
278 &backlog, &str_t, &ssluser, &root, &cert, &key, &verbose
281 /* "+": stop on first non-option */
282 opts = getopt32(argv, "+c:+C:i:x:u:l:Eb:hpt:v",
283 &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
284 &backlog, &str_t, &verbose
287 if (opts & OPT_C) { /* -C n[:message] */
288 max_per_host = bb_strtou(str_C, &str_C, 10);
292 msg_per_host = str_C + 1;
293 len_per_host = strlen(msg_per_host);
296 if (max_per_host > cmax)
299 xget_uidgid(&ugid, user);
302 if (opts & OPT_U) ssluser = optarg;
303 if (opts & OPT_slash) root = optarg;
304 if (opts & OPT_Z) cert = optarg;
305 if (opts & OPT_K) key = optarg;
308 if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
309 argv[0] = (char*)"0.0.0.0";
311 /* Per-IP flood protection is not thought-out for UDP */
315 bb_sanitize_stdio(); /* fd# 0,1,2 must be opened */
320 if ((getuid() == 0) && !(opts & OPT_u)) {
321 xfunc_exitcode = 100;
322 bb_error_msg_and_die(bb_msg_you_must_be_root);
325 if (!uidgid_get(&sslugid, ssluser, 1)) {
327 bb_perror_msg_and_die("can't get user/group: %s", ssluser);
329 bb_error_msg_and_die("unknown user/group %s", ssluser);
331 if (!cert) cert = "./cert.pem";
332 if (!key) key = cert;
333 if (matrixSslOpen() < 0)
334 fatal("can't initialize ssl");
335 if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
337 fatal("can't read cert, key, or ca file");
338 fatal("can't read cert or key file");
340 if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
341 fatal("can't create ssl session");
345 signal(SIGCHLD, sig_child_handler);
346 bb_signals(BB_FATAL_SIGS, sig_term_handler);
347 signal(SIGPIPE, SIG_IGN);
350 ipsvd_perhost_init(cmax);
352 local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
353 lsa = xhost2sockaddr(argv[0], local_port);
356 sock = xsocket(lsa->u.sa.sa_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
357 setsockopt_reuseaddr(sock);
358 sa_len = lsa->len; /* I presume sockaddr len stays the same */
359 xbind(sock, &lsa->u.sa, sa_len);
361 xlisten(sock, backlog);
362 close_on_exec_on(sock);
363 } else { /* udp: needed for recv_from_to to work: */
364 socket_want_pktinfo(sock);
366 /* ndelay_off(sock); - it is the default I think? */
370 /* drop permissions */
377 char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
379 bb_error_msg("listening on %s, starting, uid %u, gid %u", addr,
380 (unsigned)ugid.uid, (unsigned)ugid.gid);
382 bb_error_msg("listening on %s, starting", addr);
386 /* Main accept() loop */
393 /* It's important to close(0) _before_ wait loop:
394 * fd#0 can be a shared connection fd.
395 * If kept open by us, peer can't detect PROG closing it.
398 wait_for_any_sig(); /* expecting SIGCHLD */
401 sig_unblock(SIGCHLD);
402 local.len = remote.len = sa_len;
404 /* Accept a connection to fd #0 */
405 conn = accept(sock, &remote.u.sa, &remote.len);
407 /* In case recv_from_to won't be able to recover local addr.
408 * Also sets port - recv_from_to is unable to do it. */
410 conn = recv_from_to(sock, NULL, 0, MSG_PEEK,
411 &remote.u.sa, &local.u.sa, sa_len);
416 bb_perror_msg(tcp ? "accept" : "recv");
419 xmove_fd(tcp ? conn : sock, 0);
422 /* Drop connection immediately if cur_per_host > max_per_host
423 * (minimizing load under SYN flood) */
424 remote_addr = xmalloc_sockaddr2dotted_noport(&remote.u.sa);
425 cur_per_host = ipsvd_perhost_add(remote_addr, max_per_host, &hccp);
426 if (cur_per_host > max_per_host) {
427 /* ipsvd_perhost_add detected that max is exceeded
428 * (and did not store ip in connection table) */
431 /* don't block or test for errors */
432 send(0, msg_per_host, len_per_host, MSG_DONTWAIT);
436 /* NB: remote_addr is not leaked, it is stored in conn table */
440 /* Voodoo magic: making udp sockets each receive its own
441 * packets is not trivial, and I still not sure
442 * I do it 100% right.
443 * 1) we have to do it before fork()
444 * 2) order is important - is it right now? */
446 /* Open new non-connected UDP socket for further clients... */
447 sock = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
448 setsockopt_reuseaddr(sock);
449 /* Make plain write/send work for old socket by supplying default
450 * destination address. This also restricts incoming packets
451 * to ones coming from this remote IP. */
452 xconnect(0, &remote.u.sa, sa_len);
453 /* hole? at this point we have no wildcard udp socket...
454 * can this cause clients to get "port unreachable" icmp?
455 * Yup, time window is very small, but it exists (is it?) */
456 /* ..."open new socket", continued */
457 xbind(sock, &lsa->u.sa, sa_len);
458 socket_want_pktinfo(sock);
461 * we cannot replace fd #0 - we will lose pending packet
462 * which is already buffered for us! And we cannot use fd #1
463 * instead - it will "intercept" all following packets, but child
464 * does not expect data coming *from fd #1*! */
466 /* Make it so that local addr is fixed to localp->u.sa
467 * and we don't accidentally accept packets to other local IPs. */
468 /* NB: we possibly bind to the _very_ same_ address & port as the one
469 * already bound in parent! This seems to work in Linux.
470 * (otherwise we can move socket to fd #0 only if bind succeeds) */
472 set_nport(&localp->u.sa, htons(local_port));
473 xmove_fd(xsocket(localp->u.sa.sa_family, SOCK_DGRAM, 0), 0);
474 setsockopt_reuseaddr(0); /* crucial */
475 xbind(0, &localp->u.sa, localp->len);
481 bb_perror_msg("vfork");
492 /* clean up changes done by vforked child */
497 /* Child: prepare env, log, and exec prog */
499 { /* vfork alert! every xmalloc in this block should be freed! */
500 char *local_hostname = local_hostname; /* for compiler */
501 char *local_addr = NULL;
502 char *free_me0 = NULL;
503 char *free_me1 = NULL;
504 char *free_me2 = NULL;
506 if (verbose || !(opts & OPT_E)) {
507 if (!max_per_host) /* remote_addr is not yet known */
508 free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
510 free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
511 if (!remote_hostname) {
512 bb_error_msg("can't look up hostname for %s", remote_addr);
513 remote_hostname = remote_addr;
516 /* Find out local IP peer connected to.
517 * Errors ignored (I'm not paranoid enough to imagine kernel
518 * which doesn't know local IP). */
520 getsockname(0, &local.u.sa, &local.len);
521 /* else: for UDP it is done earlier by parent */
522 local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
524 local_hostname = preset_local_hostname;
525 if (!local_hostname) {
526 free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
528 bb_error_msg_and_die("can't look up hostname for %s", local_addr);
530 /* else: local_hostname is not NULL, but is NOT malloced! */
536 bb_error_msg("concurrency %s %u/%u",
538 cur_per_host, max_per_host);
540 bb_error_msg((opts & OPT_h)
541 ? "start %u %s-%s (%s-%s)"
544 local_addr, remote_addr,
545 local_hostname, remote_hostname);
548 if (!(opts & OPT_E)) {
549 /* setup ucspi env */
550 const char *proto = tcp ? "TCP" : "UDP";
552 #ifdef SO_ORIGINAL_DST
553 /* Extract "original" destination addr:port
554 * from Linux firewall. Useful when you redirect
555 * an outbond connection to local handler, and it needs
556 * to know where it originally tried to connect */
557 if (tcp && getsockopt(0, SOL_IP, SO_ORIGINAL_DST, &local.u.sa, &local.len) == 0) {
558 char *addr = xmalloc_sockaddr2dotted(&local.u.sa);
559 xsetenv_plain("TCPORIGDSTADDR", addr);
563 xsetenv_plain("PROTO", proto);
564 xsetenv_proto(proto, "LOCALADDR", local_addr);
565 xsetenv_proto(proto, "REMOTEADDR", remote_addr);
567 xsetenv_proto(proto, "LOCALHOST", local_hostname);
568 xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
570 //compat? xsetenv_proto(proto, "REMOTEINFO", "");
572 if (cur_per_host > 0) /* can not be true for udp */
573 xsetenv_plain("TCPCONCURRENCY", utoa(cur_per_host));
583 signal(SIGPIPE, SIG_DFL); /* this one was SIG_IGNed */
584 /* Non-ignored signals revert to SIG_DFL on exec anyway */
585 /*signal(SIGCHLD, SIG_DFL);*/
586 sig_unblock(SIGCHLD);
589 strcpy(id, utoa(pid));
591 bb_perror_msg_and_die("can't execute '%s'", argv[0]);
593 BB_EXECVP_or_die(argv);
598 tcpsvd [-hpEvv] [-c n] [-C n:msg] [-b n] [-u user] [-l name]
599 [-i dir|-x cdb] [ -t sec] host port prog
601 tcpsvd creates a TCP/IP socket, binds it to the address host:port,
602 and listens on the socket for incoming connections.
604 On each incoming connection, tcpsvd conditionally runs a program,
605 with standard input reading from the socket, and standard output
606 writing to the socket, to handle this connection. tcpsvd keeps
607 listening on the socket for new connections, and can handle
608 multiple connections simultaneously.
610 tcpsvd optionally checks for special instructions depending
611 on the IP address or hostname of the client that initiated
612 the connection, see ipsvd-instruct(5).
615 host either is a hostname, or a dotted-decimal IP address,
616 or 0. If host is 0, tcpsvd accepts connections to any local
618 * busybox accepts IPv6 addresses and host:port pairs too
619 In this case second parameter is ignored
621 tcpsvd accepts connections to host:port. port may be a name
622 from /etc/services or a number.
624 prog consists of one or more arguments. For each connection,
625 tcpsvd normally runs prog, with file descriptor 0 reading from
626 the network, and file descriptor 1 writing to the network.
627 By default it also sets up TCP-related environment variables,
630 read instructions for handling new connections from the instructions
631 directory dir. See ipsvd-instruct(5) for details.
632 * ignored by busyboxed version
634 read instructions for handling new connections from the constant database
635 cdb. The constant database normally is created from an instructions
636 directory by running ipsvd-cdb(8).
637 * ignored by busyboxed version
639 timeout. This option only takes effect if the -i option is given.
640 While checking the instructions directory, check the time of last access
641 of the file that matches the clients address or hostname if any, discard
642 and remove the file if it wasn't accessed within the last sec seconds;
643 tcpsvd does not discard or remove a file if the user's write permission
644 is not set, for those files the timeout is disabled. Default is 0,
645 which means that the timeout is disabled.
646 * ignored by busyboxed version
648 local hostname. Do not look up the local hostname in DNS, but use name
649 as hostname. This option must be set if tcpsvd listens on port 53
652 drop permissions. Switch user ID to user's UID, and group ID to user's
653 primary GID after creating and binding to the socket. If user is followed
654 by a colon and a group name, the group ID is switched to the GID of group
655 instead. All supplementary groups are removed.
657 concurrency. Handle up to n connections simultaneously. Default is 30.
658 If there are n connections active, tcpsvd defers acceptance of a new
659 connection until an active connection is closed.
661 per host concurrency. Allow only up to n connections from the same IP
662 address simultaneously. If there are n active connections from one IP
663 address, new incoming connections from this IP address are closed
664 immediately. If n is followed by :msg, the message msg is written
665 to the client if possible, before closing the connection. By default
666 msg is empty. See ipsvd-instruct(5) for supported escape sequences in msg.
668 For each accepted connection, the current per host concurrency is
669 available through the environment variable TCPCONCURRENCY. n and msg
670 can be overwritten by ipsvd(7) instructions, see ipsvd-instruct(5).
671 By default tcpsvd doesn't keep track of connections.
673 Look up the client's hostname in DNS.
675 paranoid. After looking up the client's hostname in DNS, look up the IP
676 addresses in DNS for that hostname, and forget about the hostname
677 if none of the addresses match the client's IP address. You should
678 set this option if you use hostname based instructions. The -p option
679 implies the -h option.
680 * ignored by busyboxed version
682 backlog. Allow a backlog of approximately n TCP SYNs. On some systems n
683 is silently limited. Default is 20.
685 no special environment. Do not set up TCP-related environment variables.
687 verbose. Print verbose messages to standard output.
689 more verbose. Print more verbose messages to standard output.
690 * no difference between -v and -vv in busyboxed version