inetd.c revision 1.58 1 /* $NetBSD: inetd.c,v 1.58 2000/01/31 14:28:18 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.58 2000/01/31 14:28:18 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/pmap_clnt.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
235 #include "pathnames.h"
236
237 #ifdef IPSEC
238 #include <netinet6/ipsec.h>
239 #ifndef IPSEC_POLICY_IPSEC /* no ipsec support on old ipsec */
240 #undef IPSEC
241 #endif
242 #include "ipsec.h"
243 #endif
244
245 #ifdef LIBWRAP
246 # include <tcpd.h>
247 #ifndef LIBWRAP_ALLOW_FACILITY
248 # define LIBWRAP_ALLOW_FACILITY LOG_AUTH
249 #endif
250 #ifndef LIBWRAP_ALLOW_SEVERITY
251 # define LIBWRAP_ALLOW_SEVERITY LOG_INFO
252 #endif
253 #ifndef LIBWRAP_DENY_FACILITY
254 # define LIBWRAP_DENY_FACILITY LOG_AUTH
255 #endif
256 #ifndef LIBWRAP_DENY_SEVERITY
257 # define LIBWRAP_DENY_SEVERITY LOG_WARNING
258 #endif
259 int allow_severity = LIBWRAP_ALLOW_FACILITY|LIBWRAP_ALLOW_SEVERITY;
260 int deny_severity = LIBWRAP_DENY_FACILITY|LIBWRAP_DENY_SEVERITY;
261 #endif
262
263 #define TOOMANY 40 /* don't start more than TOOMANY */
264 #define CNT_INTVL 60 /* servers in CNT_INTVL sec. */
265 #define RETRYTIME (60*10) /* retry after bind or server fail */
266
267 #define SIGBLOCK (sigmask(SIGCHLD)|sigmask(SIGHUP)|sigmask(SIGALRM))
268
269 int debug;
270 #ifdef LIBWRAP
271 int lflag;
272 #endif
273 int nsock, maxsock;
274 fd_set allsock;
275 int options;
276 int timingout;
277 struct servent *sp;
278 char *curdom;
279 #ifdef NI_WITHSCOPEID
280 const int niflags = NI_NUMERICHOST | NI_NUMERICSERV | NI_WITHSCOPEID;
281 #else
282 const int niflags = NI_NUMERICHOST | NI_NUMERICSERV;
283 #endif
284
285 #ifndef OPEN_MAX
286 #define OPEN_MAX 64
287 #endif
288
289 /* Reserve some descriptors, 3 stdio + at least: 1 log, 1 conf. file */
290 #define FD_MARGIN (8)
291 typeof(((struct rlimit *)0)->rlim_cur) rlim_ofile_cur = OPEN_MAX;
292
293 #ifdef RLIMIT_NOFILE
294 struct rlimit rlim_ofile;
295 #endif
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 ISMUX(sep) (((sep)->se_type == MUX_TYPE) || \
346 ((sep)->se_type == MUXPLUS_TYPE))
347 #define ISMUXPLUS(sep) ((sep)->se_type == MUXPLUS_TYPE)
348
349
350 void chargen_dg __P((int, struct servtab *));
351 void chargen_stream __P((int, struct servtab *));
352 void close_sep __P((struct servtab *));
353 void config __P((int));
354 void daytime_dg __P((int, struct servtab *));
355 void daytime_stream __P((int, struct servtab *));
356 void discard_dg __P((int, struct servtab *));
357 void discard_stream __P((int, struct servtab *));
358 void echo_dg __P((int, struct servtab *));
359 void echo_stream __P((int, struct servtab *));
360 void endconfig __P((void));
361 struct servtab *enter __P((struct servtab *));
362 void freeconfig __P((struct servtab *));
363 struct servtab *getconfigent __P((void));
364 void goaway __P((int));
365 void machtime_dg __P((int, struct servtab *));
366 void machtime_stream __P((int, struct servtab *));
367 char *newstr __P((char *));
368 char *nextline __P((FILE *));
369 void print_service __P((char *, struct servtab *));
370 void reapchild __P((int));
371 void retry __P((int));
372 void run_service __P((int, struct servtab *));
373 int setconfig __P((void));
374 void setup __P((struct servtab *));
375 char *sskip __P((char **));
376 char *skip __P((char **));
377 void tcpmux __P((int, struct servtab *));
378 void usage __P((void));
379 void register_rpc __P((struct servtab *sep));
380 void unregister_rpc __P((struct servtab *sep));
381 void bump_nofile __P((void));
382 void inetd_setproctitle __P((char *, int));
383 void initring __P((void));
384 long machtime __P((void));
385 int port_good_dg __P((struct sockaddr *sa));
386 static int getline __P((int, char *, int));
387 int main __P((int, char *[], char *[]));
388
389 struct biltin {
390 char *bi_service; /* internally provided service name */
391 int bi_socktype; /* type of socket supported */
392 short bi_fork; /* 1 if should fork before call */
393 short bi_wait; /* 1 if should wait for child */
394 void (*bi_fn) __P((int, struct servtab *));
395 /* function which performs it */
396 } biltins[] = {
397 /* Echo received data */
398 { "echo", SOCK_STREAM, 1, 0, echo_stream },
399 { "echo", SOCK_DGRAM, 0, 0, echo_dg },
400
401 /* Internet /dev/null */
402 { "discard", SOCK_STREAM, 1, 0, discard_stream },
403 { "discard", SOCK_DGRAM, 0, 0, discard_dg },
404
405 /* Return 32 bit time since 1970 */
406 { "time", SOCK_STREAM, 0, 0, machtime_stream },
407 { "time", SOCK_DGRAM, 0, 0, machtime_dg },
408
409 /* Return human-readable time */
410 { "daytime", SOCK_STREAM, 0, 0, daytime_stream },
411 { "daytime", SOCK_DGRAM, 0, 0, daytime_dg },
412
413 /* Familiar character generator */
414 { "chargen", SOCK_STREAM, 1, 0, chargen_stream },
415 { "chargen", SOCK_DGRAM, 0, 0, chargen_dg },
416
417 { "tcpmux", SOCK_STREAM, 1, 0, tcpmux },
418
419 { NULL }
420 };
421
422 /* list of "bad" ports. I.e. ports that are most obviously used for
423 * "cycling packets" denial of service attacks. See /etc/services.
424 * List must end with port number "0".
425 */
426
427 u_int16_t bad_ports[] = { 7, 9, 13, 19, 37, 0};
428
429
430 #define NUMINT (sizeof(intab) / sizeof(struct inent))
431 char *CONFIG = _PATH_INETDCONF;
432 char **Argv;
433 char *LastArg;
434 extern char *__progname;
435
436 #ifdef sun
437 /*
438 * Sun's RPC library caches the result of `dtablesize()'
439 * This is incompatible with our "bumping" of file descriptors "on demand"
440 */
441 int
442 _rpc_dtablesize()
443 {
444 return rlim_ofile_cur;
445 }
446 #endif
447
448 int
449 main(argc, argv, envp)
450 int argc;
451 char *argv[], *envp[];
452 {
453 struct servtab *sep, *nsep;
454 struct sigvec sv;
455 int ch, dofork;
456 pid_t pid;
457
458 Argv = argv;
459 if (envp == 0 || *envp == 0)
460 envp = argv;
461 while (*envp)
462 envp++;
463 LastArg = envp[-1] + strlen(envp[-1]);
464
465 while ((ch = getopt(argc, argv,
466 #ifdef LIBWRAP
467 "dl"
468 #else
469 "d"
470 #endif
471 )) != -1)
472 switch(ch) {
473 case 'd':
474 debug = 1;
475 options |= SO_DEBUG;
476 break;
477 #ifdef LIBWRAP
478 case 'l':
479 lflag = 1;
480 break;
481 #endif
482 case '?':
483 default:
484 usage();
485 }
486 argc -= optind;
487 argv += optind;
488
489 if (argc > 0)
490 CONFIG = argv[0];
491
492 if (debug == 0)
493 daemon(0, 0);
494 openlog(__progname, LOG_PID | LOG_NOWAIT, LOG_DAEMON);
495 pidfile(NULL);
496
497 #ifdef RLIMIT_NOFILE
498 if (getrlimit(RLIMIT_NOFILE, &rlim_ofile) < 0) {
499 syslog(LOG_ERR, "getrlimit: %m");
500 } else {
501 rlim_ofile_cur = rlim_ofile.rlim_cur;
502 if (rlim_ofile_cur == RLIM_INFINITY) /* ! */
503 rlim_ofile_cur = OPEN_MAX;
504 }
505 #endif
506
507 memset(&sv, 0, sizeof(sv));
508 sv.sv_mask = SIGBLOCK;
509 sv.sv_handler = retry;
510 sigvec(SIGALRM, &sv, (struct sigvec *)0);
511 config(SIGHUP);
512 sv.sv_handler = config;
513 sigvec(SIGHUP, &sv, (struct sigvec *)0);
514 sv.sv_handler = reapchild;
515 sigvec(SIGCHLD, &sv, (struct sigvec *)0);
516 sv.sv_handler = goaway;
517 sigvec(SIGTERM, &sv, (struct sigvec *)0);
518 sv.sv_handler = goaway;
519 sigvec(SIGINT, &sv, (struct sigvec *)0);
520 sv.sv_mask = 0L;
521 sv.sv_handler = SIG_IGN;
522 sigvec(SIGPIPE, &sv, (struct sigvec *)0);
523
524 {
525 /* space for daemons to overwrite environment for ps */
526 #define DUMMYSIZE 100
527 char dummy[DUMMYSIZE];
528
529 (void)memset(dummy, 'x', DUMMYSIZE - 1);
530 dummy[DUMMYSIZE - 1] = '\0';
531
532 (void)setenv("inetd_dummy", dummy, 1);
533 }
534
535 for (;;) {
536 int n, ctrl;
537 fd_set readable;
538
539 if (nsock == 0) {
540 (void) sigblock(SIGBLOCK);
541 while (nsock == 0)
542 sigpause(0L);
543 (void) sigsetmask(0L);
544 }
545 readable = allsock;
546 if ((n = select(maxsock + 1, &readable, (fd_set *)0,
547 (fd_set *)0, (struct timeval *)0)) <= 0) {
548 if (n == -1 && errno != EINTR) {
549 syslog(LOG_WARNING, "select: %m");
550 sleep(1);
551 }
552 continue;
553 }
554 for (sep = servtab; n && sep; sep = nsep) {
555 nsep = sep->se_next;
556 if (sep->se_fd != -1 && FD_ISSET(sep->se_fd, &readable)) {
557 n--;
558 if (debug)
559 fprintf(stderr, "someone wants %s\n", sep->se_service);
560 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM) {
561 /* XXX here do the libwrap check-before-accept */
562 ctrl = accept(sep->se_fd, (struct sockaddr *)0,
563 (int *)0);
564 if (debug)
565 fprintf(stderr, "accept, ctrl %d\n", ctrl);
566 if (ctrl < 0) {
567 if (errno != EINTR)
568 syslog(LOG_WARNING,
569 "accept (for %s): %m",
570 sep->se_service);
571 continue;
572 }
573 } else
574 ctrl = sep->se_fd;
575 (void) sigblock(SIGBLOCK);
576 pid = 0;
577 #ifdef LIBWRAP_INTERNAL
578 dofork = 1;
579 #else
580 dofork = (sep->se_bi == 0 || sep->se_bi->bi_fork);
581 #endif
582 if (dofork) {
583 if (sep->se_count++ == 0)
584 (void)gettimeofday(&sep->se_time,
585 (struct timezone *)0);
586 else if (sep->se_count >= sep->se_max) {
587 struct timeval now;
588
589 (void)gettimeofday(&now, (struct timezone *)0);
590 if (now.tv_sec - sep->se_time.tv_sec >
591 CNT_INTVL) {
592 sep->se_time = now;
593 sep->se_count = 1;
594 } else {
595 syslog(LOG_ERR,
596 "%s/%s server failing (looping), service terminated\n",
597 sep->se_service, sep->se_proto);
598 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
599 close(ctrl);
600 close_sep(sep);
601 sigsetmask(0L);
602 if (!timingout) {
603 timingout = 1;
604 alarm(RETRYTIME);
605 }
606 continue;
607 }
608 }
609 pid = fork();
610 if (pid < 0) {
611 syslog(LOG_ERR, "fork: %m");
612 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
613 close(ctrl);
614 sigsetmask(0L);
615 sleep(1);
616 continue;
617 }
618 if (pid != 0 && sep->se_wait) {
619 sep->se_wait = pid;
620 FD_CLR(sep->se_fd, &allsock);
621 nsock--;
622 }
623 if (pid == 0) {
624 sv.sv_mask = 0L;
625 sv.sv_handler = SIG_DFL;
626 sigvec(SIGPIPE, &sv, (struct sigvec *)0);
627 if (debug)
628 setsid();
629 }
630 }
631 sigsetmask(0L);
632 if (pid == 0) {
633 run_service(ctrl, sep);
634 if (dofork)
635 exit(0);
636 }
637 if (!sep->se_wait && sep->se_socktype == SOCK_STREAM)
638 close(ctrl);
639 }
640 }
641 }
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 if (sep->se_fd != -1) {
836 if (ipsecsetup(sep->se_family, sep->se_fd,
837 sep->se_policy) < 0 && sep->se_policy) {
838 syslog(LOG_ERR, "%s/%s: "
839 "ipsec initialization failed",
840 sep->se_service, sep->se_proto);
841 sep->se_checked = 0;
842 sigsetmask(omask);
843 continue;
844 }
845 }
846 #endif
847 SWAP(int, cp->se_type, sep->se_type);
848 SWAP(int, cp->se_max, sep->se_max);
849 #undef SWAP
850 if (isrpcservice(sep))
851 unregister_rpc(sep);
852 sep->se_rpcversl = cp->se_rpcversl;
853 sep->se_rpcversh = cp->se_rpcversh;
854 sigsetmask(omask);
855 freeconfig(cp);
856 if (debug)
857 print_service("REDO", sep);
858 } else {
859 sep = enter(cp);
860 if (debug)
861 print_service("ADD ", sep);
862 }
863 sep->se_checked = 1;
864
865 switch (sep->se_family) {
866 case AF_LOCAL:
867 if (sep->se_fd != -1)
868 break;
869 n = strlen(sep->se_service);
870 if (n > sizeof(sep->se_ctrladdr_un.sun_path)) {
871 syslog(LOG_ERR, "%s: address too long",
872 sep->se_service);
873 sep->se_checked = 0;
874 continue;
875 }
876 (void)unlink(sep->se_service);
877 strncpy(sep->se_ctrladdr_un.sun_path,
878 sep->se_service, n);
879 sep->se_ctrladdr_un.sun_family = AF_LOCAL;
880 sep->se_ctrladdr_size = n +
881 sizeof(sep->se_ctrladdr_un) -
882 sizeof(sep->se_ctrladdr_un.sun_path);
883 if (!ISMUX(sep))
884 setup(sep);
885 break;
886 case AF_INET:
887 #ifdef INET6
888 case AF_INET6:
889 #endif
890 {
891 struct addrinfo hints, *res;
892 char *host, *port;
893 int error;
894
895 memset(&hints, 0, sizeof(hints));
896 hints.ai_family = sep->se_family;
897 hints.ai_socktype = sep->se_socktype;
898 if (!strcmp(sep->se_hostaddr, "*")) {
899 hints.ai_flags = AI_PASSIVE;
900 host = NULL;
901 } else
902 host = sep->se_hostaddr;
903 if (isrpcservice(sep) || ISMUX(sep))
904 port = "0";
905 else
906 port = sep->se_service;
907 error = getaddrinfo(host, port, &hints, &res);
908 if (error) {
909 syslog(LOG_ERR, "%s/%s: %s: %s",
910 sep->se_service, sep->se_proto,
911 sep->se_hostaddr, gai_strerror(error));
912 sep->se_checked = 0;
913 continue;
914 }
915 if (res->ai_next) {
916 syslog(LOG_ERR,
917 "%s/%s: %s: resolved to multiple addr",
918 sep->se_service, sep->se_proto,
919 sep->se_hostaddr);
920 sep->se_checked = 0;
921 freeaddrinfo(res);
922 continue;
923 }
924 memcpy(&sep->se_ctrladdr, res->ai_addr,
925 res->ai_addrlen);
926 if (ISMUX(sep)) {
927 sep->se_fd = -1;
928 freeaddrinfo(res);
929 continue;
930 }
931 sep->se_ctrladdr_size = res->ai_addrlen;
932 freeaddrinfo(res);
933 #ifdef RPC
934 if (isrpcservice(sep)) {
935 struct rpcent *rp;
936
937 sep->se_rpcprog = atoi(sep->se_service);
938 if (sep->se_rpcprog == 0) {
939 rp = getrpcbyname(sep->se_service);
940 if (rp == 0) {
941 syslog(LOG_ERR,
942 "%s/%s: unknown service",
943 sep->se_service,
944 sep->se_proto);
945 sep->se_checked = 0;
946 continue;
947 }
948 sep->se_rpcprog = rp->r_number;
949 }
950 if (sep->se_fd == -1 && !ISMUX(sep))
951 setup(sep);
952 if (sep->se_fd != -1)
953 register_rpc(sep);
954 } else
955 #endif
956 {
957 if (sep->se_fd >= 0)
958 close_sep(sep);
959 if (sep->se_fd == -1 && !ISMUX(sep))
960 setup(sep);
961 }
962 }
963 }
964 }
965 endconfig();
966 /*
967 * Purge anything not looked at above.
968 */
969 omask = sigblock(SIGBLOCK);
970 sepp = &servtab;
971 while ((sep = *sepp)) {
972 if (sep->se_checked) {
973 sepp = &sep->se_next;
974 continue;
975 }
976 *sepp = sep->se_next;
977 if (sep->se_fd >= 0)
978 close_sep(sep);
979 if (isrpcservice(sep))
980 unregister_rpc(sep);
981 if (sep->se_family == AF_LOCAL)
982 (void)unlink(sep->se_service);
983 if (debug)
984 print_service("FREE", sep);
985 freeconfig(sep);
986 free((char *)sep);
987 }
988 (void) sigsetmask(omask);
989 }
990
991 void
992 retry(signo)
993 int signo;
994 {
995 struct servtab *sep;
996
997 timingout = 0;
998 for (sep = servtab; sep; sep = sep->se_next) {
999 if (sep->se_fd == -1 && !ISMUX(sep)) {
1000 switch (sep->se_family) {
1001 case AF_LOCAL:
1002 case AF_INET:
1003 #ifdef INET6
1004 case AF_INET6:
1005 #endif
1006 setup(sep);
1007 if (sep->se_fd != -1 && isrpcservice(sep))
1008 register_rpc(sep);
1009 break;
1010 }
1011 }
1012 }
1013 }
1014
1015 void
1016 goaway(signo)
1017 int signo;
1018 {
1019 struct servtab *sep;
1020
1021 for (sep = servtab; sep; sep = sep->se_next) {
1022 if (sep->se_fd == -1)
1023 continue;
1024
1025 switch (sep->se_family) {
1026 case AF_LOCAL:
1027 (void)unlink(sep->se_service);
1028 break;
1029 case AF_INET:
1030 #ifdef INET6
1031 case AF_INET6:
1032 #endif
1033 if (sep->se_wait == 1 && isrpcservice(sep))
1034 unregister_rpc(sep);
1035 break;
1036 }
1037 (void)close(sep->se_fd);
1038 }
1039 exit(0);
1040 }
1041
1042 void
1043 setup(sep)
1044 struct servtab *sep;
1045 {
1046 int on = 1;
1047
1048 if ((sep->se_fd = socket(sep->se_family, sep->se_socktype, 0)) < 0) {
1049 if (debug)
1050 fprintf(stderr, "socket failed on %s/%s: %s\n",
1051 sep->se_service, sep->se_proto, strerror(errno));
1052 syslog(LOG_ERR, "%s/%s: socket: %m",
1053 sep->se_service, sep->se_proto);
1054 return;
1055 }
1056 /* Set all listening sockets to close-on-exec. */
1057 if (fcntl(sep->se_fd, F_SETFD, FD_CLOEXEC) < 0)
1058 syslog(LOG_ERR, "fcntl (F_SETFD, FD_CLOEXEC): %m");
1059
1060 #define turnon(fd, opt) \
1061 setsockopt(fd, SOL_SOCKET, opt, (char *)&on, sizeof (on))
1062 if (strcmp(sep->se_proto, "tcp") == 0 && (options & SO_DEBUG) &&
1063 turnon(sep->se_fd, SO_DEBUG) < 0)
1064 syslog(LOG_ERR, "setsockopt (SO_DEBUG): %m");
1065 if (turnon(sep->se_fd, SO_REUSEADDR) < 0)
1066 syslog(LOG_ERR, "setsockopt (SO_REUSEADDR): %m");
1067 #undef turnon
1068
1069 /* Set the socket buffer sizes, if specified. */
1070 if (sep->se_sndbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
1071 SO_SNDBUF, (char *)&sep->se_sndbuf, sizeof(sep->se_sndbuf)) < 0)
1072 syslog(LOG_ERR, "setsockopt (SO_SNDBUF %d): %m",
1073 sep->se_sndbuf);
1074 if (sep->se_rcvbuf != 0 && setsockopt(sep->se_fd, SOL_SOCKET,
1075 SO_RCVBUF, (char *)&sep->se_rcvbuf, sizeof(sep->se_rcvbuf)) < 0)
1076 syslog(LOG_ERR, "setsockopt (SO_RCVBUF %d): %m",
1077 sep->se_rcvbuf);
1078 #ifdef IPSEC
1079 if (ipsecsetup(sep->se_family, sep->se_fd, sep->se_policy) < 0
1080 && sep->se_policy) {
1081 syslog(LOG_ERR, "%s/%s: ipsec setup failed",
1082 sep->se_service, sep->se_proto);
1083 (void)close(sep->se_fd);
1084 sep->se_fd = -1;
1085 return;
1086 }
1087 #endif
1088
1089 if (bind(sep->se_fd, &sep->se_ctrladdr, sep->se_ctrladdr_size) < 0) {
1090 if (debug)
1091 fprintf(stderr, "bind failed on %s/%s: %s\n",
1092 sep->se_service, sep->se_proto, strerror(errno));
1093 syslog(LOG_ERR, "%s/%s: bind: %m",
1094 sep->se_service, sep->se_proto);
1095 (void) close(sep->se_fd);
1096 sep->se_fd = -1;
1097 if (!timingout) {
1098 timingout = 1;
1099 alarm(RETRYTIME);
1100 }
1101 return;
1102 }
1103 if (sep->se_socktype == SOCK_STREAM)
1104 listen(sep->se_fd, 10);
1105
1106 FD_SET(sep->se_fd, &allsock);
1107 nsock++;
1108 if (sep->se_fd > maxsock) {
1109 maxsock = sep->se_fd;
1110 if (maxsock > rlim_ofile_cur - FD_MARGIN)
1111 bump_nofile();
1112 }
1113 if (debug)
1114 fprintf(stderr, "registered %s on %d\n",
1115 sep->se_server, sep->se_fd);
1116 }
1117
1118 /*
1119 * Finish with a service and its socket.
1120 */
1121 void
1122 close_sep(sep)
1123 struct servtab *sep;
1124 {
1125 if (sep->se_fd >= 0) {
1126 nsock--;
1127 FD_CLR(sep->se_fd, &allsock);
1128 (void) close(sep->se_fd);
1129 sep->se_fd = -1;
1130 }
1131 sep->se_count = 0;
1132 /*
1133 * Don't keep the pid of this running deamon: when reapchild()
1134 * reaps this pid, it would erroneously increment nsock.
1135 */
1136 if (sep->se_wait > 1)
1137 sep->se_wait = 1;
1138 }
1139
1140 void
1141 register_rpc(sep)
1142 struct servtab *sep;
1143 {
1144 #ifdef RPC
1145 int n;
1146 struct sockaddr_storage ss;
1147 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
1148 struct protoent *pp;
1149
1150 if ((pp = getprotobyname(sep->se_proto+4)) == NULL) {
1151 syslog(LOG_ERR, "%s: getproto: %m",
1152 sep->se_proto);
1153 return;
1154 }
1155 n = sizeof ss;
1156 if (getsockname(sep->se_fd, (struct sockaddr *)&ss, &n) < 0) {
1157 syslog(LOG_ERR, "%s/%s: getsockname: %m",
1158 sep->se_service, sep->se_proto);
1159 return;
1160 }
1161 if (ss.ss_family != AF_INET) { /*XXX*/
1162 syslog(LOG_ERR, "%s/%s: rpc not supported",
1163 sep->se_service, sep->se_proto);
1164 return;
1165 }
1166
1167 for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
1168 if (debug)
1169 fprintf(stderr, "pmap_set: %u %u %u %u\n",
1170 sep->se_rpcprog, n, pp->p_proto,
1171 ntohs(sin->sin_port));
1172 (void)pmap_unset(sep->se_rpcprog, n);
1173 if (!pmap_set(sep->se_rpcprog, n, pp->p_proto, ntohs(sin->sin_port)))
1174 syslog(LOG_ERR, "pmap_set: %u %u %u %u: %m",
1175 sep->se_rpcprog, n, pp->p_proto,
1176 ntohs(sin->sin_port));
1177 }
1178 #endif /* RPC */
1179 }
1180
1181 void
1182 unregister_rpc(sep)
1183 struct servtab *sep;
1184 {
1185 #ifdef RPC
1186 int n;
1187
1188 for (n = sep->se_rpcversl; n <= sep->se_rpcversh; n++) {
1189 if (debug)
1190 fprintf(stderr, "pmap_unset(%u, %u)\n",
1191 sep->se_rpcprog, n);
1192 if (!pmap_unset(sep->se_rpcprog, n))
1193 syslog(LOG_ERR, "pmap_unset(%u, %u)\n",
1194 sep->se_rpcprog, n);
1195 }
1196 #endif /* RPC */
1197 }
1198
1199
1200 struct servtab *
1201 enter(cp)
1202 struct servtab *cp;
1203 {
1204 struct servtab *sep;
1205 long omask;
1206
1207 sep = (struct servtab *)malloc(sizeof (*sep));
1208 if (sep == (struct servtab *)0) {
1209 syslog(LOG_ERR, "Out of memory.");
1210 exit(-1);
1211 }
1212 *sep = *cp;
1213 sep->se_fd = -1;
1214 sep->se_rpcprog = -1;
1215 omask = sigblock(SIGBLOCK);
1216 sep->se_next = servtab;
1217 servtab = sep;
1218 sigsetmask(omask);
1219 return (sep);
1220 }
1221
1222 FILE *fconfig = NULL;
1223 struct servtab serv;
1224 char line[LINE_MAX];
1225 char *defhost;
1226
1227 int
1228 setconfig()
1229 {
1230 if (defhost) free(defhost);
1231 defhost = newstr("*");
1232 if (fconfig != NULL) {
1233 fseek(fconfig, 0L, SEEK_SET);
1234 return (1);
1235 }
1236 fconfig = fopen(CONFIG, "r");
1237 return (fconfig != NULL);
1238 }
1239
1240 void
1241 endconfig()
1242 {
1243 if (fconfig) {
1244 (void) fclose(fconfig);
1245 fconfig = NULL;
1246 }
1247 if (defhost) {
1248 free(defhost);
1249 defhost = 0;
1250 }
1251 }
1252
1253 struct servtab *
1254 getconfigent()
1255 {
1256 struct servtab *sep = &serv;
1257 int argc, val;
1258 char *cp, *cp0, *arg, *buf0, *buf1, *sz0, *sz1;
1259 static char TCPMUX_TOKEN[] = "tcpmux/";
1260 #define MUX_LEN (sizeof(TCPMUX_TOKEN)-1)
1261 char *hostdelim;
1262 #ifdef IPSEC
1263 char *policy = NULL;
1264 #endif
1265
1266 more:
1267 while ((cp = nextline(fconfig))) {
1268 #ifdef IPSEC
1269 /* lines starting with #@ is not a comment, but the policy */
1270 if (cp[0] == '#' && cp[1] == '@') {
1271 char *p;
1272 for (p = cp + 2; p && *p && isspace(*p); p++)
1273 ;
1274 if (*p == '\0') {
1275 if (policy)
1276 free(policy);
1277 policy = NULL;
1278 } else {
1279 if (ipsecsetup_test(p) < 0) {
1280 syslog(LOG_ERR,
1281 "%s: invalid ipsec policy \"%s\"",
1282 CONFIG, p);
1283 exit(-1);
1284 } else {
1285 if (policy)
1286 free(policy);
1287 policy = newstr(p);
1288 }
1289 }
1290 }
1291 #endif
1292 if (*cp == '#' || *cp == '\0')
1293 continue;
1294 #ifdef MULOG
1295 /* Avoid use of `skip' if there is a danger of it looking
1296 * at continuation lines.
1297 */
1298 do {
1299 cp++;
1300 } while (*cp == ' ' || *cp == '\t');
1301 if (*cp == '\0')
1302 continue;
1303 if ((arg = skip(&cp)) == NULL)
1304 continue;
1305 if (strcmp(arg, "DOMAIN"))
1306 continue;
1307 if (curdom)
1308 free(curdom);
1309 curdom = NULL;
1310 while (*cp == ' ' || *cp == '\t')
1311 cp++;
1312 if (*cp == '\0')
1313 continue;
1314 arg = cp;
1315 while (*cp && *cp != ' ' && *cp != '\t')
1316 cp++;
1317 if (*cp != '\0')
1318 *cp++ = '\0';
1319 curdom = newstr(arg);
1320 #endif
1321 break;
1322 }
1323 if (cp == NULL)
1324 return ((struct servtab *)0);
1325 /*
1326 * clear the static buffer, since some fields (se_ctrladdr,
1327 * for example) don't get initialized here.
1328 */
1329 memset((caddr_t)sep, 0, sizeof *sep);
1330 arg = skip(&cp);
1331 if (cp == NULL) {
1332 /* got an empty line containing just blanks/tabs. */
1333 goto more;
1334 }
1335 /* Check for a host name. */
1336 hostdelim = strrchr(arg, ':');
1337 if (hostdelim) {
1338 *hostdelim = '\0';
1339 sep->se_hostaddr = newstr(arg);
1340 arg = hostdelim + 1;
1341 /*
1342 * If the line is of the form `host:', then just change the
1343 * default host for the following lines.
1344 */
1345 if (*arg == '\0') {
1346 arg = skip(&cp);
1347 if (cp == NULL) {
1348 free(defhost);
1349 defhost = sep->se_hostaddr;
1350 goto more;
1351 }
1352 }
1353 } else
1354 sep->se_hostaddr = newstr(defhost);
1355 if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1356 char *c = arg + MUX_LEN;
1357 if (*c == '+') {
1358 sep->se_type = MUXPLUS_TYPE;
1359 c++;
1360 } else
1361 sep->se_type = MUX_TYPE;
1362 sep->se_service = newstr(c);
1363 } else {
1364 sep->se_service = newstr(arg);
1365 sep->se_type = NORM_TYPE;
1366 }
1367
1368 arg = sskip(&cp);
1369 if (strcmp(arg, "stream") == 0)
1370 sep->se_socktype = SOCK_STREAM;
1371 else if (strcmp(arg, "dgram") == 0)
1372 sep->se_socktype = SOCK_DGRAM;
1373 else if (strcmp(arg, "rdm") == 0)
1374 sep->se_socktype = SOCK_RDM;
1375 else if (strcmp(arg, "seqpacket") == 0)
1376 sep->se_socktype = SOCK_SEQPACKET;
1377 else if (strcmp(arg, "raw") == 0)
1378 sep->se_socktype = SOCK_RAW;
1379 else
1380 sep->se_socktype = -1;
1381
1382 sep->se_proto = newstr(sskip(&cp));
1383
1384 #define MALFORMED(arg) \
1385 do { \
1386 syslog(LOG_ERR, "%s: malformed buffer size option `%s'", \
1387 sep->se_service, (arg)); \
1388 goto more; \
1389 } while (0)
1390
1391 #define GETVAL(arg) \
1392 do { \
1393 if (!isdigit(*(arg))) \
1394 MALFORMED(arg); \
1395 val = strtol((arg), &cp0, 10); \
1396 if (cp0 != NULL) { \
1397 if (cp0[1] != '\0') \
1398 MALFORMED((arg)); \
1399 if (cp0[0] == 'k') \
1400 val *= 1024; \
1401 if (cp0[0] == 'm') \
1402 val *= 1024 * 1024; \
1403 } \
1404 if (val < 1) { \
1405 syslog(LOG_ERR, "%s: invalid buffer size `%s'", \
1406 sep->se_service, (arg)); \
1407 goto more; \
1408 } \
1409 } while (0)
1410
1411 #define ASSIGN(arg) \
1412 do { \
1413 if (strcmp((arg), "sndbuf") == 0) \
1414 sep->se_sndbuf = val; \
1415 else if (strcmp((arg), "rcvbuf") == 0) \
1416 sep->se_rcvbuf = val; \
1417 else \
1418 MALFORMED((arg)); \
1419 } while (0)
1420
1421 /*
1422 * Extract the send and receive buffer sizes before parsing
1423 * the protocol.
1424 */
1425 sep->se_sndbuf = sep->se_rcvbuf = 0;
1426 buf0 = buf1 = sz0 = sz1 = NULL;
1427 if ((buf0 = strchr(sep->se_proto, ',')) != NULL) {
1428 /* Not meaningful for Tcpmux services. */
1429 if (sep->se_type != NORM_TYPE) {
1430 syslog(LOG_ERR, "%s: can't specify buffer sizes for "
1431 "tcpmux services", sep->se_service);
1432 goto more;
1433 }
1434
1435 /* Skip the , */
1436 *buf0++ = '\0';
1437
1438 /* Check to see if another socket buffer size was specified. */
1439 if ((buf1 = strchr(buf0, ',')) != NULL) {
1440 /* Skip the , */
1441 *buf1++ = '\0';
1442
1443 /* Make sure a 3rd one wasn't specified. */
1444 if (strchr(buf1, ',') != NULL) {
1445 syslog(LOG_ERR, "%s: too many buffer sizes",
1446 sep->se_service);
1447 goto more;
1448 }
1449
1450 /* Locate the size. */
1451 if ((sz1 = strchr(buf1, '=')) == NULL)
1452 MALFORMED(buf1);
1453
1454 /* Skip the = */
1455 *sz1++ = '\0';
1456 }
1457
1458 /* Locate the size. */
1459 if ((sz0 = strchr(buf0, '=')) == NULL)
1460 MALFORMED(buf0);
1461
1462 /* Skip the = */
1463 *sz0++ = '\0';
1464
1465 GETVAL(sz0);
1466 ASSIGN(buf0);
1467
1468 if (buf1 != NULL) {
1469 GETVAL(sz1);
1470 ASSIGN(buf1);
1471 }
1472 }
1473
1474 #undef ASSIGN
1475 #undef GETVAL
1476 #undef MALFORMED
1477
1478 if (strcmp(sep->se_proto, "unix") == 0) {
1479 sep->se_family = AF_LOCAL;
1480 } else {
1481 val = strlen(sep->se_proto);
1482 if (!val) {
1483 syslog(LOG_ERR, "%s: invalid protocol specified",
1484 sep->se_service);
1485 goto more;
1486 }
1487 val = sep->se_proto[val - 1];
1488 switch (val) {
1489 case '4': /*tcp4 or udp4*/
1490 sep->se_family = AF_INET;
1491 break;
1492 #ifdef INET6
1493 case '6': /*tcp6 or udp6*/
1494 sep->se_family = AF_INET6;
1495 break;
1496 #endif
1497 default:
1498 sep->se_family = AF_INET; /*will become AF_INET6*/
1499 break;
1500 }
1501 if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1502 #ifdef RPC
1503 char *cp, *ccp;
1504 cp = strchr(sep->se_service, '/');
1505 if (cp == 0) {
1506 syslog(LOG_ERR, "%s: no rpc version",
1507 sep->se_service);
1508 goto more;
1509 }
1510 *cp++ = '\0';
1511 sep->se_rpcversl = sep->se_rpcversh =
1512 strtol(cp, &ccp, 0);
1513 if (ccp == cp) {
1514 badafterall:
1515 syslog(LOG_ERR, "%s/%s: bad rpc version",
1516 sep->se_service, cp);
1517 goto more;
1518 }
1519 if (*ccp == '-') {
1520 cp = ccp + 1;
1521 sep->se_rpcversh = strtol(cp, &ccp, 0);
1522 if (ccp == cp)
1523 goto badafterall;
1524 }
1525 #else
1526 syslog(LOG_ERR, "%s: rpc services not suported",
1527 sep->se_service);
1528 goto more;
1529 #endif /* RPC */
1530 }
1531 }
1532 arg = sskip(&cp);
1533 {
1534 char *cp;
1535 if ((cp = strchr(arg, ':')) == NULL)
1536 cp = strchr(arg, '.');
1537 if (cp != NULL) {
1538 *cp++ = '\0';
1539 sep->se_max = atoi(cp);
1540 } else
1541 sep->se_max = TOOMANY;
1542 }
1543 sep->se_wait = strcmp(arg, "wait") == 0;
1544 if (ISMUX(sep)) {
1545 /*
1546 * Silently enforce "nowait" for TCPMUX services since
1547 * they don't have an assigned port to listen on.
1548 */
1549 sep->se_wait = 0;
1550
1551 if (strncmp(sep->se_proto, "tcp", 3)) {
1552 syslog(LOG_ERR,
1553 "%s: bad protocol for tcpmux service %s",
1554 CONFIG, sep->se_service);
1555 goto more;
1556 }
1557 if (sep->se_socktype != SOCK_STREAM) {
1558 syslog(LOG_ERR,
1559 "%s: bad socket type for tcpmux service %s",
1560 CONFIG, sep->se_service);
1561 goto more;
1562 }
1563 }
1564 sep->se_user = newstr(sskip(&cp));
1565 if ((sep->se_group = strchr(sep->se_user, ':')) != NULL)
1566 *sep->se_group++ = '\0';
1567 else if ((sep->se_group = strchr(sep->se_user, '.')) != NULL)
1568 *sep->se_group++ = '\0';
1569
1570 sep->se_server = newstr(sskip(&cp));
1571 if (strcmp(sep->se_server, "internal") == 0) {
1572 struct biltin *bi;
1573
1574 for (bi = biltins; bi->bi_service; bi++)
1575 if (bi->bi_socktype == sep->se_socktype &&
1576 strcmp(bi->bi_service, sep->se_service) == 0)
1577 break;
1578 if (bi->bi_service == 0) {
1579 syslog(LOG_ERR, "internal service %s unknown",
1580 sep->se_service);
1581 goto more;
1582 }
1583 sep->se_bi = bi;
1584 sep->se_wait = bi->bi_wait;
1585 } else
1586 sep->se_bi = NULL;
1587 argc = 0;
1588 for (arg = skip(&cp); cp; arg = skip(&cp)) {
1589 #if MULOG
1590 char *colon;
1591
1592 if (argc == 0 && (colon = strrchr(arg, ':'))) {
1593 while (arg < colon) {
1594 int x;
1595 char *ccp;
1596
1597 switch (*arg++) {
1598 case 'l':
1599 x = 1;
1600 if (isdigit(*arg)) {
1601 x = strtol(arg, &ccp, 0);
1602 if (ccp == arg)
1603 break;
1604 arg = ccp;
1605 }
1606 sep->se_log &= ~MULOG_RFC931;
1607 sep->se_log |= x;
1608 break;
1609 case 'a':
1610 sep->se_log |= MULOG_RFC931;
1611 break;
1612 default:
1613 break;
1614 }
1615 }
1616 arg = colon + 1;
1617 }
1618 #endif
1619 if (argc < MAXARGV)
1620 sep->se_argv[argc++] = newstr(arg);
1621 }
1622 while (argc <= MAXARGV)
1623 sep->se_argv[argc++] = NULL;
1624 #ifdef IPSEC
1625 sep->se_policy = policy ? newstr(policy) : NULL;
1626 #endif
1627 return (sep);
1628 }
1629
1630 void
1631 freeconfig(cp)
1632 struct servtab *cp;
1633 {
1634 int i;
1635
1636 if (cp->se_hostaddr)
1637 free(cp->se_hostaddr);
1638 if (cp->se_service)
1639 free(cp->se_service);
1640 if (cp->se_proto)
1641 free(cp->se_proto);
1642 if (cp->se_user)
1643 free(cp->se_user);
1644 /* Note: se_group is part of the newstr'ed se_user */
1645 if (cp->se_server)
1646 free(cp->se_server);
1647 for (i = 0; i < MAXARGV; i++)
1648 if (cp->se_argv[i])
1649 free(cp->se_argv[i]);
1650 #ifdef IPSEC
1651 if (cp->se_policy)
1652 free(cp->se_policy);
1653 #endif
1654 }
1655
1656
1657 /*
1658 * Safe skip - if skip returns null, log a syntax error in the
1659 * configuration file and exit.
1660 */
1661 char *
1662 sskip(cpp)
1663 char **cpp;
1664 {
1665 char *cp;
1666
1667 cp = skip(cpp);
1668 if (cp == NULL) {
1669 syslog(LOG_ERR, "%s: syntax error", CONFIG);
1670 exit(-1);
1671 }
1672 return (cp);
1673 }
1674
1675 char *
1676 skip(cpp)
1677 char **cpp;
1678 {
1679 char *cp = *cpp;
1680 char *start;
1681
1682 if (*cpp == NULL)
1683 return ((char *)0);
1684
1685 again:
1686 while (*cp == ' ' || *cp == '\t')
1687 cp++;
1688 if (*cp == '\0') {
1689 int c;
1690
1691 c = getc(fconfig);
1692 (void) ungetc(c, fconfig);
1693 if (c == ' ' || c == '\t')
1694 if ((cp = nextline(fconfig)))
1695 goto again;
1696 *cpp = (char *)0;
1697 return ((char *)0);
1698 }
1699 start = cp;
1700 while (*cp && *cp != ' ' && *cp != '\t')
1701 cp++;
1702 if (*cp != '\0')
1703 *cp++ = '\0';
1704 *cpp = cp;
1705 return (start);
1706 }
1707
1708 char *
1709 nextline(fd)
1710 FILE *fd;
1711 {
1712 char *cp;
1713
1714 if (fgets(line, sizeof (line), fd) == NULL)
1715 return ((char *)0);
1716 cp = strchr(line, '\n');
1717 if (cp)
1718 *cp = '\0';
1719 return (line);
1720 }
1721
1722 char *
1723 newstr(cp)
1724 char *cp;
1725 {
1726 if ((cp = strdup(cp ? cp : "")))
1727 return (cp);
1728 syslog(LOG_ERR, "strdup: %m");
1729 exit(-1);
1730 }
1731
1732 void
1733 inetd_setproctitle(a, s)
1734 char *a;
1735 int s;
1736 {
1737 int size;
1738 char *cp;
1739 struct sockaddr_storage ss;
1740 char buf[80];
1741 char hbuf[NI_MAXHOST];
1742
1743 cp = Argv[0];
1744 size = sizeof(ss);
1745 if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
1746 if (getnameinfo((struct sockaddr *)&ss, ss.ss_len,
1747 hbuf, sizeof(hbuf), NULL, 0, niflags) != 0)
1748 strcpy(hbuf, "?");
1749 (void)snprintf(buf, sizeof buf, "-%s [%s]", a, hbuf);
1750 } else
1751 (void)snprintf(buf, sizeof buf, "-%s", a);
1752 strncpy(cp, buf, LastArg - cp);
1753 cp += strlen(cp);
1754 while (cp < LastArg)
1755 *cp++ = ' ';
1756 }
1757
1758 void
1759 bump_nofile()
1760 {
1761 #ifdef RLIMIT_NOFILE
1762
1763 #define FD_CHUNK 32
1764
1765 struct rlimit rl;
1766
1767 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1768 syslog(LOG_ERR, "getrlimit: %m");
1769 return;
1770 }
1771 rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
1772 if (rl.rlim_cur <= rlim_ofile_cur) {
1773 syslog(LOG_ERR,
1774 "bump_nofile: cannot extend file limit, max = %d",
1775 (int)rl.rlim_cur);
1776 return;
1777 }
1778
1779 if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
1780 syslog(LOG_ERR, "setrlimit: %m");
1781 return;
1782 }
1783
1784 rlim_ofile_cur = rl.rlim_cur;
1785 return;
1786
1787 #else
1788 syslog(LOG_ERR, "bump_nofile: cannot extend file limit");
1789 return;
1790 #endif
1791 }
1792
1793 /*
1794 * Internet services provided internally by inetd:
1795 */
1796 #define BUFSIZE 4096
1797
1798 /* ARGSUSED */
1799 void
1800 echo_stream(s, sep) /* Echo service -- echo data back */
1801 int s;
1802 struct servtab *sep;
1803 {
1804 char buffer[BUFSIZE];
1805 int i;
1806
1807 inetd_setproctitle(sep->se_service, s);
1808 while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
1809 write(s, buffer, i) > 0)
1810 ;
1811 }
1812
1813 /* ARGSUSED */
1814 void
1815 echo_dg(s, sep) /* Echo service -- echo data back */
1816 int s;
1817 struct servtab *sep;
1818 {
1819 char buffer[BUFSIZE];
1820 int i, size;
1821 struct sockaddr_storage ss;
1822 struct sockaddr *sa;
1823
1824 sa = (struct sockaddr *)&ss;
1825 size = sizeof(ss);
1826 if ((i = recvfrom(s, buffer, sizeof(buffer), 0, sa, &size)) < 0)
1827 return;
1828 if (port_good_dg(sa))
1829 (void) sendto(s, buffer, i, 0, sa, size);
1830 }
1831
1832 /* ARGSUSED */
1833 void
1834 discard_stream(s, sep) /* Discard service -- ignore data */
1835 int s;
1836 struct servtab *sep;
1837 {
1838 char buffer[BUFSIZE];
1839
1840 inetd_setproctitle(sep->se_service, s);
1841 while ((errno = 0, read(s, buffer, sizeof(buffer)) > 0) ||
1842 errno == EINTR)
1843 ;
1844 }
1845
1846 /* ARGSUSED */
1847 void
1848 discard_dg(s, sep) /* Discard service -- ignore data */
1849 int s;
1850 struct servtab *sep;
1851 {
1852 char buffer[BUFSIZE];
1853
1854 (void) read(s, buffer, sizeof(buffer));
1855 }
1856
1857 #include <ctype.h>
1858 #define LINESIZ 72
1859 char ring[128];
1860 char *endring;
1861
1862 void
1863 initring()
1864 {
1865 int i;
1866
1867 endring = ring;
1868
1869 for (i = 0; i <= 128; ++i)
1870 if (isprint(i))
1871 *endring++ = i;
1872 }
1873
1874 /* ARGSUSED */
1875 void
1876 chargen_stream(s, sep) /* Character generator */
1877 int s;
1878 struct servtab *sep;
1879 {
1880 int len;
1881 char *rs, text[LINESIZ+2];
1882
1883 inetd_setproctitle(sep->se_service, s);
1884
1885 if (!endring) {
1886 initring();
1887 rs = ring;
1888 }
1889
1890 text[LINESIZ] = '\r';
1891 text[LINESIZ + 1] = '\n';
1892 for (rs = ring;;) {
1893 if ((len = endring - rs) >= LINESIZ)
1894 memmove(text, rs, LINESIZ);
1895 else {
1896 memmove(text, rs, len);
1897 memmove(text + len, ring, LINESIZ - len);
1898 }
1899 if (++rs == endring)
1900 rs = ring;
1901 if (write(s, text, sizeof(text)) != sizeof(text))
1902 break;
1903 }
1904 }
1905
1906 /* ARGSUSED */
1907 void
1908 chargen_dg(s, sep) /* Character generator */
1909 int s;
1910 struct servtab *sep;
1911 {
1912 struct sockaddr_storage ss;
1913 struct sockaddr *sa;
1914 static char *rs;
1915 int len, size;
1916 char text[LINESIZ+2];
1917
1918 if (endring == 0) {
1919 initring();
1920 rs = ring;
1921 }
1922
1923 sa = (struct sockaddr *)&ss;
1924 size = sizeof(ss);
1925 if (recvfrom(s, text, sizeof(text), 0, sa, &size) < 0)
1926 return;
1927
1928 if (!port_good_dg(sa))
1929 return;
1930
1931 if ((len = endring - rs) >= LINESIZ)
1932 memmove(text, rs, LINESIZ);
1933 else {
1934 memmove(text, rs, len);
1935 memmove(text + len, ring, LINESIZ - len);
1936 }
1937 if (++rs == endring)
1938 rs = ring;
1939 text[LINESIZ] = '\r';
1940 text[LINESIZ + 1] = '\n';
1941 (void) sendto(s, text, sizeof(text), 0, sa, size);
1942 }
1943
1944 /*
1945 * Return a machine readable date and time, in the form of the
1946 * number of seconds since midnight, Jan 1, 1900. Since gettimeofday
1947 * returns the number of seconds since midnight, Jan 1, 1970,
1948 * we must add 2208988800 seconds to this figure to make up for
1949 * some seventy years Bell Labs was asleep.
1950 */
1951
1952 long
1953 machtime()
1954 {
1955 struct timeval tv;
1956
1957 if (gettimeofday(&tv, (struct timezone *)0) < 0) {
1958 if (debug)
1959 fprintf(stderr, "Unable to get time of day\n");
1960 return (0L);
1961 }
1962 #define OFFSET ((u_long)25567 * 24*60*60)
1963 return (htonl((long)(tv.tv_sec + OFFSET)));
1964 #undef OFFSET
1965 }
1966
1967 /* ARGSUSED */
1968 void
1969 machtime_stream(s, sep)
1970 int s;
1971 struct servtab *sep;
1972 {
1973 long result;
1974
1975 result = machtime();
1976 (void) write(s, (char *) &result, sizeof(result));
1977 }
1978
1979 /* ARGSUSED */
1980 void
1981 machtime_dg(s, sep)
1982 int s;
1983 struct servtab *sep;
1984 {
1985 long result;
1986 struct sockaddr_storage ss;
1987 struct sockaddr *sa;
1988 int size;
1989
1990 sa = (struct sockaddr *)&ss;
1991 size = sizeof(ss);
1992 if (recvfrom(s, (char *)&result, sizeof(result), 0, sa, &size) < 0)
1993 return;
1994 if (!port_good_dg(sa))
1995 return;
1996 result = machtime();
1997 (void) sendto(s, (char *) &result, sizeof(result), 0, sa, size);
1998 }
1999
2000 /* ARGSUSED */
2001 void
2002 daytime_stream(s, sep) /* Return human-readable time of day */
2003 int s;
2004 struct servtab *sep;
2005 {
2006 char buffer[256];
2007 time_t clock;
2008 int len;
2009
2010 clock = time((time_t *) 0);
2011
2012 len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2013 (void) write(s, buffer, len);
2014 }
2015
2016 /* ARGSUSED */
2017 void
2018 daytime_dg(s, sep) /* Return human-readable time of day */
2019 int s;
2020 struct servtab *sep;
2021 {
2022 char buffer[256];
2023 time_t clock;
2024 struct sockaddr_storage ss;
2025 struct sockaddr *sa;
2026 int size, len;
2027
2028 clock = time((time_t *) 0);
2029
2030 sa = (struct sockaddr *)&ss;
2031 size = sizeof(ss);
2032 if (recvfrom(s, buffer, sizeof(buffer), 0, sa, &size) < 0)
2033 return;
2034 if (!port_good_dg(sa))
2035 return;
2036 len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2037 (void) sendto(s, buffer, len, 0, sa, size);
2038 }
2039
2040 /*
2041 * print_service:
2042 * Dump relevant information to stderr
2043 */
2044 void
2045 print_service(action, sep)
2046 char *action;
2047 struct servtab *sep;
2048 {
2049 if (isrpcservice(sep))
2050 fprintf(stderr,
2051 "%s: %s rpcprog=%d, rpcvers = %d/%d, proto=%s, wait:max=%d.%d, user:group=%s.%s builtin=%lx server=%s"
2052 #ifdef IPSEC
2053 " policy=\"%s\""
2054 #endif
2055 "\n",
2056 action, sep->se_service,
2057 sep->se_rpcprog, sep->se_rpcversh, sep->se_rpcversl, sep->se_proto,
2058 sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2059 (long)sep->se_bi, sep->se_server
2060 #ifdef IPSEC
2061 , (sep->se_policy ? sep->se_policy : "")
2062 #endif
2063 );
2064 else
2065 fprintf(stderr,
2066 "%s: %s proto=%s, wait:max=%d.%d, user:group=%s.%s builtin=%lx server=%s"
2067 #ifdef IPSEC
2068 " policy=%s"
2069 #endif
2070 "\n",
2071 action, sep->se_service, sep->se_proto,
2072 sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2073 (long)sep->se_bi, sep->se_server
2074 #ifdef IPSEC
2075 , (sep->se_policy ? sep->se_policy : "")
2076 #endif
2077 );
2078 }
2079
2080 void
2081 usage()
2082 {
2083
2084 #ifdef LIBWRAP
2085 (void)fprintf(stderr, "usage: %s [-dl] [conf]\n", __progname);
2086 #else
2087 (void)fprintf(stderr, "usage: %s [-d] [conf]\n", __progname);
2088 #endif
2089 exit(1);
2090 }
2091
2092
2093 /*
2094 * Based on TCPMUX.C by Mark K. Lottor November 1988
2095 * sri-nic::ps:<mkl>tcpmux.c
2096 */
2097
2098 static int /* # of characters upto \r,\n or \0 */
2099 getline(fd, buf, len)
2100 int fd;
2101 char *buf;
2102 int len;
2103 {
2104 int count = 0, n;
2105
2106 do {
2107 n = read(fd, buf, len-count);
2108 if (n == 0)
2109 return (count);
2110 if (n < 0)
2111 return (-1);
2112 while (--n >= 0) {
2113 if (*buf == '\r' || *buf == '\n' || *buf == '\0')
2114 return (count);
2115 count++;
2116 buf++;
2117 }
2118 } while (count < len);
2119 return (count);
2120 }
2121
2122 #define MAX_SERV_LEN (256+2) /* 2 bytes for \r\n */
2123
2124 #define strwrite(fd, buf) (void) write(fd, buf, sizeof(buf)-1)
2125
2126 void
2127 tcpmux(ctrl, sep)
2128 int ctrl;
2129 struct servtab *sep;
2130 {
2131 char service[MAX_SERV_LEN+1];
2132 int len;
2133
2134 /* Get requested service name */
2135 if ((len = getline(ctrl, service, MAX_SERV_LEN)) < 0) {
2136 strwrite(ctrl, "-Error reading service name\r\n");
2137 goto reject;
2138 }
2139 service[len] = '\0';
2140
2141 if (debug)
2142 fprintf(stderr, "tcpmux: someone wants %s\n", service);
2143
2144 /*
2145 * Help is a required command, and lists available services,
2146 * one per line.
2147 */
2148 if (!strcasecmp(service, "help")) {
2149 strwrite(ctrl, "+Available services:\r\n");
2150 strwrite(ctrl, "help\r\n");
2151 for (sep = servtab; sep; sep = sep->se_next) {
2152 if (!ISMUX(sep))
2153 continue;
2154 (void)write(ctrl, sep->se_service,
2155 strlen(sep->se_service));
2156 strwrite(ctrl, "\r\n");
2157 }
2158 goto reject;
2159 }
2160
2161 /* Try matching a service in inetd.conf with the request */
2162 for (sep = servtab; sep; sep = sep->se_next) {
2163 if (!ISMUX(sep))
2164 continue;
2165 if (!strcasecmp(service, sep->se_service)) {
2166 if (ISMUXPLUS(sep))
2167 strwrite(ctrl, "+Go\r\n");
2168 run_service(ctrl, sep);
2169 return;
2170 }
2171 }
2172 strwrite(ctrl, "-Service not available\r\n");
2173 reject:
2174 _exit(1);
2175 }
2176
2177
2178 #ifdef MULOG
2179 dolog(sep, ctrl)
2180 struct servtab *sep;
2181 int ctrl;
2182 {
2183 struct sockaddr_storage ss;
2184 struct sockaddr *sa = (struct sockaddr *)&ss;
2185 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
2186 int len = sizeof(ss);
2187 struct hostent *hp;
2188 char *host, *dp, buf[BUFSIZ], *rfc931_name();
2189 int connected = 1;
2190
2191 switch (sep->se_family) {
2192 case AF_INET:
2193 #ifdef INET6
2194 case AF_INET6:
2195 #endif
2196 break;
2197 default;
2198 return;
2199 }
2200
2201 if (getpeername(ctrl, sa, &len) < 0) {
2202 if (errno != ENOTCONN) {
2203 syslog(LOG_ERR, "getpeername: %m");
2204 return;
2205 }
2206 if (recvfrom(ctrl, buf, sizeof(buf), MSG_PEEK, sa, &len) < 0) {
2207 syslog(LOG_ERR, "recvfrom: %m");
2208 return;
2209 }
2210 connected = 0;
2211 }
2212 switch (sa->sa_family) {
2213 case AF_INET:
2214 #ifdef INET6
2215 case AF_INET6:
2216 #endif
2217 break;
2218 default;
2219 syslog(LOG_ERR, "unexpected address family %u", sa->sa_family);
2220 return;
2221 }
2222
2223 if (getnameinfo(sa, sa->sa_len, buf, sizeof(buf), NULL, 0, 0) != 0)
2224 strcpy(buf, "?");
2225 host = buf;
2226
2227 switch (sep->se_log & ~MULOG_RFC931) {
2228 case 0:
2229 return;
2230 case 1:
2231 if (curdom == NULL || *curdom == '\0')
2232 break;
2233 dp = host + strlen(host) - strlen(curdom);
2234 if (dp < host)
2235 break;
2236 if (debug)
2237 fprintf(stderr, "check \"%s\" against curdom \"%s\"\n",
2238 host, curdom);
2239 if (strcasecmp(dp, curdom) == 0)
2240 return;
2241 break;
2242 case 2:
2243 default:
2244 break;
2245 }
2246
2247 openlog("", LOG_NOWAIT, MULOG);
2248
2249 if (connected && (sep->se_log & MULOG_RFC931))
2250 syslog(LOG_INFO, "%s@%s wants %s",
2251 rfc931_name(sa, ctrl), host, sep->se_service);
2252 else
2253 syslog(LOG_INFO, "%s wants %s",
2254 host, sep->se_service);
2255 }
2256
2257 /*
2258 * From tcp_log by
2259 * Wietse Venema, Eindhoven University of Technology, The Netherlands.
2260 */
2261 #if 0
2262 static char sccsid[] = "@(#) rfc931.c 1.3 92/08/31 22:54:46";
2263 #endif
2264
2265 #include <setjmp.h>
2266
2267 #define RFC931_PORT 113 /* Semi-well-known port */
2268 #define TIMEOUT 4
2269 #define TIMEOUT2 10
2270
2271 static jmp_buf timebuf;
2272
2273 /* timeout - handle timeouts */
2274
2275 static void timeout(sig)
2276 int sig;
2277 {
2278 longjmp(timebuf, sig);
2279 }
2280
2281 /* rfc931_name - return remote user name */
2282
2283 char *
2284 rfc931_name(there, ctrl)
2285 struct sockaddr *there; /* remote link information */
2286 int ctrl;
2287 {
2288 struct sockaddr_storage here; /* local link information */
2289 struct sockaddr_storage sin; /* for talking to RFC931 daemon */
2290 int length;
2291 int s;
2292 unsigned remote;
2293 unsigned local;
2294 static char user[256]; /* XXX */
2295 char buf[256];
2296 char *cp;
2297 char *result = "USER_UNKNOWN";
2298 int len;
2299 u_int16_t myport, hisport;
2300
2301 /* Find out local port number of our stdin. */
2302
2303 length = sizeof(here);
2304 if (getsockname(ctrl, (struct sockaddr *) &here, &length) == -1) {
2305 syslog(LOG_ERR, "getsockname: %m");
2306 return (result);
2307 }
2308 switch (here.ss_family) {
2309 case AF_INET:
2310 myport = ((struct sockaddr_in *)&here)->sin_port;
2311 break;
2312 #ifdef INET6
2313 case AF_INET6:
2314 myport = ((struct sockaddr_in6 *)&here)->sin6_port;
2315 break;
2316 #endif
2317 }
2318 switch (there->sa_family) {
2319 case AF_INET:
2320 hisport = ((struct sockaddr_in *)sa)->sin_port;
2321 break;
2322 #ifdef INET6
2323 case AF_INET6:
2324 hisport = ((struct sockaddr_in6 *)sa)->sin6_port;
2325 break;
2326 #endif
2327 }
2328 /* Set up timer so we won't get stuck. */
2329
2330 if ((s = socket(here.ss_family, SOCK_STREAM, 0)) == -1) {
2331 syslog(LOG_ERR, "socket: %m");
2332 return (result);
2333 }
2334
2335 sin = here;
2336 switch (sin.ss_family) {
2337 case AF_INET:
2338 ((struct sockaddr_in *)&sin)->sin_port = htons(0);
2339 break;
2340 #ifdef INET6
2341 case AF_INET6:
2342 ((struct sockaddr_in6 *)&sin)->sin6_port = htons(0);
2343 break;
2344 #endif
2345 }
2346 if (bind(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2347 syslog(LOG_ERR, "bind: %m");
2348 return (result);
2349 }
2350
2351 signal(SIGALRM, timeout);
2352 if (setjmp(timebuf)) {
2353 close(s); /* not: fclose(fp) */
2354 return (result);
2355 }
2356 alarm(TIMEOUT);
2357
2358 /* Connect to the RFC931 daemon. */
2359
2360 memcpy(&sin, there, there->sa_len);
2361 switch (sin.ss_family) {
2362 case AF_INET:
2363 ((struct sockaddr_in *)&sin)->sin_port = htons(RFC931_PORT);
2364 break;
2365 #ifdef INET6
2366 case AF_INET6:
2367 ((struct sockaddr_in6 *)&sin)->sin6_port = htons(RFC931_PORT);
2368 break;
2369 #endif
2370 }
2371 if (connect(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2372 close(s);
2373 alarm(0);
2374 return (result);
2375 }
2376
2377 /* Query the RFC 931 server. Would 13-byte writes ever be broken up? */
2378 (void)snprintf(buf, sizeof buf, "%u,%u\r\n", ntohs(hisport),
2379 ntohs(myport));
2380
2381
2382 for (len = 0, cp = buf; len < strlen(buf); ) {
2383 int n;
2384
2385 if ((n = write(s, cp, strlen(buf) - len)) == -1) {
2386 close(s);
2387 alarm(0);
2388 return (result);
2389 }
2390 cp += n;
2391 len += n;
2392 }
2393
2394 /* Read response */
2395 for (cp = buf; cp < buf + sizeof(buf) - 1; ) {
2396 char c;
2397 if (read(s, &c, 1) != 1) {
2398 close(s);
2399 alarm(0);
2400 return (result);
2401 }
2402 if (c == '\n')
2403 break;
2404 *cp++ = c;
2405 }
2406 *cp = '\0';
2407
2408 if (sscanf(buf, "%u , %u : USERID :%*[^:]:%255s", &remote, &local, user) == 3
2409 && ntohs(hisport) == remote
2410 && ntohs(myport) == local) {
2411
2412 /* Strip trailing carriage return. */
2413 if (cp = strchr(user, '\r'))
2414 *cp = 0;
2415 result = user;
2416 }
2417
2418 alarm(0);
2419 close(s);
2420 return (result);
2421 }
2422 #endif
2423
2424 /*
2425 * check if the port where send data to is one of the obvious ports
2426 * that are used for denial of service attacks like two echo ports
2427 * just echoing data between them
2428 */
2429 int
2430 port_good_dg(sa)
2431 struct sockaddr *sa;
2432 {
2433 u_int16_t port;
2434 int i, bad;
2435 char hbuf[NI_MAXHOST];
2436
2437 bad = 0;
2438
2439 switch (sa->sa_family) {
2440 case AF_INET:
2441 port = ntohs(((struct sockaddr_in *)sa)->sin_port);
2442 break;
2443 #ifdef INET6
2444 case AF_INET6:
2445 port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
2446 break;
2447 #endif
2448 default:
2449 /* XXX unsupported af, is it safe to assume it to be safe? */
2450 return 1;
2451 }
2452
2453 for (i = 0; bad_ports[i] != 0; i++)
2454 if (port == bad_ports[i]) {
2455 bad = 1;
2456 break;
2457 }
2458
2459 if (bad) {
2460 if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf),
2461 NULL, 0, niflags) != 0)
2462 strcpy(hbuf, "?");
2463 syslog(LOG_WARNING,"Possible DoS attack from %s, Port %d",
2464 hbuf, port);
2465 return (0);
2466 } else
2467 return (1);
2468 }
2469
2470