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