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.
34 /* Wants <limits.h> etc, thus included after libbb.h: */
36 #include <linux/types.h> /* for __be32 etc */
37 #include <linux/netfilter_ipv4.h>
40 // TODO: move into this file:
41 #include "tcpudp_perhost.h"
44 #include "matrixSsl.h"
50 unsigned max_per_host;
51 unsigned cur_per_host;
55 char *env_var[1]; /* actually bigger */
57 #define G (*(struct globals*)&bb_common_bufsiz1)
58 #define verbose (G.verbose )
59 #define max_per_host (G.max_per_host)
60 #define cur_per_host (G.cur_per_host)
61 #define cnum (G.cnum )
62 #define cmax (G.cmax )
63 #define env_cur (G.env_cur )
64 #define env_var (G.env_var )
65 #define INIT_G() do { \
67 env_cur = &env_var[0]; \
71 /* We have to be careful about leaking memory in repeated setenv's */
72 static void xsetenv_plain(const char *n, const char *v)
74 char *var = xasprintf("%s=%s", n, v);
79 static void xsetenv_proto(const char *proto, const char *n, const char *v)
81 char *var = xasprintf("%s%s=%s", proto, n, v);
86 static void undo_xsetenv(void)
88 char **pp = env_cur = &env_var[0];
91 bb_unsetenv_and_free(var);
96 static void sig_term_handler(int sig)
99 bb_error_msg("got signal %u, exit", sig);
100 kill_myself_with_sig(sig);
103 /* Little bloated, but tries to give accurate info how child exited.
104 * Makes easier to spot segfaulting children etc... */
105 static void print_waitstat(unsigned pid, int wstat)
108 const char *cause = "?exit";
110 if (WIFEXITED(wstat)) {
112 e = WEXITSTATUS(wstat);
113 } else if (WIFSIGNALED(wstat)) {
117 bb_error_msg("end %d %s %d", pid, cause, e);
120 /* Must match getopt32 in main! */
135 OPT_U = (1 << 13), /* from here: sslsvd only */
136 OPT_slash = (1 << 14),
141 static void connection_status(void)
143 /* "only 1 client max" desn't need this */
145 bb_error_msg("status %u/%u", cnum, cmax);
148 static void sig_child_handler(int sig UNUSED_PARAM)
153 while ((pid = wait_any_nohang(&wstat)) > 0) {
155 ipsvd_perhost_remove(pid);
159 print_waitstat(pid, wstat);
165 int tcpudpsvd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
166 int tcpudpsvd_main(int argc UNUSED_PARAM, char **argv)
171 const char *instructs;
172 char *msg_per_host = NULL;
173 unsigned len_per_host = len_per_host; /* gcc */
175 struct bb_uidgid_t ugid;
179 char *preset_local_hostname = NULL;
180 char *remote_hostname = remote_hostname; /* for compiler */
181 char *remote_addr = remote_addr; /* for compiler */
182 len_and_sockaddr *lsa;
183 len_and_sockaddr local, remote;
188 unsigned backlog = 20;
193 tcp = (applet_name[0] == 't');
195 /* 3+ args, -i at most once, -p implies -h, -v is counter, -b N, -c N */
196 opt_complementary = "-3:i--i:ph:vv:b+:c+";
198 opts = getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:vU:/:Z:K:",
199 &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
200 &backlog, &str_t, &ssluser, &root, &cert, &key, &verbose
203 /* "+": stop on first non-option */
204 opts = getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:v",
205 &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
206 &backlog, &str_t, &verbose
209 if (opts & OPT_C) { /* -C n[:message] */
210 max_per_host = bb_strtou(str_C, &str_C, 10);
214 msg_per_host = str_C + 1;
215 len_per_host = strlen(msg_per_host);
218 if (max_per_host > cmax)
221 xget_uidgid(&ugid, user);
224 if (opts & OPT_U) ssluser = optarg;
225 if (opts & OPT_slash) root = optarg;
226 if (opts & OPT_Z) cert = optarg;
227 if (opts & OPT_K) key = optarg;
230 if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
231 argv[0] = (char*)"0.0.0.0";
233 /* Per-IP flood protection is not thought-out for UDP */
237 bb_sanitize_stdio(); /* fd# 0,1,2 must be opened */
242 if ((getuid() == 0) && !(opts & OPT_u)) {
243 xfunc_exitcode = 100;
244 bb_error_msg_and_die(bb_msg_you_must_be_root);
247 if (!uidgid_get(&sslugid, ssluser, 1)) {
249 bb_perror_msg_and_die("can't get user/group: %s", ssluser);
251 bb_error_msg_and_die("unknown user/group %s", ssluser);
253 if (!cert) cert = "./cert.pem";
254 if (!key) key = cert;
255 if (matrixSslOpen() < 0)
256 fatal("can't initialize ssl");
257 if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
259 fatal("can't read cert, key, or ca file");
260 fatal("can't read cert or key file");
262 if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
263 fatal("can't create ssl session");
267 signal(SIGCHLD, sig_child_handler);
268 bb_signals(BB_FATAL_SIGS, sig_term_handler);
269 signal(SIGPIPE, SIG_IGN);
272 ipsvd_perhost_init(cmax);
274 local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
275 lsa = xhost2sockaddr(argv[0], local_port);
278 sock = xsocket(lsa->u.sa.sa_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
279 setsockopt_reuseaddr(sock);
280 sa_len = lsa->len; /* I presume sockaddr len stays the same */
281 xbind(sock, &lsa->u.sa, sa_len);
283 xlisten(sock, backlog);
284 close_on_exec_on(sock);
285 } else { /* udp: needed for recv_from_to to work: */
286 socket_want_pktinfo(sock);
288 /* ndelay_off(sock); - it is the default I think? */
292 /* drop permissions */
299 char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
301 bb_error_msg("listening on %s, starting, uid %u, gid %u", addr,
302 (unsigned)ugid.uid, (unsigned)ugid.gid);
304 bb_error_msg("listening on %s, starting", addr);
308 /* Main accept() loop */
314 wait_for_any_sig(); /* expecting SIGCHLD */
316 /* Accept a connection to fd #0 */
320 sig_unblock(SIGCHLD);
321 local.len = remote.len = sa_len;
323 conn = accept(sock, &remote.u.sa, &remote.len);
325 /* In case recv_from_to won't be able to recover local addr.
326 * Also sets port - recv_from_to is unable to do it. */
328 conn = recv_from_to(sock, NULL, 0, MSG_PEEK,
329 &remote.u.sa, &local.u.sa, sa_len);
334 bb_perror_msg(tcp ? "accept" : "recv");
337 xmove_fd(tcp ? conn : sock, 0);
340 /* Drop connection immediately if cur_per_host > max_per_host
341 * (minimizing load under SYN flood) */
342 remote_addr = xmalloc_sockaddr2dotted_noport(&remote.u.sa);
343 cur_per_host = ipsvd_perhost_add(remote_addr, max_per_host, &hccp);
344 if (cur_per_host > max_per_host) {
345 /* ipsvd_perhost_add detected that max is exceeded
346 * (and did not store ip in connection table) */
349 /* don't block or test for errors */
350 send(0, msg_per_host, len_per_host, MSG_DONTWAIT);
354 /* NB: remote_addr is not leaked, it is stored in conn table */
358 /* Voodoo magic: making udp sockets each receive its own
359 * packets is not trivial, and I still not sure
360 * I do it 100% right.
361 * 1) we have to do it before fork()
362 * 2) order is important - is it right now? */
364 /* Open new non-connected UDP socket for further clients... */
365 sock = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
366 setsockopt_reuseaddr(sock);
367 /* Make plain write/send work for old socket by supplying default
368 * destination address. This also restricts incoming packets
369 * to ones coming from this remote IP. */
370 xconnect(0, &remote.u.sa, sa_len);
371 /* hole? at this point we have no wildcard udp socket...
372 * can this cause clients to get "port unreachable" icmp?
373 * Yup, time window is very small, but it exists (is it?) */
374 /* ..."open new socket", continued */
375 xbind(sock, &lsa->u.sa, sa_len);
376 socket_want_pktinfo(sock);
379 * we cannot replace fd #0 - we will lose pending packet
380 * which is already buffered for us! And we cannot use fd #1
381 * instead - it will "intercept" all following packets, but child
382 * does not expect data coming *from fd #1*! */
384 /* Make it so that local addr is fixed to localp->u.sa
385 * and we don't accidentally accept packets to other local IPs. */
386 /* NB: we possibly bind to the _very_ same_ address & port as the one
387 * already bound in parent! This seems to work in Linux.
388 * (otherwise we can move socket to fd #0 only if bind succeeds) */
390 set_nport(localp, htons(local_port));
391 xmove_fd(xsocket(localp->u.sa.sa_family, SOCK_DGRAM, 0), 0);
392 setsockopt_reuseaddr(0); /* crucial */
393 xbind(0, &localp->u.sa, localp->len);
399 bb_perror_msg("vfork");
410 /* clean up changes done by vforked child */
415 /* Child: prepare env, log, and exec prog */
417 { /* vfork alert! every xmalloc in this block should be freed! */
418 char *local_hostname = local_hostname; /* for compiler */
419 char *local_addr = NULL;
420 char *free_me0 = NULL;
421 char *free_me1 = NULL;
422 char *free_me2 = NULL;
424 if (verbose || !(opts & OPT_E)) {
425 if (!max_per_host) /* remote_addr is not yet known */
426 free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
428 free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
429 if (!remote_hostname) {
430 bb_error_msg("can't look up hostname for %s", remote_addr);
431 remote_hostname = remote_addr;
434 /* Find out local IP peer connected to.
435 * Errors ignored (I'm not paranoid enough to imagine kernel
436 * which doesn't know local IP). */
438 getsockname(0, &local.u.sa, &local.len);
439 /* else: for UDP it is done earlier by parent */
440 local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
442 local_hostname = preset_local_hostname;
443 if (!local_hostname) {
444 free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
446 bb_error_msg_and_die("can't look up hostname for %s", local_addr);
448 /* else: local_hostname is not NULL, but is NOT malloced! */
454 bb_error_msg("concurrency %s %u/%u",
456 cur_per_host, max_per_host);
458 bb_error_msg((opts & OPT_h)
459 ? "start %u %s-%s (%s-%s)"
462 local_addr, remote_addr,
463 local_hostname, remote_hostname);
466 if (!(opts & OPT_E)) {
467 /* setup ucspi env */
468 const char *proto = tcp ? "TCP" : "UDP";
470 #ifdef SO_ORIGINAL_DST
471 /* Extract "original" destination addr:port
472 * from Linux firewall. Useful when you redirect
473 * an outbond connection to local handler, and it needs
474 * to know where it originally tried to connect */
475 if (tcp && getsockopt(0, SOL_IP, SO_ORIGINAL_DST, &local.u.sa, &local.len) == 0) {
476 char *addr = xmalloc_sockaddr2dotted(&local.u.sa);
477 xsetenv_plain("TCPORIGDSTADDR", addr);
481 xsetenv_plain("PROTO", proto);
482 xsetenv_proto(proto, "LOCALADDR", local_addr);
483 xsetenv_proto(proto, "REMOTEADDR", remote_addr);
485 xsetenv_proto(proto, "LOCALHOST", local_hostname);
486 xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
488 //compat? xsetenv_proto(proto, "REMOTEINFO", "");
490 if (cur_per_host > 0) /* can not be true for udp */
491 xsetenv_plain("TCPCONCURRENCY", utoa(cur_per_host));
501 signal(SIGPIPE, SIG_DFL); /* this one was SIG_IGNed */
502 /* Non-ignored signals revert to SIG_DFL on exec anyway */
503 /*signal(SIGCHLD, SIG_DFL);*/
504 sig_unblock(SIGCHLD);
507 strcpy(id, utoa(pid));
509 bb_perror_msg_and_die("can't execute '%s'", argv[0]);
511 BB_EXECVP_or_die(argv);
516 tcpsvd [-hpEvv] [-c n] [-C n:msg] [-b n] [-u user] [-l name]
517 [-i dir|-x cdb] [ -t sec] host port prog
519 tcpsvd creates a TCP/IP socket, binds it to the address host:port,
520 and listens on the socket for incoming connections.
522 On each incoming connection, tcpsvd conditionally runs a program,
523 with standard input reading from the socket, and standard output
524 writing to the socket, to handle this connection. tcpsvd keeps
525 listening on the socket for new connections, and can handle
526 multiple connections simultaneously.
528 tcpsvd optionally checks for special instructions depending
529 on the IP address or hostname of the client that initiated
530 the connection, see ipsvd-instruct(5).
533 host either is a hostname, or a dotted-decimal IP address,
534 or 0. If host is 0, tcpsvd accepts connections to any local
536 * busybox accepts IPv6 addresses and host:port pairs too
537 In this case second parameter is ignored
539 tcpsvd accepts connections to host:port. port may be a name
540 from /etc/services or a number.
542 prog consists of one or more arguments. For each connection,
543 tcpsvd normally runs prog, with file descriptor 0 reading from
544 the network, and file descriptor 1 writing to the network.
545 By default it also sets up TCP-related environment variables,
548 read instructions for handling new connections from the instructions
549 directory dir. See ipsvd-instruct(5) for details.
550 * ignored by busyboxed version
552 read instructions for handling new connections from the constant database
553 cdb. The constant database normally is created from an instructions
554 directory by running ipsvd-cdb(8).
555 * ignored by busyboxed version
557 timeout. This option only takes effect if the -i option is given.
558 While checking the instructions directory, check the time of last access
559 of the file that matches the clients address or hostname if any, discard
560 and remove the file if it wasn't accessed within the last sec seconds;
561 tcpsvd does not discard or remove a file if the user's write permission
562 is not set, for those files the timeout is disabled. Default is 0,
563 which means that the timeout is disabled.
564 * ignored by busyboxed version
566 local hostname. Do not look up the local hostname in DNS, but use name
567 as hostname. This option must be set if tcpsvd listens on port 53
570 drop permissions. Switch user ID to user's UID, and group ID to user's
571 primary GID after creating and binding to the socket. If user is followed
572 by a colon and a group name, the group ID is switched to the GID of group
573 instead. All supplementary groups are removed.
575 concurrency. Handle up to n connections simultaneously. Default is 30.
576 If there are n connections active, tcpsvd defers acceptance of a new
577 connection until an active connection is closed.
579 per host concurrency. Allow only up to n connections from the same IP
580 address simultaneously. If there are n active connections from one IP
581 address, new incoming connections from this IP address are closed
582 immediately. If n is followed by :msg, the message msg is written
583 to the client if possible, before closing the connection. By default
584 msg is empty. See ipsvd-instruct(5) for supported escape sequences in msg.
586 For each accepted connection, the current per host concurrency is
587 available through the environment variable TCPCONCURRENCY. n and msg
588 can be overwritten by ipsvd(7) instructions, see ipsvd-instruct(5).
589 By default tcpsvd doesn't keep track of connections.
591 Look up the client's hostname in DNS.
593 paranoid. After looking up the client's hostname in DNS, look up the IP
594 addresses in DNS for that hostname, and forget about the hostname
595 if none of the addresses match the client's IP address. You should
596 set this option if you use hostname based instructions. The -p option
597 implies the -h option.
598 * ignored by busyboxed version
600 backlog. Allow a backlog of approximately n TCP SYNs. On some systems n
601 is silently limited. Default is 20.
603 no special environment. Do not set up TCP-related environment variables.
605 verbose. Print verbose messsages to standard output.
607 more verbose. Print more verbose messages to standard output.
608 * no difference between -v and -vv in busyboxed version