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