inetd.c revision 1.102 1 /* $NetBSD: inetd.c,v 1.102 2007/01/02 16:00:46 rillig Exp $ */
2
3 /*-
4 * Copyright (c) 1998, 2003 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center and by Matthias Scheler.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*
41 * Copyright (c) 1983, 1991, 1993, 1994
42 * The Regents of the University of California. All rights reserved.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. Neither the name of the University nor the names of its contributors
53 * may be used to endorse or promote products derived from this software
54 * without specific prior written permission.
55 *
56 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * SUCH DAMAGE.
67 */
68
69 #include <sys/cdefs.h>
70 #ifndef lint
71 __COPYRIGHT("@(#) Copyright (c) 1983, 1991, 1993, 1994\n\
72 The Regents of the University of California. All rights reserved.\n");
73 #if 0
74 static char sccsid[] = "@(#)inetd.c 8.4 (Berkeley) 4/13/94";
75 #else
76 __RCSID("$NetBSD: inetd.c,v 1.102 2007/01/02 16:00:46 rillig Exp $");
77 #endif
78 #endif /* not lint */
79
80 /*
81 * Inetd - Internet super-server
82 *
83 * This program invokes all internet services as needed. Connection-oriented
84 * services are invoked each time a connection is made, by creating a process.
85 * This process is passed the connection as file descriptor 0 and is expected
86 * to do a getpeername to find out the source host and port.
87 *
88 * Datagram oriented services are invoked when a datagram
89 * arrives; a process is created and passed a pending message
90 * on file descriptor 0. Datagram servers may either connect
91 * to their peer, freeing up the original socket for inetd
92 * to receive further messages on, or ``take over the socket'',
93 * processing all arriving datagrams and, eventually, timing
94 * out. The first type of server is said to be ``multi-threaded'';
95 * the second type of server ``single-threaded''.
96 *
97 * Inetd uses a configuration file which is read at startup
98 * and, possibly, at some later time in response to a hangup signal.
99 * The configuration file is ``free format'' with fields given in the
100 * order shown below. Continuation lines for an entry must being with
101 * a space or tab. All fields must be present in each entry.
102 *
103 * service name must be in /etc/services or must
104 * name a tcpmux service
105 * socket type stream/dgram/raw/rdm/seqpacket
106 * protocol must be in /etc/protocols
107 * wait/nowait[:max] single-threaded/multi-threaded, max #
108 * user[:group] user/group to run daemon as
109 * server program full path name
110 * server program arguments maximum of MAXARGS (20)
111 *
112 * For RPC services
113 * service name/version must be in /etc/rpc
114 * socket type stream/dgram/raw/rdm/seqpacket
115 * protocol must be in /etc/protocols
116 * wait/nowait[:max] single-threaded/multi-threaded
117 * user[:group] user to run daemon as
118 * server program full path name
119 * server program arguments maximum of MAXARGS (20)
120 *
121 * For non-RPC services, the "service name" can be of the form
122 * hostaddress:servicename, in which case the hostaddress is used
123 * as the host portion of the address to listen on. If hostaddress
124 * consists of a single `*' character, INADDR_ANY is used.
125 *
126 * A line can also consist of just
127 * hostaddress:
128 * where hostaddress is as in the preceding paragraph. Such a line must
129 * have no further fields; the specified hostaddress is remembered and
130 * used for all further lines that have no hostaddress specified,
131 * until the next such line (or EOF). (This is why * is provided to
132 * allow explicit specification of INADDR_ANY.) A line
133 * *:
134 * is implicitly in effect at the beginning of the file.
135 *
136 * The hostaddress specifier may (and often will) contain dots;
137 * the service name must not.
138 *
139 * For RPC services, host-address specifiers are accepted and will
140 * work to some extent; however, because of limitations in the
141 * portmapper interface, it will not work to try to give more than
142 * one line for any given RPC service, even if the host-address
143 * specifiers are different.
144 *
145 * TCP services without official port numbers are handled with the
146 * RFC1078-based tcpmux internal service. Tcpmux listens on port 1 for
147 * requests. When a connection is made from a foreign host, the service
148 * requested is passed to tcpmux, which looks it up in the servtab list
149 * and returns the proper entry for the service. Tcpmux returns a
150 * negative reply if the service doesn't exist, otherwise the invoked
151 * server is expected to return the positive reply if the service type in
152 * inetd.conf file has the prefix "tcpmux/". If the service type has the
153 * prefix "tcpmux/+", tcpmux will return the positive reply for the
154 * process; this is for compatibility with older server code, and also
155 * allows you to invoke programs that use stdin/stdout without putting any
156 * special server code in them. Services that use tcpmux are "nowait"
157 * because they do not have a well-known port and hence cannot listen
158 * for new requests.
159 *
160 * Comment lines are indicated by a `#' in column 1.
161 *
162 * #ifdef IPSEC
163 * Comment lines that start with "#@" denote IPsec policy string, as described
164 * in ipsec_set_policy(3). This will affect all the following items in
165 * inetd.conf(8). To reset the policy, just use "#@" line. By default,
166 * there's no IPsec policy.
167 * #endif
168 */
169
170 /*
171 * Here's the scoop concerning the user:group feature:
172 *
173 * 1) set-group-option off.
174 *
175 * a) user = root: NO setuid() or setgid() is done
176 *
177 * b) other: setuid()
178 * setgid(primary group as found in passwd)
179 * initgroups(name, primary group)
180 *
181 * 2) set-group-option on.
182 *
183 * a) user = root: NO setuid()
184 * setgid(specified group)
185 * NO initgroups()
186 *
187 * b) other: setuid()
188 * setgid(specified group)
189 * initgroups(name, specified group)
190 *
191 */
192
193 #include <sys/param.h>
194 #include <sys/stat.h>
195 #include <sys/ioctl.h>
196 #include <sys/socket.h>
197 #include <sys/un.h>
198 #include <sys/wait.h>
199 #include <sys/time.h>
200 #include <sys/resource.h>
201 #include <sys/event.h>
202
203 #ifndef RLIMIT_NOFILE
204 #define RLIMIT_NOFILE RLIMIT_OFILE
205 #endif
206
207 #ifndef NO_RPC
208 #define RPC
209 #endif
210
211 #include <net/if.h>
212
213 #include <netinet/in.h>
214 #include <arpa/inet.h>
215 #ifdef RPC
216 #include <rpc/rpc.h>
217 #include <rpc/rpcb_clnt.h>
218 #include <netconfig.h>
219 #endif
220
221 #include <ctype.h>
222 #include <errno.h>
223 #include <fcntl.h>
224 #include <grp.h>
225 #include <netdb.h>
226 #include <pwd.h>
227 #include <signal.h>
228 #include <stdio.h>
229 #include <stdlib.h>
230 #include <string.h>
231 #include <syslog.h>
232 #include <unistd.h>
233 #include <util.h>
234 #include <ifaddrs.h>
235
236 #include "pathnames.h"
237
238 #ifdef IPSEC
239 #include <netinet6/ipsec.h>
240 #ifndef IPSEC_POLICY_IPSEC /* no ipsec support on old ipsec */
241 #undef IPSEC
242 #endif
243 #include "ipsec.h"
244 #endif
245
246 #ifdef LIBWRAP
247 # include <tcpd.h>
248 #ifndef LIBWRAP_ALLOW_FACILITY
249 # define LIBWRAP_ALLOW_FACILITY LOG_AUTH
250 #endif
251 #ifndef LIBWRAP_ALLOW_SEVERITY
252 # define LIBWRAP_ALLOW_SEVERITY LOG_INFO
253 #endif
254 #ifndef LIBWRAP_DENY_FACILITY
255 # define LIBWRAP_DENY_FACILITY LOG_AUTH
256 #endif
257 #ifndef LIBWRAP_DENY_SEVERITY
258 # define LIBWRAP_DENY_SEVERITY LOG_WARNING
259 #endif
260 int allow_severity = LIBWRAP_ALLOW_FACILITY|LIBWRAP_ALLOW_SEVERITY;
261 int deny_severity = LIBWRAP_DENY_FACILITY|LIBWRAP_DENY_SEVERITY;
262 #endif
263
264 #define TOOMANY 40 /* don't start more than TOOMANY */
265 #define CNT_INTVL 60 /* servers in CNT_INTVL sec. */
266 #define RETRYTIME (60*10) /* retry after bind or server fail */
267
268 #define A_CNT(a) (sizeof (a) / sizeof (a[0]))
269
270 int debug;
271 #ifdef LIBWRAP
272 int lflag;
273 #endif
274 int maxsock;
275 int kq;
276 int options;
277 int timingout;
278 struct servent *sp;
279 char *curdom;
280 const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
281
282 #ifndef OPEN_MAX
283 #define OPEN_MAX 64
284 #endif
285
286 /* Reserve some descriptors, 3 stdio + at least: 1 log, 1 conf. file */
287 #define FD_MARGIN (8)
288 rlim_t rlim_ofile_cur = OPEN_MAX;
289
290 #ifdef RLIMIT_NOFILE
291 struct rlimit rlim_ofile;
292 #endif
293
294 struct kevent changebuf[64];
295 size_t changes;
296
297 struct servtab {
298 char *se_hostaddr; /* host address to listen on */
299 char *se_service; /* name of service */
300 int se_socktype; /* type of socket to use */
301 int se_family; /* address family */
302 char *se_proto; /* protocol used */
303 int se_sndbuf; /* sndbuf size */
304 int se_rcvbuf; /* rcvbuf size */
305 int se_rpcprog; /* rpc program number */
306 int se_rpcversl; /* rpc program lowest version */
307 int se_rpcversh; /* rpc program highest version */
308 #define isrpcservice(sep) ((sep)->se_rpcversl != 0)
309 pid_t se_wait; /* single threaded server */
310 short se_checked; /* looked at during merge */
311 char *se_user; /* user name to run as */
312 char *se_group; /* group name to run as */
313 struct biltin *se_bi; /* if built-in, description */
314 char *se_server; /* server program */
315 #define MAXARGV 20
316 char *se_argv[MAXARGV+1]; /* program arguments */
317 #ifdef IPSEC
318 char *se_policy; /* IPsec poilcy string */
319 #endif
320 int se_fd; /* open descriptor */
321 int se_type; /* type */
322 union {
323 struct sockaddr se_un_ctrladdr;
324 struct sockaddr_in se_un_ctrladdr_in;
325 struct sockaddr_in6 se_un_ctrladdr_in6;
326 struct sockaddr_un se_un_ctrladdr_un;
327 } se_un; /* bound address */
328 #define se_ctrladdr se_un.se_un_ctrladdr
329 #define se_ctrladdr_in se_un.se_un_ctrladdr_in
330 #define se_ctrladdr_un se_un.se_un_ctrladdr_un
331 int se_ctrladdr_size;
332 int se_max; /* max # of instances of this service */
333 int se_count; /* number started since se_time */
334 struct timeval se_time; /* start of se_count */
335 #ifdef MULOG
336 int se_log;
337 #define MULOG_RFC931 0x40000000
338 #endif
339 struct servtab *se_next;
340 } *servtab;
341
342 #define NORM_TYPE 0
343 #define MUX_TYPE 1
344 #define MUXPLUS_TYPE 2
345 #define FAITH_TYPE 3
346 #define ISMUX(sep) (((sep)->se_type == MUX_TYPE) || \
347 ((sep)->se_type == MUXPLUS_TYPE))
348 #define ISMUXPLUS(sep) ((sep)->se_type == MUXPLUS_TYPE)
349
350
351 static void chargen_dg(int, struct servtab *);
352 static void chargen_stream(int, struct servtab *);
353 static void close_sep(struct servtab *);
354 static void config(void);
355 static void daytime_dg(int, struct servtab *);
356 static void daytime_stream(int, struct servtab *);
357 static void discard_dg(int, struct servtab *);
358 static void discard_stream(int, struct servtab *);
359 static void echo_dg(int, struct servtab *);
360 static void echo_stream(int, struct servtab *);
361 static void endconfig(void);
362 static struct servtab *enter(struct servtab *);
363 static void freeconfig(struct servtab *);
364 static struct servtab *getconfigent(void);
365 static void goaway(void);
366 static void machtime_dg(int, struct servtab *);
367 static void machtime_stream(int, struct servtab *);
368 static char *newstr(char *);
369 static char *nextline(FILE *);
370 static void print_service(char *, struct servtab *);
371 static void reapchild(void);
372 static void retry(void);
373 static void run_service(int, struct servtab *);
374 static int setconfig(void);
375 static void setup(struct servtab *);
376 static char *sskip(char **);
377 static char *skip(char **);
378 static void tcpmux(int, struct servtab *);
379 static void usage(void);
380 static void register_rpc(struct servtab *);
381 static void unregister_rpc(struct servtab *);
382 static void bump_nofile(void);
383 static void inetd_setproctitle(char *, int);
384 static void initring(void);
385 static uint32_t machtime(void);
386 static int port_good_dg(struct sockaddr *);
387 static int dg_broadcast(struct in_addr *);
388 static int my_kevent(const struct kevent *, size_t, struct kevent *,
389 size_t);
390 static struct kevent * allocchange(void);
391 static int getline(int, char *, int);
392 static void spawn(struct servtab *, int);
393 #ifdef MULOG
394 static void dolog(struct servtab *, int);
395 static void timeout(int);
396 static char *rfc931_name(struct sockaddr *, int);
397 #endif
398
399 struct biltin {
400 char *bi_service; /* internally provided service name */
401 int bi_socktype; /* type of socket supported */
402 short bi_fork; /* 1 if should fork before call */
403 short bi_wait; /* 1 if should wait for child */
404 void (*bi_fn)(int, struct servtab *);
405 /* function which performs it */
406 } biltins[] = {
407 /* Echo received data */
408 { "echo", SOCK_STREAM, 1, 0, echo_stream },
409 { "echo", SOCK_DGRAM, 0, 0, echo_dg },
410
411 /* Internet /dev/null */
412 { "discard", SOCK_STREAM, 1, 0, discard_stream },
413 { "discard", SOCK_DGRAM, 0, 0, discard_dg },
414
415 /* Return 32 bit time since 1970 */
416 { "time", SOCK_STREAM, 0, 0, machtime_stream },
417 { "time", SOCK_DGRAM, 0, 0, machtime_dg },
418
419 /* Return human-readable time */
420 { "daytime", SOCK_STREAM, 0, 0, daytime_stream },
421 { "daytime", SOCK_DGRAM, 0, 0, daytime_dg },
422
423 /* Familiar character generator */
424 { "chargen", SOCK_STREAM, 1, 0, chargen_stream },
425 { "chargen", SOCK_DGRAM, 0, 0, chargen_dg },
426
427 { "tcpmux", SOCK_STREAM, 1, 0, tcpmux },
428
429 { NULL }
430 };
431
432 /* list of "bad" ports. I.e. ports that are most obviously used for
433 * "cycling packets" denial of service attacks. See /etc/services.
434 * List must end with port number "0".
435 */
436
437 u_int16_t bad_ports[] = { 7, 9, 13, 19, 37, 0 };
438
439
440 #define NUMINT (sizeof(intab) / sizeof(struct inent))
441 char *CONFIG = _PATH_INETDCONF;
442
443 static int my_signals[] =
444 { SIGALRM, SIGHUP, SIGCHLD, SIGTERM, SIGINT, SIGPIPE };
445
446 int
447 main(int argc, char *argv[])
448 {
449 int ch, n, reload = 1;
450
451 while ((ch = getopt(argc, argv,
452 #ifdef LIBWRAP
453 "dl"
454 #else
455 "d"
456 #endif
457 )) != -1)
458 switch(ch) {
459 case 'd':
460 debug = 1;
461 options |= SO_DEBUG;
462 break;
463 #ifdef LIBWRAP
464 case 'l':
465 lflag = 1;
466 break;
467 #endif
468 case '?':
469 default:
470 usage();
471 }
472 argc -= optind;
473 argv += optind;
474
475 if (argc > 0)
476 CONFIG = argv[0];
477
478 if (!debug)
479 daemon(0, 0);
480 openlog("inetd", LOG_PID | LOG_NOWAIT, LOG_DAEMON);
481 pidfile(NULL);
482
483 kq = kqueue();
484 if (kq < 0) {
485 syslog(LOG_ERR, "kqueue: %m");
486 return (EXIT_FAILURE);
487 }
488
489 #ifdef RLIMIT_NOFILE
490 if (getrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0) {
491 syslog(LOG_ERR, "getrlimit: %m");
492 } else {
493 rlim_ofile_cur = rlim_ofile.rlim_cur;
494 if (rlim_ofile_cur == RLIM_INFINITY) /* ! */
495 rlim_ofile_cur = OPEN_MAX;
496 }
497 #endif
498
499 for (n = 0; n < (int)A_CNT(my_signals); n++) {
500 int signum;
501
502 signum = my_signals[n];
503 if (signum != SIGCHLD)
504 (void) signal(signum, SIG_IGN);
505
506 if (signum != SIGPIPE) {
507 struct kevent *ev;
508
509 ev = allocchange();
510 EV_SET(ev, signum, EVFILT_SIGNAL, EV_ADD | EV_ENABLE,
511 0, 0, 0);
512 }
513 }
514
515 for (;;) {
516 int ctrl;
517 struct kevent eventbuf[64], *ev;
518 struct servtab *sep;
519
520 if (reload) {
521 reload = 0;
522 config();
523 }
524
525 n = my_kevent(changebuf, changes, eventbuf, A_CNT(eventbuf));
526 changes = 0;
527
528 for (ev = eventbuf; n > 0; ev++, n--) {
529 if (ev->filter == EVFILT_SIGNAL) {
530 switch (ev->ident) {
531 case SIGALRM:
532 retry();
533 break;
534 case SIGCHLD:
535 reapchild();
536 break;
537 case SIGTERM:
538 case SIGINT:
539 goaway();
540 break;
541 case SIGHUP:
542 reload = 1;
543 break;
544 }
545 continue;
546 }
547 if (ev->filter != EVFILT_READ)
548 continue;
549 sep = (struct servtab *)ev->udata;
550 /* Paranoia */
551 if ((int)ev->ident != sep->se_fd)
552 continue;
553 if (debug)
554 fprintf(stderr, "someone wants %s\n",
555 sep->se_service);
556 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
557 /* XXX here do the libwrap check-before-accept*/
558 ctrl = accept(sep->se_fd, NULL, NULL);
559 if (debug)
560 fprintf(stderr, "accept, ctrl %d\n",
561 ctrl);
562 if (ctrl < 0) {
563 if (errno != EINTR)
564 syslog(LOG_WARNING,
565 "accept (for %s): %m",
566 sep->se_service);
567 continue;
568 }
569 } else
570 ctrl = sep->se_fd;
571 spawn(sep, ctrl);
572 }
573 }
574 }
575
576 static void
577 spawn(struct servtab *sep, int ctrl)
578 {
579 int dofork;
580 pid_t pid;
581
582 pid = 0;
583 #ifdef LIBWRAP_INTERNAL
584 dofork = 1;
585 #else
586 dofork = (sep->se_bi == 0 || sep->se_bi->bi_fork);
587 #endif
588 if (dofork) {
589 if (sep->se_count++ == 0)
590 (void)gettimeofday(&sep->se_time, NULL);
591 else if (sep->se_count >= sep->se_max) {
592 struct timeval now;
593
594 (void)gettimeofday(&now, NULL);
595 if (now.tv_sec - sep->se_time.tv_sec > CNT_INTVL) {
596 sep->se_time = now;
597 sep->se_count = 1;
598 } else {
599 syslog(LOG_ERR,
600 "%s/%s max spawn rate (%d in %d seconds) "
601 "exceeded; service not started",
602 sep->se_service, sep->se_proto,
603 sep->se_max, CNT_INTVL);
604 if (!sep->se_wait && sep->se_socktype ==
605 SOCK_STREAM)
606 close(ctrl);
607 close_sep(sep);
608 if (!timingout) {
609 timingout = 1;
610 alarm(RETRYTIME);
611 }
612 return;
613 }
614 }
615 pid = fork();
616 if (pid < 0) {
617 syslog(LOG_ERR, "fork: %m");
618 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
619 close(ctrl);
620 sleep(1);
621 return;
622 }
623 if (pid != 0 && sep->se_wait) {
624 struct kevent *ev;
625
626 sep->se_wait = pid;
627 ev = allocchange();
628 EV_SET(ev, sep->se_fd, EVFILT_READ,
629 EV_DELETE, 0, 0, 0);
630 }
631 if (pid == 0) {
632 size_t n;
633
634 for (n = 0; n < A_CNT(my_signals); n++)
635 (void) signal(my_signals[n], SIG_DFL);
636 if (debug)
637 setsid();
638 }
639 }
640 if (pid == 0) {
641 run_service(ctrl, sep);
642 if (dofork)
643 exit(0);
644 }
645 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
646 close(ctrl);
647 }
648
649 static void
650 run_service(int ctrl, struct servtab *sep)
651 {
652 struct passwd *pwd;
653 struct group *grp = NULL; /* XXX gcc */
654 char buf[NI_MAXSERV];
655 #ifdef LIBWRAP
656 struct request_info req;
657 int denied;
658 char *service = NULL; /* XXX gcc */
659 #endif
660
661 #ifdef LIBWRAP
662 #ifndef LIBWRAP_INTERNAL
663 if (sep->se_bi == 0)
664 #endif
665 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
666 request_init(&req, RQ_DAEMON, sep->se_argv[0] ?
667 sep->se_argv[0] : sep->se_service, RQ_FILE, ctrl, NULL);
668 fromhost(&req);
669 denied = !hosts_access(&req);
670 if (denied || lflag) {
671 if (getnameinfo(&sep->se_ctrladdr,
672 sep->se_ctrladdr.sa_len, NULL, 0,
673 buf, sizeof(buf), 0) != 0) {
674 /* shouldn't happen */
675 (void)snprintf(buf, sizeof buf, "%d",
676 ntohs(sep->se_ctrladdr_in.sin_port));
677 }
678 service = buf;
679 }
680 if (denied) {
681 syslog(deny_severity,
682 "refused connection from %.500s, service %s (%s)",
683 eval_client(&req), service, sep->se_proto);
684 goto reject;
685 }
686 if (lflag) {
687 syslog(allow_severity,
688 "connection from %.500s, service %s (%s)",
689 eval_client(&req), service, sep->se_proto);
690 }
691 }
692 #endif /* LIBWRAP */
693
694 if (sep->se_bi) {
695 (*sep->se_bi->bi_fn)(ctrl, sep);
696 } else {
697 if ((pwd = getpwnam(sep->se_user)) == NULL) {
698 syslog(LOG_ERR, "%s/%s: %s: No such user",
699 sep->se_service, sep->se_proto, sep->se_user);
700 goto reject;
701 }
702 if (sep->se_group &&
703 (grp = getgrnam(sep->se_group)) == NULL) {
704 syslog(LOG_ERR, "%s/%s: %s: No such group",
705 sep->se_service, sep->se_proto, sep->se_group);
706 goto reject;
707 }
708 if (pwd->pw_uid) {
709 if (sep->se_group)
710 pwd->pw_gid = grp->gr_gid;
711 if (setgid(pwd->pw_gid) < 0) {
712 syslog(LOG_ERR,
713 "%s/%s: can't set gid %d: %m", sep->se_service,
714 sep->se_proto, pwd->pw_gid);
715 goto reject;
716 }
717 (void) initgroups(pwd->pw_name,
718 pwd->pw_gid);
719 if (setuid(pwd->pw_uid) < 0) {
720 syslog(LOG_ERR,
721 "%s/%s: can't set uid %d: %m", sep->se_service,
722 sep->se_proto, pwd->pw_uid);
723 goto reject;
724 }
725 } else if (sep->se_group) {
726 (void) setgid((gid_t)grp->gr_gid);
727 }
728 if (debug)
729 fprintf(stderr, "%d execl %s\n",
730 getpid(), sep->se_server);
731 #ifdef MULOG
732 if (sep->se_log)
733 dolog(sep, ctrl);
734 #endif
735 /* Set our control descriptor to not close-on-exec... */
736 if (fcntl(ctrl, F_SETFD, 0) < 0)
737 syslog(LOG_ERR, "fcntl (F_SETFD, 0): %m");
738 /* ...and dup it to stdin, stdout, and stderr. */
739 if (ctrl != 0) {
740 dup2(ctrl, 0);
741 close(ctrl);
742 ctrl = 0;
743 }
744 dup2(0, 1);
745 dup2(0, 2);
746 #ifdef RLIMIT_NOFILE
747 if (rlim_ofile.rlim_cur != rlim_ofile_cur &&
748 setrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0)
749 syslog(LOG_ERR, "setrlimit: %m");
750 #endif
751 execv(sep->se_server, sep->se_argv);
752 syslog(LOG_ERR, "cannot execute %s: %m", sep->se_server);
753 reject:
754 if (sep->se_socktype != SOCK_STREAM)
755 recv(ctrl, buf, sizeof (buf), 0);
756 _exit(1);
757 }
758 }
759
760 static void
761 reapchild(void)
762 {
763 int status;
764 pid_t pid;
765 struct servtab *sep;
766
767 for (;;) {
768 pid = wait3(&status, WNOHANG, NULL);
769 if (pid <= 0)
770 break;
771 if (debug)
772 (void) fprintf(stderr, "%d reaped, status %#x\n",
773 pid, status);
774 for (sep = servtab; sep != NULL; sep = sep->se_next)
775 if (sep->se_wait == pid) {
776 struct kevent *ev;
777
778 if (WIFEXITED(status) && WEXITSTATUS(status))
779 syslog(LOG_WARNING,
780 "%s: exit status 0x%x",
781 sep->se_server, WEXITSTATUS(status));
782 else if (WIFSIGNALED(status))
783 syslog(LOG_WARNING,
784 "%s: exit signal 0x%x",
785 sep->se_server, WTERMSIG(status));
786 sep->se_wait = 1;
787 ev = allocchange();
788 EV_SET(ev, sep->se_fd, EVFILT_READ,
789 EV_ADD | EV_ENABLE, 0, 0, (intptr_t)sep);
790 if (debug)
791 fprintf(stderr, "restored %s, fd %d\n",
792 sep->se_service, sep->se_fd);
793 }
794 }
795 }
796
797 static void
798 config(void)
799 {
800 struct servtab *sep, *cp, **sepp;
801 size_t n;
802
803 if (!setconfig()) {
804 syslog(LOG_ERR, "%s: %m", CONFIG);
805 return;
806 }
807 for (sep = servtab; sep != NULL; sep = sep->se_next)
808 sep->se_checked = 0;
809 while ((cp = getconfigent())) {
810 for (sep = servtab; sep != NULL; sep = sep->se_next)
811 if (strcmp(sep->se_service, cp->se_service) == 0 &&
812 strcmp(sep->se_hostaddr, cp->se_hostaddr) == 0 &&
813 strcmp(sep->se_proto, cp->se_proto) == 0 &&
814 ISMUX(sep) == ISMUX(cp))
815 break;
816 if (sep != NULL) {
817 int i;
818
819 #define SWAP(type, a, b) {type c = a; a = b; b = c;}
820
821 /*
822 * sep->se_wait may be holding the pid of a daemon
823 * that we're waiting for. If so, don't overwrite
824 * it unless the config file explicitly says don't
825 * wait.
826 */
827 if (cp->se_bi == 0 &&
828 (sep->se_wait == 1 || cp->se_wait == 0))
829 sep->se_wait = cp->se_wait;
830 SWAP(char *, sep->se_user, cp->se_user);
831 SWAP(char *, sep->se_group, cp->se_group);
832 SWAP(char *, sep->se_server, cp->se_server);
833 for (i = 0; i < MAXARGV; i++)
834 SWAP(char *, sep->se_argv[i], cp->se_argv[i]);
835 #ifdef IPSEC
836 SWAP(char *, sep->se_policy, cp->se_policy);
837 #endif
838 SWAP(int, cp->se_type, sep->se_type);
839 SWAP(int, cp->se_max, sep->se_max);
840 #undef SWAP
841 if (isrpcservice(sep))
842 unregister_rpc(sep);
843 sep->se_rpcversl = cp->se_rpcversl;
844 sep->se_rpcversh = cp->se_rpcversh;
845 freeconfig(cp);
846 if (debug)
847 print_service("REDO", sep);
848 } else {
849 sep = enter(cp);
850 if (debug)
851 print_service("ADD ", sep);
852 }
853 sep->se_checked = 1;
854
855 switch (sep->se_family) {
856 case AF_LOCAL:
857 if (sep->se_fd != -1)
858 break;
859 n = strlen(sep->se_service);
860 if (n > sizeof(sep->se_ctrladdr_un.sun_path)) {
861 syslog(LOG_ERR, "%s: address too long",
862 sep->se_service);
863 sep->se_checked = 0;
864 continue;
865 }
866 (void)unlink(sep->se_service);
867 strncpy(sep->se_ctrladdr_un.sun_path,
868 sep->se_service, n);
869 sep->se_ctrladdr_un.sun_family = AF_LOCAL;
870 sep->se_ctrladdr_size = n +
871 sizeof(sep->se_ctrladdr_un) -
872 sizeof(sep->se_ctrladdr_un.sun_path);
873 if (!ISMUX(sep))
874 setup(sep);
875 break;
876 case AF_INET:
877 #ifdef INET6
878 case AF_INET6:
879 #endif
880 {
881 struct addrinfo hints, *res;
882 char *host, *port;
883 int error;
884 int s;
885
886 /* check if the family is supported */
887 s = socket(sep->se_family, SOCK_DGRAM, 0);
888 if (s < 0) {
889 syslog(LOG_WARNING,
890 "%s/%s: %s: the address family is not "
891 "supported by the kernel",
892 sep->se_service, sep->se_proto,
893 sep->se_hostaddr);
894 sep->se_checked = 0;
895 continue;
896 }
897 close(s);
898
899 memset(&hints, 0, sizeof(hints));
900 hints.ai_family = sep->se_family;
901 hints.ai_socktype = sep->se_socktype;
902 hints.ai_flags = AI_PASSIVE;
903 if (!strcmp(sep->se_hostaddr, "*"))
904 host = NULL;
905 else
906 host = sep->se_hostaddr;
907 if (isrpcservice(sep) || ISMUX(sep))
908 port = "0";
909 else
910 port = sep->se_service;
911 error = getaddrinfo(host, port, &hints, &res);
912 if (error) {
913 if (error == EAI_SERVICE) {
914 /* gai_strerror not friendly enough */
915 syslog(LOG_WARNING, "%s/%s: "
916 "unknown service",
917 sep->se_service, sep->se_proto);
918 } else {
919 syslog(LOG_ERR, "%s/%s: %s: %s",
920 sep->se_service, sep->se_proto,
921 sep->se_hostaddr,
922 gai_strerror(error));
923 }
924 sep->se_checked = 0;
925 continue;
926 }
927 if (res->ai_next) {
928 syslog(LOG_ERR,
929 "%s/%s: %s: resolved to multiple addr",
930 sep->se_service, sep->se_proto,
931 sep->se_hostaddr);
932 sep->se_checked = 0;
933 freeaddrinfo(res);
934 continue;
935 }
936 memcpy(&sep->se_ctrladdr, res->ai_addr,
937 res->ai_addrlen);
938 if (ISMUX(sep)) {
939 sep->se_fd = -1;
940 freeaddrinfo(res);
941 continue;
942 }
943 sep->se_ctrladdr_size = res->ai_addrlen;
944 freeaddrinfo(res);
945 #ifdef RPC
946 if (isrpcservice(sep)) {
947 struct rpcent *rp;
948
949 sep->se_rpcprog = atoi(sep->se_service);
950 if (sep->se_rpcprog == 0) {
951 rp = getrpcbyname(sep->se_service);
952 if (rp == 0) {
953 syslog(LOG_ERR,
954 "%s/%s: unknown service",
955 sep->se_service,
956 sep->se_proto);
957 sep->se_checked = 0;
958 continue;
959 }
960 sep->se_rpcprog = rp->r_number;
961 }
962 if (sep->se_fd == -1 && !ISMUX(sep))
963 setup(sep);
964 if (sep->se_fd != -1)
965 register_rpc(sep);
966 } else
967 #endif
968 {
969 if (sep->se_fd >= 0)
970 close_sep(sep);
971 if (sep->se_fd == -1 && !ISMUX(sep))
972 setup(sep);
973 }
974 }
975 }
976 }
977 endconfig();
978 /*
979 * Purge anything not looked at above.
980 */
981 sepp = &servtab;
982 while ((sep = *sepp)) {
983 if (sep->se_checked) {
984 sepp = &sep->se_next;
985 continue;
986 }
987 *sepp = sep->se_next;
988 if (sep->se_fd >= 0)
989 close_sep(sep);
990 if (isrpcservice(sep))
991 unregister_rpc(sep);
992 if (sep->se_family == AF_LOCAL)
993 (void)unlink(sep->se_service);
994 if (debug)
995 print_service("FREE", sep);
996 freeconfig(sep);
997 free(sep);
998 }
999 }
1000
1001 static void
1002 retry(void)
1003 {
1004 struct servtab *sep;
1005
1006 timingout = 0;
1007 for (sep = servtab; sep != NULL; sep = sep->se_next) {
1008 if (sep->se_fd == -1 && !ISMUX(sep)) {
1009 switch (sep->se_family) {
1010 case AF_LOCAL:
1011 case AF_INET:
1012 #ifdef INET6
1013 case AF_INET6:
1014 #endif
1015 setup(sep);
1016 if (sep->se_fd != -1 && isrpcservice(sep))
1017 register_rpc(sep);
1018 break;
1019 }
1020 }
1021 }
1022 }
1023
1024 static void
1025 goaway(void)
1026 {
1027 struct servtab *sep;
1028
1029 for (sep = servtab; sep != NULL; sep = sep->se_next) {
1030 if (sep->se_fd == -1)
1031 continue;
1032
1033 switch (sep->se_family) {
1034 case AF_LOCAL:
1035 (void)unlink(sep->se_service);
1036 break;
1037 case AF_INET:
1038 #ifdef INET6
1039 case AF_INET6:
1040 #endif
1041 if (sep->se_wait == 1 && isrpcservice(sep))
1042 unregister_rpc(sep);
1043 break;
1044 }
1045 (void)close(sep->se_fd);
1046 }
1047 exit(0);
1048 }
1049
1050 static void
1051 setup(struct servtab *sep)
1052 {
1053 int on = 1;
1054 #ifdef INET6
1055 int off = 0;
1056 #endif
1057 struct kevent *ev;
1058
1059 if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
1060 if (debug)
1061 fprintf(stderr, "socket failed on %s/%s: %s\n",
1062 sep->se_service, sep->se_proto, strerror(errno));
1063 syslog(LOG_ERR, "%s/%s: socket: %m",
1064 sep->se_service, sep->se_proto);
1065 return;
1066 }
1067 /* Set all listening sockets to close-on-exec. */
1068 if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0) {
1069 syslog(LOG_ERR, "%s/%s: fcntl(F_SETFD, FD_CLOEXEC): %m",
1070 sep->se_service, sep->se_proto);
1071 close(sep->se_fd);
1072 return;
1073 }
1074
1075 #define turnon(fd, opt) \
1076 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1077 if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1078 turnon(sep->se_fd, SO_DEBUG) < 0)
1079 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1080 if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1081 syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1082 #undef turnon
1083
1084 /* Set the socket buffer sizes, if specified. */
1085 if (sep->se_sndbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
1086 SO_SNDBUF, (char *)&sep->se_sndbuf, sizeof(sep->se_sndbuf)) < 0)
1087 syslog(LOG_ERR, "setsockopt (SO_SNDBUF %d): %m",
1088 sep->se_sndbuf);
1089 if (sep->se_rcvbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
1090 SO_RCVBUF, (char *)&sep->se_rcvbuf, sizeof(sep->se_rcvbuf)) < 0)
1091 syslog(LOG_ERR, "setsockopt (SO_RCVBUF %d): %m",
1092 sep->se_rcvbuf);
1093 #ifdef INET6
1094 if (sep->se_family == AF_INET6) {
1095 int *v;
1096 v = (sep->se_type == FAITH_TYPE) ? &on : &off;
1097 if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_FAITH,
1098 (char *)v, sizeof(*v)) < 0)
1099 syslog(LOG_ERR, "setsockopt (IPV6_FAITH): %m");
1100 }
1101 #endif
1102 #ifdef IPSEC
1103 if (ipsecsetup(sep->se_family, sep->se_fd, sep->se_policy) < 0 &&
1104 sep->se_policy) {
1105 syslog(LOG_ERR, "%s/%s: ipsec setup failed",
1106 sep->se_service, sep->se_proto);
1107 (void)close(sep->se_fd);
1108 sep->se_fd = -1;
1109 return;
1110 }
1111 #endif
1112
1113 if (bind(sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size) < 0) {
1114 if (debug)
1115 fprintf(stderr, "bind failed on %s/%s: %s\n",
1116 sep->se_service, sep->se_proto, strerror(errno));
1117 syslog(LOG_ERR, "%s/%s: bind: %m",
1118 sep->se_service, sep->se_proto);
1119 (void) close(sep->se_fd);
1120 sep->se_fd = -1;
1121 if (!timingout) {
1122 timingout = 1;
1123 alarm(RETRYTIME);
1124 }
1125 return;
1126 }
1127 if (sep->se_socktype == SOCK_STREAM)
1128 listen(sep->se_fd, 10);
1129
1130 ev = allocchange();
1131 EV_SET(ev, sep->se_fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0,
1132 (intptr_t)sep);
1133 if (sep->se_fd > maxsock) {
1134 maxsock = sep->se_fd;
1135 if (maxsock > rlim_ofile_cur - FD_MARGIN)
1136 bump_nofile();
1137 }
1138 if (debug)
1139 fprintf(stderr, "registered %s on %d\n",
1140 sep->se_server, sep->se_fd);
1141 }
1142
1143 /*
1144 * Finish with a service and its socket.
1145 */
1146 static void
1147 close_sep(struct servtab *sep)
1148 {
1149 if (sep->se_fd >= 0) {
1150 (void) close(sep->se_fd);
1151 sep->se_fd = -1;
1152 }
1153 sep->se_count = 0;
1154 }
1155
1156 static void
1157 register_rpc(struct servtab *sep)
1158 {
1159 #ifdef RPC
1160 struct netbuf nbuf;
1161 struct sockaddr_storage ss;
1162 struct netconfig *nconf;
1163 socklen_t socklen;
1164 int n;
1165
1166 if ((nconf = getnetconfigent(sep->se_proto+4)) == NULL) {
1167 syslog(LOG_ERR, "%s: getnetconfigent failed",
1168 sep->se_proto);
1169 return;
1170 }
1171 socklen = sizeof ss;
1172 if (getsockname(sep->se_fd, (struct sockaddr *)&ss, &socklen) < 0) {
1173 syslog(LOG_ERR, "%s/%s: getsockname: %m",
1174 sep->se_service, sep->se_proto);
1175 return;
1176 }
1177
1178 nbuf.buf = &ss;
1179 nbuf.len = ss.ss_len;
1180 nbuf.maxlen = sizeof (struct sockaddr_storage);
1181 for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
1182 if (debug)
1183 fprintf(stderr, "rpcb_set: %u %d %s %s\n",
1184 sep->se_rpcprog, n, nconf->nc_netid,
1185 taddr2uaddr(nconf, &nbuf));
1186 (void)rpcb_unset(sep->se_rpcprog, n, nconf);
1187 if (!rpcb_set(sep->se_rpcprog, n, nconf, &nbuf))
1188 syslog(LOG_ERR, "rpcb_set: %u %d %s %s%s",
1189 sep->se_rpcprog, n, nconf->nc_netid,
1190 taddr2uaddr(nconf, &nbuf), clnt_spcreateerror(""));
1191 }
1192 #endif /* RPC */
1193 }
1194
1195 static void
1196 unregister_rpc(struct servtab *sep)
1197 {
1198 #ifdef RPC
1199 int n;
1200 struct netconfig *nconf;
1201
1202 if ((nconf = getnetconfigent(sep->se_proto+4)) == NULL) {
1203 syslog(LOG_ERR, "%s: getnetconfigent failed",
1204 sep->se_proto);
1205 return;
1206 }
1207
1208 for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
1209 if (debug)
1210 fprintf(stderr, "rpcb_unset(%u, %d, %s)\n",
1211 sep->se_rpcprog, n, nconf->nc_netid);
1212 if (!rpcb_unset(sep->se_rpcprog, n, nconf))
1213 syslog(LOG_ERR, "rpcb_unset(%u, %d, %s) failed\n",
1214 sep->se_rpcprog, n, nconf->nc_netid);
1215 }
1216 #endif /* RPC */
1217 }
1218
1219
1220 static struct servtab *
1221 enter(struct servtab *cp)
1222 {
1223 struct servtab *sep;
1224
1225 sep = (struct servtab *)malloc(sizeof (*sep));
1226 if (sep == NULL) {
1227 syslog(LOG_ERR, "Out of memory.");
1228 exit(1);
1229 }
1230 *sep = *cp;
1231 sep->se_fd = -1;
1232 sep->se_rpcprog = -1;
1233 sep->se_next = servtab;
1234 servtab = sep;
1235 return (sep);
1236 }
1237
1238 FILE *fconfig = NULL;
1239 struct servtab serv;
1240 char line[LINE_MAX];
1241 char *defhost;
1242 #ifdef IPSEC
1243 static char *policy = NULL;
1244 #endif
1245
1246 static int
1247 setconfig(void)
1248 {
1249 if (defhost)
1250 free(defhost);
1251 defhost = newstr("*");
1252 #ifdef IPSEC
1253 if (policy)
1254 free(policy);
1255 policy = NULL;
1256 #endif
1257 if (fconfig != NULL) {
1258 fseek(fconfig, 0L, SEEK_SET);
1259 return (1);
1260 }
1261 fconfig = fopen(CONFIG, "r");
1262 return (fconfig != NULL);
1263 }
1264
1265 static void
1266 endconfig(void)
1267 {
1268 if (fconfig != NULL) {
1269 (void) fclose(fconfig);
1270 fconfig = NULL;
1271 }
1272 if (defhost != NULL) {
1273 free(defhost);
1274 defhost = NULL;
1275 }
1276 }
1277
1278 static struct servtab *
1279 getconfigent(void)
1280 {
1281 struct servtab *sep = &serv;
1282 int argc, val;
1283 char *cp, *cp0, *arg, *buf0, *buf1, *sz0, *sz1;
1284 static char TCPMUX_TOKEN[] = "tcpmux/";
1285 #define MUX_LEN (sizeof(TCPMUX_TOKEN)-1)
1286 char *hostdelim;
1287
1288 more:
1289 while ((cp = nextline(fconfig))) {
1290 #ifdef IPSEC
1291 /* lines starting with #@ is not a comment, but the policy */
1292 if (cp[0] == '#' && cp[1] == '@') {
1293 char *p;
1294 for (p = cp + 2; p && *p && isspace((unsigned char)*p); p++)
1295 ;
1296 if (*p == '\0') {
1297 if (policy)
1298 free(policy);
1299 policy = NULL;
1300 } else {
1301 if (ipsecsetup_test(p) < 0) {
1302 syslog(LOG_ERR,
1303 "%s: invalid ipsec policy \"%s\"",
1304 CONFIG, p);
1305 exit(1);
1306 } else {
1307 if (policy)
1308 free(policy);
1309 policy = newstr(p);
1310 }
1311 }
1312 }
1313 #endif
1314 if (*cp == '#' || *cp == '\0')
1315 continue;
1316 #ifdef MULOG
1317 /* Avoid use of `skip' if there is a danger of it looking
1318 * at continuation lines.
1319 */
1320 do {
1321 cp++;
1322 } while (*cp == ' ' || *cp == '\t');
1323 if (*cp == '\0')
1324 continue;
1325 if ((arg = skip(&cp)) == NULL)
1326 continue;
1327 if (strcmp(arg, "DOMAIN"))
1328 continue;
1329 if (curdom)
1330 free(curdom);
1331 curdom = NULL;
1332 while (*cp == ' ' || *cp == '\t')
1333 cp++;
1334 if (*cp == '\0')
1335 continue;
1336 arg = cp;
1337 while (*cp && *cp != ' ' && *cp != '\t')
1338 cp++;
1339 if (*cp != '\0')
1340 *cp++ = '\0';
1341 curdom = newstr(arg);
1342 #endif
1343 break;
1344 }
1345 if (cp == NULL)
1346 return (NULL);
1347 /*
1348 * clear the static buffer, since some fields (se_ctrladdr,
1349 * for example) don't get initialized here.
1350 */
1351 memset((caddr_t)sep, 0, sizeof *sep);
1352 arg = skip(&cp);
1353 if (cp == NULL) {
1354 /* got an empty line containing just blanks/tabs. */
1355 goto more;
1356 }
1357 /* Check for a host name. */
1358 hostdelim = strrchr(arg, ':');
1359 if (hostdelim) {
1360 *hostdelim = '\0';
1361 if (arg[0] == '[' && hostdelim > arg && hostdelim[-1] == ']') {
1362 hostdelim[-1] = '\0';
1363 sep->se_hostaddr = newstr(arg + 1);
1364 } else
1365 sep->se_hostaddr = newstr(arg);
1366 arg = hostdelim + 1;
1367 /*
1368 * If the line is of the form `host:', then just change the
1369 * default host for the following lines.
1370 */
1371 if (*arg == '\0') {
1372 arg = skip(&cp);
1373 if (cp == NULL) {
1374 free(defhost);
1375 defhost = sep->se_hostaddr;
1376 goto more;
1377 }
1378 }
1379 } else
1380 sep->se_hostaddr = newstr(defhost);
1381 if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1382 char *c = arg + MUX_LEN;
1383 if (*c == '+') {
1384 sep->se_type = MUXPLUS_TYPE;
1385 c++;
1386 } else
1387 sep->se_type = MUX_TYPE;
1388 sep->se_service = newstr(c);
1389 } else {
1390 sep->se_service = newstr(arg);
1391 sep->se_type = NORM_TYPE;
1392 }
1393
1394 arg = sskip(&cp);
1395 if (strcmp(arg, "stream") == 0)
1396 sep->se_socktype = SOCK_STREAM;
1397 else if (strcmp(arg, "dgram") == 0)
1398 sep->se_socktype = SOCK_DGRAM;
1399 else if (strcmp(arg, "rdm") == 0)
1400 sep->se_socktype = SOCK_RDM;
1401 else if (strcmp(arg, "seqpacket") == 0)
1402 sep->se_socktype = SOCK_SEQPACKET;
1403 else if (strcmp(arg, "raw") == 0)
1404 sep->se_socktype = SOCK_RAW;
1405 else
1406 sep->se_socktype = -1;
1407
1408 arg = sskip(&cp);
1409 if (sep->se_type == NORM_TYPE &&
1410 strncmp(arg, "faith/", strlen("faith/")) == 0) {
1411 arg += strlen("faith/");
1412 sep->se_type = FAITH_TYPE;
1413 }
1414 sep->se_proto = newstr(arg);
1415
1416 #define MALFORMED(arg) \
1417 do { \
1418 syslog(LOG_ERR, "%s: malformed buffer size option `%s'", \
1419 sep->se_service, (arg)); \
1420 goto more; \
1421 } while (0)
1422
1423 #define GETVAL(arg) \
1424 do { \
1425 if (!isdigit((unsigned char)*(arg))) \
1426 MALFORMED(arg); \
1427 val = strtol((arg), &cp0, 10); \
1428 if (cp0 != NULL) { \
1429 if (cp0[1] != '\0') \
1430 MALFORMED((arg)); \
1431 if (cp0[0] == 'k') \
1432 val *= 1024; \
1433 if (cp0[0] == 'm') \
1434 val *= 1024 * 1024; \
1435 } \
1436 if (val < 1) { \
1437 syslog(LOG_ERR, "%s: invalid buffer size `%s'", \
1438 sep->se_service, (arg)); \
1439 goto more; \
1440 } \
1441 } while (0)
1442
1443 #define ASSIGN(arg) \
1444 do { \
1445 if (strcmp((arg), "sndbuf") == 0) \
1446 sep->se_sndbuf = val; \
1447 else if (strcmp((arg), "rcvbuf") == 0) \
1448 sep->se_rcvbuf = val; \
1449 else \
1450 MALFORMED((arg)); \
1451 } while (0)
1452
1453 /*
1454 * Extract the send and receive buffer sizes before parsing
1455 * the protocol.
1456 */
1457 sep->se_sndbuf = sep->se_rcvbuf = 0;
1458 buf0 = buf1 = sz0 = sz1 = NULL;
1459 if ((buf0 = strchr(sep->se_proto, ',')) != NULL) {
1460 /* Not meaningful for Tcpmux services. */
1461 if (ISMUX(sep)) {
1462 syslog(LOG_ERR, "%s: can't specify buffer sizes for "
1463 "tcpmux services", sep->se_service);
1464 goto more;
1465 }
1466
1467 /* Skip the , */
1468 *buf0++ = '\0';
1469
1470 /* Check to see if another socket buffer size was specified. */
1471 if ((buf1 = strchr(buf0, ',')) != NULL) {
1472 /* Skip the , */
1473 *buf1++ = '\0';
1474
1475 /* Make sure a 3rd one wasn't specified. */
1476 if (strchr(buf1, ',') != NULL) {
1477 syslog(LOG_ERR, "%s: too many buffer sizes",
1478 sep->se_service);
1479 goto more;
1480 }
1481
1482 /* Locate the size. */
1483 if ((sz1 = strchr(buf1, '=')) == NULL)
1484 MALFORMED(buf1);
1485
1486 /* Skip the = */
1487 *sz1++ = '\0';
1488 }
1489
1490 /* Locate the size. */
1491 if ((sz0 = strchr(buf0, '=')) == NULL)
1492 MALFORMED(buf0);
1493
1494 /* Skip the = */
1495 *sz0++ = '\0';
1496
1497 GETVAL(sz0);
1498 ASSIGN(buf0);
1499
1500 if (buf1 != NULL) {
1501 GETVAL(sz1);
1502 ASSIGN(buf1);
1503 }
1504 }
1505
1506 #undef ASSIGN
1507 #undef GETVAL
1508 #undef MALFORMED
1509
1510 if (strcmp(sep->se_proto, "unix") == 0) {
1511 sep->se_family = AF_LOCAL;
1512 } else {
1513 val = strlen(sep->se_proto);
1514 if (!val) {
1515 syslog(LOG_ERR, "%s: invalid protocol specified",
1516 sep->se_service);
1517 goto more;
1518 }
1519 val = sep->se_proto[val - 1];
1520 switch (val) {
1521 case '4': /*tcp4 or udp4*/
1522 sep->se_family = AF_INET;
1523 break;
1524 #ifdef INET6
1525 case '6': /*tcp6 or udp6*/
1526 sep->se_family = AF_INET6;
1527 break;
1528 #endif
1529 default:
1530 sep->se_family = AF_INET; /*will become AF_INET6*/
1531 break;
1532 }
1533 if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1534 #ifdef RPC
1535 char *cp, *ccp;
1536 cp = strchr(sep->se_service, '/');
1537 if (cp == 0) {
1538 syslog(LOG_ERR, "%s: no rpc version",
1539 sep->se_service);
1540 goto more;
1541 }
1542 *cp++ = '\0';
1543 sep->se_rpcversl = sep->se_rpcversh =
1544 strtol(cp, &ccp, 0);
1545 if (ccp == cp) {
1546 badafterall:
1547 syslog(LOG_ERR, "%s/%s: bad rpc version",
1548 sep->se_service, cp);
1549 goto more;
1550 }
1551 if (*ccp == '-') {
1552 cp = ccp + 1;
1553 sep->se_rpcversh = strtol(cp, &ccp, 0);
1554 if (ccp == cp)
1555 goto badafterall;
1556 }
1557 #else
1558 syslog(LOG_ERR, "%s: rpc services not suported",
1559 sep->se_service);
1560 goto more;
1561 #endif /* RPC */
1562 }
1563 }
1564 arg = sskip(&cp);
1565 {
1566 char *cp;
1567 if ((cp = strchr(arg, ':')) == NULL)
1568 cp = strchr(arg, '.');
1569 if (cp != NULL) {
1570 *cp++ = '\0';
1571 sep->se_max = atoi(cp);
1572 } else
1573 sep->se_max = TOOMANY;
1574 }
1575 sep->se_wait = strcmp(arg, "wait") == 0;
1576 if (ISMUX(sep)) {
1577 /*
1578 * Silently enforce "nowait" for TCPMUX services since
1579 * they don't have an assigned port to listen on.
1580 */
1581 sep->se_wait = 0;
1582
1583 if (strncmp(sep->se_proto, "tcp", 3)) {
1584 syslog(LOG_ERR,
1585 "%s: bad protocol for tcpmux service %s",
1586 CONFIG, sep->se_service);
1587 goto more;
1588 }
1589 if (sep->se_socktype != SOCK_STREAM) {
1590 syslog(LOG_ERR,
1591 "%s: bad socket type for tcpmux service %s",
1592 CONFIG, sep->se_service);
1593 goto more;
1594 }
1595 }
1596 sep->se_user = newstr(sskip(&cp));
1597 if ((sep->se_group = strchr(sep->se_user, ':')) != NULL)
1598 *sep->se_group++ = '\0';
1599 else if ((sep->se_group = strchr(sep->se_user, '.')) != NULL)
1600 *sep->se_group++ = '\0';
1601
1602 sep->se_server = newstr(sskip(&cp));
1603 if (strcmp(sep->se_server, "internal") == 0) {
1604 struct biltin *bi;
1605
1606 for (bi = biltins; bi->bi_service; bi++)
1607 if (bi->bi_socktype == sep->se_socktype &&
1608 strcmp(bi->bi_service, sep->se_service) == 0)
1609 break;
1610 if (bi->bi_service == 0) {
1611 syslog(LOG_ERR, "internal service %s unknown",
1612 sep->se_service);
1613 goto more;
1614 }
1615 sep->se_bi = bi;
1616 sep->se_wait = bi->bi_wait;
1617 } else
1618 sep->se_bi = NULL;
1619 argc = 0;
1620 for (arg = skip(&cp); cp; arg = skip(&cp)) {
1621 #if MULOG
1622 char *colon;
1623
1624 if (argc == 0 && (colon = strrchr(arg, ':'))) {
1625 while (arg < colon) {
1626 int x;
1627 char *ccp;
1628
1629 switch (*arg++) {
1630 case 'l':
1631 x = 1;
1632 if (isdigit(*arg)) {
1633 x = strtol(arg, &ccp, 0);
1634 if (ccp == arg)
1635 break;
1636 arg = ccp;
1637 }
1638 sep->se_log &= ~MULOG_RFC931;
1639 sep->se_log |= x;
1640 break;
1641 case 'a':
1642 sep->se_log |= MULOG_RFC931;
1643 break;
1644 default:
1645 break;
1646 }
1647 }
1648 arg = colon + 1;
1649 }
1650 #endif
1651 if (argc < MAXARGV)
1652 sep->se_argv[argc++] = newstr(arg);
1653 }
1654 while (argc <= MAXARGV)
1655 sep->se_argv[argc++] = NULL;
1656 #ifdef IPSEC
1657 sep->se_policy = policy ? newstr(policy) : NULL;
1658 #endif
1659 return (sep);
1660 }
1661
1662 static void
1663 freeconfig(struct servtab *cp)
1664 {
1665 int i;
1666
1667 if (cp->se_hostaddr)
1668 free(cp->se_hostaddr);
1669 if (cp->se_service)
1670 free(cp->se_service);
1671 if (cp->se_proto)
1672 free(cp->se_proto);
1673 if (cp->se_user)
1674 free(cp->se_user);
1675 /* Note: se_group is part of the newstr'ed se_user */
1676 if (cp->se_server)
1677 free(cp->se_server);
1678 for (i = 0; i < MAXARGV; i++)
1679 if (cp->se_argv[i])
1680 free(cp->se_argv[i]);
1681 #ifdef IPSEC
1682 if (cp->se_policy)
1683 free(cp->se_policy);
1684 #endif
1685 }
1686
1687
1688 /*
1689 * Safe skip - if skip returns null, log a syntax error in the
1690 * configuration file and exit.
1691 */
1692 static char *
1693 sskip(char **cpp)
1694 {
1695 char *cp;
1696
1697 cp = skip(cpp);
1698 if (cp == NULL) {
1699 syslog(LOG_ERR, "%s: syntax error", CONFIG);
1700 exit(1);
1701 }
1702 return (cp);
1703 }
1704
1705 static char *
1706 skip(char **cpp)
1707 {
1708 char *cp = *cpp;
1709 char *start;
1710 char quote;
1711
1712 if (*cpp == NULL)
1713 return (NULL);
1714
1715 again:
1716 while (*cp == ' ' || *cp == '\t')
1717 cp++;
1718 if (*cp == '\0') {
1719 int c;
1720
1721 c = getc(fconfig);
1722 (void) ungetc(c, fconfig);
1723 if (c == ' ' || c == '\t')
1724 if ((cp = nextline(fconfig)))
1725 goto again;
1726 *cpp = NULL;
1727 return (NULL);
1728 }
1729 start = cp;
1730 quote = '\0';
1731 while (*cp && (quote || (*cp != ' ' && *cp != '\t'))) {
1732 if (*cp == '\'' || *cp == '"') {
1733 if (quote && *cp != quote)
1734 cp++;
1735 else {
1736 if (quote)
1737 quote = '\0';
1738 else
1739 quote = *cp;
1740 memmove(cp, cp+1, strlen(cp));
1741 }
1742 } else
1743 cp++;
1744 }
1745 if (*cp != '\0')
1746 *cp++ = '\0';
1747 *cpp = cp;
1748 return (start);
1749 }
1750
1751 static char *
1752 nextline(FILE *fd)
1753 {
1754 char *cp;
1755
1756 if (fgets(line, sizeof (line), fd) == NULL)
1757 return (NULL);
1758 cp = strchr(line, '\n');
1759 if (cp)
1760 *cp = '\0';
1761 return (line);
1762 }
1763
1764 static char *
1765 newstr(char *cp)
1766 {
1767 if ((cp = strdup((cp != NULL) ? cp : "")) != NULL)
1768 return (cp);
1769 syslog(LOG_ERR, "strdup: %m");
1770 exit(1);
1771 }
1772
1773 static void
1774 inetd_setproctitle(char *a, int s)
1775 {
1776 socklen_t size;
1777 struct sockaddr_storage ss;
1778 char hbuf[NI_MAXHOST], *hp;
1779
1780 size = sizeof(ss);
1781 if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
1782 if (getnameinfo((struct sockaddr *)&ss, size, hp = hbuf,
1783 sizeof(hbuf), NULL, 0, niflags) != 0)
1784 hp = "?";
1785 setproctitle("-%s [%s]", a, hp);
1786 } else
1787 setproctitle("-%s", a);
1788 }
1789
1790 static void
1791 bump_nofile(void)
1792 {
1793 #ifdef RLIMIT_NOFILE
1794
1795 #define FD_CHUNK 32
1796
1797 struct rlimit rl;
1798
1799 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1800 syslog(LOG_ERR, "getrlimit: %m");
1801 return;
1802 }
1803 rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
1804 if (rl.rlim_cur <= rlim_ofile_cur) {
1805 syslog(LOG_ERR,
1806 "bump_nofile: cannot extend file limit, max = %d",
1807 (int)rl.rlim_cur);
1808 return;
1809 }
1810
1811 if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
1812 syslog(LOG_ERR, "setrlimit: %m");
1813 return;
1814 }
1815
1816 rlim_ofile_cur = rl.rlim_cur;
1817 return;
1818
1819 #else
1820 syslog(LOG_ERR, "bump_nofile: cannot extend file limit");
1821 return;
1822 #endif
1823 }
1824
1825 /*
1826 * Internet services provided internally by inetd:
1827 */
1828 #define BUFSIZE 4096
1829
1830 /* ARGSUSED */
1831 static void
1832 echo_stream(int s, struct servtab *sep) /* Echo service -- echo data back */
1833 {
1834 char buffer[BUFSIZE];
1835 int i;
1836
1837 inetd_setproctitle(sep->se_service, s);
1838 while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
1839 write(s, buffer, i) > 0)
1840 ;
1841 }
1842
1843 /* ARGSUSED */
1844 static void
1845 echo_dg(int s, struct servtab *sep) /* Echo service -- echo data back */
1846 {
1847 char buffer[BUFSIZE];
1848 int i;
1849 socklen_t size;
1850 struct sockaddr_storage ss;
1851 struct sockaddr *sa;
1852
1853 sa = (struct sockaddr *)&ss;
1854 size = sizeof(ss);
1855 if ((i = recvfrom(s, buffer, sizeof(buffer), 0, sa, &size)) < 0)
1856 return;
1857 if (port_good_dg(sa))
1858 (void) sendto(s, buffer, i, 0, sa, size);
1859 }
1860
1861 /* ARGSUSED */
1862 static void
1863 discard_stream(int s, struct servtab *sep) /* Discard service -- ignore data */
1864 {
1865 char buffer[BUFSIZE];
1866
1867 inetd_setproctitle(sep->se_service, s);
1868 while ((errno = 0, read(s, buffer, sizeof(buffer)) > 0) ||
1869 errno == EINTR)
1870 ;
1871 }
1872
1873 /* ARGSUSED */
1874 static void
1875 discard_dg(int s, struct servtab *sep) /* Discard service -- ignore data */
1876
1877 {
1878 char buffer[BUFSIZE];
1879
1880 (void) read(s, buffer, sizeof(buffer));
1881 }
1882
1883 #include <ctype.h>
1884 #define LINESIZ 72
1885 char ring[128];
1886 char *endring;
1887
1888 static void
1889 initring(void)
1890 {
1891 int i;
1892
1893 endring = ring;
1894
1895 for (i = 0; i <= 128; ++i)
1896 if (isprint(i))
1897 *endring++ = i;
1898 }
1899
1900 /* ARGSUSED */
1901 static void
1902 chargen_stream(int s,struct servtab *sep) /* Character generator */
1903 {
1904 int len;
1905 char *rs, text[LINESIZ+2];
1906
1907 inetd_setproctitle(sep->se_service, s);
1908
1909 if (!endring) {
1910 initring();
1911 rs = ring;
1912 }
1913
1914 text[LINESIZ] = '\r';
1915 text[LINESIZ + 1] = '\n';
1916 for (rs = ring;;) {
1917 if ((len = endring - rs) >= LINESIZ)
1918 memmove(text, rs, LINESIZ);
1919 else {
1920 memmove(text, rs, len);
1921 memmove(text + len, ring, LINESIZ - len);
1922 }
1923 if (++rs == endring)
1924 rs = ring;
1925 if (write(s, text, sizeof(text)) != sizeof(text))
1926 break;
1927 }
1928 }
1929
1930 /* ARGSUSED */
1931 static void
1932 chargen_dg(int s, struct servtab *sep) /* Character generator */
1933 {
1934 struct sockaddr_storage ss;
1935 struct sockaddr *sa;
1936 static char *rs;
1937 int len;
1938 socklen_t size;
1939 char text[LINESIZ+2];
1940
1941 if (endring == 0) {
1942 initring();
1943 rs = ring;
1944 }
1945
1946 sa = (struct sockaddr *)&ss;
1947 size = sizeof(ss);
1948 if (recvfrom(s, text, sizeof(text), 0, sa, &size) < 0)
1949 return;
1950
1951 if (!port_good_dg(sa))
1952 return;
1953
1954 if ((len = endring - rs) >= LINESIZ)
1955 memmove(text, rs, LINESIZ);
1956 else {
1957 memmove(text, rs, len);
1958 memmove(text + len, ring, LINESIZ - len);
1959 }
1960 if (++rs == endring)
1961 rs = ring;
1962 text[LINESIZ] = '\r';
1963 text[LINESIZ + 1] = '\n';
1964 (void) sendto(s, text, sizeof(text), 0, sa, size);
1965 }
1966
1967 /*
1968 * Return a machine readable date and time, in the form of the
1969 * number of seconds since midnight, Jan 1, 1900. Since gettimeofday
1970 * returns the number of seconds since midnight, Jan 1, 1970,
1971 * we must add 2208988800 seconds to this figure to make up for
1972 * some seventy years Bell Labs was asleep.
1973 */
1974
1975 static uint32_t
1976 machtime(void)
1977 {
1978 struct timeval tv;
1979
1980 if (gettimeofday(&tv, NULL) < 0) {
1981 if (debug)
1982 fprintf(stderr, "Unable to get time of day\n");
1983 return (0);
1984 }
1985 #define OFFSET ((uint32_t)25567 * 24*60*60)
1986 return (htonl((uint32_t)(tv.tv_sec + OFFSET)));
1987 #undef OFFSET
1988 }
1989
1990 /* ARGSUSED */
1991 static void
1992 machtime_stream(int s, struct servtab *sep)
1993 {
1994 uint32_t result;
1995
1996 result = machtime();
1997 (void) write(s, (char *) &result, sizeof(result));
1998 }
1999
2000 /* ARGSUSED */
2001 void
2002 machtime_dg(int s, struct servtab *sep)
2003 {
2004 uint32_t result;
2005 struct sockaddr_storage ss;
2006 struct sockaddr *sa;
2007 socklen_t size;
2008
2009 sa = (struct sockaddr *)&ss;
2010 size = sizeof(ss);
2011 if (recvfrom(s, (char *)&result, sizeof(result), 0, sa, &size) < 0)
2012 return;
2013 if (!port_good_dg(sa))
2014 return;
2015 result = machtime();
2016 (void) sendto(s, (char *) &result, sizeof(result), 0, sa, size);
2017 }
2018
2019 /* ARGSUSED */
2020 static void
2021 daytime_stream(int s,struct servtab *sep)
2022 /* Return human-readable time of day */
2023 {
2024 char buffer[256];
2025 time_t clock;
2026 int len;
2027
2028 clock = time((time_t *) 0);
2029
2030 len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2031 (void) write(s, buffer, len);
2032 }
2033
2034 /* ARGSUSED */
2035 void
2036 daytime_dg(int s, struct servtab *sep)
2037 /* Return human-readable time of day */
2038 {
2039 char buffer[256];
2040 time_t clock;
2041 struct sockaddr_storage ss;
2042 struct sockaddr *sa;
2043 socklen_t size;
2044 int len;
2045
2046 clock = time((time_t *) 0);
2047
2048 sa = (struct sockaddr *)&ss;
2049 size = sizeof(ss);
2050 if (recvfrom(s, buffer, sizeof(buffer), 0, sa, &size) < 0)
2051 return;
2052 if (!port_good_dg(sa))
2053 return;
2054 len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2055 (void) sendto(s, buffer, len, 0, sa, size);
2056 }
2057
2058 /*
2059 * print_service:
2060 * Dump relevant information to stderr
2061 */
2062 static void
2063 print_service(char *action, struct servtab *sep)
2064 {
2065
2066 if (isrpcservice(sep))
2067 fprintf(stderr,
2068 "%s: %s rpcprog=%d, rpcvers = %d/%d, proto=%s, wait.max=%d.%d, user:group=%s:%s builtin=%lx server=%s"
2069 #ifdef IPSEC
2070 " policy=\"%s\""
2071 #endif
2072 "\n",
2073 action, sep->se_service,
2074 sep->se_rpcprog, sep->se_rpcversh, sep->se_rpcversl, sep->se_proto,
2075 sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2076 (long)sep->se_bi, sep->se_server
2077 #ifdef IPSEC
2078 , (sep->se_policy ? sep->se_policy : "")
2079 #endif
2080 );
2081 else
2082 fprintf(stderr,
2083 "%s: %s proto=%s%s, wait.max=%d.%d, user:group=%s:%s builtin=%lx server=%s"
2084 #ifdef IPSEC
2085 " policy=%s"
2086 #endif
2087 "\n",
2088 action, sep->se_service,
2089 sep->se_type == FAITH_TYPE ? "faith/" : "",
2090 sep->se_proto,
2091 sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2092 (long)sep->se_bi, sep->se_server
2093 #ifdef IPSEC
2094 , (sep->se_policy ? sep->se_policy : "")
2095 #endif
2096 );
2097 }
2098
2099 static void
2100 usage(void)
2101 {
2102 #ifdef LIBWRAP
2103 (void)fprintf(stderr, "usage: %s [-dl] [conf]\n", getprogname());
2104 #else
2105 (void)fprintf(stderr, "usage: %s [-d] [conf]\n", getprogname());
2106 #endif
2107 exit(1);
2108 }
2109
2110
2111 /*
2112 * Based on TCPMUX.C by Mark K. Lottor November 1988
2113 * sri-nic::ps:<mkl>tcpmux.c
2114 */
2115
2116 static int /* # of characters upto \r,\n or \0 */
2117 getline(int fd, char *buf, int len)
2118 {
2119 int count = 0, n;
2120
2121 do {
2122 n = read(fd, buf, len-count);
2123 if (n == 0)
2124 return (count);
2125 if (n < 0)
2126 return (-1);
2127 while (--n >= 0) {
2128 if (*buf == '\r' || *buf == '\n' || *buf == '\0')
2129 return (count);
2130 count++;
2131 buf++;
2132 }
2133 } while (count < len);
2134 return (count);
2135 }
2136
2137 #define MAX_SERV_LEN (256+2) /* 2 bytes for \r\n */
2138
2139 #define strwrite(fd, buf) (void) write(fd, buf, sizeof(buf)-1)
2140
2141 static void
2142 tcpmux(int ctrl, struct servtab *sep)
2143 {
2144 char service[MAX_SERV_LEN+1];
2145 int len;
2146
2147 /* Get requested service name */
2148 if ((len = getline(ctrl, service, MAX_SERV_LEN)) < 0) {
2149 strwrite(ctrl, "-Error reading service name\r\n");
2150 goto reject;
2151 }
2152 service[len] = '\0';
2153
2154 if (debug)
2155 fprintf(stderr, "tcpmux: someone wants %s\n", service);
2156
2157 /*
2158 * Help is a required command, and lists available services,
2159 * one per line.
2160 */
2161 if (!strcasecmp(service, "help")) {
2162 strwrite(ctrl, "+Available services:\r\n");
2163 strwrite(ctrl, "help\r\n");
2164 for (sep = servtab; sep != NULL; sep = sep->se_next) {
2165 if (!ISMUX(sep))
2166 continue;
2167 (void)write(ctrl, sep->se_service,
2168 strlen(sep->se_service));
2169 strwrite(ctrl, "\r\n");
2170 }
2171 goto reject;
2172 }
2173
2174 /* Try matching a service in inetd.conf with the request */
2175 for (sep = servtab; sep != NULL; sep = sep->se_next) {
2176 if (!ISMUX(sep))
2177 continue;
2178 if (!strcasecmp(service, sep->se_service)) {
2179 if (ISMUXPLUS(sep))
2180 strwrite(ctrl, "+Go\r\n");
2181 run_service(ctrl, sep);
2182 return;
2183 }
2184 }
2185 strwrite(ctrl, "-Service not available\r\n");
2186 reject:
2187 _exit(1);
2188 }
2189
2190 #ifdef MULOG
2191 void
2192 dolog(struct servtab *sep, int ctrl)
2193 {
2194 struct sockaddr_storage ss;
2195 struct sockaddr *sa = (struct sockaddr *)&ss;
2196 socklen_t len = sizeof(ss);
2197 char *host, *dp, buf[BUFSIZ];
2198 int connected = 1;
2199
2200 switch (sep->se_family) {
2201 case AF_INET:
2202 #ifdef INET6
2203 case AF_INET6:
2204 #endif
2205 break;
2206 default:
2207 return;
2208 }
2209
2210 if (getpeername(ctrl, sa, &len) < 0) {
2211 if (errno != ENOTCONN) {
2212 syslog(LOG_ERR, "getpeername: %m");
2213 return;
2214 }
2215 if (recvfrom(ctrl, buf, sizeof(buf), MSG_PEEK, sa, &len) < 0) {
2216 syslog(LOG_ERR, "recvfrom: %m");
2217 return;
2218 }
2219 connected = 0;
2220 }
2221 switch (sa->sa_family) {
2222 case AF_INET:
2223 #ifdef INET6
2224 case AF_INET6:
2225 #endif
2226 break;
2227 default:
2228 syslog(LOG_ERR, "unexpected address family %u", sa->sa_family);
2229 return;
2230 }
2231
2232 if (getnameinfo(sa, len, buf, sizeof(buf), NULL, 0, 0) != 0)
2233 strlcpy(buf, "?", sizeof(buf));
2234 host = buf;
2235
2236 switch (sep->se_log & ~MULOG_RFC931) {
2237 case 0:
2238 return;
2239 case 1:
2240 if (curdom == NULL || *curdom == '\0')
2241 break;
2242 dp = host + strlen(host) - strlen(curdom);
2243 if (dp < host)
2244 break;
2245 if (debug)
2246 fprintf(stderr, "check \"%s\" against curdom \"%s\"\n",
2247 host, curdom);
2248 if (strcasecmp(dp, curdom) == 0)
2249 return;
2250 break;
2251 case 2:
2252 default:
2253 break;
2254 }
2255
2256 openlog("", LOG_NOWAIT, MULOG);
2257
2258 if (connected && (sep->se_log & MULOG_RFC931))
2259 syslog(LOG_INFO, "%s@%s wants %s",
2260 rfc931_name(sa, ctrl), host, sep->se_service);
2261 else
2262 syslog(LOG_INFO, "%s wants %s",
2263 host, sep->se_service);
2264 }
2265
2266 /*
2267 * From tcp_log by
2268 * Wietse Venema, Eindhoven University of Technology, The Netherlands.
2269 */
2270 #if 0
2271 static char sccsid[] = "@(#) rfc931.c 1.3 92/08/31 22:54:46";
2272 #endif
2273
2274 #include <setjmp.h>
2275
2276 #define RFC931_PORT 113 /* Semi-well-known port */
2277 #define TIMEOUT 4
2278 #define TIMEOUT2 10
2279
2280 static jmp_buf timebuf;
2281
2282 /* timeout - handle timeouts */
2283
2284 static void
2285 timeout(int sig)
2286 {
2287 longjmp(timebuf, sig);
2288 }
2289
2290 /* rfc931_name - return remote user name */
2291
2292 char *
2293 rfc931_name(struct sockaddr *there, /* remote link information */
2294 int ctrl)
2295 {
2296 struct sockaddr_storage here; /* local link information */
2297 struct sockaddr_storage sin; /* for talking to RFC931 daemon */
2298 socklen_t length;
2299 int s;
2300 unsigned remote;
2301 unsigned local;
2302 static char user[256]; /* XXX */
2303 char buf[256];
2304 char *cp;
2305 char *result = "USER_UNKNOWN";
2306 int len;
2307 u_int16_t myport, hisport;
2308
2309 /* Find out local port number of our stdin. */
2310
2311 length = sizeof(here);
2312 if (getsockname(ctrl, (struct sockaddr *) &here, &length) == -1) {
2313 syslog(LOG_ERR, "getsockname: %m");
2314 return (result);
2315 }
2316 switch (here.ss_family) {
2317 case AF_INET:
2318 myport = ((struct sockaddr_in *)&here)->sin_port;
2319 break;
2320 #ifdef INET6
2321 case AF_INET6:
2322 myport = ((struct sockaddr_in6 *)&here)->sin6_port;
2323 break;
2324 #endif
2325 }
2326 switch (there->sa_family) {
2327 case AF_INET:
2328 hisport = ((struct sockaddr_in *)&there)->sin_port;
2329 break;
2330 #ifdef INET6
2331 case AF_INET6:
2332 hisport = ((struct sockaddr_in6 *)&there)->sin6_port;
2333 break;
2334 #endif
2335 }
2336 /* Set up timer so we won't get stuck. */
2337
2338 if ((s = socket(here.ss_family, SOCK_STREAM, 0)) == -1) {
2339 syslog(LOG_ERR, "socket: %m");
2340 return (result);
2341 }
2342
2343 sin = here;
2344 switch (sin.ss_family) {
2345 case AF_INET:
2346 ((struct sockaddr_in *)&sin)->sin_port = htons(0);
2347 break;
2348 #ifdef INET6
2349 case AF_INET6:
2350 ((struct sockaddr_in6 *)&sin)->sin6_port = htons(0);
2351 break;
2352 #endif
2353 }
2354 if (bind(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2355 syslog(LOG_ERR, "bind: %m");
2356 return (result);
2357 }
2358
2359 signal(SIGALRM, timeout);
2360 if (setjmp(timebuf)) {
2361 close(s); /* not: fclose(fp) */
2362 return (result);
2363 }
2364 alarm(TIMEOUT);
2365
2366 /* Connect to the RFC931 daemon. */
2367
2368 memcpy(&sin, there, there->sa_len);
2369 switch (sin.ss_family) {
2370 case AF_INET:
2371 ((struct sockaddr_in *)&sin)->sin_port = htons(RFC931_PORT);
2372 break;
2373 #ifdef INET6
2374 case AF_INET6:
2375 ((struct sockaddr_in6 *)&sin)->sin6_port = htons(RFC931_PORT);
2376 break;
2377 #endif
2378 }
2379 if (connect(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2380 close(s);
2381 alarm(0);
2382 return (result);
2383 }
2384
2385 /* Query the RFC 931 server. Would 13-byte writes ever be broken up? */
2386 (void)snprintf(buf, sizeof buf, "%u,%u\r\n", ntohs(hisport),
2387 ntohs(myport));
2388
2389 for (len = 0, cp = buf; len < strlen(buf); ) {
2390 int n;
2391
2392 if ((n = write(s, cp, strlen(buf) - len)) == -1) {
2393 close(s);
2394 alarm(0);
2395 return (result);
2396 }
2397 cp += n;
2398 len += n;
2399 }
2400
2401 /* Read response */
2402 for (cp = buf; cp < buf + sizeof(buf) - 1; ) {
2403 char c;
2404 if (read(s, &c, 1) != 1) {
2405 close(s);
2406 alarm(0);
2407 return (result);
2408 }
2409 if (c == '\n')
2410 break;
2411 *cp++ = c;
2412 }
2413 *cp = '\0';
2414
2415 if (sscanf(buf, "%u , %u : USERID :%*[^:]:%255s", &remote, &local,
2416 user) == 3 && ntohs(hisport) == remote && ntohs(myport) == local) {
2417 /* Strip trailing carriage return. */
2418 if ((cp = strchr(user, '\r')) != NULL)
2419 *cp = 0;
2420 result = user;
2421 }
2422
2423 alarm(0);
2424 close(s);
2425 return (result);
2426 }
2427 #endif
2428
2429 /*
2430 * check if the address/port where send data to is one of the obvious ports
2431 * that are used for denial of service attacks like two echo ports
2432 * just echoing data between them
2433 */
2434 static int
2435 port_good_dg(struct sockaddr *sa)
2436 {
2437 struct in_addr in;
2438 #ifdef INET6
2439 struct in6_addr *in6;
2440 #endif
2441 u_int16_t port;
2442 int i, bad;
2443 char hbuf[NI_MAXHOST];
2444
2445 bad = 0;
2446
2447 switch (sa->sa_family) {
2448 case AF_INET:
2449 in.s_addr = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr);
2450 port = ntohs(((struct sockaddr_in *)sa)->sin_port);
2451 #ifdef INET6
2452 v4chk:
2453 #endif
2454 if (IN_MULTICAST(in.s_addr))
2455 goto bad;
2456 switch ((in.s_addr & 0xff000000) >> 24) {
2457 case 0: case 127: case 255:
2458 goto bad;
2459 }
2460 if (dg_broadcast(&in))
2461 goto bad;
2462 break;
2463 #ifdef INET6
2464 case AF_INET6:
2465 in6 = &((struct sockaddr_in6 *)sa)->sin6_addr;
2466 port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
2467 if (IN6_IS_ADDR_MULTICAST(in6) || IN6_IS_ADDR_UNSPECIFIED(in6))
2468 goto bad;
2469 if (IN6_IS_ADDR_V4MAPPED(in6) || IN6_IS_ADDR_V4COMPAT(in6)) {
2470 memcpy(&in, &in6->s6_addr[12], sizeof(in));
2471 in.s_addr = ntohl(in.s_addr);
2472 goto v4chk;
2473 }
2474 break;
2475 #endif
2476 default:
2477 /* XXX unsupported af, is it safe to assume it to be safe? */
2478 return (1);
2479 }
2480
2481 for (i = 0; bad_ports[i] != 0; i++) {
2482 if (port == bad_ports[i])
2483 goto bad;
2484 }
2485
2486 return (1);
2487
2488 bad:
2489 if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0,
2490 niflags) != 0)
2491 strlcpy(hbuf, "?", sizeof(hbuf));
2492 syslog(LOG_WARNING,"Possible DoS attack from %s, Port %d",
2493 hbuf, port);
2494 return (0);
2495 }
2496
2497 /* XXX need optimization */
2498 static int
2499 dg_broadcast(struct in_addr *in)
2500 {
2501 struct ifaddrs *ifa, *ifap;
2502 struct sockaddr_in *sin;
2503
2504 if (getifaddrs(&ifap) < 0)
2505 return (0);
2506 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
2507 if (ifa->ifa_addr->sa_family != AF_INET ||
2508 (ifa->ifa_flags & IFF_BROADCAST) == 0)
2509 continue;
2510 sin = (struct sockaddr_in *)ifa->ifa_broadaddr;
2511 if (sin->sin_addr.s_addr == in->s_addr) {
2512 freeifaddrs(ifap);
2513 return (1);
2514 }
2515 }
2516 freeifaddrs(ifap);
2517 return (0);
2518 }
2519
2520 static int
2521 my_kevent(const struct kevent *changelist, size_t nchanges,
2522 struct kevent *eventlist, size_t nevents)
2523 {
2524 int result;
2525
2526 while ((result = kevent(kq, changelist, nchanges, eventlist, nevents,
2527 NULL)) < 0)
2528 if (errno != EINTR) {
2529 syslog(LOG_ERR, "kevent: %m");
2530 exit(EXIT_FAILURE);
2531 }
2532
2533 return (result);
2534 }
2535
2536 static struct kevent *
2537 allocchange(void)
2538 {
2539 if (changes == A_CNT(changebuf)) {
2540 (void) my_kevent(changebuf, A_CNT(changebuf), NULL, 0);
2541 changes = 0;
2542 }
2543
2544 return (&changebuf[changes++]);
2545 }
2546