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