*
* Copyright (C) 2007 Denys Vlasenko.
*
- * Licensed under GPLv2, see file LICENSE in this tarball for details.
+ * Licensed under GPLv2, see file LICENSE in this source tree.
*/
/* Based on ipsvd-0.12.1. This tcpsvd accepts all options
* with wrong source IP...
* - don't know how to retrieve ORIGDST for udp.
*/
+//config:config TCPSVD
+//config: bool "tcpsvd (14 kb)"
+//config: default y
+//config: help
+//config: tcpsvd listens on a TCP port and runs a program for each new
+//config: connection.
+//config:
+//config:config UDPSVD
+//config: bool "udpsvd (13 kb)"
+//config: default y
+//config: help
+//config: udpsvd listens on an UDP port and runs a program for each new
+//config: connection.
+
+//applet:IF_TCPSVD(APPLET_ODDNAME(tcpsvd, tcpudpsvd, BB_DIR_USR_BIN, BB_SUID_DROP, tcpsvd))
+//applet:IF_UDPSVD(APPLET_ODDNAME(udpsvd, tcpudpsvd, BB_DIR_USR_BIN, BB_SUID_DROP, udpsvd))
+
+//kbuild:lib-$(CONFIG_TCPSVD) += tcpudp.o tcpudp_perhost.o
+//kbuild:lib-$(CONFIG_UDPSVD) += tcpudp.o tcpudp_perhost.o
+
+//usage:#define tcpsvd_trivial_usage
+//usage: "[-hEv] [-c N] [-C N[:MSG]] [-b N] [-u USER] [-l NAME] IP PORT PROG"
+/* with not-implemented options: */
+/* //usage: "[-hpEvv] [-c N] [-C N[:MSG]] [-b N] [-u USER] [-l NAME] [-i DIR|-x CDB] [-t SEC] IP PORT PROG" */
+//usage:#define tcpsvd_full_usage "\n\n"
+//usage: "Create TCP socket, bind to IP:PORT and listen for incoming connections.\n"
+//usage: "Run PROG for each connection.\n"
+//usage: "\n IP PORT IP:PORT to listen on"
+//usage: "\n PROG ARGS Program to run"
+//usage: "\n -u USER[:GRP] Change to user/group after bind"
+//usage: "\n -c N Up to N connections simultaneously (default 30)"
+//usage: "\n -b N Allow backlog of approximately N TCP SYNs (default 20)"
+//usage: "\n -C N[:MSG] Allow only up to N connections from the same IP:"
+//usage: "\n new connections from this IP address are closed"
+//usage: "\n immediately, MSG is written to the peer before close"
+//usage: "\n -E Don't set up environment"
+//usage: "\n -h Look up peer's hostname"
+//usage: "\n -l NAME Local hostname (else look up local hostname in DNS)"
+//usage: "\n -v Verbose"
+//usage: "\n"
+//usage: "\nEnvironment if no -E:"
+//usage: "\nPROTO='TCP'"
+//usage: "\nTCPREMOTEADDR='ip:port'" IF_FEATURE_IPV6(" ('[ip]:port' for IPv6)")
+//usage: "\nTCPLOCALADDR='ip:port'"
+//usage: "\nTCPORIGDSTADDR='ip:port' of destination before firewall"
+//usage: "\n Useful for REDIRECTed-to-local connections:"
+//usage: "\n iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to 8080"
+//usage: "\nTCPCONCURRENCY=num_of_connects_from_this_ip"
+//usage: "\nIf -h:"
+//usage: "\nTCPLOCALHOST='hostname' (-l NAME is used if specified)"
+//usage: "\nTCPREMOTEHOST='hostname'"
+
+//usage:
+//usage:#define udpsvd_trivial_usage
+//usage: "[-hEv] [-c N] [-u USER] [-l NAME] IP PORT PROG"
+//usage:#define udpsvd_full_usage "\n\n"
+//usage: "Create UDP socket, bind to IP:PORT and wait for incoming packets.\n"
+//usage: "Run PROG for each packet, redirecting all further packets with same\n"
+//usage: "peer ip:port to it.\n"
+//usage: "\n IP PORT IP:PORT to listen on"
+//usage: "\n PROG ARGS Program to run"
+//usage: "\n -u USER[:GRP] Change to user/group after bind"
+//usage: "\n -c N Up to N connections simultaneously (default 30)"
+//usage: "\n -E Don't set up environment"
+//usage: "\n -h Look up peer's hostname"
+//usage: "\n -l NAME Local hostname (else look up local hostname in DNS)"
+//usage: "\n -v Verbose"
+//usage: "\n"
+//usage: "\nEnvironment if no -E:"
+//usage: "\nPROTO='UDP'"
+//usage: "\nUDPREMOTEADDR='ip:port'" IF_FEATURE_IPV6(" ('[ip]:port' for IPv6)")
+//usage: "\nUDPLOCALADDR='ip:port'"
+//usage: "\nIf -h:"
+//usage: "\nUDPLOCALHOST='hostname' (-l NAME is used if specified)"
+//usage: "\nUDPREMOTEHOST='hostname'"
#include "libbb.h"
-/* Wants <limits.h> etc, thus included after libbb.h: */
-#include <linux/types.h> /* for __be32 etc */
-#include <linux/netfilter_ipv4.h>
+#include "common_bufsiz.h"
+
+#ifdef __linux__
+/* from linux/netfilter_ipv4.h: */
+# undef SO_ORIGINAL_DST
+# define SO_ORIGINAL_DST 80
+#endif
// TODO: move into this file:
#include "tcpudp_perhost.h"
unsigned cur_per_host;
unsigned cnum;
unsigned cmax;
+ struct hcc *cc;
char **env_cur;
char *env_var[1]; /* actually bigger */
-};
-#define G (*(struct globals*)&bb_common_bufsiz1)
+} FIX_ALIASING;
+#define G (*(struct globals*)bb_common_bufsiz1)
#define verbose (G.verbose )
#define max_per_host (G.max_per_host)
#define cur_per_host (G.cur_per_host)
#define env_cur (G.env_cur )
#define env_var (G.env_var )
#define INIT_G() do { \
+ setup_common_bufsiz(); \
cmax = 30; \
env_cur = &env_var[0]; \
} while (0)
char **pp = env_cur = &env_var[0];
while (*pp) {
char *var = *pp;
- *strchrnul(var, '=') = '\0';
- unsetenv(var);
- free(var);
+ bb_unsetenv_and_free(var);
*pp++ = NULL;
}
}
while ((pid = wait_any_nohang(&wstat)) > 0) {
if (max_per_host)
- ipsvd_perhost_remove(pid);
+ ipsvd_perhost_remove(G.cc, pid);
if (cnum)
cnum--;
if (verbose)
int sock;
int conn;
unsigned backlog = 20;
+ unsigned opts;
INIT_G();
tcp = (applet_name[0] == 't');
- /* 3+ args, -i at most once, -p implies -h, -v is counter, -b N, -c N */
- opt_complementary = "-3:i--i:ph:vv:b+:c+";
+ /* "+": stop on first non-option */
#ifdef SSLSVD
- getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:vU:/:Z:K:",
+ opts = getopt32(argv, "^+"
+ "c:+C:i:x:u:l:Eb:+hpt:vU:/:Z:K:" /* -c NUM, -b NUM */
+ "\0"
+ /* 3+ args, -i at most once, -p implies -h, -v is a counter */
+ "-3:i--i:ph:vv",
&cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
&backlog, &str_t, &ssluser, &root, &cert, &key, &verbose
);
#else
- /* "+": stop on first non-option */
- getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:v",
+ opts = getopt32(argv, "^+"
+ "c:+C:i:x:u:l:Eb:+hpt:v" /* -c NUM, -b NUM */
+ "\0"
+ /* 3+ args, -i at most once, -p implies -h, -v is a counter */
+ "-3:i--i:ph:vv",
&cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
&backlog, &str_t, &verbose
);
#endif
- if (option_mask32 & OPT_C) { /* -C n[:message] */
+ if (opts & OPT_C) { /* -C n[:message] */
max_per_host = bb_strtou(str_C, &str_C, 10);
if (str_C[0]) {
if (str_C[0] != ':')
}
if (max_per_host > cmax)
max_per_host = cmax;
- if (option_mask32 & OPT_u) {
+ if (opts & OPT_u) {
xget_uidgid(&ugid, user);
}
#ifdef SSLSVD
- if (option_mask32 & OPT_U) ssluser = optarg;
- if (option_mask32 & OPT_slash) root = optarg;
- if (option_mask32 & OPT_Z) cert = optarg;
- if (option_mask32 & OPT_K) key = optarg;
+ if (opts & OPT_U) ssluser = optarg;
+ if (opts & OPT_slash) root = optarg;
+ if (opts & OPT_Z) cert = optarg;
+ if (opts & OPT_K) key = optarg;
#endif
argv += optind;
if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
#ifdef SSLSVD
sslser = user;
client = 0;
- if ((getuid() == 0) && !(option_mask32 & OPT_u)) {
- xfunc_exitcode = 100;
- bb_error_msg_and_die("-U ssluser must be set when running as root");
+ if ((getuid() == 0) && !(opts & OPT_u)) {
+ xfunc_error_retval = 100;
+ bb_simple_error_msg_and_die(bb_msg_you_must_be_root);
}
- if (option_mask32 & OPT_u)
+ if (opts & OPT_u)
if (!uidgid_get(&sslugid, ssluser, 1)) {
if (errno) {
bb_perror_msg_and_die("can't get user/group: %s", ssluser);
if (!cert) cert = "./cert.pem";
if (!key) key = cert;
if (matrixSslOpen() < 0)
- fatal("cannot initialize ssl");
+ fatal("can't initialize ssl");
if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
if (client)
- fatal("cannot read cert, key, or ca file");
- fatal("cannot read cert or key file");
+ fatal("can't read cert, key, or ca file");
+ fatal("can't read cert or key file");
}
if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
- fatal("cannot create ssl session");
+ fatal("can't create ssl session");
#endif
sig_block(SIGCHLD);
signal(SIGPIPE, SIG_IGN);
if (max_per_host)
- ipsvd_perhost_init(cmax);
+ G.cc = ipsvd_perhost_init(cmax);
local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
lsa = xhost2sockaddr(argv[0], local_port);
setsockopt_reuseaddr(sock);
sa_len = lsa->len; /* I presume sockaddr len stays the same */
xbind(sock, &lsa->u.sa, sa_len);
- if (tcp)
+ if (tcp) {
xlisten(sock, backlog);
- else /* udp: needed for recv_from_to to work: */
+ close_on_exec_on(sock);
+ } else { /* udp: needed for recv_from_to to work: */
socket_want_pktinfo(sock);
+ }
/* ndelay_off(sock); - it is the default I think? */
#ifndef SSLSVD
- if (option_mask32 & OPT_u) {
+ if (opts & OPT_u) {
/* drop permissions */
xsetgid(ugid.gid);
xsetuid(ugid.uid);
if (verbose) {
char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
- bb_error_msg("listening on %s, starting", addr);
- free(addr);
-#ifndef SSLSVD
- if (option_mask32 & OPT_u)
- printf(", uid %u, gid %u",
+ if (opts & OPT_u)
+ bb_error_msg("listening on %s, starting, uid %u, gid %u", addr,
(unsigned)ugid.uid, (unsigned)ugid.gid);
-#endif
+ else
+ bb_error_msg("listening on %s, starting", addr);
+ free(addr);
}
/* Main accept() loop */
again:
hccp = NULL;
+ again1:
+ close(0);
+ /* It's important to close(0) _before_ wait loop:
+ * fd#0 can be a shared connection fd.
+ * If kept open by us, peer can't detect PROG closing it.
+ */
while (cnum >= cmax)
wait_for_any_sig(); /* expecting SIGCHLD */
- /* Accept a connection to fd #0 */
- again1:
- close(0);
again2:
sig_unblock(SIGCHLD);
local.len = remote.len = sa_len;
if (tcp) {
+ /* Accept a connection to fd #0 */
conn = accept(sock, &remote.u.sa, &remote.len);
} else {
/* In case recv_from_to won't be able to recover local addr.
sig_block(SIGCHLD);
if (conn < 0) {
if (errno != EINTR)
- bb_perror_msg(tcp ? "accept" : "recv");
+ bb_simple_perror_msg(tcp ? "accept" : "recv");
goto again2;
}
xmove_fd(tcp ? conn : sock, 0);
/* Drop connection immediately if cur_per_host > max_per_host
* (minimizing load under SYN flood) */
remote_addr = xmalloc_sockaddr2dotted_noport(&remote.u.sa);
- cur_per_host = ipsvd_perhost_add(remote_addr, max_per_host, &hccp);
+ cur_per_host = ipsvd_perhost_add(G.cc, remote_addr, max_per_host, &hccp);
if (cur_per_host > max_per_host) {
/* ipsvd_perhost_add detected that max is exceeded
* (and did not store ip in connection table) */
* already bound in parent! This seems to work in Linux.
* (otherwise we can move socket to fd #0 only if bind succeeds) */
close(0);
- set_nport(localp, htons(local_port));
+ set_nport(&localp->u.sa, htons(local_port));
xmove_fd(xsocket(localp->u.sa.sa_family, SOCK_DGRAM, 0), 0);
setsockopt_reuseaddr(0); /* crucial */
xbind(0, &localp->u.sa, localp->len);
pid = vfork();
if (pid == -1) {
- bb_perror_msg("vfork");
+ bb_simple_perror_msg("vfork");
goto again;
}
/* Child: prepare env, log, and exec prog */
- /* Closing tcp listening socket */
- if (tcp)
- close(sock);
-
{ /* vfork alert! every xmalloc in this block should be freed! */
char *local_hostname = local_hostname; /* for compiler */
char *local_addr = NULL;
char *free_me1 = NULL;
char *free_me2 = NULL;
- if (verbose || !(option_mask32 & OPT_E)) {
+ if (verbose || !(opts & OPT_E)) {
if (!max_per_host) /* remote_addr is not yet known */
free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
- if (option_mask32 & OPT_h) {
+ if (opts & OPT_h) {
free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
if (!remote_hostname) {
- bb_error_msg("cannot look up hostname for %s", remote_addr);
+ bb_error_msg("can't look up hostname for %s", remote_addr);
remote_hostname = remote_addr;
}
}
getsockname(0, &local.u.sa, &local.len);
/* else: for UDP it is done earlier by parent */
local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
- if (option_mask32 & OPT_h) {
+ if (opts & OPT_h) {
local_hostname = preset_local_hostname;
if (!local_hostname) {
free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
if (!local_hostname)
- bb_error_msg_and_die("cannot look up hostname for %s", local_addr);
+ bb_error_msg_and_die("can't look up hostname for %s", local_addr);
}
/* else: local_hostname is not NULL, but is NOT malloced! */
}
remote_addr,
cur_per_host, max_per_host);
}
- bb_error_msg((option_mask32 & OPT_h)
+ bb_error_msg((opts & OPT_h)
? "start %u %s-%s (%s-%s)"
: "start %u %s-%s",
pid,
local_hostname, remote_hostname);
}
- if (!(option_mask32 & OPT_E)) {
+ if (!(opts & OPT_E)) {
/* setup ucspi env */
const char *proto = tcp ? "TCP" : "UDP";
+#ifdef SO_ORIGINAL_DST
/* Extract "original" destination addr:port
* from Linux firewall. Useful when you redirect
* an outbond connection to local handler, and it needs
xsetenv_plain("TCPORIGDSTADDR", addr);
free(addr);
}
+#endif
xsetenv_plain("PROTO", proto);
xsetenv_proto(proto, "LOCALADDR", local_addr);
xsetenv_proto(proto, "REMOTEADDR", remote_addr);
- if (option_mask32 & OPT_h) {
+ if (opts & OPT_h) {
xsetenv_proto(proto, "LOCALHOST", local_hostname);
xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
}
xdup2(0, 1);
- signal(SIGTERM, SIG_DFL);
- signal(SIGPIPE, SIG_DFL);
- signal(SIGCHLD, SIG_DFL);
+ signal(SIGPIPE, SIG_DFL); /* this one was SIG_IGNed */
+ /* Non-ignored signals revert to SIG_DFL on exec anyway */
+ /*signal(SIGCHLD, SIG_DFL);*/
sig_unblock(SIGCHLD);
#ifdef SSLSVD
strcpy(id, utoa(pid));
ssl_io(0, argv);
+ bb_perror_msg_and_die("can't execute '%s'", argv[0]);
#else
- BB_EXECVP(argv[0], argv);
+ BB_EXECVP_or_die(argv);
#endif
- bb_perror_msg_and_die("exec '%s'", argv[0]);
}
/*
-E
no special environment. Do not set up TCP-related environment variables.
-v
- verbose. Print verbose messsages to standard output.
+ verbose. Print verbose messages to standard output.
-vv
more verbose. Print more verbose messages to standard output.
* no difference between -v and -vv in busyboxed version