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