xref: /csrg-svn/usr.sbin/sendmail/src/daemon.c (revision 64035)
1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #include <errno.h>
10 #include "sendmail.h"
11 
12 #ifndef lint
13 #ifdef DAEMON
14 static char sccsid[] = "@(#)daemon.c	8.5 (Berkeley) 07/26/93 (with daemon mode)";
15 #else
16 static char sccsid[] = "@(#)daemon.c	8.5 (Berkeley) 07/26/93 (without daemon mode)";
17 #endif
18 #endif /* not lint */
19 
20 #ifdef DAEMON
21 
22 # include <netdb.h>
23 # include <sys/wait.h>
24 # include <sys/time.h>
25 
26 #ifdef NAMED_BIND
27 # include <arpa/nameser.h>
28 # include <resolv.h>
29 #endif
30 
31 /*
32 **  DAEMON.C -- routines to use when running as a daemon.
33 **
34 **	This entire file is highly dependent on the 4.2 BSD
35 **	interprocess communication primitives.  No attempt has
36 **	been made to make this file portable to Version 7,
37 **	Version 6, MPX files, etc.  If you should try such a
38 **	thing yourself, I recommend chucking the entire file
39 **	and starting from scratch.  Basic semantics are:
40 **
41 **	getrequests()
42 **		Opens a port and initiates a connection.
43 **		Returns in a child.  Must set InChannel and
44 **		OutChannel appropriately.
45 **	clrdaemon()
46 **		Close any open files associated with getting
47 **		the connection; this is used when running the queue,
48 **		etc., to avoid having extra file descriptors during
49 **		the queue run and to avoid confusing the network
50 **		code (if it cares).
51 **	makeconnection(host, port, outfile, infile, usesecureport)
52 **		Make a connection to the named host on the given
53 **		port.  Set *outfile and *infile to the files
54 **		appropriate for communication.  Returns zero on
55 **		success, else an exit status describing the
56 **		error.
57 **	host_map_lookup(map, hbuf, avp, pstat)
58 **		Convert the entry in hbuf into a canonical form.
59 */
60 /*
61 **  GETREQUESTS -- open mail IPC port and get requests.
62 **
63 **	Parameters:
64 **		none.
65 **
66 **	Returns:
67 **		none.
68 **
69 **	Side Effects:
70 **		Waits until some interesting activity occurs.  When
71 **		it does, a child is created to process it, and the
72 **		parent waits for completion.  Return from this
73 **		routine is always in the child.  The file pointers
74 **		"InChannel" and "OutChannel" should be set to point
75 **		to the communication channel.
76 */
77 
78 int		DaemonSocket	= -1;		/* fd describing socket */
79 SOCKADDR	DaemonAddr;			/* socket for incoming */
80 int		ListenQueueSize = 10;		/* size of listen queue */
81 
82 getrequests()
83 {
84 	int t;
85 	register struct servent *sp;
86 	int on = 1;
87 	bool refusingconnections = TRUE;
88 	FILE *pidf;
89 	extern void reapchild();
90 
91 	/*
92 	**  Set up the address for the mailer.
93 	*/
94 
95 	if (DaemonAddr.sin.sin_family == 0)
96 		DaemonAddr.sin.sin_family = AF_INET;
97 	if (DaemonAddr.sin.sin_addr.s_addr == 0)
98 		DaemonAddr.sin.sin_addr.s_addr = INADDR_ANY;
99 	if (DaemonAddr.sin.sin_port == 0)
100 	{
101 		sp = getservbyname("smtp", "tcp");
102 		if (sp == NULL)
103 		{
104 			syserr("554 service \"smtp\" unknown");
105 			goto severe;
106 		}
107 		DaemonAddr.sin.sin_port = sp->s_port;
108 	}
109 
110 	/*
111 	**  Try to actually open the connection.
112 	*/
113 
114 	if (tTd(15, 1))
115 		printf("getrequests: port 0x%x\n", DaemonAddr.sin.sin_port);
116 
117 	/* get a socket for the SMTP connection */
118 	DaemonSocket = socket(DaemonAddr.sa.sa_family, SOCK_STREAM, 0);
119 	if (DaemonSocket < 0)
120 	{
121 		/* probably another daemon already */
122 		syserr("getrequests: can't create socket");
123 	  severe:
124 # ifdef LOG
125 		if (LogLevel > 0)
126 			syslog(LOG_ALERT, "problem creating SMTP socket");
127 # endif /* LOG */
128 		finis();
129 	}
130 
131 	/* turn on network debugging? */
132 	if (tTd(15, 101))
133 		(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG, (char *)&on, sizeof on);
134 
135 	(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof on);
136 	(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof on);
137 
138 	switch (DaemonAddr.sa.sa_family)
139 	{
140 # ifdef NETINET
141 	  case AF_INET:
142 		t = sizeof DaemonAddr.sin;
143 		break;
144 # endif
145 
146 # ifdef NETISO
147 	  case AF_ISO:
148 		t = sizeof DaemonAddr.siso;
149 		break;
150 # endif
151 
152 	  default:
153 		t = sizeof DaemonAddr;
154 		break;
155 	}
156 
157 	if (bind(DaemonSocket, &DaemonAddr.sa, t) < 0)
158 	{
159 		syserr("getrequests: cannot bind");
160 		(void) close(DaemonSocket);
161 		goto severe;
162 	}
163 
164 	(void) setsignal(SIGCHLD, reapchild);
165 
166 	/* write the pid to the log file for posterity */
167 	pidf = fopen(PidFile, "w");
168 	if (pidf != NULL)
169 	{
170 		extern char *CommandLineArgs;
171 
172 		/* write the process id on line 1 */
173 		fprintf(pidf, "%d\n", getpid());
174 
175 		/* line 2 contains all command line flags */
176 		fprintf(pidf, "%s\n", CommandLineArgs);
177 
178 		/* flush and close */
179 		fclose(pidf);
180 	}
181 
182 
183 	if (tTd(15, 1))
184 		printf("getrequests: %d\n", DaemonSocket);
185 
186 	for (;;)
187 	{
188 		register int pid;
189 		auto int lotherend;
190 		extern bool refuseconnections();
191 
192 		/* see if we are rejecting connections */
193 		CurrentLA = getla();
194 		if (refuseconnections())
195 		{
196 			if (!refusingconnections)
197 			{
198 				/* don't queue so peer will fail quickly */
199 				(void) listen(DaemonSocket, 0);
200 				refusingconnections = TRUE;
201 			}
202 			setproctitle("rejecting connections: load average: %d",
203 				CurrentLA);
204 			sleep(5);
205 			continue;
206 		}
207 
208 		if (refusingconnections)
209 		{
210 			/* start listening again */
211 			if (listen(DaemonSocket, ListenQueueSize) < 0)
212 			{
213 				syserr("getrequests: cannot listen");
214 				(void) close(DaemonSocket);
215 				goto severe;
216 			}
217 			setproctitle("accepting connections");
218 			refusingconnections = FALSE;
219 		}
220 
221 		/* wait for a connection */
222 		do
223 		{
224 			errno = 0;
225 			lotherend = sizeof RealHostAddr;
226 			t = accept(DaemonSocket,
227 			    (struct sockaddr *)&RealHostAddr, &lotherend);
228 		} while (t < 0 && errno == EINTR);
229 		if (t < 0)
230 		{
231 			syserr("getrequests: accept");
232 			sleep(5);
233 			continue;
234 		}
235 
236 		/*
237 		**  Create a subprocess to process the mail.
238 		*/
239 
240 		if (tTd(15, 2))
241 			printf("getrequests: forking (fd = %d)\n", t);
242 
243 		pid = fork();
244 		if (pid < 0)
245 		{
246 			syserr("daemon: cannot fork");
247 			sleep(10);
248 			(void) close(t);
249 			continue;
250 		}
251 
252 		if (pid == 0)
253 		{
254 			extern char *hostnamebyanyaddr();
255 
256 			/*
257 			**  CHILD -- return to caller.
258 			**	Collect verified idea of sending host.
259 			**	Verify calling user id if possible here.
260 			*/
261 
262 			(void) setsignal(SIGCHLD, SIG_DFL);
263 			OpMode = MD_SMTP;
264 
265 			/* determine host name */
266 			RealHostName = newstr(hostnamebyanyaddr(&RealHostAddr));
267 
268 #ifdef LOG
269 			if (LogLevel > 11)
270 			{
271 				/* log connection information */
272 				syslog(LOG_INFO, "connect from %s (%s)",
273 					RealHostName, anynet_ntoa(&RealHostAddr));
274 			}
275 #endif
276 
277 			(void) close(DaemonSocket);
278 			InChannel = fdopen(t, "r");
279 			OutChannel = fdopen(dup(t), "w");
280 
281 			/* should we check for illegal connection here? XXX */
282 #ifdef XLA
283 			if (!xla_host_ok(RealHostName))
284 			{
285 				message("421 Too many SMTP sessions for this host");
286 				exit(0);
287 			}
288 #endif
289 
290 			if (tTd(15, 2))
291 				printf("getreq: returning\n");
292 			return;
293 		}
294 
295 		/* close the port so that others will hang (for a while) */
296 		(void) close(t);
297 	}
298 	/*NOTREACHED*/
299 }
300 /*
301 **  CLRDAEMON -- reset the daemon connection
302 **
303 **	Parameters:
304 **		none.
305 **
306 **	Returns:
307 **		none.
308 **
309 **	Side Effects:
310 **		releases any resources used by the passive daemon.
311 */
312 
313 clrdaemon()
314 {
315 	if (DaemonSocket >= 0)
316 		(void) close(DaemonSocket);
317 	DaemonSocket = -1;
318 }
319 /*
320 **  SETDAEMONOPTIONS -- set options for running the daemon
321 **
322 **	Parameters:
323 **		p -- the options line.
324 **
325 **	Returns:
326 **		none.
327 */
328 
329 setdaemonoptions(p)
330 	register char *p;
331 {
332 	if (DaemonAddr.sa.sa_family == AF_UNSPEC)
333 		DaemonAddr.sa.sa_family = AF_INET;
334 
335 	while (p != NULL)
336 	{
337 		register char *f;
338 		register char *v;
339 
340 		while (isascii(*p) && isspace(*p))
341 			p++;
342 		if (*p == '\0')
343 			break;
344 		f = p;
345 		p = strchr(p, ',');
346 		if (p != NULL)
347 			*p++ = '\0';
348 		v = strchr(f, '=');
349 		if (v == NULL)
350 			continue;
351 		while (isascii(*++v) && isspace(*v))
352 			continue;
353 
354 		switch (*f)
355 		{
356 		  case 'F':		/* address family */
357 			if (isascii(*v) && isdigit(*v))
358 				DaemonAddr.sa.sa_family = atoi(v);
359 #ifdef NETINET
360 			else if (strcasecmp(v, "inet") == 0)
361 				DaemonAddr.sa.sa_family = AF_INET;
362 #endif
363 #ifdef NETISO
364 			else if (strcasecmp(v, "iso") == 0)
365 				DaemonAddr.sa.sa_family = AF_ISO;
366 #endif
367 #ifdef NETNS
368 			else if (strcasecmp(v, "ns") == 0)
369 				DaemonAddr.sa.sa_family = AF_NS;
370 #endif
371 #ifdef NETX25
372 			else if (strcasecmp(v, "x.25") == 0)
373 				DaemonAddr.sa.sa_family = AF_CCITT;
374 #endif
375 			else
376 				syserr("554 Unknown address family %s in Family=option", v);
377 			break;
378 
379 		  case 'A':		/* address */
380 			switch (DaemonAddr.sa.sa_family)
381 			{
382 #ifdef NETINET
383 			  case AF_INET:
384 				if (isascii(*v) && isdigit(*v))
385 					DaemonAddr.sin.sin_addr.s_addr = inet_network(v);
386 				else
387 				{
388 					register struct netent *np;
389 
390 					np = getnetbyname(v);
391 					if (np == NULL)
392 						syserr("554 network \"%s\" unknown", v);
393 					else
394 						DaemonAddr.sin.sin_addr.s_addr = np->n_net;
395 				}
396 				break;
397 #endif
398 
399 			  default:
400 				syserr("554 Address= option unsupported for family %d",
401 					DaemonAddr.sa.sa_family);
402 				break;
403 			}
404 			break;
405 
406 		  case 'P':		/* port */
407 			switch (DaemonAddr.sa.sa_family)
408 			{
409 				short port;
410 
411 #ifdef NETINET
412 			  case AF_INET:
413 				if (isascii(*v) && isdigit(*v))
414 					DaemonAddr.sin.sin_port = atoi(v);
415 				else
416 				{
417 					register struct servent *sp;
418 
419 					sp = getservbyname(v, "tcp");
420 					if (sp == NULL)
421 						syserr("554 service \"%s\" unknown", v);
422 					else
423 						DaemonAddr.sin.sin_port = sp->s_port;
424 				}
425 				break;
426 #endif
427 
428 #ifdef NETISO
429 			  case AF_ISO:
430 				/* assume two byte transport selector */
431 				if (isascii(*v) && isdigit(*v))
432 					port = atoi(v);
433 				else
434 				{
435 					register struct servent *sp;
436 
437 					sp = getservbyname(v, "tcp");
438 					if (sp == NULL)
439 						syserr("554 service \"%s\" unknown", v);
440 					else
441 						port = sp->s_port;
442 				}
443 				bcopy((char *) &port, TSEL(&DaemonAddr.siso), 2);
444 				break;
445 #endif
446 
447 			  default:
448 				syserr("554 Port= option unsupported for family %d",
449 					DaemonAddr.sa.sa_family);
450 				break;
451 			}
452 			break;
453 
454 		  case 'L':		/* listen queue size */
455 			ListenQueueSize = atoi(v);
456 			break;
457 		}
458 	}
459 }
460 /*
461 **  MAKECONNECTION -- make a connection to an SMTP socket on another machine.
462 **
463 **	Parameters:
464 **		host -- the name of the host.
465 **		port -- the port number to connect to.
466 **		mci -- a pointer to the mail connection information
467 **			structure to be filled in.
468 **		usesecureport -- if set, use a low numbered (reserved)
469 **			port to provide some rudimentary authentication.
470 **
471 **	Returns:
472 **		An exit code telling whether the connection could be
473 **			made and if not why not.
474 **
475 **	Side Effects:
476 **		none.
477 */
478 
479 SOCKADDR	CurHostAddr;		/* address of current host */
480 
481 int
482 makeconnection(host, port, mci, usesecureport)
483 	char *host;
484 	u_short port;
485 	register MCI *mci;
486 	bool usesecureport;
487 {
488 	register int i, s;
489 	register struct hostent *hp = (struct hostent *)NULL;
490 	SOCKADDR addr;
491 	int sav_errno;
492 	int addrlen;
493 #ifdef NAMED_BIND
494 	extern int h_errno;
495 #endif
496 
497 	/*
498 	**  Set up the address for the mailer.
499 	**	Accept "[a.b.c.d]" syntax for host name.
500 	*/
501 
502 #ifdef NAMED_BIND
503 	h_errno = 0;
504 #endif
505 	errno = 0;
506 	bzero(&CurHostAddr, sizeof CurHostAddr);
507 	CurHostName = host;
508 
509 	if (host[0] == '[')
510 	{
511 		long hid;
512 		register char *p = strchr(host, ']');
513 
514 		if (p != NULL)
515 		{
516 			*p = '\0';
517 #ifdef NETINET
518 			hid = inet_addr(&host[1]);
519 			if (hid == -1)
520 #endif
521 			{
522 				/* try it as a host name (avoid MX lookup) */
523 				hp = gethostbyname(&host[1]);
524 				*p = ']';
525 				goto gothostent;
526 			}
527 			*p = ']';
528 		}
529 		if (p == NULL)
530 		{
531 			usrerr("553 Invalid numeric domain spec \"%s\"", host);
532 			return (EX_NOHOST);
533 		}
534 #ifdef NETINET
535 		addr.sin.sin_family = AF_INET;		/*XXX*/
536 		addr.sin.sin_addr.s_addr = hid;
537 #endif
538 	}
539 	else
540 	{
541 		hp = gethostbyname(host);
542 gothostent:
543 		if (hp == NULL)
544 		{
545 #ifdef NAMED_BIND
546 			if (errno == ETIMEDOUT || h_errno == TRY_AGAIN)
547 				return (EX_TEMPFAIL);
548 
549 			/* if name server is specified, assume temp fail */
550 			if (errno == ECONNREFUSED && UseNameServer)
551 				return (EX_TEMPFAIL);
552 #endif
553 			return (EX_NOHOST);
554 		}
555 		addr.sa.sa_family = hp->h_addrtype;
556 		switch (hp->h_addrtype)
557 		{
558 #ifdef NETINET
559 		  case AF_INET:
560 			bcopy(hp->h_addr,
561 				&addr.sin.sin_addr,
562 				hp->h_length);
563 			break;
564 #endif
565 
566 		  default:
567 			bcopy(hp->h_addr,
568 				addr.sa.sa_data,
569 				hp->h_length);
570 			break;
571 		}
572 		i = 1;
573 	}
574 
575 	/*
576 	**  Determine the port number.
577 	*/
578 
579 	if (port != 0)
580 		port = htons(port);
581 	else
582 	{
583 		register struct servent *sp = getservbyname("smtp", "tcp");
584 
585 		if (sp == NULL)
586 		{
587 			syserr("554 makeconnection: service \"smtp\" unknown");
588 			return (EX_OSERR);
589 		}
590 		port = sp->s_port;
591 	}
592 
593 	switch (addr.sa.sa_family)
594 	{
595 #ifdef NETINET
596 	  case AF_INET:
597 		addr.sin.sin_port = port;
598 		addrlen = sizeof (struct sockaddr_in);
599 		break;
600 #endif
601 
602 #ifdef NETISO
603 	  case AF_ISO:
604 		/* assume two byte transport selector */
605 		bcopy((char *) &port, TSEL((struct sockaddr_iso *) &addr), 2);
606 		addrlen = sizeof (struct sockaddr_iso);
607 		break;
608 #endif
609 
610 	  default:
611 		syserr("Can't connect to address family %d", addr.sa.sa_family);
612 		return (EX_NOHOST);
613 	}
614 
615 	/*
616 	**  Try to actually open the connection.
617 	*/
618 
619 #ifdef XLA
620 	/* if too many connections, don't bother trying */
621 	if (!xla_noqueue_ok(host))
622 		return EX_TEMPFAIL;
623 #endif
624 
625 	for (;;)
626 	{
627 		if (tTd(16, 1))
628 			printf("makeconnection (%s [%s])\n",
629 				host, anynet_ntoa(&addr));
630 
631 		/* save for logging */
632 		CurHostAddr = addr;
633 
634 		if (usesecureport)
635 		{
636 			int rport = IPPORT_RESERVED - 1;
637 
638 			s = rresvport(&rport);
639 		}
640 		else
641 		{
642 			s = socket(AF_INET, SOCK_STREAM, 0);
643 		}
644 		if (s < 0)
645 		{
646 			sav_errno = errno;
647 			syserr("makeconnection: no socket");
648 			goto failure;
649 		}
650 
651 		if (tTd(16, 1))
652 			printf("makeconnection: fd=%d\n", s);
653 
654 		/* turn on network debugging? */
655 		if (tTd(16, 101))
656 		{
657 			int on = 1;
658 			(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG,
659 					  (char *)&on, sizeof on);
660 		}
661 		if (CurEnv->e_xfp != NULL)
662 			(void) fflush(CurEnv->e_xfp);		/* for debugging */
663 		errno = 0;					/* for debugging */
664 		if (connect(s, (struct sockaddr *) &addr, addrlen) >= 0)
665 			break;
666 
667 		/* couldn't connect.... figure out why */
668 		sav_errno = errno;
669 		(void) close(s);
670 		if (hp && hp->h_addr_list[i])
671 		{
672 			if (tTd(16, 1))
673 				printf("Connect failed (%s); trying new address....\n",
674 					errstring(sav_errno));
675 			switch (addr.sa.sa_family)
676 			{
677 #ifdef NETINET
678 			  case AF_INET:
679 				bcopy(hp->h_addr_list[i++],
680 				      &addr.sin.sin_addr,
681 				      hp->h_length);
682 				break;
683 #endif
684 
685 			  default:
686 				bcopy(hp->h_addr_list[i++],
687 					addr.sa.sa_data,
688 					hp->h_length);
689 				break;
690 			}
691 			continue;
692 		}
693 
694 		/* failure, decide if temporary or not */
695 	failure:
696 #ifdef XLA
697 		xla_host_end(host);
698 #endif
699 		if (transienterror(sav_errno))
700 			return EX_TEMPFAIL;
701 		else
702 		{
703 			message("%s", errstring(sav_errno));
704 			return (EX_UNAVAILABLE);
705 		}
706 	}
707 
708 	/* connection ok, put it into canonical form */
709 	mci->mci_out = fdopen(s, "w");
710 	mci->mci_in = fdopen(dup(s), "r");
711 
712 	return (EX_OK);
713 }
714 /*
715 **  MYHOSTNAME -- return the name of this host.
716 **
717 **	Parameters:
718 **		hostbuf -- a place to return the name of this host.
719 **		size -- the size of hostbuf.
720 **
721 **	Returns:
722 **		A list of aliases for this host.
723 **
724 **	Side Effects:
725 **		Sets the MyIpAddrs buffer to a list of my IP addresses.
726 */
727 
728 struct in_addr	MyIpAddrs[MAXIPADDR + 1];
729 
730 char **
731 myhostname(hostbuf, size)
732 	char hostbuf[];
733 	int size;
734 {
735 	register struct hostent *hp;
736 	extern struct hostent *gethostbyname();
737 
738 	if (gethostname(hostbuf, size) < 0)
739 	{
740 		(void) strcpy(hostbuf, "localhost");
741 	}
742 	hp = gethostbyname(hostbuf);
743 	if (hp != NULL)
744 	{
745 		(void) strncpy(hostbuf, hp->h_name, size - 1);
746 		hostbuf[size - 1] = '\0';
747 
748 		if (hp->h_addrtype == AF_INET && hp->h_length == 4)
749 		{
750 			register int i;
751 
752 			for (i = 0; i < MAXIPADDR; i++)
753 			{
754 				if (hp->h_addr_list[i] == NULL)
755 					break;
756 				MyIpAddrs[i].s_addr = *(u_long *) hp->h_addr_list[i];
757 			}
758 			MyIpAddrs[i].s_addr = 0;
759 		}
760 
761 		return (hp->h_aliases);
762 	}
763 	else
764 		return (NULL);
765 }
766 /*
767 **  GETAUTHINFO -- get the real host name asociated with a file descriptor
768 **
769 **	Uses RFC1413 protocol to try to get info from the other end.
770 **
771 **	Parameters:
772 **		fd -- the descriptor
773 **
774 **	Returns:
775 **		The user@host information associated with this descriptor.
776 **
777 **	Side Effects:
778 **		Sets RealHostName to the name of the host at the other end.
779 */
780 
781 #ifdef IDENTPROTO
782 
783 static jmp_buf	CtxAuthTimeout;
784 
785 static
786 authtimeout()
787 {
788 	longjmp(CtxAuthTimeout, 1);
789 }
790 
791 #endif
792 
793 char *
794 getauthinfo(fd)
795 	int fd;
796 {
797 	SOCKADDR fa;
798 	int falen;
799 	register char *p;
800 #ifdef IDENTPROTO
801 	SOCKADDR la;
802 	int lalen;
803 	register struct servent *sp;
804 	int s;
805 	int i;
806 	EVENT *ev;
807 #endif
808 	static char hbuf[MAXNAME * 2 + 2];
809 	extern char *hostnamebyanyaddr();
810 	extern char RealUserName[];			/* main.c */
811 
812 	falen = sizeof fa;
813 	if (getpeername(fd, &fa.sa, &falen) < 0 || falen <= 0)
814 	{
815 		RealHostName = "localhost";
816 		(void) sprintf(hbuf, "%s@localhost", RealUserName);
817 		if (tTd(9, 1))
818 			printf("getauthinfo: %s\n", hbuf);
819 		return hbuf;
820 	}
821 
822 	RealHostName = newstr(hostnamebyanyaddr(&fa));
823 	RealHostAddr = fa;
824 
825 #ifdef IDENTPROTO
826 	lalen = sizeof la;
827 	if (fa.sa.sa_family != AF_INET ||
828 	    getsockname(fd, &la.sa, &lalen) < 0 || lalen <= 0 ||
829 	    la.sa.sa_family != AF_INET)
830 	{
831 		/* no ident info */
832 		goto noident;
833 	}
834 
835 	/* create ident query */
836 	(void) sprintf(hbuf, "%d,%d\r\n",
837 		ntohs(fa.sin.sin_port), ntohs(la.sin.sin_port));
838 
839 	/* create local address */
840 	bzero(&la, sizeof la);
841 
842 	/* create foreign address */
843 	sp = getservbyname("auth", "tcp");
844 	if (sp != NULL)
845 		fa.sin.sin_port = sp->s_port;
846 	else
847 		fa.sin.sin_port = htons(113);
848 
849 	s = -1;
850 	if (setjmp(CtxAuthTimeout) != 0)
851 	{
852 		if (s >= 0)
853 			(void) close(s);
854 		goto noident;
855 	}
856 
857 	/* put a timeout around the whole thing */
858 	ev = setevent((time_t) 30, authtimeout, 0);
859 
860 	/* connect to foreign IDENT server */
861 	s = socket(AF_INET, SOCK_STREAM, 0);
862 	if (s < 0)
863 	{
864 		clrevent(ev);
865 		goto noident;
866 	}
867 	if (connect(s, &fa.sa, sizeof fa.sin) < 0)
868 	{
869 closeident:
870 		(void) close(s);
871 		clrevent(ev);
872 		goto noident;
873 	}
874 
875 	if (tTd(9, 10))
876 		printf("getauthinfo: sent %s", hbuf);
877 
878 	/* send query */
879 	if (write(s, hbuf, strlen(hbuf)) < 0)
880 		goto closeident;
881 
882 	/* get result */
883 	i = read(s, hbuf, sizeof hbuf);
884 	(void) close(s);
885 	clrevent(ev);
886 	if (i <= 0)
887 		goto noident;
888 	if (hbuf[--i] == '\n' && hbuf[--i] == '\r')
889 		i--;
890 	hbuf[++i] = '\0';
891 
892 	if (tTd(9, 3))
893 		printf("getauthinfo:  got %s\n", hbuf);
894 
895 	/* parse result */
896 	p = strchr(hbuf, ':');
897 	if (p == NULL)
898 	{
899 		/* malformed response */
900 		goto noident;
901 	}
902 	while (isascii(*++p) && isspace(*p))
903 		continue;
904 	if (strncasecmp(p, "userid", 6) != 0)
905 	{
906 		/* presumably an error string */
907 		goto noident;
908 	}
909 	p += 6;
910 	while (isascii(*p) && isspace(*p))
911 		p++;
912 	if (*p++ != ':')
913 	{
914 		/* either useridxx or malformed response */
915 		goto noident;
916 	}
917 
918 	/* p now points to the OSTYPE field */
919 	p = strchr(p, ':');
920 	if (p == NULL)
921 	{
922 		/* malformed response */
923 		goto noident;
924 	}
925 
926 	/* 1413 says don't do this -- but it's broken otherwise */
927 	while (isascii(*++p) && isspace(*p))
928 		continue;
929 
930 	/* p now points to the authenticated name */
931 	(void) sprintf(hbuf, "%s@%s", p, RealHostName);
932 	goto finish;
933 
934 #endif /* IDENTPROTO */
935 
936 noident:
937 	(void) strcpy(hbuf, RealHostName);
938 
939 finish:
940 	if (RealHostName[0] != '[')
941 	{
942 		p = &hbuf[strlen(hbuf)];
943 		(void) sprintf(p, " [%s]", anynet_ntoa(&RealHostAddr));
944 	}
945 	if (tTd(9, 1))
946 		printf("getauthinfo: %s\n", hbuf);
947 	return hbuf;
948 }
949 /*
950 **  HOST_MAP_LOOKUP -- turn a hostname into canonical form
951 **
952 **	Parameters:
953 **		map -- a pointer to this map (unused).
954 **		name -- the (presumably unqualified) hostname.
955 **		av -- unused -- for compatibility with other mapping
956 **			functions.
957 **		statp -- an exit status (out parameter) -- set to
958 **			EX_TEMPFAIL if the name server is unavailable.
959 **
960 **	Returns:
961 **		The mapping, if found.
962 **		NULL if no mapping found.
963 **
964 **	Side Effects:
965 **		Looks up the host specified in hbuf.  If it is not
966 **		the canonical name for that host, return the canonical
967 **		name.
968 */
969 
970 char *
971 host_map_lookup(map, name, av, statp)
972 	MAP *map;
973 	char *name;
974 	char **av;
975 	int *statp;
976 {
977 	register struct hostent *hp;
978 	u_long in_addr;
979 	char *cp;
980 	int i;
981 	register STAB *s;
982 	char hbuf[MAXNAME];
983 	extern struct hostent *gethostbyaddr();
984 	extern int h_errno;
985 
986 	/*
987 	**  See if we have already looked up this name.  If so, just
988 	**  return it.
989 	*/
990 
991 	s = stab(name, ST_NAMECANON, ST_ENTER);
992 	if (bitset(NCF_VALID, s->s_namecanon.nc_flags))
993 	{
994 		if (tTd(9, 1))
995 			printf("host_map_lookup(%s) => CACHE %s\n",
996 				name, s->s_namecanon.nc_cname);
997 		errno = s->s_namecanon.nc_errno;
998 		h_errno = s->s_namecanon.nc_herrno;
999 		*statp = s->s_namecanon.nc_stat;
1000 		return s->s_namecanon.nc_cname;
1001 	}
1002 
1003 	/*
1004 	**  If first character is a bracket, then it is an address
1005 	**  lookup.  Address is copied into a temporary buffer to
1006 	**  strip the brackets and to preserve name if address is
1007 	**  unknown.
1008 	*/
1009 
1010 	if (*name != '[')
1011 	{
1012 		extern bool getcanonname();
1013 
1014 		if (tTd(9, 1))
1015 			printf("host_map_lookup(%s) => ", name);
1016 		s->s_namecanon.nc_flags |= NCF_VALID;		/* will be soon */
1017 		(void) strcpy(hbuf, name);
1018 		if (getcanonname(hbuf, sizeof hbuf - 1, TRUE))
1019 		{
1020 			if (tTd(9, 1))
1021 				printf("%s\n", hbuf);
1022 			cp = map_rewrite(map, hbuf, strlen(hbuf), av);
1023 			s->s_namecanon.nc_cname = newstr(cp);
1024 			return cp;
1025 		}
1026 		else
1027 		{
1028 			register struct hostent *hp;
1029 
1030 			if (tTd(9, 1))
1031 				printf("FAIL (%d)\n", h_errno);
1032 			s->s_namecanon.nc_errno = errno;
1033 			s->s_namecanon.nc_herrno = h_errno;
1034 			switch (h_errno)
1035 			{
1036 			  case TRY_AGAIN:
1037 				if (UseNameServer)
1038 				{
1039 					char *msg = "Recipient domain nameserver timed out";
1040 
1041 					message(msg);
1042 					if (CurEnv->e_message == NULL)
1043 						CurEnv->e_message = newstr(msg);
1044 				}
1045 				*statp = EX_TEMPFAIL;
1046 				break;
1047 
1048 			  case HOST_NOT_FOUND:
1049 				*statp = EX_NOHOST;
1050 				break;
1051 
1052 			  case NO_RECOVERY:
1053 				*statp = EX_SOFTWARE;
1054 				break;
1055 
1056 			  default:
1057 				*statp = EX_UNAVAILABLE;
1058 				break;
1059 			}
1060 			s->s_namecanon.nc_stat = *statp;
1061 			if (*statp != EX_TEMPFAIL || UseNameServer)
1062 				return NULL;
1063 
1064 			/*
1065 			**  Try to look it up in /etc/hosts
1066 			*/
1067 
1068 			hp = gethostbyname(name);
1069 			if (hp == NULL)
1070 			{
1071 				/* no dice there either */
1072 				s->s_namecanon.nc_stat = *statp = EX_NOHOST;
1073 				return NULL;
1074 			}
1075 
1076 			s->s_namecanon.nc_stat = *statp = EX_OK;
1077 			cp = map_rewrite(map, hp->h_name, strlen(hp->h_name), av);
1078 			s->s_namecanon.nc_cname = newstr(cp);
1079 			return cp;
1080 		}
1081 	}
1082 	if ((cp = strchr(name, ']')) == NULL)
1083 		return (NULL);
1084 	*cp = '\0';
1085 	in_addr = inet_addr(&name[1]);
1086 
1087 	/* check to see if this is one of our addresses */
1088 	for (i = 0; MyIpAddrs[i].s_addr != 0; i++)
1089 	{
1090 		if (MyIpAddrs[i].s_addr == in_addr)
1091 		{
1092 			return map_rewrite(map, MyHostName, strlen(MyHostName), av);
1093 		}
1094 	}
1095 
1096 	/* nope -- ask the name server */
1097 	hp = gethostbyaddr((char *)&in_addr, sizeof(struct in_addr), AF_INET);
1098 	s->s_namecanon.nc_errno = errno;
1099 	s->s_namecanon.nc_herrno = h_errno;
1100 	s->s_namecanon.nc_flags |= NCF_VALID;		/* will be soon */
1101 	if (hp == NULL)
1102 	{
1103 		s->s_namecanon.nc_stat = *statp = EX_NOHOST;
1104 		return (NULL);
1105 	}
1106 
1107 	/* found a match -- copy out */
1108 	cp = map_rewrite(map, hp->h_name, strlen(hp->h_name), av);
1109 	s->s_namecanon.nc_stat = *statp = EX_OK;
1110 	s->s_namecanon.nc_cname = newstr(cp);
1111 	return cp;
1112 }
1113 /*
1114 **  ANYNET_NTOA -- convert a network address to printable form.
1115 **
1116 **	Parameters:
1117 **		sap -- a pointer to a sockaddr structure.
1118 **
1119 **	Returns:
1120 **		A printable version of that sockaddr.
1121 */
1122 
1123 char *
1124 anynet_ntoa(sap)
1125 	register SOCKADDR *sap;
1126 {
1127 	register char *bp;
1128 	register char *ap;
1129 	int l;
1130 	static char buf[80];
1131 
1132 	/* check for null/zero family */
1133 	if (sap == NULL)
1134 		return "NULLADDR";
1135 	if (sap->sa.sa_family == 0)
1136 		return "0";
1137 
1138 #ifdef NETINET
1139 	if (sap->sa.sa_family == AF_INET)
1140 	{
1141 		extern char *inet_ntoa();
1142 
1143 		return inet_ntoa(((struct sockaddr_in *) sap)->sin_addr);
1144 	}
1145 #endif
1146 
1147 	/* unknown family -- just dump bytes */
1148 	(void) sprintf(buf, "Family %d: ", sap->sa.sa_family);
1149 	bp = &buf[strlen(buf)];
1150 	ap = sap->sa.sa_data;
1151 	for (l = sizeof sap->sa.sa_data; --l >= 0; )
1152 	{
1153 		(void) sprintf(bp, "%02x:", *ap++ & 0377);
1154 		bp += 3;
1155 	}
1156 	*--bp = '\0';
1157 	return buf;
1158 }
1159 /*
1160 **  HOSTNAMEBYANYADDR -- return name of host based on address
1161 **
1162 **	Parameters:
1163 **		sap -- SOCKADDR pointer
1164 **
1165 **	Returns:
1166 **		text representation of host name.
1167 **
1168 **	Side Effects:
1169 **		none.
1170 */
1171 
1172 char *
1173 hostnamebyanyaddr(sap)
1174 	register SOCKADDR *sap;
1175 {
1176 	register struct hostent *hp;
1177 
1178 #ifdef NAMED_BIND
1179 	int saveretry;
1180 
1181 	/* shorten name server timeout to avoid higher level timeouts */
1182 	saveretry = _res.retry;
1183 	_res.retry = 3;
1184 #endif /* NAMED_BIND */
1185 
1186 	switch (sap->sa.sa_family)
1187 	{
1188 #ifdef NETINET
1189 	  case AF_INET:
1190 		hp = gethostbyaddr((char *) &sap->sin.sin_addr,
1191 			sizeof sap->sin.sin_addr,
1192 			AF_INET);
1193 		break;
1194 #endif
1195 
1196 #ifdef NETISO
1197 	  case AF_ISO:
1198 		hp = gethostbyaddr((char *) &sap->siso.siso_addr,
1199 			sizeof sap->siso.siso_addr,
1200 			AF_ISO);
1201 		break;
1202 #endif
1203 
1204 	  default:
1205 		hp = gethostbyaddr(sap->sa.sa_data,
1206 			   sizeof sap->sa.sa_data,
1207 			   sap->sa.sa_family);
1208 		break;
1209 	}
1210 
1211 #ifdef NAMED_BIND
1212 	_res.retry = saveretry;
1213 #endif /* NAMED_BIND */
1214 
1215 	if (hp != NULL)
1216 		return hp->h_name;
1217 	else
1218 	{
1219 		/* produce a dotted quad */
1220 		static char buf[512];
1221 
1222 		(void) sprintf(buf, "[%s]", anynet_ntoa(sap));
1223 		return buf;
1224 	}
1225 }
1226 
1227 # else /* DAEMON */
1228 /* code for systems without sophisticated networking */
1229 
1230 /*
1231 **  MYHOSTNAME -- stub version for case of no daemon code.
1232 **
1233 **	Can't convert to upper case here because might be a UUCP name.
1234 **
1235 **	Mark, you can change this to be anything you want......
1236 */
1237 
1238 char **
1239 myhostname(hostbuf, size)
1240 	char hostbuf[];
1241 	int size;
1242 {
1243 	register FILE *f;
1244 
1245 	hostbuf[0] = '\0';
1246 	f = fopen("/usr/include/whoami", "r");
1247 	if (f != NULL)
1248 	{
1249 		(void) fgets(hostbuf, size, f);
1250 		fixcrlf(hostbuf, TRUE);
1251 		(void) fclose(f);
1252 	}
1253 	return (NULL);
1254 }
1255 /*
1256 **  GETAUTHINFO -- get the real host name asociated with a file descriptor
1257 **
1258 **	Parameters:
1259 **		fd -- the descriptor
1260 **
1261 **	Returns:
1262 **		The host name associated with this descriptor, if it can
1263 **			be determined.
1264 **		NULL otherwise.
1265 **
1266 **	Side Effects:
1267 **		none
1268 */
1269 
1270 char *
1271 getauthinfo(fd)
1272 	int fd;
1273 {
1274 	return NULL;
1275 }
1276 /*
1277 **  MAPHOSTNAME -- turn a hostname into canonical form
1278 **
1279 **	Parameters:
1280 **		map -- a pointer to the database map.
1281 **		name -- a buffer containing a hostname.
1282 **		avp -- a pointer to a (cf file defined) argument vector.
1283 **		statp -- an exit status (out parameter).
1284 **
1285 **	Returns:
1286 **		mapped host name
1287 **		FALSE otherwise.
1288 **
1289 **	Side Effects:
1290 **		Looks up the host specified in name.  If it is not
1291 **		the canonical name for that host, replace it with
1292 **		the canonical name.  If the name is unknown, or it
1293 **		is already the canonical name, leave it unchanged.
1294 */
1295 
1296 /*ARGSUSED*/
1297 char *
1298 host_map_lookup(map, name, avp, statp)
1299 	MAP *map;
1300 	char *name;
1301 	char **avp;
1302 	char *statp;
1303 {
1304 	register struct hostent *hp;
1305 
1306 	hp = gethostbyname(name);
1307 	if (hp != NULL)
1308 		return hp->h_name;
1309 	*statp = EX_NOHOST;
1310 	return NULL;
1311 }
1312 
1313 #endif /* DAEMON */
1314