inetd.c revision 1.97 1 /* $NetBSD: inetd.c,v 1.97 2004/10/20 11:37:42 pk 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.97 2004/10/20 11:37:42 pk 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 < A_CNT(my_signals); n++) {
500 int signum;
501
502 signum = my_signals[n];
503 (void) signal(signum, SIG_IGN);
504
505 if (signum != SIGPIPE) {
506 struct kevent *ev;
507
508 ev = allocchange();
509 EV_SET(ev, signum, EVFILT_SIGNAL, EV_ADD | EV_ENABLE,
510 0, 0, 0);
511 }
512 }
513
514 for (;;) {
515 int ctrl;
516 struct kevent eventbuf[64], *ev;
517 struct servtab *sep;
518
519 if (reload) {
520 reload = 0;
521 config();
522 }
523
524 n = my_kevent(changebuf, changes, eventbuf, A_CNT(eventbuf));
525 changes = 0;
526
527 for (ev = eventbuf; n > 0; ev++, n--) {
528 if (ev->filter == EVFILT_SIGNAL) {
529 switch (ev->ident) {
530 case SIGALRM:
531 retry();
532 break;
533 case SIGCHLD:
534 reapchild();
535 break;
536 case SIGTERM:
537 case SIGINT:
538 goaway();
539 break;
540 case SIGHUP:
541 reload = 1;
542 break;
543 }
544 continue;
545 }
546 if (ev->filter != EVFILT_READ)
547 continue;
548 sep = (struct servtab *)ev->udata;
549 /* Paranoia */
550 if (ev->ident != sep->se_fd)
551 continue;
552 if (debug)
553 fprintf(stderr, "someone wants %s\n",
554 sep->se_service);
555 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
556 /* XXX here do the libwrap check-before-accept*/
557 ctrl = accept(sep->se_fd, NULL, NULL);
558 if (debug)
559 fprintf(stderr, "accept, ctrl %d\n",
560 ctrl);
561 if (ctrl < 0) {
562 if (errno != EINTR)
563 syslog(LOG_WARNING,
564 "accept (for %s): %m",
565 sep->se_service);
566 continue;
567 }
568 } else
569 ctrl = sep->se_fd;
570 spawn(sep, ctrl);
571 }
572 }
573 }
574
575 static void
576 spawn(struct servtab *sep, int ctrl)
577 {
578 int dofork;
579 pid_t pid;
580
581 pid = 0;
582 #ifdef LIBWRAP_INTERNAL
583 dofork = 1;
584 #else
585 dofork = (sep->se_bi == 0 || sep->se_bi->bi_fork);
586 #endif
587 if (dofork) {
588 if (sep->se_count++ == 0)
589 (void)gettimeofday(&sep->se_time, NULL);
590 else if (sep->se_count >= sep->se_max) {
591 struct timeval now;
592
593 (void)gettimeofday(&now, NULL);
594 if (now.tv_sec - sep->se_time.tv_sec > CNT_INTVL) {
595 sep->se_time = now;
596 sep->se_count = 1;
597 } else {
598 syslog(LOG_ERR,
599 "%s/%s max spawn rate (%d in %d seconds) "
600 "exceeded; service not started",
601 sep->se_service, sep->se_proto,
602 sep->se_max, CNT_INTVL);
603 if (!sep->se_wait && sep->se_socktype ==
604 SOCK_STREAM)
605 close(ctrl);
606 close_sep(sep);
607 if (!timingout) {
608 timingout = 1;
609 alarm(RETRYTIME);
610 }
611 return;
612 }
613 }
614 pid = fork();
615 if (pid < 0) {
616 syslog(LOG_ERR, "fork: %m");
617 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
618 close(ctrl);
619 sleep(1);
620 return;
621 }
622 if (pid != 0 && sep->se_wait) {
623 struct kevent *ev;
624
625 sep->se_wait = pid;
626 ev = allocchange();
627 EV_SET(ev, sep->se_fd, EVFILT_READ,
628 EV_DELETE, 0, 0, 0);
629 }
630 if (pid == 0) {
631 int n;
632
633 for (n = 0; n < A_CNT(my_signals); n++)
634 (void) signal(my_signals[n], SIG_DFL);
635 if (debug)
636 setsid();
637 }
638 }
639 if (pid == 0) {
640 run_service(ctrl, sep);
641 if (dofork)
642 exit(0);
643 }
644 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
645 close(ctrl);
646 }
647
648 static void
649 run_service(int ctrl, struct servtab *sep)
650 {
651 struct passwd *pwd;
652 struct group *grp = NULL; /* XXX gcc */
653 char buf[NI_MAXSERV];
654 #ifdef LIBWRAP
655 struct request_info req;
656 int denied;
657 char *service = NULL; /* XXX gcc */
658 #endif
659
660 #ifdef LIBWRAP
661 #ifndef LIBWRAP_INTERNAL
662 if (sep->se_bi == 0)
663 #endif
664 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
665 request_init(&req, RQ_DAEMON, sep->se_argv[0] ?
666 sep->se_argv[0] : sep->se_service, RQ_FILE, ctrl, NULL);
667 fromhost(&req);
668 denied = !hosts_access(&req);
669 if (denied || lflag) {
670 if (getnameinfo(&sep->se_ctrladdr,
671 sep->se_ctrladdr.sa_len, NULL, 0,
672 buf, sizeof(buf), 0) != 0) {
673 /* shouldn't happen */
674 (void)snprintf(buf, sizeof buf, "%d",
675 ntohs(sep->se_ctrladdr_in.sin_port));
676 }
677 service = buf;
678 }
679 if (denied) {
680 syslog(deny_severity,
681 "refused connection from %.500s, service %s (%s)",
682 eval_client(&req), service, sep->se_proto);
683 goto reject;
684 }
685 if (lflag) {
686 syslog(allow_severity,
687 "connection from %.500s, service %s (%s)",
688 eval_client(&req), service, sep->se_proto);
689 }
690 }
691 #endif /* LIBWRAP */
692
693 if (sep->se_bi) {
694 (*sep->se_bi->bi_fn)(ctrl, sep);
695 } else {
696 if ((pwd = getpwnam(sep->se_user)) == NULL) {
697 syslog(LOG_ERR, "%s/%s: %s: No such user",
698 sep->se_service, sep->se_proto, sep->se_user);
699 goto reject;
700 }
701 if (sep->se_group &&
702 (grp = getgrnam(sep->se_group)) == NULL) {
703 syslog(LOG_ERR, "%s/%s: %s: No such group",
704 sep->se_service, sep->se_proto, sep->se_group);
705 goto reject;
706 }
707 if (pwd->pw_uid) {
708 if (sep->se_group)
709 pwd->pw_gid = grp->gr_gid;
710 if (setgid(pwd->pw_gid) < 0) {
711 syslog(LOG_ERR,
712 "%s/%s: can't set gid %d: %m", sep->se_service,
713 sep->se_proto, pwd->pw_gid);
714 goto reject;
715 }
716 (void) initgroups(pwd->pw_name,
717 pwd->pw_gid);
718 if (setuid(pwd->pw_uid) < 0) {
719 syslog(LOG_ERR,
720 "%s/%s: can't set uid %d: %m", sep->se_service,
721 sep->se_proto, pwd->pw_uid);
722 goto reject;
723 }
724 } else if (sep->se_group) {
725 (void) setgid((gid_t)grp->gr_gid);
726 }
727 if (debug)
728 fprintf(stderr, "%d execl %s\n",
729 getpid(), sep->se_server);
730 #ifdef MULOG
731 if (sep->se_log)
732 dolog(sep, ctrl);
733 #endif
734 /* Set our control descriptor to not close-on-exec... */
735 if (fcntl(ctrl, F_SETFD, 0) < 0)
736 syslog(LOG_ERR, "fcntl (F_SETFD, 0): %m");
737 /* ...and dup it to stdin, stdout, and stderr. */
738 if (ctrl != 0) {
739 dup2(ctrl, 0);
740 close(ctrl);
741 ctrl = 0;
742 }
743 dup2(0, 1);
744 dup2(0, 2);
745 #ifdef RLIMIT_NOFILE
746 if (rlim_ofile.rlim_cur != rlim_ofile_cur &&
747 setrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0)
748 syslog(LOG_ERR, "setrlimit: %m");
749 #endif
750 execv(sep->se_server, sep->se_argv);
751 syslog(LOG_ERR, "cannot execute %s: %m", sep->se_server);
752 reject:
753 if (sep->se_socktype != SOCK_STREAM)
754 recv(ctrl, buf, sizeof (buf), 0);
755 _exit(1);
756 }
757 }
758
759 static void
760 reapchild(void)
761 {
762 int status;
763 pid_t pid;
764 struct servtab *sep;
765
766 for (;;) {
767 pid = wait3(&status, WNOHANG, NULL);
768 if (pid <= 0)
769 break;
770 if (debug)
771 (void) fprintf(stderr, "%d reaped, status %#x\n",
772 pid, status);
773 for (sep = servtab; sep != NULL; sep = sep->se_next)
774 if (sep->se_wait == pid) {
775 struct kevent *ev;
776
777 if (WIFEXITED(status) && WEXITSTATUS(status))
778 syslog(LOG_WARNING,
779 "%s: exit status 0x%x",
780 sep->se_server, WEXITSTATUS(status));
781 else if (WIFSIGNALED(status))
782 syslog(LOG_WARNING,
783 "%s: exit signal 0x%x",
784 sep->se_server, WTERMSIG(status));
785 sep->se_wait = 1;
786 ev = allocchange();
787 EV_SET(ev, sep->se_fd, EVFILT_READ,
788 EV_ADD | EV_ENABLE, 0, 0, (intptr_t)sep);
789 if (debug)
790 fprintf(stderr, "restored %s, fd %d\n",
791 sep->se_service, sep->se_fd);
792 }
793 }
794 }
795
796 static void
797 config(void)
798 {
799 struct servtab *sep, *cp, **sepp;
800 int n;
801
802 if (!setconfig()) {
803 syslog(LOG_ERR, "%s: %m", CONFIG);
804 return;
805 }
806 for (sep = servtab; sep != NULL; sep = sep->se_next)
807 sep->se_checked = 0;
808 while ((cp = getconfigent())) {
809 for (sep = servtab; sep != NULL; sep = sep->se_next)
810 if (strcmp(sep->se_service, cp->se_service) == 0 &&
811 strcmp(sep->se_hostaddr, cp->se_hostaddr) == 0 &&
812 strcmp(sep->se_proto, cp->se_proto) == 0 &&
813 ISMUX(sep) == ISMUX(cp))
814 break;
815 if (sep != NULL) {
816 int i;
817
818 #define SWAP(type, a, b) {type c=(type)a; (type)a=(type)b; (type)b=(type)c;}
819
820 /*
821 * sep->se_wait may be holding the pid of a daemon
822 * that we're waiting for. If so, don't overwrite
823 * it unless the config file explicitly says don't
824 * wait.
825 */
826 if (cp->se_bi == 0 &&
827 (sep->se_wait == 1 || cp->se_wait == 0))
828 sep->se_wait = cp->se_wait;
829 SWAP(char *, sep->se_user, cp->se_user);
830 SWAP(char *, sep->se_group, cp->se_group);
831 SWAP(char *, sep->se_server, cp->se_server);
832 for (i = 0; i < MAXARGV; i++)
833 SWAP(char *, sep->se_argv[i], cp->se_argv[i]);
834 #ifdef IPSEC
835 SWAP(char *, sep->se_policy, cp->se_policy);
836 #endif
837 SWAP(int, cp->se_type, sep->se_type);
838 SWAP(int, cp->se_max, sep->se_max);
839 #undef SWAP
840 if (isrpcservice(sep))
841 unregister_rpc(sep);
842 sep->se_rpcversl = cp->se_rpcversl;
843 sep->se_rpcversh = cp->se_rpcversh;
844 freeconfig(cp);
845 if (debug)
846 print_service("REDO", sep);
847 } else {
848 sep = enter(cp);
849 if (debug)
850 print_service("ADD ", sep);
851 }
852 sep->se_checked = 1;
853
854 switch (sep->se_family) {
855 case AF_LOCAL:
856 if (sep->se_fd != -1)
857 break;
858 n = strlen(sep->se_service);
859 if (n > sizeof(sep->se_ctrladdr_un.sun_path)) {
860 syslog(LOG_ERR, "%s: address too long",
861 sep->se_service);
862 sep->se_checked = 0;
863 continue;
864 }
865 (void)unlink(sep->se_service);
866 strncpy(sep->se_ctrladdr_un.sun_path,
867 sep->se_service, n);
868 sep->se_ctrladdr_un.sun_family = AF_LOCAL;
869 sep->se_ctrladdr_size = n +
870 sizeof(sep->se_ctrladdr_un) -
871 sizeof(sep->se_ctrladdr_un.sun_path);
872 if (!ISMUX(sep))
873 setup(sep);
874 break;
875 case AF_INET:
876 #ifdef INET6
877 case AF_INET6:
878 #endif
879 {
880 struct addrinfo hints, *res;
881 char *host, *port;
882 int error;
883 int s;
884
885 /* check if the family is supported */
886 s = socket(sep->se_family, SOCK_DGRAM, 0);
887 if (s < 0) {
888 syslog(LOG_WARNING,
889 "%s/%s: %s: the address family is not "
890 "supported by the kernel",
891 sep->se_service, sep->se_proto,
892 sep->se_hostaddr);
893 sep->se_checked = 0;
894 continue;
895 }
896 close(s);
897
898 memset(&hints, 0, sizeof(hints));
899 hints.ai_family = sep->se_family;
900 hints.ai_socktype = sep->se_socktype;
901 hints.ai_flags = AI_PASSIVE;
902 if (!strcmp(sep->se_hostaddr, "*"))
903 host = NULL;
904 else
905 host = sep->se_hostaddr;
906 if (isrpcservice(sep) || ISMUX(sep))
907 port = "0";
908 else
909 port = sep->se_service;
910 error = getaddrinfo(host, port, &hints, &res);
911 if (error) {
912 if (error == EAI_SERVICE) {
913 /* gai_strerror not friendly enough */
914 syslog(LOG_WARNING, "%s/%s: "
915 "unknown service",
916 sep->se_service, sep->se_proto);
917 } else {
918 syslog(LOG_ERR, "%s/%s: %s: %s",
919 sep->se_service, sep->se_proto,
920 sep->se_hostaddr,
921 gai_strerror(error));
922 }
923 sep->se_checked = 0;
924 continue;
925 }
926 if (res->ai_next) {
927 syslog(LOG_ERR,
928 "%s/%s: %s: resolved to multiple addr",
929 sep->se_service, sep->se_proto,
930 sep->se_hostaddr);
931 sep->se_checked = 0;
932 freeaddrinfo(res);
933 continue;
934 }
935 memcpy(&sep->se_ctrladdr, res->ai_addr,
936 res->ai_addrlen);
937 if (ISMUX(sep)) {
938 sep->se_fd = -1;
939 freeaddrinfo(res);
940 continue;
941 }
942 sep->se_ctrladdr_size = res->ai_addrlen;
943 freeaddrinfo(res);
944 #ifdef RPC
945 if (isrpcservice(sep)) {
946 struct rpcent *rp;
947
948 sep->se_rpcprog = atoi(sep->se_service);
949 if (sep->se_rpcprog == 0) {
950 rp = getrpcbyname(sep->se_service);
951 if (rp == 0) {
952 syslog(LOG_ERR,
953 "%s/%s: unknown service",
954 sep->se_service,
955 sep->se_proto);
956 sep->se_checked = 0;
957 continue;
958 }
959 sep->se_rpcprog = rp->r_number;
960 }
961 if (sep->se_fd == -1 && !ISMUX(sep))
962 setup(sep);
963 if (sep->se_fd != -1)
964 register_rpc(sep);
965 } else
966 #endif
967 {
968 if (sep->se_fd >= 0)
969 close_sep(sep);
970 if (sep->se_fd == -1 && !ISMUX(sep))
971 setup(sep);
972 }
973 }
974 }
975 }
976 endconfig();
977 /*
978 * Purge anything not looked at above.
979 */
980 sepp = &servtab;
981 while ((sep = *sepp)) {
982 if (sep->se_checked) {
983 sepp = &sep->se_next;
984 continue;
985 }
986 *sepp = sep->se_next;
987 if (sep->se_fd >= 0)
988 close_sep(sep);
989 if (isrpcservice(sep))
990 unregister_rpc(sep);
991 if (sep->se_family == AF_LOCAL)
992 (void)unlink(sep->se_service);
993 if (debug)
994 print_service("FREE", sep);
995 freeconfig(sep);
996 free(sep);
997 }
998 }
999
1000 static void
1001 retry(void)
1002 {
1003 struct servtab *sep;
1004
1005 timingout = 0;
1006 for (sep = servtab; sep != NULL; sep = sep->se_next) {
1007 if (sep->se_fd == -1 && !ISMUX(sep)) {
1008 switch (sep->se_family) {
1009 case AF_LOCAL:
1010 case AF_INET:
1011 #ifdef INET6
1012 case AF_INET6:
1013 #endif
1014 setup(sep);
1015 if (sep->se_fd != -1 && isrpcservice(sep))
1016 register_rpc(sep);
1017 break;
1018 }
1019 }
1020 }
1021 }
1022
1023 static void
1024 goaway(void)
1025 {
1026 struct servtab *sep;
1027
1028 for (sep = servtab; sep != NULL; sep = sep->se_next) {
1029 if (sep->se_fd == -1)
1030 continue;
1031
1032 switch (sep->se_family) {
1033 case AF_LOCAL:
1034 (void)unlink(sep->se_service);
1035 break;
1036 case AF_INET:
1037 #ifdef INET6
1038 case AF_INET6:
1039 #endif
1040 if (sep->se_wait == 1 && isrpcservice(sep))
1041 unregister_rpc(sep);
1042 break;
1043 }
1044 (void)close(sep->se_fd);
1045 }
1046 exit(0);
1047 }
1048
1049 static void
1050 setup(struct servtab *sep)
1051 {
1052 int on = 1;
1053 #ifdef INET6
1054 int off = 0;
1055 #endif
1056 struct kevent *ev;
1057
1058 if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
1059 if (debug)
1060 fprintf(stderr, "socket failed on %s/%s: %s\n",
1061 sep->se_service, sep->se_proto, strerror(errno));
1062 syslog(LOG_ERR, "%s/%s: socket: %m",
1063 sep->se_service, sep->se_proto);
1064 return;
1065 }
1066 /* Set all listening sockets to close-on-exec. */
1067 if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0) {
1068 syslog(LOG_ERR, "%s/%s: fcntl(F_SETFD, FD_CLOEXEC): %m",
1069 sep->se_service, sep->se_proto);
1070 close(sep->se_fd);
1071 return;
1072 }
1073
1074 #define turnon(fd, opt) \
1075 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1076 if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1077 turnon(sep->se_fd, SO_DEBUG) < 0)
1078 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1079 if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1080 syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1081 #undef turnon
1082
1083 /* Set the socket buffer sizes, if specified. */
1084 if (sep->se_sndbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
1085 SO_SNDBUF, (char *)&sep->se_sndbuf, sizeof(sep->se_sndbuf)) < 0)
1086 syslog(LOG_ERR, "setsockopt (SO_SNDBUF %d): %m",
1087 sep->se_sndbuf);
1088 if (sep->se_rcvbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
1089 SO_RCVBUF, (char *)&sep->se_rcvbuf, sizeof(sep->se_rcvbuf)) < 0)
1090 syslog(LOG_ERR, "setsockopt (SO_RCVBUF %d): %m",
1091 sep->se_rcvbuf);
1092 #ifdef INET6
1093 if (sep->se_family == AF_INET6) {
1094 int *v;
1095 v = (sep->se_type == FAITH_TYPE) ? &on : &off;
1096 if (setsockopt(sep->se_fd, IPPROTO_IPV6, IPV6_FAITH,
1097 (char *)v, sizeof(*v)) < 0)
1098 syslog(LOG_ERR, "setsockopt (IPV6_FAITH): %m");
1099 }
1100 #endif
1101 #ifdef IPSEC
1102 if (ipsecsetup(sep->se_family, sep->se_fd, sep->se_policy) < 0 &&
1103 sep->se_policy) {
1104 syslog(LOG_ERR, "%s/%s: ipsec setup failed",
1105 sep->se_service, sep->se_proto);
1106 (void)close(sep->se_fd);
1107 sep->se_fd = -1;
1108 return;
1109 }
1110 #endif
1111
1112 if (bind(sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size) < 0) {
1113 if (debug)
1114 fprintf(stderr, "bind failed on %s/%s: %s\n",
1115 sep->se_service, sep->se_proto, strerror(errno));
1116 syslog(LOG_ERR, "%s/%s: bind: %m",
1117 sep->se_service, sep->se_proto);
1118 (void) close(sep->se_fd);
1119 sep->se_fd = -1;
1120 if (!timingout) {
1121 timingout = 1;
1122 alarm(RETRYTIME);
1123 }
1124 return;
1125 }
1126 if (sep->se_socktype == SOCK_STREAM)
1127 listen(sep->se_fd, 10);
1128
1129 ev = allocchange();
1130 EV_SET(ev, sep->se_fd, EVFILT_READ, EV_ADD | EV_ENABLE, 0, 0,
1131 (intptr_t)sep);
1132 if (sep->se_fd > maxsock) {
1133 maxsock = sep->se_fd;
1134 if (maxsock > rlim_ofile_cur - FD_MARGIN)
1135 bump_nofile();
1136 }
1137 if (debug)
1138 fprintf(stderr, "registered %s on %d\n",
1139 sep->se_server, sep->se_fd);
1140 }
1141
1142 /*
1143 * Finish with a service and its socket.
1144 */
1145 static void
1146 close_sep(struct servtab *sep)
1147 {
1148 if (sep->se_fd >= 0) {
1149 (void) close(sep->se_fd);
1150 sep->se_fd = -1;
1151 }
1152 sep->se_count = 0;
1153 }
1154
1155 static void
1156 register_rpc(struct servtab *sep)
1157 {
1158 #ifdef RPC
1159 int n;
1160 struct netbuf nbuf;
1161 struct sockaddr_storage ss;
1162 struct netconfig *nconf;
1163
1164 if ((nconf = getnetconfigent(sep->se_proto+4)) == NULL) {
1165 syslog(LOG_ERR, "%s: getnetconfigent failed",
1166 sep->se_proto);
1167 return;
1168 }
1169 n = sizeof ss;
1170 if (getsockname(sep->se_fd, (struct sockaddr *)&ss, &n) < 0) {
1171 syslog(LOG_ERR, "%s/%s: getsockname: %m",
1172 sep->se_service, sep->se_proto);
1173 return;
1174 }
1175
1176 nbuf.buf = &ss;
1177 nbuf.len = ss.ss_len;
1178 nbuf.maxlen = sizeof (struct sockaddr_storage);
1179 for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
1180 if (debug)
1181 fprintf(stderr, "rpcb_set: %u %d %s %s\n",
1182 sep->se_rpcprog, n, nconf->nc_netid,
1183 taddr2uaddr(nconf, &nbuf));
1184 (void)rpcb_unset(sep->se_rpcprog, n, nconf);
1185 if (!rpcb_set(sep->se_rpcprog, n, nconf, &nbuf))
1186 syslog(LOG_ERR, "rpcb_set: %u %d %s %s%s",
1187 sep->se_rpcprog, n, nconf->nc_netid,
1188 taddr2uaddr(nconf, &nbuf), clnt_spcreateerror(""));
1189 }
1190 #endif /* RPC */
1191 }
1192
1193 static void
1194 unregister_rpc(struct servtab *sep)
1195 {
1196 #ifdef RPC
1197 int n;
1198 struct netconfig *nconf;
1199
1200 if ((nconf = getnetconfigent(sep->se_proto+4)) == NULL) {
1201 syslog(LOG_ERR, "%s: getnetconfigent failed",
1202 sep->se_proto);
1203 return;
1204 }
1205
1206 for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
1207 if (debug)
1208 fprintf(stderr, "rpcb_unset(%u, %d, %s)\n",
1209 sep->se_rpcprog, n, nconf->nc_netid);
1210 if (!rpcb_unset(sep->se_rpcprog, n, nconf))
1211 syslog(LOG_ERR, "rpcb_unset(%u, %d, %s) failed\n",
1212 sep->se_rpcprog, n, nconf->nc_netid);
1213 }
1214 #endif /* RPC */
1215 }
1216
1217
1218 static struct servtab *
1219 enter(struct servtab *cp)
1220 {
1221 struct servtab *sep;
1222
1223 sep = (struct servtab *)malloc(sizeof (*sep));
1224 if (sep == NULL) {
1225 syslog(LOG_ERR, "Out of memory.");
1226 exit(1);
1227 }
1228 *sep = *cp;
1229 sep->se_fd = -1;
1230 sep->se_rpcprog = -1;
1231 sep->se_next = servtab;
1232 servtab = sep;
1233 return (sep);
1234 }
1235
1236 FILE *fconfig = NULL;
1237 struct servtab serv;
1238 char line[LINE_MAX];
1239 char *defhost;
1240 #ifdef IPSEC
1241 static char *policy = NULL;
1242 #endif
1243
1244 static int
1245 setconfig(void)
1246 {
1247 if (defhost)
1248 free(defhost);
1249 defhost = newstr("*");
1250 #ifdef IPSEC
1251 if (policy)
1252 free(policy);
1253 policy = NULL;
1254 #endif
1255 if (fconfig != NULL) {
1256 fseek(fconfig, 0L, SEEK_SET);
1257 return (1);
1258 }
1259 fconfig = fopen(CONFIG, "r");
1260 return (fconfig != NULL);
1261 }
1262
1263 static void
1264 endconfig(void)
1265 {
1266 if (fconfig != NULL) {
1267 (void) fclose(fconfig);
1268 fconfig = NULL;
1269 }
1270 if (defhost != NULL) {
1271 free(defhost);
1272 defhost = NULL;
1273 }
1274 }
1275
1276 static struct servtab *
1277 getconfigent(void)
1278 {
1279 struct servtab *sep = &serv;
1280 int argc, val;
1281 char *cp, *cp0, *arg, *buf0, *buf1, *sz0, *sz1;
1282 static char TCPMUX_TOKEN[] = "tcpmux/";
1283 #define MUX_LEN (sizeof(TCPMUX_TOKEN)-1)
1284 char *hostdelim;
1285
1286 more:
1287 while ((cp = nextline(fconfig))) {
1288 #ifdef IPSEC
1289 /* lines starting with #@ is not a comment, but the policy */
1290 if (cp[0] == '#' && cp[1] == '@') {
1291 char *p;
1292 for (p = cp + 2; p && *p && isspace(*p); p++)
1293 ;
1294 if (*p == '\0') {
1295 if (policy)
1296 free(policy);
1297 policy = NULL;
1298 } else {
1299 if (ipsecsetup_test(p) < 0) {
1300 syslog(LOG_ERR,
1301 "%s: invalid ipsec policy \"%s\"",
1302 CONFIG, p);
1303 exit(1);
1304 } else {
1305 if (policy)
1306 free(policy);
1307 policy = newstr(p);
1308 }
1309 }
1310 }
1311 #endif
1312 if (*cp == '#' || *cp == '\0')
1313 continue;
1314 #ifdef MULOG
1315 /* Avoid use of `skip' if there is a danger of it looking
1316 * at continuation lines.
1317 */
1318 do {
1319 cp++;
1320 } while (*cp == ' ' || *cp == '\t');
1321 if (*cp == '\0')
1322 continue;
1323 if ((arg = skip(&cp)) == NULL)
1324 continue;
1325 if (strcmp(arg, "DOMAIN"))
1326 continue;
1327 if (curdom)
1328 free(curdom);
1329 curdom = NULL;
1330 while (*cp == ' ' || *cp == '\t')
1331 cp++;
1332 if (*cp == '\0')
1333 continue;
1334 arg = cp;
1335 while (*cp && *cp != ' ' && *cp != '\t')
1336 cp++;
1337 if (*cp != '\0')
1338 *cp++ = '\0';
1339 curdom = newstr(arg);
1340 #endif
1341 break;
1342 }
1343 if (cp == NULL)
1344 return (NULL);
1345 /*
1346 * clear the static buffer, since some fields (se_ctrladdr,
1347 * for example) don't get initialized here.
1348 */
1349 memset((caddr_t)sep, 0, sizeof *sep);
1350 arg = skip(&cp);
1351 if (cp == NULL) {
1352 /* got an empty line containing just blanks/tabs. */
1353 goto more;
1354 }
1355 /* Check for a host name. */
1356 hostdelim = strrchr(arg, ':');
1357 if (hostdelim) {
1358 *hostdelim = '\0';
1359 if (arg[0] == '[' && hostdelim > arg && hostdelim[-1] == ']') {
1360 hostdelim[-1] = '\0';
1361 sep->se_hostaddr = newstr(arg + 1);
1362 } else
1363 sep->se_hostaddr = newstr(arg);
1364 arg = hostdelim + 1;
1365 /*
1366 * If the line is of the form `host:', then just change the
1367 * default host for the following lines.
1368 */
1369 if (*arg == '\0') {
1370 arg = skip(&cp);
1371 if (cp == NULL) {
1372 free(defhost);
1373 defhost = sep->se_hostaddr;
1374 goto more;
1375 }
1376 }
1377 } else
1378 sep->se_hostaddr = newstr(defhost);
1379 if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1380 char *c = arg + MUX_LEN;
1381 if (*c == '+') {
1382 sep->se_type = MUXPLUS_TYPE;
1383 c++;
1384 } else
1385 sep->se_type = MUX_TYPE;
1386 sep->se_service = newstr(c);
1387 } else {
1388 sep->se_service = newstr(arg);
1389 sep->se_type = NORM_TYPE;
1390 }
1391
1392 arg = sskip(&cp);
1393 if (strcmp(arg, "stream") == 0)
1394 sep->se_socktype = SOCK_STREAM;
1395 else if (strcmp(arg, "dgram") == 0)
1396 sep->se_socktype = SOCK_DGRAM;
1397 else if (strcmp(arg, "rdm") == 0)
1398 sep->se_socktype = SOCK_RDM;
1399 else if (strcmp(arg, "seqpacket") == 0)
1400 sep->se_socktype = SOCK_SEQPACKET;
1401 else if (strcmp(arg, "raw") == 0)
1402 sep->se_socktype = SOCK_RAW;
1403 else
1404 sep->se_socktype = -1;
1405
1406 arg = sskip(&cp);
1407 if (sep->se_type == NORM_TYPE &&
1408 strncmp(arg, "faith/", strlen("faith/")) == 0) {
1409 arg += strlen("faith/");
1410 sep->se_type = FAITH_TYPE;
1411 }
1412 sep->se_proto = newstr(arg);
1413
1414 #define MALFORMED(arg) \
1415 do { \
1416 syslog(LOG_ERR, "%s: malformed buffer size option `%s'", \
1417 sep->se_service, (arg)); \
1418 goto more; \
1419 } while (0)
1420
1421 #define GETVAL(arg) \
1422 do { \
1423 if (!isdigit(*(arg))) \
1424 MALFORMED(arg); \
1425 val = strtol((arg), &cp0, 10); \
1426 if (cp0 != NULL) { \
1427 if (cp0[1] != '\0') \
1428 MALFORMED((arg)); \
1429 if (cp0[0] == 'k') \
1430 val *= 1024; \
1431 if (cp0[0] == 'm') \
1432 val *= 1024 * 1024; \
1433 } \
1434 if (val < 1) { \
1435 syslog(LOG_ERR, "%s: invalid buffer size `%s'", \
1436 sep->se_service, (arg)); \
1437 goto more; \
1438 } \
1439 } while (0)
1440
1441 #define ASSIGN(arg) \
1442 do { \
1443 if (strcmp((arg), "sndbuf") == 0) \
1444 sep->se_sndbuf = val; \
1445 else if (strcmp((arg), "rcvbuf") == 0) \
1446 sep->se_rcvbuf = val; \
1447 else \
1448 MALFORMED((arg)); \
1449 } while (0)
1450
1451 /*
1452 * Extract the send and receive buffer sizes before parsing
1453 * the protocol.
1454 */
1455 sep->se_sndbuf = sep->se_rcvbuf = 0;
1456 buf0 = buf1 = sz0 = sz1 = NULL;
1457 if ((buf0 = strchr(sep->se_proto, ',')) != NULL) {
1458 /* Not meaningful for Tcpmux services. */
1459 if (ISMUX(sep)) {
1460 syslog(LOG_ERR, "%s: can't specify buffer sizes for "
1461 "tcpmux services", sep->se_service);
1462 goto more;
1463 }
1464
1465 /* Skip the , */
1466 *buf0++ = '\0';
1467
1468 /* Check to see if another socket buffer size was specified. */
1469 if ((buf1 = strchr(buf0, ',')) != NULL) {
1470 /* Skip the , */
1471 *buf1++ = '\0';
1472
1473 /* Make sure a 3rd one wasn't specified. */
1474 if (strchr(buf1, ',') != NULL) {
1475 syslog(LOG_ERR, "%s: too many buffer sizes",
1476 sep->se_service);
1477 goto more;
1478 }
1479
1480 /* Locate the size. */
1481 if ((sz1 = strchr(buf1, '=')) == NULL)
1482 MALFORMED(buf1);
1483
1484 /* Skip the = */
1485 *sz1++ = '\0';
1486 }
1487
1488 /* Locate the size. */
1489 if ((sz0 = strchr(buf0, '=')) == NULL)
1490 MALFORMED(buf0);
1491
1492 /* Skip the = */
1493 *sz0++ = '\0';
1494
1495 GETVAL(sz0);
1496 ASSIGN(buf0);
1497
1498 if (buf1 != NULL) {
1499 GETVAL(sz1);
1500 ASSIGN(buf1);
1501 }
1502 }
1503
1504 #undef ASSIGN
1505 #undef GETVAL
1506 #undef MALFORMED
1507
1508 if (strcmp(sep->se_proto, "unix") == 0) {
1509 sep->se_family = AF_LOCAL;
1510 } else {
1511 val = strlen(sep->se_proto);
1512 if (!val) {
1513 syslog(LOG_ERR, "%s: invalid protocol specified",
1514 sep->se_service);
1515 goto more;
1516 }
1517 val = sep->se_proto[val - 1];
1518 switch (val) {
1519 case '4': /*tcp4 or udp4*/
1520 sep->se_family = AF_INET;
1521 break;
1522 #ifdef INET6
1523 case '6': /*tcp6 or udp6*/
1524 sep->se_family = AF_INET6;
1525 break;
1526 #endif
1527 default:
1528 sep->se_family = AF_INET; /*will become AF_INET6*/
1529 break;
1530 }
1531 if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1532 #ifdef RPC
1533 char *cp, *ccp;
1534 cp = strchr(sep->se_service, '/');
1535 if (cp == 0) {
1536 syslog(LOG_ERR, "%s: no rpc version",
1537 sep->se_service);
1538 goto more;
1539 }
1540 *cp++ = '\0';
1541 sep->se_rpcversl = sep->se_rpcversh =
1542 strtol(cp, &ccp, 0);
1543 if (ccp == cp) {
1544 badafterall:
1545 syslog(LOG_ERR, "%s/%s: bad rpc version",
1546 sep->se_service, cp);
1547 goto more;
1548 }
1549 if (*ccp == '-') {
1550 cp = ccp + 1;
1551 sep->se_rpcversh = strtol(cp, &ccp, 0);
1552 if (ccp == cp)
1553 goto badafterall;
1554 }
1555 #else
1556 syslog(LOG_ERR, "%s: rpc services not suported",
1557 sep->se_service);
1558 goto more;
1559 #endif /* RPC */
1560 }
1561 }
1562 arg = sskip(&cp);
1563 {
1564 char *cp;
1565 if ((cp = strchr(arg, ':')) == NULL)
1566 cp = strchr(arg, '.');
1567 if (cp != NULL) {
1568 *cp++ = '\0';
1569 sep->se_max = atoi(cp);
1570 } else
1571 sep->se_max = TOOMANY;
1572 }
1573 sep->se_wait = strcmp(arg, "wait") == 0;
1574 if (ISMUX(sep)) {
1575 /*
1576 * Silently enforce "nowait" for TCPMUX services since
1577 * they don't have an assigned port to listen on.
1578 */
1579 sep->se_wait = 0;
1580
1581 if (strncmp(sep->se_proto, "tcp", 3)) {
1582 syslog(LOG_ERR,
1583 "%s: bad protocol for tcpmux service %s",
1584 CONFIG, sep->se_service);
1585 goto more;
1586 }
1587 if (sep->se_socktype != SOCK_STREAM) {
1588 syslog(LOG_ERR,
1589 "%s: bad socket type for tcpmux service %s",
1590 CONFIG, sep->se_service);
1591 goto more;
1592 }
1593 }
1594 sep->se_user = newstr(sskip(&cp));
1595 if ((sep->se_group = strchr(sep->se_user, ':')) != NULL)
1596 *sep->se_group++ = '\0';
1597 else if ((sep->se_group = strchr(sep->se_user, '.')) != NULL)
1598 *sep->se_group++ = '\0';
1599
1600 sep->se_server = newstr(sskip(&cp));
1601 if (strcmp(sep->se_server, "internal") == 0) {
1602 struct biltin *bi;
1603
1604 for (bi = biltins; bi->bi_service; bi++)
1605 if (bi->bi_socktype == sep->se_socktype &&
1606 strcmp(bi->bi_service, sep->se_service) == 0)
1607 break;
1608 if (bi->bi_service == 0) {
1609 syslog(LOG_ERR, "internal service %s unknown",
1610 sep->se_service);
1611 goto more;
1612 }
1613 sep->se_bi = bi;
1614 sep->se_wait = bi->bi_wait;
1615 } else
1616 sep->se_bi = NULL;
1617 argc = 0;
1618 for (arg = skip(&cp); cp; arg = skip(&cp)) {
1619 #if MULOG
1620 char *colon;
1621
1622 if (argc == 0 && (colon = strrchr(arg, ':'))) {
1623 while (arg < colon) {
1624 int x;
1625 char *ccp;
1626
1627 switch (*arg++) {
1628 case 'l':
1629 x = 1;
1630 if (isdigit(*arg)) {
1631 x = strtol(arg, &ccp, 0);
1632 if (ccp == arg)
1633 break;
1634 arg = ccp;
1635 }
1636 sep->se_log &= ~MULOG_RFC931;
1637 sep->se_log |= x;
1638 break;
1639 case 'a':
1640 sep->se_log |= MULOG_RFC931;
1641 break;
1642 default:
1643 break;
1644 }
1645 }
1646 arg = colon + 1;
1647 }
1648 #endif
1649 if (argc < MAXARGV)
1650 sep->se_argv[argc++] = newstr(arg);
1651 }
1652 while (argc <= MAXARGV)
1653 sep->se_argv[argc++] = NULL;
1654 #ifdef IPSEC
1655 sep->se_policy = policy ? newstr(policy) : NULL;
1656 #endif
1657 return (sep);
1658 }
1659
1660 static void
1661 freeconfig(struct servtab *cp)
1662 {
1663 int i;
1664
1665 if (cp->se_hostaddr)
1666 free(cp->se_hostaddr);
1667 if (cp->se_service)
1668 free(cp->se_service);
1669 if (cp->se_proto)
1670 free(cp->se_proto);
1671 if (cp->se_user)
1672 free(cp->se_user);
1673 /* Note: se_group is part of the newstr'ed se_user */
1674 if (cp->se_server)
1675 free(cp->se_server);
1676 for (i = 0; i < MAXARGV; i++)
1677 if (cp->se_argv[i])
1678 free(cp->se_argv[i]);
1679 #ifdef IPSEC
1680 if (cp->se_policy)
1681 free(cp->se_policy);
1682 #endif
1683 }
1684
1685
1686 /*
1687 * Safe skip - if skip returns null, log a syntax error in the
1688 * configuration file and exit.
1689 */
1690 static char *
1691 sskip(char **cpp)
1692 {
1693 char *cp;
1694
1695 cp = skip(cpp);
1696 if (cp == NULL) {
1697 syslog(LOG_ERR, "%s: syntax error", CONFIG);
1698 exit(1);
1699 }
1700 return (cp);
1701 }
1702
1703 static char *
1704 skip(char **cpp)
1705 {
1706 char *cp = *cpp;
1707 char *start;
1708 char quote;
1709
1710 if (*cpp == NULL)
1711 return (NULL);
1712
1713 again:
1714 while (*cp == ' ' || *cp == '\t')
1715 cp++;
1716 if (*cp == '\0') {
1717 int c;
1718
1719 c = getc(fconfig);
1720 (void) ungetc(c, fconfig);
1721 if (c == ' ' || c == '\t')
1722 if ((cp = nextline(fconfig)))
1723 goto again;
1724 *cpp = NULL;
1725 return (NULL);
1726 }
1727 start = cp;
1728 quote = '\0';
1729 while (*cp && (quote || (*cp != ' ' && *cp != '\t'))) {
1730 if (*cp == '\'' || *cp == '"') {
1731 if (quote && *cp != quote)
1732 cp++;
1733 else {
1734 if (quote)
1735 quote = '\0';
1736 else
1737 quote = *cp;
1738 memmove(cp, cp+1, strlen(cp));
1739 }
1740 } else
1741 cp++;
1742 }
1743 if (*cp != '\0')
1744 *cp++ = '\0';
1745 *cpp = cp;
1746 return (start);
1747 }
1748
1749 static char *
1750 nextline(FILE *fd)
1751 {
1752 char *cp;
1753
1754 if (fgets(line, sizeof (line), fd) == NULL)
1755 return (NULL);
1756 cp = strchr(line, '\n');
1757 if (cp)
1758 *cp = '\0';
1759 return (line);
1760 }
1761
1762 static char *
1763 newstr(char *cp)
1764 {
1765 if ((cp = strdup((cp !=NULL )? cp : "")) != NULL)
1766 return (cp);
1767 syslog(LOG_ERR, "strdup: %m");
1768 exit(1);
1769 }
1770
1771 static void
1772 inetd_setproctitle(char *a, int s)
1773 {
1774 socklen_t size;
1775 struct sockaddr_storage ss;
1776 char hbuf[NI_MAXHOST];
1777
1778 size = sizeof(ss);
1779 if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
1780 if (getnameinfo((struct sockaddr *)&ss, size, hbuf,
1781 sizeof(hbuf), NULL, 0, niflags) == 0)
1782 setproctitle("-%s [%s]", a, hbuf);
1783 else
1784 setproctitle("-%s [?]", a);
1785 } else
1786 setproctitle("-%s", a);
1787 }
1788
1789 static void
1790 bump_nofile(void)
1791 {
1792 #ifdef RLIMIT_NOFILE
1793
1794 #define FD_CHUNK 32
1795
1796 struct rlimit rl;
1797
1798 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1799 syslog(LOG_ERR, "getrlimit: %m");
1800 return;
1801 }
1802 rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
1803 if (rl.rlim_cur <= rlim_ofile_cur) {
1804 syslog(LOG_ERR,
1805 "bump_nofile: cannot extend file limit, max = %d",
1806 (int)rl.rlim_cur);
1807 return;
1808 }
1809
1810 if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
1811 syslog(LOG_ERR, "setrlimit: %m");
1812 return;
1813 }
1814
1815 rlim_ofile_cur = rl.rlim_cur;
1816 return;
1817
1818 #else
1819 syslog(LOG_ERR, "bump_nofile: cannot extend file limit");
1820 return;
1821 #endif
1822 }
1823
1824 /*
1825 * Internet services provided internally by inetd:
1826 */
1827 #define BUFSIZE 4096
1828
1829 /* ARGSUSED */
1830 static void
1831 echo_stream(int s, struct servtab *sep) /* Echo service -- echo data back */
1832 {
1833 char buffer[BUFSIZE];
1834 int i;
1835
1836 inetd_setproctitle(sep->se_service, s);
1837 while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
1838 write(s, buffer, i) > 0)
1839 ;
1840 }
1841
1842 /* ARGSUSED */
1843 static void
1844 echo_dg(int s, struct servtab *sep) /* Echo service -- echo data back */
1845 {
1846 char buffer[BUFSIZE];
1847 int i;
1848 socklen_t size;
1849 struct sockaddr_storage ss;
1850 struct sockaddr *sa;
1851
1852 sa = (struct sockaddr *)&ss;
1853 size = sizeof(ss);
1854 if ((i = recvfrom(s, buffer, sizeof(buffer), 0, sa, &size)) < 0)
1855 return;
1856 if (port_good_dg(sa))
1857 (void) sendto(s, buffer, i, 0, sa, size);
1858 }
1859
1860 /* ARGSUSED */
1861 static void
1862 discard_stream(int s, struct servtab *sep) /* Discard service -- ignore data */
1863 {
1864 char buffer[BUFSIZE];
1865
1866 inetd_setproctitle(sep->se_service, s);
1867 while ((errno = 0, read(s, buffer, sizeof(buffer)) > 0) ||
1868 errno == EINTR)
1869 ;
1870 }
1871
1872 /* ARGSUSED */
1873 static void
1874 discard_dg(int s, struct servtab *sep) /* Discard service -- ignore data */
1875
1876 {
1877 char buffer[BUFSIZE];
1878
1879 (void) read(s, buffer, sizeof(buffer));
1880 }
1881
1882 #include <ctype.h>
1883 #define LINESIZ 72
1884 char ring[128];
1885 char *endring;
1886
1887 static void
1888 initring(void)
1889 {
1890 int i;
1891
1892 endring = ring;
1893
1894 for (i = 0; i <= 128; ++i)
1895 if (isprint(i))
1896 *endring++ = i;
1897 }
1898
1899 /* ARGSUSED */
1900 static void
1901 chargen_stream(int s,struct servtab *sep) /* Character generator */
1902 {
1903 int len;
1904 char *rs, text[LINESIZ+2];
1905
1906 inetd_setproctitle(sep->se_service, s);
1907
1908 if (!endring) {
1909 initring();
1910 rs = ring;
1911 }
1912
1913 text[LINESIZ] = '\r';
1914 text[LINESIZ + 1] = '\n';
1915 for (rs = ring;;) {
1916 if ((len = endring - rs) >= LINESIZ)
1917 memmove(text, rs, LINESIZ);
1918 else {
1919 memmove(text, rs, len);
1920 memmove(text + len, ring, LINESIZ - len);
1921 }
1922 if (++rs == endring)
1923 rs = ring;
1924 if (write(s, text, sizeof(text)) != sizeof(text))
1925 break;
1926 }
1927 }
1928
1929 /* ARGSUSED */
1930 static void
1931 chargen_dg(int s, struct servtab *sep) /* Character generator */
1932 {
1933 struct sockaddr_storage ss;
1934 struct sockaddr *sa;
1935 static char *rs;
1936 int len;
1937 socklen_t size;
1938 char text[LINESIZ+2];
1939
1940 if (endring == 0) {
1941 initring();
1942 rs = ring;
1943 }
1944
1945 sa = (struct sockaddr *)&ss;
1946 size = sizeof(ss);
1947 if (recvfrom(s, text, sizeof(text), 0, sa, &size) < 0)
1948 return;
1949
1950 if (!port_good_dg(sa))
1951 return;
1952
1953 if ((len = endring - rs) >= LINESIZ)
1954 memmove(text, rs, LINESIZ);
1955 else {
1956 memmove(text, rs, len);
1957 memmove(text + len, ring, LINESIZ - len);
1958 }
1959 if (++rs == endring)
1960 rs = ring;
1961 text[LINESIZ] = '\r';
1962 text[LINESIZ + 1] = '\n';
1963 (void) sendto(s, text, sizeof(text), 0, sa, size);
1964 }
1965
1966 /*
1967 * Return a machine readable date and time, in the form of the
1968 * number of seconds since midnight, Jan 1, 1900. Since gettimeofday
1969 * returns the number of seconds since midnight, Jan 1, 1970,
1970 * we must add 2208988800 seconds to this figure to make up for
1971 * some seventy years Bell Labs was asleep.
1972 */
1973
1974 static uint32_t
1975 machtime(void)
1976 {
1977 struct timeval tv;
1978
1979 if (gettimeofday(&tv, NULL) < 0) {
1980 if (debug)
1981 fprintf(stderr, "Unable to get time of day\n");
1982 return (0);
1983 }
1984 #define OFFSET ((uint32_t)25567 * 24*60*60)
1985 return (htonl((uint32_t)(tv.tv_sec + OFFSET)));
1986 #undef OFFSET
1987 }
1988
1989 /* ARGSUSED */
1990 static void
1991 machtime_stream(int s, struct servtab *sep)
1992 {
1993 uint32_t result;
1994
1995 result = machtime();
1996 (void) write(s, (char *) &result, sizeof(result));
1997 }
1998
1999 /* ARGSUSED */
2000 void
2001 machtime_dg(int s, struct servtab *sep)
2002 {
2003 uint32_t result;
2004 struct sockaddr_storage ss;
2005 struct sockaddr *sa;
2006 socklen_t size;
2007
2008 sa = (struct sockaddr *)&ss;
2009 size = sizeof(ss);
2010 if (recvfrom(s, (char *)&result, sizeof(result), 0, sa, &size) < 0)
2011 return;
2012 if (!port_good_dg(sa))
2013 return;
2014 result = machtime();
2015 (void) sendto(s, (char *) &result, sizeof(result), 0, sa, size);
2016 }
2017
2018 /* ARGSUSED */
2019 static void
2020 daytime_stream(int s,struct servtab *sep)
2021 /* Return human-readable time of day */
2022 {
2023 char buffer[256];
2024 time_t clock;
2025 int len;
2026
2027 clock = time((time_t *) 0);
2028
2029 len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2030 (void) write(s, buffer, len);
2031 }
2032
2033 /* ARGSUSED */
2034 void
2035 daytime_dg(int s, struct servtab *sep)
2036 /* Return human-readable time of day */
2037 {
2038 char buffer[256];
2039 time_t clock;
2040 struct sockaddr_storage ss;
2041 struct sockaddr *sa;
2042 socklen_t size;
2043 int len;
2044
2045 clock = time((time_t *) 0);
2046
2047 sa = (struct sockaddr *)&ss;
2048 size = sizeof(ss);
2049 if (recvfrom(s, buffer, sizeof(buffer), 0, sa, &size) < 0)
2050 return;
2051 if (!port_good_dg(sa))
2052 return;
2053 len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2054 (void) sendto(s, buffer, len, 0, sa, size);
2055 }
2056
2057 /*
2058 * print_service:
2059 * Dump relevant information to stderr
2060 */
2061 static void
2062 print_service(char *action, struct servtab *sep)
2063 {
2064
2065 if (isrpcservice(sep))
2066 fprintf(stderr,
2067 "%s: %s rpcprog=%d, rpcvers = %d/%d, proto=%s, wait.max=%d.%d, user:group=%s:%s builtin=%lx server=%s"
2068 #ifdef IPSEC
2069 " policy=\"%s\""
2070 #endif
2071 "\n",
2072 action, sep->se_service,
2073 sep->se_rpcprog, sep->se_rpcversh, sep->se_rpcversl, sep->se_proto,
2074 sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2075 (long)sep->se_bi, sep->se_server
2076 #ifdef IPSEC
2077 , (sep->se_policy ? sep->se_policy : "")
2078 #endif
2079 );
2080 else
2081 fprintf(stderr,
2082 "%s: %s proto=%s%s, wait.max=%d.%d, user:group=%s:%s builtin=%lx server=%s"
2083 #ifdef IPSEC
2084 " policy=%s"
2085 #endif
2086 "\n",
2087 action, sep->se_service,
2088 sep->se_type == FAITH_TYPE ? "faith/" : "",
2089 sep->se_proto,
2090 sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2091 (long)sep->se_bi, sep->se_server
2092 #ifdef IPSEC
2093 , (sep->se_policy ? sep->se_policy : "")
2094 #endif
2095 );
2096 }
2097
2098 static void
2099 usage(void)
2100 {
2101 #ifdef LIBWRAP
2102 (void)fprintf(stderr, "usage: %s [-dl] [conf]\n", getprogname());
2103 #else
2104 (void)fprintf(stderr, "usage: %s [-d] [conf]\n", getprogname());
2105 #endif
2106 exit(1);
2107 }
2108
2109
2110 /*
2111 * Based on TCPMUX.C by Mark K. Lottor November 1988
2112 * sri-nic::ps:<mkl>tcpmux.c
2113 */
2114
2115 static int /* # of characters upto \r,\n or \0 */
2116 getline(int fd, char *buf, int len)
2117 {
2118 int count = 0, n;
2119
2120 do {
2121 n = read(fd, buf, len-count);
2122 if (n == 0)
2123 return (count);
2124 if (n < 0)
2125 return (-1);
2126 while (--n >= 0) {
2127 if (*buf == '\r' || *buf == '\n' || *buf == '\0')
2128 return (count);
2129 count++;
2130 buf++;
2131 }
2132 } while (count < len);
2133 return (count);
2134 }
2135
2136 #define MAX_SERV_LEN (256+2) /* 2 bytes for \r\n */
2137
2138 #define strwrite(fd, buf) (void) write(fd, buf, sizeof(buf)-1)
2139
2140 static void
2141 tcpmux(int ctrl, struct servtab *sep)
2142 {
2143 char service[MAX_SERV_LEN+1];
2144 int len;
2145
2146 /* Get requested service name */
2147 if ((len = getline(ctrl, service, MAX_SERV_LEN)) < 0) {
2148 strwrite(ctrl, "-Error reading service name\r\n");
2149 goto reject;
2150 }
2151 service[len] = '\0';
2152
2153 if (debug)
2154 fprintf(stderr, "tcpmux: someone wants %s\n", service);
2155
2156 /*
2157 * Help is a required command, and lists available services,
2158 * one per line.
2159 */
2160 if (!strcasecmp(service, "help")) {
2161 strwrite(ctrl, "+Available services:\r\n");
2162 strwrite(ctrl, "help\r\n");
2163 for (sep = servtab; sep != NULL; sep = sep->se_next) {
2164 if (!ISMUX(sep))
2165 continue;
2166 (void)write(ctrl, sep->se_service,
2167 strlen(sep->se_service));
2168 strwrite(ctrl, "\r\n");
2169 }
2170 goto reject;
2171 }
2172
2173 /* Try matching a service in inetd.conf with the request */
2174 for (sep = servtab; sep != NULL; sep = sep->se_next) {
2175 if (!ISMUX(sep))
2176 continue;
2177 if (!strcasecmp(service, sep->se_service)) {
2178 if (ISMUXPLUS(sep))
2179 strwrite(ctrl, "+Go\r\n");
2180 run_service(ctrl, sep);
2181 return;
2182 }
2183 }
2184 strwrite(ctrl, "-Service not available\r\n");
2185 reject:
2186 _exit(1);
2187 }
2188
2189 #ifdef MULOG
2190 void
2191 dolog(struct servtab *sep, int ctrl)
2192 {
2193 struct sockaddr_storage ss;
2194 struct sockaddr *sa = (struct sockaddr *)&ss;
2195 socklen_t len = sizeof(ss);
2196 char *host, *dp, buf[BUFSIZ];
2197 int connected = 1;
2198
2199 switch (sep->se_family) {
2200 case AF_INET:
2201 #ifdef INET6
2202 case AF_INET6:
2203 #endif
2204 break;
2205 default:
2206 return;
2207 }
2208
2209 if (getpeername(ctrl, sa, &len) < 0) {
2210 if (errno != ENOTCONN) {
2211 syslog(LOG_ERR, "getpeername: %m");
2212 return;
2213 }
2214 if (recvfrom(ctrl, buf, sizeof(buf), MSG_PEEK, sa, &len) < 0) {
2215 syslog(LOG_ERR, "recvfrom: %m");
2216 return;
2217 }
2218 connected = 0;
2219 }
2220 switch (sa->sa_family) {
2221 case AF_INET:
2222 #ifdef INET6
2223 case AF_INET6:
2224 #endif
2225 break;
2226 default:
2227 syslog(LOG_ERR, "unexpected address family %u", sa->sa_family);
2228 return;
2229 }
2230
2231 if (getnameinfo(sa, len, buf, sizeof(buf), NULL, 0, 0) != 0)
2232 strlcpy(buf, "?", sizeof(buf));
2233 host = buf;
2234
2235 switch (sep->se_log & ~MULOG_RFC931) {
2236 case 0:
2237 return;
2238 case 1:
2239 if (curdom == NULL || *curdom == '\0')
2240 break;
2241 dp = host + strlen(host) - strlen(curdom);
2242 if (dp < host)
2243 break;
2244 if (debug)
2245 fprintf(stderr, "check \"%s\" against curdom \"%s\"\n",
2246 host, curdom);
2247 if (strcasecmp(dp, curdom) == 0)
2248 return;
2249 break;
2250 case 2:
2251 default:
2252 break;
2253 }
2254
2255 openlog("", LOG_NOWAIT, MULOG);
2256
2257 if (connected && (sep->se_log & MULOG_RFC931))
2258 syslog(LOG_INFO, "%s@%s wants %s",
2259 rfc931_name(sa, ctrl), host, sep->se_service);
2260 else
2261 syslog(LOG_INFO, "%s wants %s",
2262 host, sep->se_service);
2263 }
2264
2265 /*
2266 * From tcp_log by
2267 * Wietse Venema, Eindhoven University of Technology, The Netherlands.
2268 */
2269 #if 0
2270 static char sccsid[] = "@(#) rfc931.c 1.3 92/08/31 22:54:46";
2271 #endif
2272
2273 #include <setjmp.h>
2274
2275 #define RFC931_PORT 113 /* Semi-well-known port */
2276 #define TIMEOUT 4
2277 #define TIMEOUT2 10
2278
2279 static jmp_buf timebuf;
2280
2281 /* timeout - handle timeouts */
2282
2283 static void
2284 timeout(int sig)
2285 {
2286 longjmp(timebuf, sig);
2287 }
2288
2289 /* rfc931_name - return remote user name */
2290
2291 char *
2292 rfc931_name(struct sockaddr *there, /* remote link information */
2293 int ctrl)
2294 {
2295 struct sockaddr_storage here; /* local link information */
2296 struct sockaddr_storage sin; /* for talking to RFC931 daemon */
2297 socklen_t length;
2298 int s;
2299 unsigned remote;
2300 unsigned local;
2301 static char user[256]; /* XXX */
2302 char buf[256];
2303 char *cp;
2304 char *result = "USER_UNKNOWN";
2305 int len;
2306 u_int16_t myport, hisport;
2307
2308 /* Find out local port number of our stdin. */
2309
2310 length = sizeof(here);
2311 if (getsockname(ctrl, (struct sockaddr *) &here, &length) == -1) {
2312 syslog(LOG_ERR, "getsockname: %m");
2313 return (result);
2314 }
2315 switch (here.ss_family) {
2316 case AF_INET:
2317 myport = ((struct sockaddr_in *)&here)->sin_port;
2318 break;
2319 #ifdef INET6
2320 case AF_INET6:
2321 myport = ((struct sockaddr_in6 *)&here)->sin6_port;
2322 break;
2323 #endif
2324 }
2325 switch (there->sa_family) {
2326 case AF_INET:
2327 hisport = ((struct sockaddr_in *)&there)->sin_port;
2328 break;
2329 #ifdef INET6
2330 case AF_INET6:
2331 hisport = ((struct sockaddr_in6 *)&there)->sin6_port;
2332 break;
2333 #endif
2334 }
2335 /* Set up timer so we won't get stuck. */
2336
2337 if ((s = socket(here.ss_family, SOCK_STREAM, 0)) == -1) {
2338 syslog(LOG_ERR, "socket: %m");
2339 return (result);
2340 }
2341
2342 sin = here;
2343 switch (sin.ss_family) {
2344 case AF_INET:
2345 ((struct sockaddr_in *)&sin)->sin_port = htons(0);
2346 break;
2347 #ifdef INET6
2348 case AF_INET6:
2349 ((struct sockaddr_in6 *)&sin)->sin6_port = htons(0);
2350 break;
2351 #endif
2352 }
2353 if (bind(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2354 syslog(LOG_ERR, "bind: %m");
2355 return (result);
2356 }
2357
2358 signal(SIGALRM, timeout);
2359 if (setjmp(timebuf)) {
2360 close(s); /* not: fclose(fp) */
2361 return (result);
2362 }
2363 alarm(TIMEOUT);
2364
2365 /* Connect to the RFC931 daemon. */
2366
2367 memcpy(&sin, there, there->sa_len);
2368 switch (sin.ss_family) {
2369 case AF_INET:
2370 ((struct sockaddr_in *)&sin)->sin_port = htons(RFC931_PORT);
2371 break;
2372 #ifdef INET6
2373 case AF_INET6:
2374 ((struct sockaddr_in6 *)&sin)->sin6_port = htons(RFC931_PORT);
2375 break;
2376 #endif
2377 }
2378 if (connect(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2379 close(s);
2380 alarm(0);
2381 return (result);
2382 }
2383
2384 /* Query the RFC 931 server. Would 13-byte writes ever be broken up? */
2385 (void)snprintf(buf, sizeof buf, "%u,%u\r\n", ntohs(hisport),
2386 ntohs(myport));
2387
2388 for (len = 0, cp = buf; len < strlen(buf); ) {
2389 int n;
2390
2391 if ((n = write(s, cp, strlen(buf) - len)) == -1) {
2392 close(s);
2393 alarm(0);
2394 return (result);
2395 }
2396 cp += n;
2397 len += n;
2398 }
2399
2400 /* Read response */
2401 for (cp = buf; cp < buf + sizeof(buf) - 1; ) {
2402 char c;
2403 if (read(s, &c, 1) != 1) {
2404 close(s);
2405 alarm(0);
2406 return (result);
2407 }
2408 if (c == '\n')
2409 break;
2410 *cp++ = c;
2411 }
2412 *cp = '\0';
2413
2414 if (sscanf(buf, "%u , %u : USERID :%*[^:]:%255s", &remote, &local,
2415 user) == 3 && ntohs(hisport) == remote && ntohs(myport) == local) {
2416 /* Strip trailing carriage return. */
2417 if ((cp = strchr(user, '\r')) != NULL)
2418 *cp = 0;
2419 result = user;
2420 }
2421
2422 alarm(0);
2423 close(s);
2424 return (result);
2425 }
2426 #endif
2427
2428 /*
2429 * check if the address/port where send data to is one of the obvious ports
2430 * that are used for denial of service attacks like two echo ports
2431 * just echoing data between them
2432 */
2433 static int
2434 port_good_dg(struct sockaddr *sa)
2435 {
2436 struct in_addr in;
2437 #ifdef INET6
2438 struct in6_addr *in6;
2439 #endif
2440 u_int16_t port;
2441 int i, bad;
2442 char hbuf[NI_MAXHOST];
2443
2444 bad = 0;
2445
2446 switch (sa->sa_family) {
2447 case AF_INET:
2448 in.s_addr = ntohl(((struct sockaddr_in *)sa)->sin_addr.s_addr);
2449 port = ntohs(((struct sockaddr_in *)sa)->sin_port);
2450 #ifdef INET6
2451 v4chk:
2452 #endif
2453 if (IN_MULTICAST(in.s_addr))
2454 goto bad;
2455 switch ((in.s_addr & 0xff000000) >> 24) {
2456 case 0: case 127: case 255:
2457 goto bad;
2458 }
2459 if (dg_broadcast(&in))
2460 goto bad;
2461 break;
2462 #ifdef INET6
2463 case AF_INET6:
2464 in6 = &((struct sockaddr_in6 *)sa)->sin6_addr;
2465 port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
2466 if (IN6_IS_ADDR_MULTICAST(in6) || IN6_IS_ADDR_UNSPECIFIED(in6))
2467 goto bad;
2468 if (IN6_IS_ADDR_V4MAPPED(in6) || IN6_IS_ADDR_V4COMPAT(in6)) {
2469 memcpy(&in, &in6->s6_addr[12], sizeof(in));
2470 in.s_addr = ntohl(in.s_addr);
2471 goto v4chk;
2472 }
2473 break;
2474 #endif
2475 default:
2476 /* XXX unsupported af, is it safe to assume it to be safe? */
2477 return (1);
2478 }
2479
2480 for (i = 0; bad_ports[i] != 0; i++) {
2481 if (port == bad_ports[i])
2482 goto bad;
2483 }
2484
2485 return (1);
2486
2487 bad:
2488 if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0,
2489 niflags) != 0)
2490 strlcpy(hbuf, "?", sizeof(hbuf));
2491 syslog(LOG_WARNING,"Possible DoS attack from %s, Port %d",
2492 hbuf, port);
2493 return (0);
2494 }
2495
2496 /* XXX need optimization */
2497 static int
2498 dg_broadcast(struct in_addr *in)
2499 {
2500 struct ifaddrs *ifa, *ifap;
2501 struct sockaddr_in *sin;
2502
2503 if (getifaddrs(&ifap) < 0)
2504 return (0);
2505 for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
2506 if (ifa->ifa_addr->sa_family != AF_INET ||
2507 (ifa->ifa_flags & IFF_BROADCAST) == 0)
2508 continue;
2509 sin = (struct sockaddr_in *)ifa->ifa_broadaddr;
2510 if (sin->sin_addr.s_addr == in->s_addr) {
2511 freeifaddrs(ifap);
2512 return (1);
2513 }
2514 }
2515 freeifaddrs(ifap);
2516 return (0);
2517 }
2518
2519 static int
2520 my_kevent(const struct kevent *changelist, size_t nchanges,
2521 struct kevent *eventlist, size_t nevents)
2522 {
2523 int result;
2524
2525 while ((result = kevent(kq, changelist, nchanges, eventlist, nevents,
2526 NULL)) < 0)
2527 if (errno != EINTR) {
2528 syslog(LOG_ERR, "kevent: %m");
2529 exit(EXIT_FAILURE);
2530 }
2531
2532 return (result);
2533 }
2534
2535 static struct kevent *
2536 allocchange(void)
2537 {
2538 if (changes == A_CNT(changebuf)) {
2539 (void) my_kevent(changebuf, A_CNT(changebuf), NULL, 0);
2540 changes = 0;
2541 }
2542
2543 return (&changebuf[changes++]);
2544 }
2545