xref: /dragonfly/usr.sbin/inetd/builtins.c (revision 2cd2d2b5)
1 /*-
2  * Copyright (c) 1983, 1991, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/usr.sbin/inetd/builtins.c,v 1.19.2.7 2002/07/22 14:05:56 fanf Exp $
27  * $DragonFly: src/usr.sbin/inetd/builtins.c,v 1.4 2003/11/16 15:17:36 eirikn Exp $
28  *
29  */
30 
31 #include <sys/filio.h>
32 #include <sys/ioccom.h>
33 #include <sys/param.h>
34 #include <sys/stat.h>
35 #include <sys/socket.h>
36 #include <sys/sysctl.h>
37 #include <sys/ucred.h>
38 #include <sys/uio.h>
39 #include <sys/utsname.h>
40 
41 #include <ctype.h>
42 #include <err.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <limits.h>
46 #include <pwd.h>
47 #include <signal.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sysexits.h>
51 #include <syslog.h>
52 #include <unistd.h>
53 
54 #include "inetd.h"
55 
56 void		chargen_dg(int, struct servtab *);
57 void		chargen_stream(int, struct servtab *);
58 void		daytime_dg(int, struct servtab *);
59 void		daytime_stream(int, struct servtab *);
60 void		discard_dg(int, struct servtab *);
61 void		discard_stream(int, struct servtab *);
62 void		echo_dg(int, struct servtab *);
63 void		echo_stream(int, struct servtab *);
64 static int	getline(int, char *, int);
65 void		iderror(int, int, int, const char *);
66 void		ident_stream(int, struct servtab *);
67 void		initring(void);
68 unsigned long	machtime(void);
69 void		machtime_dg(int, struct servtab *);
70 void		machtime_stream(int, struct servtab *);
71 
72 char ring[128];
73 char *endring;
74 
75 
76 struct biltin biltins[] = {
77 	/* Echo received data */
78 	{ "echo",	SOCK_STREAM,	1, -1,	echo_stream },
79 	{ "echo",	SOCK_DGRAM,	0, 1,	echo_dg },
80 
81 	/* Internet /dev/null */
82 	{ "discard",	SOCK_STREAM,	1, -1,	discard_stream },
83 	{ "discard",	SOCK_DGRAM,	0, 1,	discard_dg },
84 
85 	/* Return 32 bit time since 1900 */
86 	{ "time",	SOCK_STREAM,	0, -1,	machtime_stream },
87 	{ "time",	SOCK_DGRAM,	0, 1,	machtime_dg },
88 
89 	/* Return human-readable time */
90 	{ "daytime",	SOCK_STREAM,	0, -1,	daytime_stream },
91 	{ "daytime",	SOCK_DGRAM,	0, 1,	daytime_dg },
92 
93 	/* Familiar character generator */
94 	{ "chargen",	SOCK_STREAM,	1, -1,	chargen_stream },
95 	{ "chargen",	SOCK_DGRAM,	0, 1,	chargen_dg },
96 
97 	{ "tcpmux",	SOCK_STREAM,	1, -1,	(bi_fn_t *)tcpmux },
98 
99 	{ "auth",	SOCK_STREAM,	1, -1,	ident_stream },
100 
101 	{ NULL,		0,		0, 0,	NULL }
102 };
103 
104 /*
105  * RFC864 Character Generator Protocol. Generates character data without
106  * any regard for input.
107  */
108 
109 void
110 initring(void)
111 {
112 	int i;
113 
114 	endring = ring;
115 
116 	for (i = 0; i <= 128; ++i)
117 		if (isprint(i))
118 			*endring++ = i;
119 }
120 
121 /* ARGSUSED */
122 void
123 chargen_dg(int s, struct servtab *sep)		/* Character generator */
124 {
125 	struct sockaddr_storage ss;
126 	static char *rs;
127 	int len;
128 	socklen_t size;
129 	char text[LINESIZ+2];
130 
131 	if (endring == 0) {
132 		initring();
133 		rs = ring;
134 	}
135 
136 	size = sizeof(ss);
137 	if (recvfrom(s, text, sizeof(text), 0,
138 		     (struct sockaddr *)&ss, &size) < 0)
139 		return;
140 
141 	if (check_loop((struct sockaddr *)&ss, sep))
142 		return;
143 
144 	if ((len = endring - rs) >= LINESIZ)
145 		memmove(text, rs, LINESIZ);
146 	else {
147 		memmove(text, rs, len);
148 		memmove(text + len, ring, LINESIZ - len);
149 	}
150 	if (++rs == endring)
151 		rs = ring;
152 	text[LINESIZ] = '\r';
153 	text[LINESIZ + 1] = '\n';
154 	(void) sendto(s, text, sizeof(text), 0, (struct sockaddr *)&ss, size);
155 }
156 
157 /* ARGSUSED */
158 void
159 chargen_stream(int s, struct servtab *sep)		/* Character generator */
160 {
161 	int len;
162 	char *rs, text[LINESIZ+2];
163 
164 	inetd_setproctitle(sep->se_service, s);
165 
166 	if (!endring) {
167 		initring();
168 		rs = ring;
169 	}
170 
171 	text[LINESIZ] = '\r';
172 	text[LINESIZ + 1] = '\n';
173 	for (rs = ring;;) {
174 		if ((len = endring - rs) >= LINESIZ)
175 			memmove(text, rs, LINESIZ);
176 		else {
177 			memmove(text, rs, len);
178 			memmove(text + len, ring, LINESIZ - len);
179 		}
180 		if (++rs == endring)
181 			rs = ring;
182 		if (write(s, text, sizeof(text)) != sizeof(text))
183 			break;
184 	}
185 	exit(0);
186 }
187 
188 /*
189  * RFC867 Daytime Protocol. Sends the current date and time as an ascii
190  * character string without any regard for input.
191  */
192 
193 /* ARGSUSED */
194 void
195 daytime_dg(int s, struct servtab *sep)		/* Return human-readable time of day */
196 {
197 	char buffer[256];
198 	time_t now;
199 	struct sockaddr_storage ss;
200 	socklen_t size;
201 
202 	now = time((time_t *) 0);
203 
204 	size = sizeof(ss);
205 	if (recvfrom(s, buffer, sizeof(buffer), 0,
206 		     (struct sockaddr *)&ss, &size) < 0)
207 		return;
208 
209 	if (check_loop((struct sockaddr *)&ss, sep))
210 		return;
211 
212 	(void) sprintf(buffer, "%.24s\r\n", ctime(&now));
213 	(void) sendto(s, buffer, strlen(buffer), 0,
214 		      (struct sockaddr *)&ss, size);
215 }
216 
217 /* ARGSUSED */
218 void
219 daytime_stream(int s, struct servtab *sep __unused) /* Return human-readable time of day */
220 {
221 	char buffer[256];
222 	time_t now;
223 
224 	now = time((time_t *) 0);
225 
226 	(void) sprintf(buffer, "%.24s\r\n", ctime(&now));
227 	(void) send(s, buffer, strlen(buffer), MSG_EOF);
228 }
229 
230 /*
231  * RFC863 Discard Protocol. Any data received is thrown away and no response
232  * is sent.
233  */
234 
235 /* ARGSUSED */
236 void
237 discard_dg(int s, struct servtab *sep __unused) /* Discard service -- ignore data */
238 {
239 	char buffer[BUFSIZE];
240 
241 	(void) read(s, buffer, sizeof(buffer));
242 }
243 
244 /* ARGSUSED */
245 void
246 discard_stream(int s, struct servtab *sep) /* Discard service -- ignore data */
247 {
248 	int ret;
249 	char buffer[BUFSIZE];
250 
251 	inetd_setproctitle(sep->se_service, s);
252 	while (1) {
253 		while ((ret = read(s, buffer, sizeof(buffer))) > 0)
254 			;
255 		if (ret == 0 || errno != EINTR)
256 			break;
257 	}
258 	exit(0);
259 }
260 
261 /*
262  * RFC862 Echo Protocol. Any data received is sent back to the sender as
263  * received.
264  */
265 
266 /* ARGSUSED */
267 void
268 echo_dg(int s, struct servtab *sep) /* Echo service -- echo data back */
269 {
270 	char buffer[65536]; /* Should be sizeof(max datagram). */
271 	int i;
272 	socklen_t size;
273 	struct sockaddr_storage ss;
274 
275 	size = sizeof(ss);
276 	if ((i = recvfrom(s, buffer, sizeof(buffer), 0,
277 			  (struct sockaddr *)&ss, &size)) < 0)
278 		return;
279 
280 	if (check_loop((struct sockaddr *)&ss, sep))
281 		return;
282 
283 	(void) sendto(s, buffer, i, 0, (struct sockaddr *)&ss, size);
284 }
285 
286 /* ARGSUSED */
287 void
288 echo_stream(int s, struct servtab *sep)		/* Echo service -- echo data back */
289 {
290 	char buffer[BUFSIZE];
291 	int i;
292 
293 	inetd_setproctitle(sep->se_service, s);
294 	while ((i = read(s, buffer, sizeof(buffer))) > 0 &&
295 	    write(s, buffer, i) > 0)
296 		;
297 	exit(0);
298 }
299 
300 /*
301  * RFC1413 Identification Protocol. Given a TCP port number pair, return a
302  * character string which identifies the owner of that connection on the
303  * server's system. Extended to allow for ~/.fakeid support and ~/.noident
304  * support.
305  */
306 
307 /* RFC 1413 says the following are the only errors you can return. */
308 #define ID_INVALID	"INVALID-PORT"	/* Port number improperly specified. */
309 #define ID_NOUSER	"NO-USER"	/* Port not in use/not identifable. */
310 #define ID_HIDDEN	"HIDDEN-USER"	/* Hiden at user's request. */
311 #define ID_UNKNOWN	"UNKNOWN-ERROR"	/* Everything else. */
312 
313 /* ARGSUSED */
314 void
315 iderror(int lport, int fport, int s, const char *er)	/* Generic ident_stream error-sending func */
316 {
317 	char *p;
318 
319 	asprintf(&p, "%d , %d : ERROR : %s\r\n", lport, fport, er);
320 	if (p == NULL) {
321 		syslog(LOG_ERR, "asprintf: %m");
322 		exit(EX_OSERR);
323 	}
324 	send(s, p, strlen(p), MSG_EOF);
325 	free(p);
326 
327 	exit(0);
328 }
329 
330 /* ARGSUSED */
331 void
332 ident_stream(int s, struct servtab *sep)		/* Ident service (AKA "auth") */
333 {
334 	struct utsname un;
335 	struct stat sb;
336 	struct sockaddr_in sin4[2];
337 #ifdef INET6
338 	struct sockaddr_in6 sin6[2];
339 #endif
340 	struct sockaddr_storage ss[2];
341 	struct ucred uc;
342 	struct timeval tv = {
343 		10,
344 		0
345 	}, to;
346 	struct passwd *pw = NULL;
347 	fd_set fdset;
348 	char buf[BUFSIZE], *p, **av, *osname = NULL, e;
349 	char idbuf[MAXLOGNAME] = ""; /* Big enough to hold uid in decimal. */
350 	socklen_t socklen;
351 	ssize_t ssize;
352 	size_t size, bufsiz;
353 	int c, fflag = 0, nflag = 0, rflag = 0, argc = 0;
354 	int gflag = 0, iflag = 0, Fflag = 0, getcredfail = 0, onreadlen;
355 	u_short lport, fport;
356 
357 	inetd_setproctitle(sep->se_service, s);
358 	/*
359 	 * Reset getopt() since we are a fork() but not an exec() from
360 	 * a parent which used getopt() already.
361 	 */
362 	optind = 1;
363 	optreset = 1;
364 	/*
365 	 * Take the internal argument vector and count it out to make an
366 	 * argument count for getopt. This can be used for any internal
367 	 * service to read arguments and use getopt() easily.
368 	 */
369 	for (av = sep->se_argv; *av; av++)
370 		argc++;
371 	if (argc) {
372 		int sec, usec;
373 		size_t i;
374 		u_int32_t rnd32;
375 
376 		while ((c = getopt(argc, sep->se_argv, "d:fFgino:rt:")) != -1)
377 			switch (c) {
378 			case 'd':
379 				if (!gflag)
380 					strlcpy(idbuf, optarg, sizeof(idbuf));
381 				break;
382 			case 'f':
383 				fflag = 1;
384 				break;
385 			case 'F':
386 				fflag = 1;
387 				Fflag=1;
388 				break;
389 			case 'g':
390 				gflag = 1;
391 				rnd32 = 0;	/* Shush, compiler. */
392 				/*
393 				 * The number of bits in "rnd32" divided
394 				 * by the number of bits needed per iteration
395 				 * gives a more optimal way to reload the
396 				 * random number only when necessary.
397 				 *
398 				 * 32 bits from arc4random corresponds to
399 				 * about 6 base-36 digits, so we reseed evey 6.
400 				 */
401 				for (i = 0; i < sizeof(idbuf) - 1; i++) {
402 					static const char *const base36 =
403 					    "0123456789"
404 					    "abcdefghijklmnopqrstuvwxyz";
405 					if (i % 6 == 0)
406 						rnd32 = arc4random();
407 					idbuf[i] = base36[rnd32 % 36];
408 					rnd32 /= 36;
409 				}
410 				idbuf[i] = '\0';
411 				break;
412 			case 'i':
413 				iflag = 1;
414 				break;
415 			case 'n':
416 				nflag = 1;
417 				break;
418 			case 'o':
419 				osname = optarg;
420 				break;
421 			case 'r':
422 				rflag = 1;
423 				break;
424 			case 't':
425 				switch (sscanf(optarg, "%d.%d", &sec, &usec)) {
426 				case 2:
427 					tv.tv_usec = usec;
428 					/* FALLTHROUGH */
429 				case 1:
430 					tv.tv_sec = sec;
431 					break;
432 				default:
433 					if (debug)
434 						warnx("bad -t argument");
435 					break;
436 				}
437 				break;
438 			default:
439 				break;
440 			}
441 	}
442 	if (osname == NULL) {
443 		if (uname(&un) == -1)
444 			iderror(0, 0, s, ID_UNKNOWN);
445 		osname = un.sysname;
446 	}
447 
448 	/*
449 	 * We're going to prepare for and execute reception of a
450 	 * packet of data from the user. The data is in the format
451 	 * "local_port , foreign_port\r\n" (with local being the
452 	 * server's port and foreign being the client's.)
453 	 */
454 	gettimeofday(&to, NULL);
455 	to.tv_sec += tv.tv_sec;
456 	to.tv_usec += tv.tv_usec;
457 	if (to.tv_usec >= 1000000) {
458 		to.tv_usec -= 1000000;
459 		to.tv_sec++;
460 	}
461 
462 	size = 0;
463 	bufsiz = sizeof(buf) - 1;
464 	FD_ZERO(&fdset);
465  	while (bufsiz > 0) {
466 		gettimeofday(&tv, NULL);
467 		tv.tv_sec = to.tv_sec - tv.tv_sec;
468 		tv.tv_usec = to.tv_usec - tv.tv_usec;
469 		if (tv.tv_usec < 0) {
470 			tv.tv_usec += 1000000;
471 			tv.tv_sec--;
472 		}
473 		if (tv.tv_sec < 0)
474 			break;
475 		FD_SET(s, &fdset);
476 		if (select(s + 1, &fdset, NULL, NULL, &tv) == -1)
477 			iderror(0, 0, s, ID_UNKNOWN);
478 		if (ioctl(s, FIONREAD, &onreadlen) == -1)
479 			iderror(0, 0, s, ID_UNKNOWN);
480 		if ((size_t)onreadlen > bufsiz)
481 			onreadlen = bufsiz;
482 		ssize = read(s, &buf[size], (size_t)onreadlen);
483 		if (ssize == -1)
484 			iderror(0, 0, s, ID_UNKNOWN);
485 		else if (ssize == 0)
486 			break;
487 		bufsiz -= ssize;
488 		size += ssize;
489 		if (memchr(&buf[size - ssize], '\n', ssize) != NULL)
490 			break;
491  	}
492 	buf[size] = '\0';
493 	/* Read two characters, and check for a delimiting character */
494 	if (sscanf(buf, "%hu , %hu%c", &lport, &fport, &e) != 3 || isdigit(e))
495 		iderror(0, 0, s, ID_INVALID);
496 
497 	/* Send garbage? */
498 	if (gflag)
499 		goto printit;
500 
501 	/*
502 	 * If not "real" (-r), send a HIDDEN-USER error for everything.
503 	 * If -d is used to set a fallback username, this is used to
504 	 * override it, and the fallback is returned instead.
505 	 */
506 	if (!rflag) {
507 		if (*idbuf == '\0')
508 			iderror(lport, fport, s, ID_HIDDEN);
509 		goto printit;
510 	}
511 
512 	/*
513 	 * We take the input and construct an array of two sockaddr_ins
514 	 * which contain the local address information and foreign
515 	 * address information, respectively, used to look up the
516 	 * credentials for the socket (which are returned by the
517 	 * sysctl "net.inet.tcp.getcred" when we call it.)
518 	 */
519 	socklen = sizeof(ss[0]);
520 	if (getsockname(s, (struct sockaddr *)&ss[0], &socklen) == -1)
521 		iderror(lport, fport, s, ID_UNKNOWN);
522 	socklen = sizeof(ss[1]);
523 	if (getpeername(s, (struct sockaddr *)&ss[1], &socklen) == -1)
524 		iderror(lport, fport, s, ID_UNKNOWN);
525 	if (ss[0].ss_family != ss[1].ss_family)
526 		iderror(lport, fport, s, ID_UNKNOWN);
527 	size = sizeof(uc);
528 	switch (ss[0].ss_family) {
529 	case AF_INET:
530 		sin4[0] = *(struct sockaddr_in *)&ss[0];
531 		sin4[0].sin_port = htons(lport);
532 		sin4[1] = *(struct sockaddr_in *)&ss[1];
533 		sin4[1].sin_port = htons(fport);
534 		if (sysctlbyname("net.inet.tcp.getcred", &uc, &size, sin4,
535 				 sizeof(sin4)) == -1)
536 			getcredfail = errno;
537 		break;
538 #ifdef INET6
539 	case AF_INET6:
540 		sin6[0] = *(struct sockaddr_in6 *)&ss[0];
541 		sin6[0].sin6_port = htons(lport);
542 		sin6[1] = *(struct sockaddr_in6 *)&ss[1];
543 		sin6[1].sin6_port = htons(fport);
544 		if (sysctlbyname("net.inet6.tcp6.getcred", &uc, &size, sin6,
545 				 sizeof(sin6)) == -1)
546 			getcredfail = errno;
547 		break;
548 #endif
549 	default: /* should not reach here */
550 		getcredfail = EAFNOSUPPORT;
551 		break;
552 	}
553 	if (getcredfail != 0) {
554 		if (*idbuf == '\0')
555 			iderror(lport, fport, s,
556 			    getcredfail == ENOENT ? ID_NOUSER : ID_UNKNOWN);
557 		goto printit;
558 	}
559 
560 	/* Look up the pw to get the username and home directory*/
561 	errno = 0;
562 	pw = getpwuid(uc.cr_uid);
563 	if (pw == NULL)
564 		iderror(lport, fport, s, errno == 0 ? ID_NOUSER : ID_UNKNOWN);
565 
566 	if (iflag)
567 		snprintf(idbuf, sizeof(idbuf), "%u", (unsigned)pw->pw_uid);
568 	else
569 		strlcpy(idbuf, pw->pw_name, sizeof(idbuf));
570 
571 	/*
572 	 * If enabled, we check for a file named ".noident" in the user's
573 	 * home directory. If found, we return HIDDEN-USER.
574 	 */
575 	if (nflag) {
576 		if (asprintf(&p, "%s/.noident", pw->pw_dir) == -1)
577 			iderror(lport, fport, s, ID_UNKNOWN);
578 		if (lstat(p, &sb) == 0) {
579 			free(p);
580 			iderror(lport, fport, s, ID_HIDDEN);
581 		}
582 		free(p);
583 	}
584 
585 	/*
586 	 * Here, if enabled, we read a user's ".fakeid" file in their
587 	 * home directory. It consists of a line containing the name
588 	 * they want.
589 	 */
590 	if (fflag) {
591 		int fakeid_fd;
592 
593 		/*
594 		 * Here we set ourself to effectively be the user, so we don't
595 		 * open any files we have no permission to open, especially
596 		 * symbolic links to sensitive root-owned files or devices.
597 		 */
598 		if (initgroups(pw->pw_name, pw->pw_gid) == -1)
599 			iderror(lport, fport, s, ID_UNKNOWN);
600 		if (seteuid(pw->pw_uid) == -1)
601 			iderror(lport, fport, s, ID_UNKNOWN);
602 		/*
603 		 * We can't stat() here since that would be a race
604 		 * condition.
605 		 * Therefore, we open the file we have permissions to open
606 		 * and if it's not a regular file, we close it and end up
607 		 * returning the user's real username.
608 		 */
609 		if (asprintf(&p, "%s/.fakeid", pw->pw_dir) == -1)
610 			iderror(lport, fport, s, ID_UNKNOWN);
611 		fakeid_fd = open(p, O_RDONLY | O_NONBLOCK);
612 		free(p);
613 		if (fakeid_fd == -1 || fstat(fakeid_fd, &sb) == -1 ||
614 		    !S_ISREG(sb.st_mode))
615 			goto fakeid_fail;
616 
617 		if ((ssize = read(fakeid_fd, buf, sizeof(buf) - 1)) < 0)
618 			goto fakeid_fail;
619 		buf[ssize] = '\0';
620 
621 		/*
622 		 * Usually, the file will have the desired identity
623 		 * in the form "identity\n". Allow for leading white
624 		 * space and trailing white space/end of line.
625 		 */
626 		p = buf;
627 		p += strspn(p, " \t");
628 		p[strcspn(p, " \t\r\n")] = '\0';
629 		if (strlen(p) > MAXLOGNAME - 1) /* Too long (including nul)? */
630 			p[MAXLOGNAME - 1] = '\0';
631 
632 		/*
633 		 * If the name is a zero-length string or matches it
634 		 * the id or name of another user (unless permitted by -F)
635 		 * then it is invalid.
636 		 */
637 		if (*p == '\0')
638 			goto fakeid_fail;
639 		if (!Fflag) {
640 			if (iflag) {
641 				if (p[strspn(p, "0123456789")] == '\0' &&
642 				    getpwuid(atoi(p)) != NULL)
643 					goto fakeid_fail;
644 			} else {
645 				if (getpwnam(p) != NULL)
646 					goto fakeid_fail;
647 			}
648 		}
649 
650 		strlcpy(idbuf, p, sizeof(idbuf));
651 
652 fakeid_fail:
653 		if (fakeid_fd != -1)
654 			close(fakeid_fd);
655 	}
656 
657 printit:
658 	/* Finally, we make and send the reply. */
659 	if (asprintf(&p, "%d , %d : USERID : %s : %s\r\n", lport, fport, osname,
660 	    idbuf) == -1) {
661 		syslog(LOG_ERR, "asprintf: %m");
662 		exit(EX_OSERR);
663 	}
664 	send(s, p, strlen(p), MSG_EOF);
665 	free(p);
666 
667 	exit(0);
668 }
669 
670 /*
671  * RFC738 Time Server.
672  * Return a machine readable date and time, in the form of the
673  * number of seconds since midnight, Jan 1, 1900.  Since gettimeofday
674  * returns the number of seconds since midnight, Jan 1, 1970,
675  * we must add 2208988800 seconds to this figure to make up for
676  * some seventy years Bell Labs was asleep.
677  */
678 
679 unsigned long
680 machtime(void)
681 {
682 	struct timeval tv;
683 
684 	if (gettimeofday(&tv, (struct timezone *)NULL) < 0) {
685 		if (debug)
686 			warnx("unable to get time of day");
687 		return (0L);
688 	}
689 #define	OFFSET ((u_long)25567 * 24*60*60)
690 	return (htonl((long)(tv.tv_sec + OFFSET)));
691 #undef OFFSET
692 }
693 
694 /* ARGSUSED */
695 void
696 machtime_dg(int s, struct servtab *sep)
697 {
698 	unsigned long result;
699 	struct sockaddr_storage ss;
700 	socklen_t size;
701 
702 	size = sizeof(ss);
703 	if (recvfrom(s, (char *)&result, sizeof(result), 0,
704 		     (struct sockaddr *)&ss, &size) < 0)
705 		return;
706 
707 	if (check_loop((struct sockaddr *)&ss, sep))
708 		return;
709 
710 	result = machtime();
711 	(void) sendto(s, (char *) &result, sizeof(result), 0,
712 		      (struct sockaddr *)&ss, size);
713 }
714 
715 /* ARGSUSED */
716 void
717 machtime_stream(int s, struct servtab *sep __unused)
718 {
719 	unsigned long result;
720 
721 	result = machtime();
722 	(void) send(s, (char *) &result, sizeof(result), MSG_EOF);
723 }
724 
725 /*
726  * RFC1078 TCP Port Service Multiplexer (TCPMUX). Service connections to
727  * services based on the service name sent.
728  *
729  *  Based on TCPMUX.C by Mark K. Lottor November 1988
730  *  sri-nic::ps:<mkl>tcpmux.c
731  */
732 
733 #define MAX_SERV_LEN	(256+2)		/* 2 bytes for \r\n */
734 #define strwrite(fd, buf)	(void) write(fd, buf, sizeof(buf)-1)
735 
736 static int		/* # of characters upto \r,\n or \0 */
737 getline(int fd, char *buf, int len)
738 {
739 	int count = 0, n;
740 	struct sigaction sa;
741 
742 	sa.sa_flags = 0;
743 	sigemptyset(&sa.sa_mask);
744 	sa.sa_handler = SIG_DFL;
745 	sigaction(SIGALRM, &sa, (struct sigaction *)0);
746 	do {
747 		alarm(10);
748 		n = read(fd, buf, len-count);
749 		alarm(0);
750 		if (n == 0)
751 			return (count);
752 		if (n < 0)
753 			return (-1);
754 		while (--n >= 0) {
755 			if (*buf == '\r' || *buf == '\n' || *buf == '\0')
756 				return (count);
757 			count++;
758 			buf++;
759 		}
760 	} while (count < len);
761 	return (count);
762 }
763 
764 struct servtab *
765 tcpmux(int s)
766 {
767 	struct servtab *sep;
768 	char service[MAX_SERV_LEN+1];
769 	int len;
770 
771 	/* Get requested service name */
772 	if ((len = getline(s, service, MAX_SERV_LEN)) < 0) {
773 		strwrite(s, "-Error reading service name\r\n");
774 		return (NULL);
775 	}
776 	service[len] = '\0';
777 
778 	if (debug)
779 		warnx("tcpmux: someone wants %s", service);
780 
781 	/*
782 	 * Help is a required command, and lists available services,
783 	 * one per line.
784 	 */
785 	if (!strcasecmp(service, "help")) {
786 		for (sep = servtab; sep; sep = sep->se_next) {
787 			if (!ISMUX(sep))
788 				continue;
789 			(void)write(s,sep->se_service,strlen(sep->se_service));
790 			strwrite(s, "\r\n");
791 		}
792 		return (NULL);
793 	}
794 
795 	/* Try matching a service in inetd.conf with the request */
796 	for (sep = servtab; sep; sep = sep->se_next) {
797 		if (!ISMUX(sep))
798 			continue;
799 		if (!strcasecmp(service, sep->se_service)) {
800 			if (ISMUXPLUS(sep)) {
801 				strwrite(s, "+Go\r\n");
802 			}
803 			return (sep);
804 		}
805 	}
806 	strwrite(s, "-Service not available\r\n");
807 	return (NULL);
808 }
809