dos2unix: tiny shrink
[oweals/busybox.git] / ipsvd / tcpudp.c
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 tarball for details.
8  */
9
10 /* Based on ipsvd 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.
13  *
14  * Code inside "#ifdef SSLSVD" is for sslsvd and is currently unused.
15  *
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!).
20  *
21  * TCPORIGDSTADDR is Busybox-specific addition.
22  *
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.
30  */
31
32 #include <limits.h>
33 #include <linux/netfilter_ipv4.h> /* wants <limits.h> */
34
35 #include "libbb.h"
36 #include "ipsvd_perhost.h"
37
38 #ifdef SSLSVD
39 #include "matrixSsl.h"
40 #include "ssl_io.h"
41 #endif
42
43 struct globals {
44         unsigned verbose;
45         unsigned max_per_host;
46         unsigned cur_per_host;
47         unsigned cnum;
48         unsigned cmax;
49         char **env_cur;
50         char *env_var[1]; /* actually bigger */
51 };
52 #define G (*(struct globals*)&bb_common_bufsiz1)
53 #define verbose      (G.verbose     )
54 #define max_per_host (G.max_per_host)
55 #define cur_per_host (G.cur_per_host)
56 #define cnum         (G.cnum        )
57 #define cmax         (G.cmax        )
58 #define env_cur      (G.env_cur     )
59 #define env_var      (G.env_var     )
60 #define INIT_G() \
61         do { \
62                 cmax = 30; \
63                 env_cur = &env_var[0]; \
64         } while (0)
65
66
67 /* We have to be careful about leaking memory in repeated setenv's */
68 static void xsetenv_plain(const char *n, const char *v)
69 {
70         char *var = xasprintf("%s=%s", n, v);
71         *env_cur++ = var;
72         putenv(var);
73 }
74
75 static void xsetenv_proto(const char *proto, const char *n, const char *v)
76 {
77         char *var = xasprintf("%s%s=%s", proto, n, v);
78         *env_cur++ = var;
79         putenv(var);
80 }
81
82 static void undo_xsetenv(void)
83 {
84         char **pp = env_cur = &env_var[0];
85         while (*pp) {
86                 char *var = *pp;
87                 *strchrnul(var, '=') = '\0';
88                 unsetenv(var);
89                 free(var);
90                 *pp++ = NULL;
91         }
92 }
93
94 static void sig_term_handler(int sig)
95 {
96         if (verbose)
97                 bb_error_msg("got signal %u, exit", sig);
98         kill_myself_with_sig(sig);
99 }
100
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)
104 {
105         unsigned e = 0;
106         const char *cause = "?exit";
107
108         if (WIFEXITED(wstat)) {
109                 cause++;
110                 e = WEXITSTATUS(wstat);
111         } else if (WIFSIGNALED(wstat)) {
112                 cause = "signal";
113                 e = WTERMSIG(wstat);
114         }
115         bb_error_msg("end %d %s %d", pid, cause, e);
116 }
117
118 /* Must match getopt32 in main! */
119 enum {
120         OPT_c = (1 << 0),
121         OPT_C = (1 << 1),
122         OPT_i = (1 << 2),
123         OPT_x = (1 << 3),
124         OPT_u = (1 << 4),
125         OPT_l = (1 << 5),
126         OPT_E = (1 << 6),
127         OPT_b = (1 << 7),
128         OPT_h = (1 << 8),
129         OPT_p = (1 << 9),
130         OPT_t = (1 << 10),
131         OPT_v = (1 << 11),
132         OPT_V = (1 << 12),
133         OPT_U = (1 << 13), /* from here: sslsvd only */
134         OPT_slash = (1 << 14),
135         OPT_Z = (1 << 15),
136         OPT_K = (1 << 16),
137 };
138
139 static void connection_status(void)
140 {
141         /* "only 1 client max" desn't need this */
142         if (cmax > 1)
143                 bb_error_msg("status %u/%u", cnum, cmax);
144 }
145
146 static void sig_child_handler(int sig)
147 {
148         int wstat;
149         int pid;
150
151         while ((pid = wait_any_nohang(&wstat)) > 0) {
152                 if (max_per_host)
153                         ipsvd_perhost_remove(pid);
154                 if (cnum)
155                         cnum--;
156                 if (verbose)
157                         print_waitstat(pid, wstat);
158         }
159         if (verbose)
160                 connection_status();
161 }
162
163 int tcpudpsvd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
164 int tcpudpsvd_main(int argc, char **argv)
165 {
166         char *str_c, *str_C, *str_b, *str_t;
167         char *user;
168         struct hcc *hccp;
169         const char *instructs;
170         char *msg_per_host = NULL;
171         unsigned len_per_host = len_per_host; /* gcc */
172 #ifndef SSLSVD
173         struct bb_uidgid_t ugid;
174 #endif
175         bool tcp;
176         uint16_t local_port;
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;
182         socklen_t sa_len;
183         int pid;
184         int sock;
185         int conn;
186         unsigned backlog = 20;
187
188         INIT_G();
189
190         tcp = (applet_name[0] == 't');
191
192         /* 3+ args, -i at most once, -p implies -h, -v is counter */
193         opt_complementary = "-3:i--i:ph:vv";
194 #ifdef SSLSVD
195         getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:vU:/:Z:K:",
196                 &str_c, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
197                 &str_b, &str_t, &ssluser, &root, &cert, &key, &verbose
198         );
199 #else
200         getopt32(argv, "+c:C:i:x:u:l:Eb:hpt:v",
201                 &str_c, &str_C, &instructs, &instructs, &user, &preset_local_hostname,
202                 &str_b, &str_t, &verbose
203         );
204 #endif
205         if (option_mask32 & OPT_c)
206                 cmax = xatou_range(str_c, 1, INT_MAX);
207         if (option_mask32 & OPT_C) { /* -C n[:message] */
208                 max_per_host = bb_strtou(str_C, &str_C, 10);
209                 if (str_C[0]) {
210                         if (str_C[0] != ':')
211                                 bb_show_usage();
212                         msg_per_host = str_C + 1;
213                         len_per_host = strlen(msg_per_host);
214                 }
215         }
216         if (max_per_host > cmax)
217                 max_per_host = cmax;
218         if (option_mask32 & OPT_u) {
219                 if (!get_uidgid(&ugid, user, 1))
220                         bb_error_msg_and_die("unknown user/group: %s", user);
221         }
222         if (option_mask32 & OPT_b)
223                 backlog = xatou(str_b);
224 #ifdef SSLSVD
225         if (option_mask32 & OPT_U) ssluser = optarg;
226         if (option_mask32 & OPT_slash) root = optarg;
227         if (option_mask32 & OPT_Z) cert = optarg;
228         if (option_mask32 & OPT_K) key = optarg;
229 #endif
230         argv += optind;
231         if (!argv[0][0] || LONE_CHAR(argv[0], '0'))
232                 argv[0] = (char*)"0.0.0.0";
233
234         /* Per-IP flood protection is not thought-out for UDP */
235         if (!tcp)
236                 max_per_host = 0;
237
238         bb_sanitize_stdio(); /* fd# 0,1,2 must be opened */
239
240 #ifdef SSLSVD
241         sslser = user;
242         client = 0;
243         if ((getuid() == 0) && !(option_mask32 & OPT_u)) {
244                 xfunc_exitcode = 100;
245                 bb_error_msg_and_die("-U ssluser must be set when running as root");
246         }
247         if (option_mask32 & OPT_u)
248                 if (!uidgid_get(&sslugid, ssluser, 1)) {
249                         if (errno) {
250                                 bb_perror_msg_and_die("fatal: cannot get user/group: %s", ssluser);
251                         }
252                         bb_error_msg_and_die("unknown user/group '%s'", ssluser);
253                 }
254         if (!cert) cert = "./cert.pem";
255         if (!key) key = cert;
256         if (matrixSslOpen() < 0)
257                 fatal("cannot initialize ssl");
258         if (matrixSslReadKeys(&keys, cert, key, 0, ca) < 0) {
259                 if (client)
260                         fatal("cannot read cert, key, or ca file");
261                 fatal("cannot read cert or key file");
262         }
263         if (matrixSslNewSession(&ssl, keys, 0, SSL_FLAGS_SERVER) < 0)
264                 fatal("cannot create ssl session");
265 #endif
266
267         sig_block(SIGCHLD);
268         signal(SIGCHLD, sig_child_handler);
269         bb_signals(BB_SIGS_FATAL, sig_term_handler);
270         signal(SIGPIPE, SIG_IGN);
271
272         if (max_per_host)
273                 ipsvd_perhost_init(cmax);
274
275         local_port = bb_lookup_port(argv[1], tcp ? "tcp" : "udp", 0);
276         lsa = xhost2sockaddr(argv[0], local_port);
277         argv += 2;
278
279         sock = xsocket(lsa->u.sa.sa_family, tcp ? SOCK_STREAM : SOCK_DGRAM, 0);
280         setsockopt_reuseaddr(sock);
281         sa_len = lsa->len; /* I presume sockaddr len stays the same */
282         xbind(sock, &lsa->u.sa, sa_len);
283         if (tcp)
284                 xlisten(sock, backlog);
285         else /* udp: needed for recv_from_to to work: */
286                 socket_want_pktinfo(sock);
287         /* ndelay_off(sock); - it is the default I think? */
288
289 #ifndef SSLSVD
290         if (option_mask32 & OPT_u) {
291                 /* drop permissions */
292                 xsetgid(ugid.gid);
293                 xsetuid(ugid.uid);
294         }
295 #endif
296
297         if (verbose) {
298                 char *addr = xmalloc_sockaddr2dotted(&lsa->u.sa);
299                 bb_error_msg("listening on %s, starting", addr);
300                 free(addr);
301 #ifndef SSLSVD
302                 if (option_mask32 & OPT_u)
303                         printf(", uid %u, gid %u",
304                                 (unsigned)ugid.uid, (unsigned)ugid.gid);
305 #endif
306         }
307
308         /* Main accept() loop */
309
310  again:
311         hccp = NULL;
312
313         while (cnum >= cmax)
314                 wait_for_any_sig(); /* expecting SIGCHLD */
315
316         /* Accept a connection to fd #0 */
317  again1:
318         close(0);
319  again2:
320         sig_unblock(SIGCHLD);
321         local.len = remote.len = sa_len;
322         if (tcp) {
323                 conn = accept(sock, &remote.u.sa, &remote.len);
324         } else {
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. */
327                 local = *lsa;
328                 conn = recv_from_to(sock, NULL, 0, MSG_DONTWAIT | MSG_PEEK,
329                                 &remote.u.sa, &local.u.sa, sa_len);
330         }
331         sig_block(SIGCHLD);
332         if (conn < 0) {
333                 if (errno != EINTR)
334                         bb_perror_msg(tcp ? "accept" : "recv");
335                 goto again2;
336         }
337         xmove_fd(tcp ? conn : sock, 0);
338
339         if (max_per_host) {
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) */
347                         free(remote_addr);
348                         if (msg_per_host) {
349                                 /* don't block or test for errors */
350                                 send(0, msg_per_host, len_per_host, MSG_DONTWAIT);
351                         }
352                         goto again1;
353                 }
354                 /* NB: remote_addr is not leaked, it is stored in conn table */
355         }
356
357         if (!tcp) {
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? */
363
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);
377
378                 /* Doesn't work:
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*! */
383 #if 0
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) */
389                 close(0);
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);
394 #endif
395         }
396
397         pid = vfork();
398         if (pid == -1) {
399                 bb_perror_msg("vfork");
400                 goto again;
401         }
402
403         if (pid != 0) {
404                 /* Parent */
405                 cnum++;
406                 if (verbose)
407                         connection_status();
408                 if (hccp)
409                         hccp->pid = pid;
410                 /* clean up changes done by vforked child */
411                 undo_xsetenv();
412                 goto again;
413         }
414
415         /* Child: prepare env, log, and exec prog */
416
417         /* Closing tcp listening socket */
418         if (tcp)
419                 close(sock);
420
421         { /* vfork alert! every xmalloc in this block should be freed! */
422                 char *local_hostname = local_hostname; /* for compiler */
423                 char *local_addr = NULL;
424                 char *free_me0 = NULL;
425                 char *free_me1 = NULL;
426                 char *free_me2 = NULL;
427
428                 if (verbose || !(option_mask32 & OPT_E)) {
429                         if (!max_per_host) /* remote_addr is not yet known */
430                                 free_me0 = remote_addr = xmalloc_sockaddr2dotted(&remote.u.sa);
431                         if (option_mask32 & OPT_h) {
432                                 free_me1 = remote_hostname = xmalloc_sockaddr2host_noport(&remote.u.sa);
433                                 if (!remote_hostname) {
434                                         bb_error_msg("cannot look up hostname for %s", remote_addr);
435                                         remote_hostname = remote_addr;
436                                 }
437                         }
438                         /* Find out local IP peer connected to.
439                          * Errors ignored (I'm not paranoid enough to imagine kernel
440                          * which doesn't know local IP). */
441                         if (tcp)
442                                 getsockname(0, &local.u.sa, &local.len);
443                         /* else: for UDP it is done earlier by parent */
444                         local_addr = xmalloc_sockaddr2dotted(&local.u.sa);
445                         if (option_mask32 & OPT_h) {
446                                 local_hostname = preset_local_hostname;
447                                 if (!local_hostname) {
448                                         free_me2 = local_hostname = xmalloc_sockaddr2host_noport(&local.u.sa);
449                                         if (!local_hostname)
450                                                 bb_error_msg_and_die("cannot look up hostname for %s", local_addr);
451                                 }
452                                 /* else: local_hostname is not NULL, but is NOT malloced! */
453                         }
454                 }
455                 if (verbose) {
456                         pid = getpid();
457                         if (max_per_host) {
458                                 bb_error_msg("concurrency %s %u/%u",
459                                         remote_addr,
460                                         cur_per_host, max_per_host);
461                         }
462                         bb_error_msg((option_mask32 & OPT_h)
463                                 ? "start %u %s-%s (%s-%s)"
464                                 : "start %u %s-%s",
465                                 pid,
466                                 local_addr, remote_addr,
467                                 local_hostname, remote_hostname);
468                 }
469
470                 if (!(option_mask32 & OPT_E)) {
471                         /* setup ucspi env */
472                         const char *proto = tcp ? "TCP" : "UDP";
473
474                         /* Extract "original" destination addr:port
475                          * from Linux firewall. Useful when you redirect
476                          * an outbond connection to local handler, and it needs
477                          * to know where it originally tried to connect */
478                         if (tcp && getsockopt(0, SOL_IP, SO_ORIGINAL_DST, &local.u.sa, &local.len) == 0) {
479                                 char *addr = xmalloc_sockaddr2dotted(&local.u.sa);
480                                 xsetenv_plain("TCPORIGDSTADDR", addr);
481                                 free(addr);
482                         }
483                         xsetenv_plain("PROTO", proto);
484                         xsetenv_proto(proto, "LOCALADDR", local_addr);
485                         xsetenv_proto(proto, "REMOTEADDR", remote_addr);
486                         if (option_mask32 & OPT_h) {
487                                 xsetenv_proto(proto, "LOCALHOST", local_hostname);
488                                 xsetenv_proto(proto, "REMOTEHOST", remote_hostname);
489                         }
490                         //compat? xsetenv_proto(proto, "REMOTEINFO", "");
491                         /* additional */
492                         if (cur_per_host > 0) /* can not be true for udp */
493                                 xsetenv_plain("TCPCONCURRENCY", utoa(cur_per_host));
494                 }
495                 free(local_addr);
496                 free(free_me0);
497                 free(free_me1);
498                 free(free_me2);
499         }
500
501         xdup2(0, 1);
502
503         signal(SIGTERM, SIG_DFL);
504         signal(SIGPIPE, SIG_DFL);
505         signal(SIGCHLD, SIG_DFL);
506         sig_unblock(SIGCHLD);
507
508 #ifdef SSLSVD
509         strcpy(id, utoa(pid));
510         ssl_io(0, argv);
511 #else
512         BB_EXECVP(argv[0], argv);
513 #endif
514         bb_perror_msg_and_die("exec '%s'", argv[0]);
515 }
516
517 /*
518 tcpsvd [-hpEvv] [-c n] [-C n:msg] [-b n] [-u user] [-l name]
519         [-i dir|-x cdb] [ -t sec] host port prog
520
521 tcpsvd creates a TCP/IP socket, binds it to the address host:port,
522 and listens on the socket for incoming connections.
523
524 On each incoming connection, tcpsvd conditionally runs a program,
525 with standard input reading from the socket, and standard output
526 writing to the socket, to handle this connection. tcpsvd keeps
527 listening on the socket for new connections, and can handle
528 multiple connections simultaneously.
529
530 tcpsvd optionally checks for special instructions depending
531 on the IP address or hostname of the client that initiated
532 the connection, see ipsvd-instruct(5).
533
534 host
535     host either is a hostname, or a dotted-decimal IP address,
536     or 0. If host is 0, tcpsvd accepts connections to any local
537     IP address.
538     * busybox accepts IPv6 addresses and host:port pairs too
539       In this case second parameter is ignored
540 port
541     tcpsvd accepts connections to host:port. port may be a name
542     from /etc/services or a number.
543 prog
544     prog consists of one or more arguments. For each connection,
545     tcpsvd normally runs prog, with file descriptor 0 reading from
546     the network, and file descriptor 1 writing to the network.
547     By default it also sets up TCP-related environment variables,
548     see tcp-environ(5)
549 -i dir
550     read instructions for handling new connections from the instructions
551     directory dir. See ipsvd-instruct(5) for details.
552     * ignored by busyboxed version
553 -x cdb
554     read instructions for handling new connections from the constant database
555     cdb. The constant database normally is created from an instructions
556     directory by running ipsvd-cdb(8).
557     * ignored by busyboxed version
558 -t sec
559     timeout. This option only takes effect if the -i option is given.
560     While checking the instructions directory, check the time of last access
561     of the file that matches the clients address or hostname if any, discard
562     and remove the file if it wasn't accessed within the last sec seconds;
563     tcpsvd does not discard or remove a file if the user's write permission
564     is not set, for those files the timeout is disabled. Default is 0,
565     which means that the timeout is disabled.
566     * ignored by busyboxed version
567 -l name
568     local hostname. Do not look up the local hostname in DNS, but use name
569     as hostname. This option must be set if tcpsvd listens on port 53
570     to avoid loops.
571 -u user[:group]
572     drop permissions. Switch user ID to user's UID, and group ID to user's
573     primary GID after creating and binding to the socket. If user is followed
574     by a colon and a group name, the group ID is switched to the GID of group
575     instead. All supplementary groups are removed.
576 -c n
577     concurrency. Handle up to n connections simultaneously. Default is 30.
578     If there are n connections active, tcpsvd defers acceptance of a new
579     connection until an active connection is closed.
580 -C n[:msg]
581     per host concurrency. Allow only up to n connections from the same IP
582     address simultaneously. If there are n active connections from one IP
583     address, new incoming connections from this IP address are closed
584     immediately. If n is followed by :msg, the message msg is written
585     to the client if possible, before closing the connection. By default
586     msg is empty. See ipsvd-instruct(5) for supported escape sequences in msg.
587
588     For each accepted connection, the current per host concurrency is
589     available through the environment variable TCPCONCURRENCY. n and msg
590     can be overwritten by ipsvd(7) instructions, see ipsvd-instruct(5).
591     By default tcpsvd doesn't keep track of connections.
592 -h
593     Look up the client's hostname in DNS.
594 -p
595     paranoid. After looking up the client's hostname in DNS, look up the IP
596     addresses in DNS for that hostname, and forget about the hostname
597     if none of the addresses match the client's IP address. You should
598     set this option if you use hostname based instructions. The -p option
599     implies the -h option.
600     * ignored by busyboxed version
601 -b n
602     backlog. Allow a backlog of approximately n TCP SYNs. On some systems n
603     is silently limited. Default is 20.
604 -E
605     no special environment. Do not set up TCP-related environment variables.
606 -v
607     verbose. Print verbose messsages to standard output.
608 -vv
609     more verbose. Print more verbose messages to standard output.
610     * no difference between -v and -vv in busyboxed version
611 */