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 tarball for details.
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.
33 /* Wants <limits.h> etc, thus included after libbb.h: */
34 #include <linux/types.h> /* for __be32 etc */
35 #include <linux/netfilter_ipv4.h>
37 // TODO: move into this file:
38 #include "tcpudp_perhost.h"
41 #include "matrixSsl.h"
47 unsigned max_per_host;
48 unsigned cur_per_host;
52 char *env_var[1]; /* actually bigger */
54 #define G (*(struct globals*)&bb_common_bufsiz1)
55 #define verbose (G.verbose )
56 #define max_per_host (G.max_per_host)
57 #define cur_per_host (G.cur_per_host)
58 #define cnum (G.cnum )
59 #define cmax (G.cmax )
60 #define env_cur (G.env_cur )
61 #define env_var (G.env_var )
62 #define INIT_G() do { \
64 env_cur = &env_var[0]; \
68 /* We have to be careful about leaking memory in repeated setenv's */
69 static void xsetenv_plain(const char *n, const char *v)
71 char *var = xasprintf("%s=%s", n, v);
76 static void xsetenv_proto(const char *proto, const char *n, const char *v)
78 char *var = xasprintf("%s%s=%s", proto, n, v);
83 static void undo_xsetenv(void)
85 char **pp = env_cur = &env_var[0];
94 static void sig_term_handler(int sig)
97 bb_error_msg("got signal %u, exit", sig);
98 kill_myself_with_sig(sig);
101 /* Little bloated, but tries to give accurate info how child exited.
102 * Makes easier to spot segfaulting children etc... */
103 static void print_waitstat(unsigned pid, int wstat)
106 const char *cause = "?exit";
108 if (WIFEXITED(wstat)) {
110 e = WEXITSTATUS(wstat);
111 } else if (WIFSIGNALED(wstat)) {
115 bb_error_msg("end %d %s %d", pid, cause, e);
118 /* Must match getopt32 in main! */
133 OPT_U = (1 << 13), /* from here: sslsvd only */
134 OPT_slash = (1 << 14),
139 static void connection_status(void)
141 /* "only 1 client max" desn't need this */
143 bb_error_msg("status %u/%u", cnum, cmax);
146 static void sig_child_handler(int sig UNUSED_PARAM)
151 while ((pid = wait_any_nohang(&wstat)) > 0) {
153 ipsvd_perhost_remove(pid);
157 print_waitstat(pid, wstat);
163 int tcpudpsvd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
164 int tcpudpsvd_main(int argc UNUSED_PARAM, char **argv)
169 const char *instructs;
170 char *msg_per_host = NULL;
171 unsigned len_per_host = len_per_host; /* gcc */
173 struct bb_uidgid_t ugid;
177 char *preset_local_hostname = NULL;
178 char *remote_hostname = remote_hostname; /* for compiler */
179 char *remote_addr = remote_addr; /* for compiler */
180 len_and_sockaddr *lsa;
181 len_and_sockaddr local, remote;
186 unsigned backlog = 20;
191 tcp = (applet_name[0] == 't');
193 /* 3+ args, -i at most once, -p implies -h, -v is counter, -b N, -c N */
194 opt_complementary = "-3:i--i:ph:vv:b+:c+";
196 opts = getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:vU:/:Z:K:",
197 &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
198 &backlog, &str_t, &ssluser, &root, &cert, &key, &verbose
201 /* "+": stop on first non-option */
202 opts = getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:v",
203 &cmax, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
204 &backlog, &str_t, &verbose
207 if (opts & OPT_C) { /* -C n[:message] */
208 max_per_host = bb_strtou(str_C, &str_C, 10);
212 msg_per_host = str_C + 1;
213 len_per_host = strlen(msg_per_host);
216 if (max_per_host > cmax)
219 xget_uidgid(&ugid, user);
222 if (opts & OPT_U) ssluser = optarg;
223 if (opts & OPT_slash) root = optarg;
224 if (opts & OPT_Z) cert = optarg;
225 if (opts & OPT_K) key = optarg;
228 if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
229 argv[0] = (char*)"0.0.0.0";
231 /* Per-IP flood protection is not thought-out for UDP */
235 bb_sanitize_stdio(); /* fd# 0,1,2 must be opened */
240 if ((getuid() == 0) && !(opts & OPT_u)) {
241 xfunc_exitcode = 100;
242 bb_error_msg_and_die(bb_msg_you_must_be_root);
245 if (!uidgid_get(&sslugid, ssluser, 1)) {
247 bb_perror_msg_and_die("can't get user/group: %s", ssluser);
249 bb_error_msg_and_die("unknown user/group %s", ssluser);
251 if (!cert) cert = "./cert.pem";
252 if (!key) key = cert;
253 if (matrixSslOpen() < 0)
254 fatal("can't initialize ssl");
255 if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
257 fatal("can't read cert, key, or ca file");
258 fatal("can't read cert or key file");
260 if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
261 fatal("can't create ssl session");
265 signal(SIGCHLD, sig_child_handler);
266 bb_signals(BB_FATAL_SIGS, sig_term_handler);
267 signal(SIGPIPE, SIG_IGN);
270 ipsvd_perhost_init(cmax);
272 local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
273 lsa = xhost2sockaddr(argv[0], local_port);
276 sock = xsocket(lsa->u.sa.sa_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
277 setsockopt_reuseaddr(sock);
278 sa_len = lsa->len; /* I presume sockaddr len stays the same */
279 xbind(sock, &lsa->u.sa, sa_len);
281 xlisten(sock, backlog);
282 close_on_exec_on(sock);
283 } else { /* udp: needed for recv_from_to to work: */
284 socket_want_pktinfo(sock);
286 /* ndelay_off(sock); - it is the default I think? */
290 /* drop permissions */
297 char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
299 bb_error_msg("listening on %s, starting, uid %u, gid %u", addr,
300 (unsigned)ugid.uid, (unsigned)ugid.gid);
302 bb_error_msg("listening on %s, starting", addr);
306 /* Main accept() loop */
312 wait_for_any_sig(); /* expecting SIGCHLD */
314 /* Accept a connection to fd #0 */
318 sig_unblock(SIGCHLD);
319 local.len = remote.len = sa_len;
321 conn = accept(sock, &remote.u.sa, &remote.len);
323 /* In case recv_from_to won't be able to recover local addr.
324 * Also sets port - recv_from_to is unable to do it. */
326 conn = recv_from_to(sock, NULL, 0, MSG_PEEK,
327 &remote.u.sa, &local.u.sa, sa_len);
332 bb_perror_msg(tcp ? "accept" : "recv");
335 xmove_fd(tcp ? conn : sock, 0);
338 /* Drop connection immediately if cur_per_host > max_per_host
339 * (minimizing load under SYN flood) */
340 remote_addr = xmalloc_sockaddr2dotted_noport(&remote.u.sa);
341 cur_per_host = ipsvd_perhost_add(remote_addr, max_per_host, &hccp);
342 if (cur_per_host > max_per_host) {
343 /* ipsvd_perhost_add detected that max is exceeded
344 * (and did not store ip in connection table) */
347 /* don't block or test for errors */
348 send(0, msg_per_host, len_per_host, MSG_DONTWAIT);
352 /* NB: remote_addr is not leaked, it is stored in conn table */
356 /* Voodoo magic: making udp sockets each receive its own
357 * packets is not trivial, and I still not sure
358 * I do it 100% right.
359 * 1) we have to do it before fork()
360 * 2) order is important - is it right now? */
362 /* Open new non-connected UDP socket for further clients... */
363 sock = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
364 setsockopt_reuseaddr(sock);
365 /* Make plain write/send work for old socket by supplying default
366 * destination address. This also restricts incoming packets
367 * to ones coming from this remote IP. */
368 xconnect(0, &remote.u.sa, sa_len);
369 /* hole? at this point we have no wildcard udp socket...
370 * can this cause clients to get "port unreachable" icmp?
371 * Yup, time window is very small, but it exists (is it?) */
372 /* ..."open new socket", continued */
373 xbind(sock, &lsa->u.sa, sa_len);
374 socket_want_pktinfo(sock);
377 * we cannot replace fd #0 - we will lose pending packet
378 * which is already buffered for us! And we cannot use fd #1
379 * instead - it will "intercept" all following packets, but child
380 * does not expect data coming *from fd #1*! */
382 /* Make it so that local addr is fixed to localp->u.sa
383 * and we don't accidentally accept packets to other local IPs. */
384 /* NB: we possibly bind to the _very_ same_ address & port as the one
385 * already bound in parent! This seems to work in Linux.
386 * (otherwise we can move socket to fd #0 only if bind succeeds) */
388 set_nport(localp, htons(local_port));
389 xmove_fd(xsocket(localp->u.sa.sa_family, SOCK_DGRAM, 0), 0);
390 setsockopt_reuseaddr(0); /* crucial */
391 xbind(0, &localp->u.sa, localp->len);
397 bb_perror_msg("vfork");
408 /* clean up changes done by vforked child */
413 /* Child: prepare env, log, and exec prog */
415 { /* vfork alert! every xmalloc in this block should be freed! */
416 char *local_hostname = local_hostname; /* for compiler */
417 char *local_addr = NULL;
418 char *free_me0 = NULL;
419 char *free_me1 = NULL;
420 char *free_me2 = NULL;
422 if (verbose || !(opts & OPT_E)) {
423 if (!max_per_host) /* remote_addr is not yet known */
424 free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
426 free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
427 if (!remote_hostname) {
428 bb_error_msg("can't look up hostname for %s", remote_addr);
429 remote_hostname = remote_addr;
432 /* Find out local IP peer connected to.
433 * Errors ignored (I'm not paranoid enough to imagine kernel
434 * which doesn't know local IP). */
436 getsockname(0, &local.u.sa, &local.len);
437 /* else: for UDP it is done earlier by parent */
438 local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
440 local_hostname = preset_local_hostname;
441 if (!local_hostname) {
442 free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
444 bb_error_msg_and_die("can't look up hostname for %s", local_addr);
446 /* else: local_hostname is not NULL, but is NOT malloced! */
452 bb_error_msg("concurrency %s %u/%u",
454 cur_per_host, max_per_host);
456 bb_error_msg((opts & OPT_h)
457 ? "start %u %s-%s (%s-%s)"
460 local_addr, remote_addr,
461 local_hostname, remote_hostname);
464 if (!(opts & OPT_E)) {
465 /* setup ucspi env */
466 const char *proto = tcp ? "TCP" : "UDP";
468 /* Extract "original" destination addr:port
469 * from Linux firewall. Useful when you redirect
470 * an outbond connection to local handler, and it needs
471 * to know where it originally tried to connect */
472 if (tcp && getsockopt(0, SOL_IP, SO_ORIGINAL_DST, &local.u.sa, &local.len) == 0) {
473 char *addr = xmalloc_sockaddr2dotted(&local.u.sa);
474 xsetenv_plain("TCPORIGDSTADDR", addr);
477 xsetenv_plain("PROTO", proto);
478 xsetenv_proto(proto, "LOCALADDR", local_addr);
479 xsetenv_proto(proto, "REMOTEADDR", remote_addr);
481 xsetenv_proto(proto, "LOCALHOST", local_hostname);
482 xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
484 //compat? xsetenv_proto(proto, "REMOTEINFO", "");
486 if (cur_per_host > 0) /* can not be true for udp */
487 xsetenv_plain("TCPCONCURRENCY", utoa(cur_per_host));
497 signal(SIGPIPE, SIG_DFL); /* this one was SIG_IGNed */
498 /* Non-ignored signals revert to SIG_DFL on exec anyway */
499 /*signal(SIGCHLD, SIG_DFL);*/
500 sig_unblock(SIGCHLD);
503 strcpy(id, utoa(pid));
506 BB_EXECVP(argv[0], argv);
508 bb_perror_msg_and_die("exec '%s'", argv[0]);
512 tcpsvd [-hpEvv] [-c n] [-C n:msg] [-b n] [-u user] [-l name]
513 [-i dir|-x cdb] [ -t sec] host port prog
515 tcpsvd creates a TCP/IP socket, binds it to the address host:port,
516 and listens on the socket for incoming connections.
518 On each incoming connection, tcpsvd conditionally runs a program,
519 with standard input reading from the socket, and standard output
520 writing to the socket, to handle this connection. tcpsvd keeps
521 listening on the socket for new connections, and can handle
522 multiple connections simultaneously.
524 tcpsvd optionally checks for special instructions depending
525 on the IP address or hostname of the client that initiated
526 the connection, see ipsvd-instruct(5).
529 host either is a hostname, or a dotted-decimal IP address,
530 or 0. If host is 0, tcpsvd accepts connections to any local
532 * busybox accepts IPv6 addresses and host:port pairs too
533 In this case second parameter is ignored
535 tcpsvd accepts connections to host:port. port may be a name
536 from /etc/services or a number.
538 prog consists of one or more arguments. For each connection,
539 tcpsvd normally runs prog, with file descriptor 0 reading from
540 the network, and file descriptor 1 writing to the network.
541 By default it also sets up TCP-related environment variables,
544 read instructions for handling new connections from the instructions
545 directory dir. See ipsvd-instruct(5) for details.
546 * ignored by busyboxed version
548 read instructions for handling new connections from the constant database
549 cdb. The constant database normally is created from an instructions
550 directory by running ipsvd-cdb(8).
551 * ignored by busyboxed version
553 timeout. This option only takes effect if the -i option is given.
554 While checking the instructions directory, check the time of last access
555 of the file that matches the clients address or hostname if any, discard
556 and remove the file if it wasn't accessed within the last sec seconds;
557 tcpsvd does not discard or remove a file if the user's write permission
558 is not set, for those files the timeout is disabled. Default is 0,
559 which means that the timeout is disabled.
560 * ignored by busyboxed version
562 local hostname. Do not look up the local hostname in DNS, but use name
563 as hostname. This option must be set if tcpsvd listens on port 53
566 drop permissions. Switch user ID to user's UID, and group ID to user's
567 primary GID after creating and binding to the socket. If user is followed
568 by a colon and a group name, the group ID is switched to the GID of group
569 instead. All supplementary groups are removed.
571 concurrency. Handle up to n connections simultaneously. Default is 30.
572 If there are n connections active, tcpsvd defers acceptance of a new
573 connection until an active connection is closed.
575 per host concurrency. Allow only up to n connections from the same IP
576 address simultaneously. If there are n active connections from one IP
577 address, new incoming connections from this IP address are closed
578 immediately. If n is followed by :msg, the message msg is written
579 to the client if possible, before closing the connection. By default
580 msg is empty. See ipsvd-instruct(5) for supported escape sequences in msg.
582 For each accepted connection, the current per host concurrency is
583 available through the environment variable TCPCONCURRENCY. n and msg
584 can be overwritten by ipsvd(7) instructions, see ipsvd-instruct(5).
585 By default tcpsvd doesn't keep track of connections.
587 Look up the client's hostname in DNS.
589 paranoid. After looking up the client's hostname in DNS, look up the IP
590 addresses in DNS for that hostname, and forget about the hostname
591 if none of the addresses match the client's IP address. You should
592 set this option if you use hostname based instructions. The -p option
593 implies the -h option.
594 * ignored by busyboxed version
596 backlog. Allow a backlog of approximately n TCP SYNs. On some systems n
597 is silently limited. Default is 20.
599 no special environment. Do not set up TCP-related environment variables.
601 verbose. Print verbose messsages to standard output.
603 more verbose. Print more verbose messages to standard output.
604 * no difference between -v and -vv in busyboxed version