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