inetd.c revision 1.59 1 /* $NetBSD: inetd.c,v 1.59 2000/03/06 19:52:13 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.59 2000/03/06 19:52:13 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 #ifdef IPSEC
1227 static char *policy = NULL;
1228 #endif
1229
1230 int
1231 setconfig()
1232 {
1233 if (defhost)
1234 free(defhost);
1235 defhost = newstr("*");
1236 #ifdef IPSEC
1237 if (policy)
1238 free(policy);
1239 policy = NULL;
1240 #endif
1241 if (fconfig != NULL) {
1242 fseek(fconfig, 0L, SEEK_SET);
1243 return (1);
1244 }
1245 fconfig = fopen(CONFIG, "r");
1246 return (fconfig != NULL);
1247 }
1248
1249 void
1250 endconfig()
1251 {
1252 if (fconfig) {
1253 (void) fclose(fconfig);
1254 fconfig = NULL;
1255 }
1256 if (defhost) {
1257 free(defhost);
1258 defhost = 0;
1259 }
1260 }
1261
1262 struct servtab *
1263 getconfigent()
1264 {
1265 struct servtab *sep = &serv;
1266 int argc, val;
1267 char *cp, *cp0, *arg, *buf0, *buf1, *sz0, *sz1;
1268 static char TCPMUX_TOKEN[] = "tcpmux/";
1269 #define MUX_LEN (sizeof(TCPMUX_TOKEN)-1)
1270 char *hostdelim;
1271
1272 more:
1273 while ((cp = nextline(fconfig))) {
1274 #ifdef IPSEC
1275 /* lines starting with #@ is not a comment, but the policy */
1276 if (cp[0] == '#' && cp[1] == '@') {
1277 char *p;
1278 for (p = cp + 2; p && *p && isspace(*p); p++)
1279 ;
1280 if (*p == '\0') {
1281 if (policy)
1282 free(policy);
1283 policy = NULL;
1284 } else {
1285 if (ipsecsetup_test(p) < 0) {
1286 syslog(LOG_ERR,
1287 "%s: invalid ipsec policy \"%s\"",
1288 CONFIG, p);
1289 exit(-1);
1290 } else {
1291 if (policy)
1292 free(policy);
1293 policy = newstr(p);
1294 }
1295 }
1296 }
1297 #endif
1298 if (*cp == '#' || *cp == '\0')
1299 continue;
1300 #ifdef MULOG
1301 /* Avoid use of `skip' if there is a danger of it looking
1302 * at continuation lines.
1303 */
1304 do {
1305 cp++;
1306 } while (*cp == ' ' || *cp == '\t');
1307 if (*cp == '\0')
1308 continue;
1309 if ((arg = skip(&cp)) == NULL)
1310 continue;
1311 if (strcmp(arg, "DOMAIN"))
1312 continue;
1313 if (curdom)
1314 free(curdom);
1315 curdom = NULL;
1316 while (*cp == ' ' || *cp == '\t')
1317 cp++;
1318 if (*cp == '\0')
1319 continue;
1320 arg = cp;
1321 while (*cp && *cp != ' ' && *cp != '\t')
1322 cp++;
1323 if (*cp != '\0')
1324 *cp++ = '\0';
1325 curdom = newstr(arg);
1326 #endif
1327 break;
1328 }
1329 if (cp == NULL)
1330 return ((struct servtab *)0);
1331 /*
1332 * clear the static buffer, since some fields (se_ctrladdr,
1333 * for example) don't get initialized here.
1334 */
1335 memset((caddr_t)sep, 0, sizeof *sep);
1336 arg = skip(&cp);
1337 if (cp == NULL) {
1338 /* got an empty line containing just blanks/tabs. */
1339 goto more;
1340 }
1341 /* Check for a host name. */
1342 hostdelim = strrchr(arg, ':');
1343 if (hostdelim) {
1344 *hostdelim = '\0';
1345 sep->se_hostaddr = newstr(arg);
1346 arg = hostdelim + 1;
1347 /*
1348 * If the line is of the form `host:', then just change the
1349 * default host for the following lines.
1350 */
1351 if (*arg == '\0') {
1352 arg = skip(&cp);
1353 if (cp == NULL) {
1354 free(defhost);
1355 defhost = sep->se_hostaddr;
1356 goto more;
1357 }
1358 }
1359 } else
1360 sep->se_hostaddr = newstr(defhost);
1361 if (strncmp(arg, TCPMUX_TOKEN, MUX_LEN) == 0) {
1362 char *c = arg + MUX_LEN;
1363 if (*c == '+') {
1364 sep->se_type = MUXPLUS_TYPE;
1365 c++;
1366 } else
1367 sep->se_type = MUX_TYPE;
1368 sep->se_service = newstr(c);
1369 } else {
1370 sep->se_service = newstr(arg);
1371 sep->se_type = NORM_TYPE;
1372 }
1373
1374 arg = sskip(&cp);
1375 if (strcmp(arg, "stream") == 0)
1376 sep->se_socktype = SOCK_STREAM;
1377 else if (strcmp(arg, "dgram") == 0)
1378 sep->se_socktype = SOCK_DGRAM;
1379 else if (strcmp(arg, "rdm") == 0)
1380 sep->se_socktype = SOCK_RDM;
1381 else if (strcmp(arg, "seqpacket") == 0)
1382 sep->se_socktype = SOCK_SEQPACKET;
1383 else if (strcmp(arg, "raw") == 0)
1384 sep->se_socktype = SOCK_RAW;
1385 else
1386 sep->se_socktype = -1;
1387
1388 sep->se_proto = newstr(sskip(&cp));
1389
1390 #define MALFORMED(arg) \
1391 do { \
1392 syslog(LOG_ERR, "%s: malformed buffer size option `%s'", \
1393 sep->se_service, (arg)); \
1394 goto more; \
1395 } while (0)
1396
1397 #define GETVAL(arg) \
1398 do { \
1399 if (!isdigit(*(arg))) \
1400 MALFORMED(arg); \
1401 val = strtol((arg), &cp0, 10); \
1402 if (cp0 != NULL) { \
1403 if (cp0[1] != '\0') \
1404 MALFORMED((arg)); \
1405 if (cp0[0] == 'k') \
1406 val *= 1024; \
1407 if (cp0[0] == 'm') \
1408 val *= 1024 * 1024; \
1409 } \
1410 if (val < 1) { \
1411 syslog(LOG_ERR, "%s: invalid buffer size `%s'", \
1412 sep->se_service, (arg)); \
1413 goto more; \
1414 } \
1415 } while (0)
1416
1417 #define ASSIGN(arg) \
1418 do { \
1419 if (strcmp((arg), "sndbuf") == 0) \
1420 sep->se_sndbuf = val; \
1421 else if (strcmp((arg), "rcvbuf") == 0) \
1422 sep->se_rcvbuf = val; \
1423 else \
1424 MALFORMED((arg)); \
1425 } while (0)
1426
1427 /*
1428 * Extract the send and receive buffer sizes before parsing
1429 * the protocol.
1430 */
1431 sep->se_sndbuf = sep->se_rcvbuf = 0;
1432 buf0 = buf1 = sz0 = sz1 = NULL;
1433 if ((buf0 = strchr(sep->se_proto, ',')) != NULL) {
1434 /* Not meaningful for Tcpmux services. */
1435 if (sep->se_type != NORM_TYPE) {
1436 syslog(LOG_ERR, "%s: can't specify buffer sizes for "
1437 "tcpmux services", sep->se_service);
1438 goto more;
1439 }
1440
1441 /* Skip the , */
1442 *buf0++ = '\0';
1443
1444 /* Check to see if another socket buffer size was specified. */
1445 if ((buf1 = strchr(buf0, ',')) != NULL) {
1446 /* Skip the , */
1447 *buf1++ = '\0';
1448
1449 /* Make sure a 3rd one wasn't specified. */
1450 if (strchr(buf1, ',') != NULL) {
1451 syslog(LOG_ERR, "%s: too many buffer sizes",
1452 sep->se_service);
1453 goto more;
1454 }
1455
1456 /* Locate the size. */
1457 if ((sz1 = strchr(buf1, '=')) == NULL)
1458 MALFORMED(buf1);
1459
1460 /* Skip the = */
1461 *sz1++ = '\0';
1462 }
1463
1464 /* Locate the size. */
1465 if ((sz0 = strchr(buf0, '=')) == NULL)
1466 MALFORMED(buf0);
1467
1468 /* Skip the = */
1469 *sz0++ = '\0';
1470
1471 GETVAL(sz0);
1472 ASSIGN(buf0);
1473
1474 if (buf1 != NULL) {
1475 GETVAL(sz1);
1476 ASSIGN(buf1);
1477 }
1478 }
1479
1480 #undef ASSIGN
1481 #undef GETVAL
1482 #undef MALFORMED
1483
1484 if (strcmp(sep->se_proto, "unix") == 0) {
1485 sep->se_family = AF_LOCAL;
1486 } else {
1487 val = strlen(sep->se_proto);
1488 if (!val) {
1489 syslog(LOG_ERR, "%s: invalid protocol specified",
1490 sep->se_service);
1491 goto more;
1492 }
1493 val = sep->se_proto[val - 1];
1494 switch (val) {
1495 case '4': /*tcp4 or udp4*/
1496 sep->se_family = AF_INET;
1497 break;
1498 #ifdef INET6
1499 case '6': /*tcp6 or udp6*/
1500 sep->se_family = AF_INET6;
1501 break;
1502 #endif
1503 default:
1504 sep->se_family = AF_INET; /*will become AF_INET6*/
1505 break;
1506 }
1507 if (strncmp(sep->se_proto, "rpc/", 4) == 0) {
1508 #ifdef RPC
1509 char *cp, *ccp;
1510 cp = strchr(sep->se_service, '/');
1511 if (cp == 0) {
1512 syslog(LOG_ERR, "%s: no rpc version",
1513 sep->se_service);
1514 goto more;
1515 }
1516 *cp++ = '\0';
1517 sep->se_rpcversl = sep->se_rpcversh =
1518 strtol(cp, &ccp, 0);
1519 if (ccp == cp) {
1520 badafterall:
1521 syslog(LOG_ERR, "%s/%s: bad rpc version",
1522 sep->se_service, cp);
1523 goto more;
1524 }
1525 if (*ccp == '-') {
1526 cp = ccp + 1;
1527 sep->se_rpcversh = strtol(cp, &ccp, 0);
1528 if (ccp == cp)
1529 goto badafterall;
1530 }
1531 #else
1532 syslog(LOG_ERR, "%s: rpc services not suported",
1533 sep->se_service);
1534 goto more;
1535 #endif /* RPC */
1536 }
1537 }
1538 arg = sskip(&cp);
1539 {
1540 char *cp;
1541 if ((cp = strchr(arg, ':')) == NULL)
1542 cp = strchr(arg, '.');
1543 if (cp != NULL) {
1544 *cp++ = '\0';
1545 sep->se_max = atoi(cp);
1546 } else
1547 sep->se_max = TOOMANY;
1548 }
1549 sep->se_wait = strcmp(arg, "wait") == 0;
1550 if (ISMUX(sep)) {
1551 /*
1552 * Silently enforce "nowait" for TCPMUX services since
1553 * they don't have an assigned port to listen on.
1554 */
1555 sep->se_wait = 0;
1556
1557 if (strncmp(sep->se_proto, "tcp", 3)) {
1558 syslog(LOG_ERR,
1559 "%s: bad protocol for tcpmux service %s",
1560 CONFIG, sep->se_service);
1561 goto more;
1562 }
1563 if (sep->se_socktype != SOCK_STREAM) {
1564 syslog(LOG_ERR,
1565 "%s: bad socket type for tcpmux service %s",
1566 CONFIG, sep->se_service);
1567 goto more;
1568 }
1569 }
1570 sep->se_user = newstr(sskip(&cp));
1571 if ((sep->se_group = strchr(sep->se_user, ':')) != NULL)
1572 *sep->se_group++ = '\0';
1573 else if ((sep->se_group = strchr(sep->se_user, '.')) != NULL)
1574 *sep->se_group++ = '\0';
1575
1576 sep->se_server = newstr(sskip(&cp));
1577 if (strcmp(sep->se_server, "internal") == 0) {
1578 struct biltin *bi;
1579
1580 for (bi = biltins; bi->bi_service; bi++)
1581 if (bi->bi_socktype == sep->se_socktype &&
1582 strcmp(bi->bi_service, sep->se_service) == 0)
1583 break;
1584 if (bi->bi_service == 0) {
1585 syslog(LOG_ERR, "internal service %s unknown",
1586 sep->se_service);
1587 goto more;
1588 }
1589 sep->se_bi = bi;
1590 sep->se_wait = bi->bi_wait;
1591 } else
1592 sep->se_bi = NULL;
1593 argc = 0;
1594 for (arg = skip(&cp); cp; arg = skip(&cp)) {
1595 #if MULOG
1596 char *colon;
1597
1598 if (argc == 0 && (colon = strrchr(arg, ':'))) {
1599 while (arg < colon) {
1600 int x;
1601 char *ccp;
1602
1603 switch (*arg++) {
1604 case 'l':
1605 x = 1;
1606 if (isdigit(*arg)) {
1607 x = strtol(arg, &ccp, 0);
1608 if (ccp == arg)
1609 break;
1610 arg = ccp;
1611 }
1612 sep->se_log &= ~MULOG_RFC931;
1613 sep->se_log |= x;
1614 break;
1615 case 'a':
1616 sep->se_log |= MULOG_RFC931;
1617 break;
1618 default:
1619 break;
1620 }
1621 }
1622 arg = colon + 1;
1623 }
1624 #endif
1625 if (argc < MAXARGV)
1626 sep->se_argv[argc++] = newstr(arg);
1627 }
1628 while (argc <= MAXARGV)
1629 sep->se_argv[argc++] = NULL;
1630 #ifdef IPSEC
1631 sep->se_policy = policy ? newstr(policy) : NULL;
1632 #endif
1633 return (sep);
1634 }
1635
1636 void
1637 freeconfig(cp)
1638 struct servtab *cp;
1639 {
1640 int i;
1641
1642 if (cp->se_hostaddr)
1643 free(cp->se_hostaddr);
1644 if (cp->se_service)
1645 free(cp->se_service);
1646 if (cp->se_proto)
1647 free(cp->se_proto);
1648 if (cp->se_user)
1649 free(cp->se_user);
1650 /* Note: se_group is part of the newstr'ed se_user */
1651 if (cp->se_server)
1652 free(cp->se_server);
1653 for (i = 0; i < MAXARGV; i++)
1654 if (cp->se_argv[i])
1655 free(cp->se_argv[i]);
1656 #ifdef IPSEC
1657 if (cp->se_policy)
1658 free(cp->se_policy);
1659 #endif
1660 }
1661
1662
1663 /*
1664 * Safe skip - if skip returns null, log a syntax error in the
1665 * configuration file and exit.
1666 */
1667 char *
1668 sskip(cpp)
1669 char **cpp;
1670 {
1671 char *cp;
1672
1673 cp = skip(cpp);
1674 if (cp == NULL) {
1675 syslog(LOG_ERR, "%s: syntax error", CONFIG);
1676 exit(-1);
1677 }
1678 return (cp);
1679 }
1680
1681 char *
1682 skip(cpp)
1683 char **cpp;
1684 {
1685 char *cp = *cpp;
1686 char *start;
1687
1688 if (*cpp == NULL)
1689 return ((char *)0);
1690
1691 again:
1692 while (*cp == ' ' || *cp == '\t')
1693 cp++;
1694 if (*cp == '\0') {
1695 int c;
1696
1697 c = getc(fconfig);
1698 (void) ungetc(c, fconfig);
1699 if (c == ' ' || c == '\t')
1700 if ((cp = nextline(fconfig)))
1701 goto again;
1702 *cpp = (char *)0;
1703 return ((char *)0);
1704 }
1705 start = cp;
1706 while (*cp && *cp != ' ' && *cp != '\t')
1707 cp++;
1708 if (*cp != '\0')
1709 *cp++ = '\0';
1710 *cpp = cp;
1711 return (start);
1712 }
1713
1714 char *
1715 nextline(fd)
1716 FILE *fd;
1717 {
1718 char *cp;
1719
1720 if (fgets(line, sizeof (line), fd) == NULL)
1721 return ((char *)0);
1722 cp = strchr(line, '\n');
1723 if (cp)
1724 *cp = '\0';
1725 return (line);
1726 }
1727
1728 char *
1729 newstr(cp)
1730 char *cp;
1731 {
1732 if ((cp = strdup(cp ? cp : "")))
1733 return (cp);
1734 syslog(LOG_ERR, "strdup: %m");
1735 exit(-1);
1736 }
1737
1738 void
1739 inetd_setproctitle(a, s)
1740 char *a;
1741 int s;
1742 {
1743 int size;
1744 char *cp;
1745 struct sockaddr_storage ss;
1746 char buf[80];
1747 char hbuf[NI_MAXHOST];
1748
1749 cp = Argv[0];
1750 size = sizeof(ss);
1751 if (getpeername(s, (struct sockaddr *)&ss, &size) == 0) {
1752 if (getnameinfo((struct sockaddr *)&ss, ss.ss_len,
1753 hbuf, sizeof(hbuf), NULL, 0, niflags) != 0)
1754 strcpy(hbuf, "?");
1755 (void)snprintf(buf, sizeof buf, "-%s [%s]", a, hbuf);
1756 } else
1757 (void)snprintf(buf, sizeof buf, "-%s", a);
1758 strncpy(cp, buf, LastArg - cp);
1759 cp += strlen(cp);
1760 while (cp < LastArg)
1761 *cp++ = ' ';
1762 }
1763
1764 void
1765 bump_nofile()
1766 {
1767 #ifdef RLIMIT_NOFILE
1768
1769 #define FD_CHUNK 32
1770
1771 struct rlimit rl;
1772
1773 if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
1774 syslog(LOG_ERR, "getrlimit: %m");
1775 return;
1776 }
1777 rl.rlim_cur = MIN(rl.rlim_max, rl.rlim_cur + FD_CHUNK);
1778 if (rl.rlim_cur <= rlim_ofile_cur) {
1779 syslog(LOG_ERR,
1780 "bump_nofile: cannot extend file limit, max = %d",
1781 (int)rl.rlim_cur);
1782 return;
1783 }
1784
1785 if (setrlimit(RLIMIT_NOFILE, &rl) < 0) {
1786 syslog(LOG_ERR, "setrlimit: %m");
1787 return;
1788 }
1789
1790 rlim_ofile_cur = rl.rlim_cur;
1791 return;
1792
1793 #else
1794 syslog(LOG_ERR, "bump_nofile: cannot extend file limit");
1795 return;
1796 #endif
1797 }
1798
1799 /*
1800 * Internet services provided internally by inetd:
1801 */
1802 #define BUFSIZE 4096
1803
1804 /* ARGSUSED */
1805 void
1806 echo_stream(s, sep) /* Echo service -- echo data back */
1807 int s;
1808 struct servtab *sep;
1809 {
1810 char buffer[BUFSIZE];
1811 int i;
1812
1813 inetd_setproctitle(sep->se_service, s);
1814 while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
1815 write(s, buffer, i) > 0)
1816 ;
1817 }
1818
1819 /* ARGSUSED */
1820 void
1821 echo_dg(s, sep) /* Echo service -- echo data back */
1822 int s;
1823 struct servtab *sep;
1824 {
1825 char buffer[BUFSIZE];
1826 int i, size;
1827 struct sockaddr_storage ss;
1828 struct sockaddr *sa;
1829
1830 sa = (struct sockaddr *)&ss;
1831 size = sizeof(ss);
1832 if ((i = recvfrom(s, buffer, sizeof(buffer), 0, sa, &size)) < 0)
1833 return;
1834 if (port_good_dg(sa))
1835 (void) sendto(s, buffer, i, 0, sa, size);
1836 }
1837
1838 /* ARGSUSED */
1839 void
1840 discard_stream(s, sep) /* Discard service -- ignore data */
1841 int s;
1842 struct servtab *sep;
1843 {
1844 char buffer[BUFSIZE];
1845
1846 inetd_setproctitle(sep->se_service, s);
1847 while ((errno = 0, read(s, buffer, sizeof(buffer)) > 0) ||
1848 errno == EINTR)
1849 ;
1850 }
1851
1852 /* ARGSUSED */
1853 void
1854 discard_dg(s, sep) /* Discard service -- ignore data */
1855 int s;
1856 struct servtab *sep;
1857 {
1858 char buffer[BUFSIZE];
1859
1860 (void) read(s, buffer, sizeof(buffer));
1861 }
1862
1863 #include <ctype.h>
1864 #define LINESIZ 72
1865 char ring[128];
1866 char *endring;
1867
1868 void
1869 initring()
1870 {
1871 int i;
1872
1873 endring = ring;
1874
1875 for (i = 0; i <= 128; ++i)
1876 if (isprint(i))
1877 *endring++ = i;
1878 }
1879
1880 /* ARGSUSED */
1881 void
1882 chargen_stream(s, sep) /* Character generator */
1883 int s;
1884 struct servtab *sep;
1885 {
1886 int len;
1887 char *rs, text[LINESIZ+2];
1888
1889 inetd_setproctitle(sep->se_service, s);
1890
1891 if (!endring) {
1892 initring();
1893 rs = ring;
1894 }
1895
1896 text[LINESIZ] = '\r';
1897 text[LINESIZ + 1] = '\n';
1898 for (rs = ring;;) {
1899 if ((len = endring - rs) >= LINESIZ)
1900 memmove(text, rs, LINESIZ);
1901 else {
1902 memmove(text, rs, len);
1903 memmove(text + len, ring, LINESIZ - len);
1904 }
1905 if (++rs == endring)
1906 rs = ring;
1907 if (write(s, text, sizeof(text)) != sizeof(text))
1908 break;
1909 }
1910 }
1911
1912 /* ARGSUSED */
1913 void
1914 chargen_dg(s, sep) /* Character generator */
1915 int s;
1916 struct servtab *sep;
1917 {
1918 struct sockaddr_storage ss;
1919 struct sockaddr *sa;
1920 static char *rs;
1921 int len, size;
1922 char text[LINESIZ+2];
1923
1924 if (endring == 0) {
1925 initring();
1926 rs = ring;
1927 }
1928
1929 sa = (struct sockaddr *)&ss;
1930 size = sizeof(ss);
1931 if (recvfrom(s, text, sizeof(text), 0, sa, &size) < 0)
1932 return;
1933
1934 if (!port_good_dg(sa))
1935 return;
1936
1937 if ((len = endring - rs) >= LINESIZ)
1938 memmove(text, rs, LINESIZ);
1939 else {
1940 memmove(text, rs, len);
1941 memmove(text + len, ring, LINESIZ - len);
1942 }
1943 if (++rs == endring)
1944 rs = ring;
1945 text[LINESIZ] = '\r';
1946 text[LINESIZ + 1] = '\n';
1947 (void) sendto(s, text, sizeof(text), 0, sa, size);
1948 }
1949
1950 /*
1951 * Return a machine readable date and time, in the form of the
1952 * number of seconds since midnight, Jan 1, 1900. Since gettimeofday
1953 * returns the number of seconds since midnight, Jan 1, 1970,
1954 * we must add 2208988800 seconds to this figure to make up for
1955 * some seventy years Bell Labs was asleep.
1956 */
1957
1958 long
1959 machtime()
1960 {
1961 struct timeval tv;
1962
1963 if (gettimeofday(&tv, (struct timezone *)0) < 0) {
1964 if (debug)
1965 fprintf(stderr, "Unable to get time of day\n");
1966 return (0L);
1967 }
1968 #define OFFSET ((u_long)25567 * 24*60*60)
1969 return (htonl((long)(tv.tv_sec + OFFSET)));
1970 #undef OFFSET
1971 }
1972
1973 /* ARGSUSED */
1974 void
1975 machtime_stream(s, sep)
1976 int s;
1977 struct servtab *sep;
1978 {
1979 long result;
1980
1981 result = machtime();
1982 (void) write(s, (char *) &result, sizeof(result));
1983 }
1984
1985 /* ARGSUSED */
1986 void
1987 machtime_dg(s, sep)
1988 int s;
1989 struct servtab *sep;
1990 {
1991 long result;
1992 struct sockaddr_storage ss;
1993 struct sockaddr *sa;
1994 int size;
1995
1996 sa = (struct sockaddr *)&ss;
1997 size = sizeof(ss);
1998 if (recvfrom(s, (char *)&result, sizeof(result), 0, sa, &size) < 0)
1999 return;
2000 if (!port_good_dg(sa))
2001 return;
2002 result = machtime();
2003 (void) sendto(s, (char *) &result, sizeof(result), 0, sa, size);
2004 }
2005
2006 /* ARGSUSED */
2007 void
2008 daytime_stream(s, sep) /* Return human-readable time of day */
2009 int s;
2010 struct servtab *sep;
2011 {
2012 char buffer[256];
2013 time_t clock;
2014 int len;
2015
2016 clock = time((time_t *) 0);
2017
2018 len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2019 (void) write(s, buffer, len);
2020 }
2021
2022 /* ARGSUSED */
2023 void
2024 daytime_dg(s, sep) /* Return human-readable time of day */
2025 int s;
2026 struct servtab *sep;
2027 {
2028 char buffer[256];
2029 time_t clock;
2030 struct sockaddr_storage ss;
2031 struct sockaddr *sa;
2032 int size, len;
2033
2034 clock = time((time_t *) 0);
2035
2036 sa = (struct sockaddr *)&ss;
2037 size = sizeof(ss);
2038 if (recvfrom(s, buffer, sizeof(buffer), 0, sa, &size) < 0)
2039 return;
2040 if (!port_good_dg(sa))
2041 return;
2042 len = snprintf(buffer, sizeof buffer, "%.24s\r\n", ctime(&clock));
2043 (void) sendto(s, buffer, len, 0, sa, size);
2044 }
2045
2046 /*
2047 * print_service:
2048 * Dump relevant information to stderr
2049 */
2050 void
2051 print_service(action, sep)
2052 char *action;
2053 struct servtab *sep;
2054 {
2055 if (isrpcservice(sep))
2056 fprintf(stderr,
2057 "%s: %s rpcprog=%d, rpcvers = %d/%d, proto=%s, wait:max=%d.%d, user:group=%s.%s builtin=%lx server=%s"
2058 #ifdef IPSEC
2059 " policy=\"%s\""
2060 #endif
2061 "\n",
2062 action, sep->se_service,
2063 sep->se_rpcprog, sep->se_rpcversh, sep->se_rpcversl, sep->se_proto,
2064 sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2065 (long)sep->se_bi, sep->se_server
2066 #ifdef IPSEC
2067 , (sep->se_policy ? sep->se_policy : "")
2068 #endif
2069 );
2070 else
2071 fprintf(stderr,
2072 "%s: %s proto=%s, wait:max=%d.%d, user:group=%s.%s builtin=%lx server=%s"
2073 #ifdef IPSEC
2074 " policy=%s"
2075 #endif
2076 "\n",
2077 action, sep->se_service, sep->se_proto,
2078 sep->se_wait, sep->se_max, sep->se_user, sep->se_group,
2079 (long)sep->se_bi, sep->se_server
2080 #ifdef IPSEC
2081 , (sep->se_policy ? sep->se_policy : "")
2082 #endif
2083 );
2084 }
2085
2086 void
2087 usage()
2088 {
2089
2090 #ifdef LIBWRAP
2091 (void)fprintf(stderr, "usage: %s [-dl] [conf]\n", __progname);
2092 #else
2093 (void)fprintf(stderr, "usage: %s [-d] [conf]\n", __progname);
2094 #endif
2095 exit(1);
2096 }
2097
2098
2099 /*
2100 * Based on TCPMUX.C by Mark K. Lottor November 1988
2101 * sri-nic::ps:<mkl>tcpmux.c
2102 */
2103
2104 static int /* # of characters upto \r,\n or \0 */
2105 getline(fd, buf, len)
2106 int fd;
2107 char *buf;
2108 int len;
2109 {
2110 int count = 0, n;
2111
2112 do {
2113 n = read(fd, buf, len-count);
2114 if (n == 0)
2115 return (count);
2116 if (n < 0)
2117 return (-1);
2118 while (--n >= 0) {
2119 if (*buf == '\r' || *buf == '\n' || *buf == '\0')
2120 return (count);
2121 count++;
2122 buf++;
2123 }
2124 } while (count < len);
2125 return (count);
2126 }
2127
2128 #define MAX_SERV_LEN (256+2) /* 2 bytes for \r\n */
2129
2130 #define strwrite(fd, buf) (void) write(fd, buf, sizeof(buf)-1)
2131
2132 void
2133 tcpmux(ctrl, sep)
2134 int ctrl;
2135 struct servtab *sep;
2136 {
2137 char service[MAX_SERV_LEN+1];
2138 int len;
2139
2140 /* Get requested service name */
2141 if ((len = getline(ctrl, service, MAX_SERV_LEN)) < 0) {
2142 strwrite(ctrl, "-Error reading service name\r\n");
2143 goto reject;
2144 }
2145 service[len] = '\0';
2146
2147 if (debug)
2148 fprintf(stderr, "tcpmux: someone wants %s\n", service);
2149
2150 /*
2151 * Help is a required command, and lists available services,
2152 * one per line.
2153 */
2154 if (!strcasecmp(service, "help")) {
2155 strwrite(ctrl, "+Available services:\r\n");
2156 strwrite(ctrl, "help\r\n");
2157 for (sep = servtab; sep; sep = sep->se_next) {
2158 if (!ISMUX(sep))
2159 continue;
2160 (void)write(ctrl, sep->se_service,
2161 strlen(sep->se_service));
2162 strwrite(ctrl, "\r\n");
2163 }
2164 goto reject;
2165 }
2166
2167 /* Try matching a service in inetd.conf with the request */
2168 for (sep = servtab; sep; sep = sep->se_next) {
2169 if (!ISMUX(sep))
2170 continue;
2171 if (!strcasecmp(service, sep->se_service)) {
2172 if (ISMUXPLUS(sep))
2173 strwrite(ctrl, "+Go\r\n");
2174 run_service(ctrl, sep);
2175 return;
2176 }
2177 }
2178 strwrite(ctrl, "-Service not available\r\n");
2179 reject:
2180 _exit(1);
2181 }
2182
2183
2184 #ifdef MULOG
2185 dolog(sep, ctrl)
2186 struct servtab *sep;
2187 int ctrl;
2188 {
2189 struct sockaddr_storage ss;
2190 struct sockaddr *sa = (struct sockaddr *)&ss;
2191 struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
2192 int len = sizeof(ss);
2193 struct hostent *hp;
2194 char *host, *dp, buf[BUFSIZ], *rfc931_name();
2195 int connected = 1;
2196
2197 switch (sep->se_family) {
2198 case AF_INET:
2199 #ifdef INET6
2200 case AF_INET6:
2201 #endif
2202 break;
2203 default;
2204 return;
2205 }
2206
2207 if (getpeername(ctrl, sa, &len) < 0) {
2208 if (errno != ENOTCONN) {
2209 syslog(LOG_ERR, "getpeername: %m");
2210 return;
2211 }
2212 if (recvfrom(ctrl, buf, sizeof(buf), MSG_PEEK, sa, &len) < 0) {
2213 syslog(LOG_ERR, "recvfrom: %m");
2214 return;
2215 }
2216 connected = 0;
2217 }
2218 switch (sa->sa_family) {
2219 case AF_INET:
2220 #ifdef INET6
2221 case AF_INET6:
2222 #endif
2223 break;
2224 default;
2225 syslog(LOG_ERR, "unexpected address family %u", sa->sa_family);
2226 return;
2227 }
2228
2229 if (getnameinfo(sa, sa->sa_len, buf, sizeof(buf), NULL, 0, 0) != 0)
2230 strcpy(buf, "?");
2231 host = buf;
2232
2233 switch (sep->se_log & ~MULOG_RFC931) {
2234 case 0:
2235 return;
2236 case 1:
2237 if (curdom == NULL || *curdom == '\0')
2238 break;
2239 dp = host + strlen(host) - strlen(curdom);
2240 if (dp < host)
2241 break;
2242 if (debug)
2243 fprintf(stderr, "check \"%s\" against curdom \"%s\"\n",
2244 host, curdom);
2245 if (strcasecmp(dp, curdom) == 0)
2246 return;
2247 break;
2248 case 2:
2249 default:
2250 break;
2251 }
2252
2253 openlog("", LOG_NOWAIT, MULOG);
2254
2255 if (connected && (sep->se_log & MULOG_RFC931))
2256 syslog(LOG_INFO, "%s@%s wants %s",
2257 rfc931_name(sa, ctrl), host, sep->se_service);
2258 else
2259 syslog(LOG_INFO, "%s wants %s",
2260 host, sep->se_service);
2261 }
2262
2263 /*
2264 * From tcp_log by
2265 * Wietse Venema, Eindhoven University of Technology, The Netherlands.
2266 */
2267 #if 0
2268 static char sccsid[] = "@(#) rfc931.c 1.3 92/08/31 22:54:46";
2269 #endif
2270
2271 #include <setjmp.h>
2272
2273 #define RFC931_PORT 113 /* Semi-well-known port */
2274 #define TIMEOUT 4
2275 #define TIMEOUT2 10
2276
2277 static jmp_buf timebuf;
2278
2279 /* timeout - handle timeouts */
2280
2281 static void timeout(sig)
2282 int sig;
2283 {
2284 longjmp(timebuf, sig);
2285 }
2286
2287 /* rfc931_name - return remote user name */
2288
2289 char *
2290 rfc931_name(there, ctrl)
2291 struct sockaddr *there; /* remote link information */
2292 int ctrl;
2293 {
2294 struct sockaddr_storage here; /* local link information */
2295 struct sockaddr_storage sin; /* for talking to RFC931 daemon */
2296 int length;
2297 int s;
2298 unsigned remote;
2299 unsigned local;
2300 static char user[256]; /* XXX */
2301 char buf[256];
2302 char *cp;
2303 char *result = "USER_UNKNOWN";
2304 int len;
2305 u_int16_t myport, hisport;
2306
2307 /* Find out local port number of our stdin. */
2308
2309 length = sizeof(here);
2310 if (getsockname(ctrl, (struct sockaddr *) &here, &length) == -1) {
2311 syslog(LOG_ERR, "getsockname: %m");
2312 return (result);
2313 }
2314 switch (here.ss_family) {
2315 case AF_INET:
2316 myport = ((struct sockaddr_in *)&here)->sin_port;
2317 break;
2318 #ifdef INET6
2319 case AF_INET6:
2320 myport = ((struct sockaddr_in6 *)&here)->sin6_port;
2321 break;
2322 #endif
2323 }
2324 switch (there->sa_family) {
2325 case AF_INET:
2326 hisport = ((struct sockaddr_in *)sa)->sin_port;
2327 break;
2328 #ifdef INET6
2329 case AF_INET6:
2330 hisport = ((struct sockaddr_in6 *)sa)->sin6_port;
2331 break;
2332 #endif
2333 }
2334 /* Set up timer so we won't get stuck. */
2335
2336 if ((s = socket(here.ss_family, SOCK_STREAM, 0)) == -1) {
2337 syslog(LOG_ERR, "socket: %m");
2338 return (result);
2339 }
2340
2341 sin = here;
2342 switch (sin.ss_family) {
2343 case AF_INET:
2344 ((struct sockaddr_in *)&sin)->sin_port = htons(0);
2345 break;
2346 #ifdef INET6
2347 case AF_INET6:
2348 ((struct sockaddr_in6 *)&sin)->sin6_port = htons(0);
2349 break;
2350 #endif
2351 }
2352 if (bind(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2353 syslog(LOG_ERR, "bind: %m");
2354 return (result);
2355 }
2356
2357 signal(SIGALRM, timeout);
2358 if (setjmp(timebuf)) {
2359 close(s); /* not: fclose(fp) */
2360 return (result);
2361 }
2362 alarm(TIMEOUT);
2363
2364 /* Connect to the RFC931 daemon. */
2365
2366 memcpy(&sin, there, there->sa_len);
2367 switch (sin.ss_family) {
2368 case AF_INET:
2369 ((struct sockaddr_in *)&sin)->sin_port = htons(RFC931_PORT);
2370 break;
2371 #ifdef INET6
2372 case AF_INET6:
2373 ((struct sockaddr_in6 *)&sin)->sin6_port = htons(RFC931_PORT);
2374 break;
2375 #endif
2376 }
2377 if (connect(s, (struct sockaddr *) &sin, sin.ss_len) == -1) {
2378 close(s);
2379 alarm(0);
2380 return (result);
2381 }
2382
2383 /* Query the RFC 931 server. Would 13-byte writes ever be broken up? */
2384 (void)snprintf(buf, sizeof buf, "%u,%u\r\n", ntohs(hisport),
2385 ntohs(myport));
2386
2387
2388 for (len = 0, cp = buf; len < strlen(buf); ) {
2389 int n;
2390
2391 if ((n = write(s, cp, strlen(buf) - len)) == -1) {
2392 close(s);
2393 alarm(0);
2394 return (result);
2395 }
2396 cp += n;
2397 len += n;
2398 }
2399
2400 /* Read response */
2401 for (cp = buf; cp < buf + sizeof(buf) - 1; ) {
2402 char c;
2403 if (read(s, &c, 1) != 1) {
2404 close(s);
2405 alarm(0);
2406 return (result);
2407 }
2408 if (c == '\n')
2409 break;
2410 *cp++ = c;
2411 }
2412 *cp = '\0';
2413
2414 if (sscanf(buf, "%u , %u : USERID :%*[^:]:%255s", &remote, &local, user) == 3
2415 && ntohs(hisport) == remote
2416 && ntohs(myport) == local) {
2417
2418 /* Strip trailing carriage return. */
2419 if (cp = strchr(user, '\r'))
2420 *cp = 0;
2421 result = user;
2422 }
2423
2424 alarm(0);
2425 close(s);
2426 return (result);
2427 }
2428 #endif
2429
2430 /*
2431 * check if the port where send data to is one of the obvious ports
2432 * that are used for denial of service attacks like two echo ports
2433 * just echoing data between them
2434 */
2435 int
2436 port_good_dg(sa)
2437 struct sockaddr *sa;
2438 {
2439 u_int16_t port;
2440 int i, bad;
2441 char hbuf[NI_MAXHOST];
2442
2443 bad = 0;
2444
2445 switch (sa->sa_family) {
2446 case AF_INET:
2447 port = ntohs(((struct sockaddr_in *)sa)->sin_port);
2448 break;
2449 #ifdef INET6
2450 case AF_INET6:
2451 port = ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
2452 break;
2453 #endif
2454 default:
2455 /* XXX unsupported af, is it safe to assume it to be safe? */
2456 return 1;
2457 }
2458
2459 for (i = 0; bad_ports[i] != 0; i++)
2460 if (port == bad_ports[i]) {
2461 bad = 1;
2462 break;
2463 }
2464
2465 if (bad) {
2466 if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf),
2467 NULL, 0, niflags) != 0)
2468 strcpy(hbuf, "?");
2469 syslog(LOG_WARNING,"Possible DoS attack from %s, Port %d",
2470 hbuf, port);
2471 return (0);
2472 } else
2473 return (1);
2474 }
2475
2476