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