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