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