xref: /csrg-svn/usr.sbin/sendmail/src/daemon.c (revision 58308)
1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * %sccs.include.redist.c%
7  */
8 
9 #include <errno.h>
10 #include <signal.h>
11 #include "sendmail.h"
12 
13 #ifndef lint
14 #ifdef DAEMON
15 static char sccsid[] = "@(#)daemon.c	6.11 (Berkeley) 02/28/93 (with daemon mode)";
16 #else
17 static char sccsid[] = "@(#)daemon.c	6.11 (Berkeley) 02/28/93 (without daemon mode)";
18 #endif
19 #endif /* not lint */
20 
21 #ifdef DAEMON
22 
23 # include <netdb.h>
24 # include <sys/wait.h>
25 # include <sys/time.h>
26 
27 /*
28 **  DAEMON.C -- routines to use when running as a daemon.
29 **
30 **	This entire file is highly dependent on the 4.2 BSD
31 **	interprocess communication primitives.  No attempt has
32 **	been made to make this file portable to Version 7,
33 **	Version 6, MPX files, etc.  If you should try such a
34 **	thing yourself, I recommend chucking the entire file
35 **	and starting from scratch.  Basic semantics are:
36 **
37 **	getrequests()
38 **		Opens a port and initiates a connection.
39 **		Returns in a child.  Must set InChannel and
40 **		OutChannel appropriately.
41 **	clrdaemon()
42 **		Close any open files associated with getting
43 **		the connection; this is used when running the queue,
44 **		etc., to avoid having extra file descriptors during
45 **		the queue run and to avoid confusing the network
46 **		code (if it cares).
47 **	makeconnection(host, port, outfile, infile, usesecureport)
48 **		Make a connection to the named host on the given
49 **		port.  Set *outfile and *infile to the files
50 **		appropriate for communication.  Returns zero on
51 **		success, else an exit status describing the
52 **		error.
53 **	maphostname(map, hbuf, hbufsiz, avp)
54 **		Convert the entry in hbuf into a canonical form.
55 */
56 /*
57 **  GETREQUESTS -- open mail IPC port and get requests.
58 **
59 **	Parameters:
60 **		none.
61 **
62 **	Returns:
63 **		none.
64 **
65 **	Side Effects:
66 **		Waits until some interesting activity occurs.  When
67 **		it does, a child is created to process it, and the
68 **		parent waits for completion.  Return from this
69 **		routine is always in the child.  The file pointers
70 **		"InChannel" and "OutChannel" should be set to point
71 **		to the communication channel.
72 */
73 
74 int	DaemonSocket	= -1;		/* fd describing socket */
75 
76 getrequests()
77 {
78 	int t;
79 	register struct servent *sp;
80 	int on = 1;
81 	bool refusingconnections = TRUE;
82 	struct sockaddr_in srvraddr;
83 	extern void reapchild();
84 
85 	/*
86 	**  Set up the address for the mailer.
87 	*/
88 
89 	sp = getservbyname("smtp", "tcp");
90 	if (sp == NULL)
91 	{
92 		syserr("554 server \"smtp\" unknown");
93 		goto severe;
94 	}
95 	srvraddr.sin_family = AF_INET;
96 	srvraddr.sin_addr.s_addr = INADDR_ANY;
97 	srvraddr.sin_port = sp->s_port;
98 
99 	/*
100 	**  Try to actually open the connection.
101 	*/
102 
103 	if (tTd(15, 1))
104 		printf("getrequests: port 0x%x\n", srvraddr.sin_port);
105 
106 	/* get a socket for the SMTP connection */
107 	DaemonSocket = socket(AF_INET, SOCK_STREAM, 0);
108 	if (DaemonSocket < 0)
109 	{
110 		/* probably another daemon already */
111 		syserr("getrequests: can't create socket");
112 	  severe:
113 # ifdef LOG
114 		if (LogLevel > 0)
115 			syslog(LOG_ALERT, "problem creating SMTP socket");
116 # endif /* LOG */
117 		finis();
118 	}
119 
120 	/* turn on network debugging? */
121 	if (tTd(15, 101))
122 		(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG, (char *)&on, sizeof on);
123 
124 	(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof on);
125 	(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof on);
126 
127 	if (bind(DaemonSocket, (struct sockaddr *)&srvraddr, sizeof srvraddr) < 0)
128 	{
129 		syserr("getrequests: cannot bind");
130 		(void) close(DaemonSocket);
131 		goto severe;
132 	}
133 
134 	(void) signal(SIGCHLD, reapchild);
135 
136 	if (tTd(15, 1))
137 		printf("getrequests: %d\n", DaemonSocket);
138 
139 	for (;;)
140 	{
141 		register int pid;
142 		auto int lotherend;
143 		extern bool refuseconnections();
144 
145 		/* see if we are rejecting connections */
146 		CurrentLA = getla();
147 		if (refuseconnections())
148 		{
149 			if (!refusingconnections)
150 			{
151 				/* don't queue so peer will fail quickly */
152 				(void) listen(DaemonSocket, 0);
153 				refusingconnections = TRUE;
154 			}
155 			setproctitle("rejecting connections: load average: %d",
156 				CurrentLA);
157 			sleep(5);
158 			continue;
159 		}
160 
161 		if (refusingconnections)
162 		{
163 			/* start listening again */
164 			if (listen(DaemonSocket, 10) < 0)
165 			{
166 				syserr("getrequests: cannot listen");
167 				(void) close(DaemonSocket);
168 				goto severe;
169 			}
170 			setproctitle("accepting connections");
171 			refusingconnections = FALSE;
172 		}
173 
174 		/* wait for a connection */
175 		do
176 		{
177 			errno = 0;
178 			lotherend = sizeof RealHostAddr;
179 			t = accept(DaemonSocket,
180 			    (struct sockaddr *)&RealHostAddr, &lotherend);
181 		} while (t < 0 && errno == EINTR);
182 		if (t < 0)
183 		{
184 			syserr("getrequests: accept");
185 			sleep(5);
186 			continue;
187 		}
188 
189 		/*
190 		**  Create a subprocess to process the mail.
191 		*/
192 
193 		if (tTd(15, 2))
194 			printf("getrequests: forking (fd = %d)\n", t);
195 
196 		pid = fork();
197 		if (pid < 0)
198 		{
199 			syserr("daemon: cannot fork");
200 			sleep(10);
201 			(void) close(t);
202 			continue;
203 		}
204 
205 		if (pid == 0)
206 		{
207 			extern struct hostent *gethostbyaddr();
208 			register struct hostent *hp;
209 			char buf[MAXNAME];
210 			extern char *inet_ntoa();
211 
212 			/*
213 			**  CHILD -- return to caller.
214 			**	Collect verified idea of sending host.
215 			**	Verify calling user id if possible here.
216 			*/
217 
218 			(void) signal(SIGCHLD, SIG_DFL);
219 
220 			/* determine host name */
221 			hp = gethostbyaddr((char *) &RealHostAddr.sin_addr, sizeof RealHostAddr.sin_addr, AF_INET);
222 			if (hp != NULL)
223 				(void) strcpy(buf, hp->h_name);
224 			else
225 			{
226 				/* produce a dotted quad */
227 				(void) sprintf(buf, "[%s]",
228 					inet_ntoa(RealHostAddr.sin_addr));
229 			}
230 
231 #ifdef LOG
232 			if (LogLevel > 10)
233 			{
234 				/* log connection information */
235 				syslog(LOG_INFO, "connect from %s (%s)",
236 					buf, inet_ntoa(RealHostAddr.sin_addr));
237 			}
238 #endif
239 
240 			/* should we check for illegal connection here? XXX */
241 
242 			RealHostName = newstr(buf);
243 
244 			(void) close(DaemonSocket);
245 			InChannel = fdopen(t, "r");
246 			OutChannel = fdopen(dup(t), "w");
247 			if (tTd(15, 2))
248 				printf("getreq: returning\n");
249 # ifdef LOG
250 			if (LogLevel > 11)
251 				syslog(LOG_DEBUG, "connected, pid=%d", getpid());
252 # endif /* LOG */
253 			return;
254 		}
255 
256 		/* close the port so that others will hang (for a while) */
257 		(void) close(t);
258 	}
259 	/*NOTREACHED*/
260 }
261 /*
262 **  CLRDAEMON -- reset the daemon connection
263 **
264 **	Parameters:
265 **		none.
266 **
267 **	Returns:
268 **		none.
269 **
270 **	Side Effects:
271 **		releases any resources used by the passive daemon.
272 */
273 
274 clrdaemon()
275 {
276 	if (DaemonSocket >= 0)
277 		(void) close(DaemonSocket);
278 	DaemonSocket = -1;
279 }
280 /*
281 **  MAKECONNECTION -- make a connection to an SMTP socket on another machine.
282 **
283 **	Parameters:
284 **		host -- the name of the host.
285 **		port -- the port number to connect to.
286 **		mci -- a pointer to the mail connection information
287 **			structure to be filled in.
288 **		usesecureport -- if set, use a low numbered (reserved)
289 **			port to provide some rudimentary authentication.
290 **
291 **	Returns:
292 **		An exit code telling whether the connection could be
293 **			made and if not why not.
294 **
295 **	Side Effects:
296 **		none.
297 */
298 
299 struct sockaddr_in	CurHostAddr;		/* address of current host */
300 
301 int
302 makeconnection(host, port, mci, usesecureport)
303 	char *host;
304 	u_short port;
305 	register MCI *mci;
306 	bool usesecureport;
307 {
308 	register int i, s;
309 	register struct hostent *hp = (struct hostent *)NULL;
310 	struct sockaddr_in addr;
311 	int sav_errno;
312 	extern char *inet_ntoa();
313 #ifdef NAMED_BIND
314 	extern int h_errno;
315 #endif
316 
317 	/*
318 	**  Set up the address for the mailer.
319 	**	Accept "[a.b.c.d]" syntax for host name.
320 	*/
321 
322 #ifdef NAMED_BIND
323 	h_errno = 0;
324 #endif
325 	errno = 0;
326 
327 	if (host[0] == '[')
328 	{
329 		long hid;
330 		register char *p = strchr(host, ']');
331 
332 		if (p != NULL)
333 		{
334 			*p = '\0';
335 			hid = inet_addr(&host[1]);
336 			*p = ']';
337 		}
338 		if (p == NULL || hid == -1)
339 		{
340 			usrerr("553 Invalid numeric domain spec \"%s\"", host);
341 			return (EX_NOHOST);
342 		}
343 		addr.sin_addr.s_addr = hid;
344 	}
345 	else
346 	{
347 		hp = gethostbyname(host);
348 		if (hp == NULL)
349 		{
350 #ifdef NAMED_BIND
351 			if (errno == ETIMEDOUT || h_errno == TRY_AGAIN)
352 				return (EX_TEMPFAIL);
353 
354 			/* if name server is specified, assume temp fail */
355 			if (errno == ECONNREFUSED && UseNameServer)
356 				return (EX_TEMPFAIL);
357 #endif
358 			return (EX_NOHOST);
359 		}
360 		bcopy(hp->h_addr, (char *) &addr.sin_addr, hp->h_length);
361 		i = 1;
362 	}
363 
364 	/*
365 	**  Determine the port number.
366 	*/
367 
368 	if (port != 0)
369 		addr.sin_port = htons(port);
370 	else
371 	{
372 		register struct servent *sp = getservbyname("smtp", "tcp");
373 
374 		if (sp == NULL)
375 		{
376 			syserr("554 makeconnection: server \"smtp\" unknown");
377 			return (EX_OSERR);
378 		}
379 		addr.sin_port = sp->s_port;
380 	}
381 
382 	/*
383 	**  Try to actually open the connection.
384 	*/
385 
386 	for (;;)
387 	{
388 		if (tTd(16, 1))
389 			printf("makeconnection (%s [%s])\n", host,
390 			    inet_ntoa(addr.sin_addr));
391 
392 		if (usesecureport)
393 		{
394 			int rport = IPPORT_RESERVED - 1;
395 
396 			s = rresvport(&rport);
397 		}
398 		else
399 		{
400 			s = socket(AF_INET, SOCK_STREAM, 0);
401 		}
402 		if (s < 0)
403 		{
404 			sav_errno = errno;
405 			syserr("makeconnection: no socket");
406 			goto failure;
407 		}
408 
409 		if (tTd(16, 1))
410 			printf("makeconnection: fd=%d\n", s);
411 
412 		/* turn on network debugging? */
413 		if (tTd(16, 101))
414 		{
415 			int on = 1;
416 			(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG,
417 					  (char *)&on, sizeof on);
418 		}
419 		if (CurEnv->e_xfp != NULL)
420 			(void) fflush(CurEnv->e_xfp);		/* for debugging */
421 		errno = 0;					/* for debugging */
422 		addr.sin_family = AF_INET;
423 		if (connect(s, (struct sockaddr *) &addr, sizeof addr) >= 0)
424 			break;
425 
426 		/* couldn't connect.... figure out why */
427 		sav_errno = errno;
428 		(void) close(s);
429 		if (hp && hp->h_addr_list[i])
430 		{
431 			if (tTd(16, 1))
432 				printf("Connect failed; trying new address....\n");
433 			bcopy(hp->h_addr_list[i++], (char *) &addr.sin_addr,
434 					hp->h_length);
435 			continue;
436 		}
437 
438 		/* failure, decide if temporary or not */
439 	failure:
440 		switch (sav_errno)
441 		{
442 		  case EISCONN:
443 		  case ETIMEDOUT:
444 		  case EINPROGRESS:
445 		  case EALREADY:
446 		  case EADDRINUSE:
447 		  case EHOSTDOWN:
448 		  case ENETDOWN:
449 		  case ENETRESET:
450 		  case ENOBUFS:
451 		  case ECONNREFUSED:
452 		  case ECONNRESET:
453 		  case EHOSTUNREACH:
454 		  case ENETUNREACH:
455 #ifdef ENOSR
456 		  case ENOSR:
457 #endif
458 			/* there are others, I'm sure..... */
459 			return (EX_TEMPFAIL);
460 
461 		  case EPERM:
462 			/* why is this happening? */
463 			syserr("makeconnection: funny failure, addr=%lx, port=%x",
464 				addr.sin_addr.s_addr, addr.sin_port);
465 			return (EX_TEMPFAIL);
466 
467 		  default:
468 			{
469 				extern char *errstring();
470 
471 				message("%s", errstring(sav_errno));
472 				return (EX_UNAVAILABLE);
473 			}
474 		}
475 	}
476 
477 	/* connection ok, put it into canonical form */
478 	mci->mci_out = fdopen(s, "w");
479 	mci->mci_in = fdopen(dup(s), "r");
480 
481 	/* save for logging */
482 	CurHostAddr = addr;
483 
484 	return (EX_OK);
485 }
486 /*
487 **  MYHOSTNAME -- return the name of this host.
488 **
489 **	Parameters:
490 **		hostbuf -- a place to return the name of this host.
491 **		size -- the size of hostbuf.
492 **
493 **	Returns:
494 **		A list of aliases for this host.
495 **
496 **	Side Effects:
497 **		Sets the MyIpAddrs buffer to a list of my IP addresses.
498 */
499 
500 struct in_addr	MyIpAddrs[MAXIPADDR + 1];
501 
502 char **
503 myhostname(hostbuf, size)
504 	char hostbuf[];
505 	int size;
506 {
507 	register struct hostent *hp;
508 	extern struct hostent *gethostbyname();
509 
510 	if (gethostname(hostbuf, size) < 0)
511 	{
512 		(void) strcpy(hostbuf, "localhost");
513 	}
514 	hp = gethostbyname(hostbuf);
515 	if (hp != NULL)
516 	{
517 		(void) strncpy(hostbuf, hp->h_name, size - 1);
518 		hostbuf[size - 1] = '\0';
519 
520 		if (hp->h_addrtype == AF_INET && hp->h_length == 4)
521 		{
522 			register int i;
523 
524 			for (i = 0; i < MAXIPADDR; i++)
525 			{
526 				if (hp->h_addr_list[i] == NULL)
527 					break;
528 				MyIpAddrs[i].s_addr = *(u_long *) hp->h_addr_list[i];
529 			}
530 			MyIpAddrs[i].s_addr = 0;
531 		}
532 
533 		return (hp->h_aliases);
534 	}
535 	else
536 		return (NULL);
537 }
538 /*
539 **  GETREALHOSTNAME -- get the real host name asociated with a file descriptor
540 **
541 **	Parameters:
542 **		fd -- the descriptor
543 **
544 **	Returns:
545 **		The host name associated with this descriptor, if it can
546 **			be determined.
547 **		NULL otherwise.
548 **
549 **	Side Effects:
550 **		none
551 */
552 
553 char *
554 getrealhostname(fd)
555 	int fd;
556 {
557 	register struct hostent *hp;
558 	struct sockaddr_in sin;
559 	int sinlen;
560 	char hbuf[MAXNAME];
561 	extern struct hostent *gethostbyaddr();
562 	extern char *inet_ntoa();
563 
564 	if (getsockname(fd, (struct sockaddr *) &sin, &sinlen) < 0)
565 		return NULL;
566 	hp = gethostbyaddr((char *) &sin.sin_addr, sizeof sin.sin_addr,
567 			   sin.sin_family);
568 	if (hp != NULL)
569 		(void) strcpy(hbuf, hp->h_name);
570 	else
571 		(void) sprintf(hbuf, "[%s]", inet_ntoa(sin.sin_addr));
572 	return hbuf;
573 }
574 /*
575 **  MAPHOSTNAME -- turn a hostname into canonical form
576 **
577 **	Parameters:
578 **		map -- a pointer to this map (unused).
579 **		hbuf -- a buffer containing a hostname.
580 **		hbsize -- the size of hbuf.
581 **		avp -- unused -- for compatibility with other mapping
582 **			functions.
583 **
584 **	Returns:
585 **		The mapping, if found.
586 **		NULL if no mapping found.
587 **
588 **	Side Effects:
589 **		Looks up the host specified in hbuf.  If it is not
590 **		the canonical name for that host, return the canonical
591 **		name.
592 */
593 
594 char *
595 maphostname(map, hbuf, hbsize, avp)
596 	MAP *map;
597 	char *hbuf;
598 	int hbsize;
599 	char **avp;
600 {
601 	register struct hostent *hp;
602 	u_long in_addr;
603 	char *cp;
604 	int i;
605 	struct hostent *gethostbyaddr();
606 
607 	/* allow room for null */
608 	hbsize--;
609 
610 	/*
611 	 * If first character is a bracket, then it is an address
612 	 * lookup.  Address is copied into a temporary buffer to
613 	 * strip the brackets and to preserve hbuf if address is
614 	 * unknown.
615 	 */
616 
617 	if (*hbuf != '[')
618 	{
619 		extern bool getcanonname();
620 
621 		if (getcanonname(hbuf, hbsize))
622 			return hbuf;
623 		else
624 			return NULL;
625 	}
626 	if ((cp = strchr(hbuf, ']')) == NULL)
627 		return (NULL);
628 	*cp = '\0';
629 	in_addr = inet_addr(&hbuf[1]);
630 
631 	/* check to see if this is one of our addresses */
632 	for (i = 0; MyIpAddrs[i].s_addr != 0; i++)
633 	{
634 		if (MyIpAddrs[i].s_addr == in_addr)
635 		{
636 			strncpy(hbuf, MyHostName, hbsize);
637 			hbuf[hbsize] = '\0';
638 			return hbuf;
639 		}
640 	}
641 
642 	/* nope -- ask the name server */
643 	hp = gethostbyaddr((char *)&in_addr, sizeof(struct in_addr), AF_INET);
644 	if (hp == NULL)
645 		return (NULL);
646 
647 	/* found a match -- copy out */
648 	if (strlen(hp->h_name) > hbsize)
649 		hp->h_name[hbsize] = '\0';
650 	(void) strcpy(hbuf, hp->h_name);
651 	return hbuf;
652 }
653 
654 # else /* DAEMON */
655 /* code for systems without sophisticated networking */
656 
657 /*
658 **  MYHOSTNAME -- stub version for case of no daemon code.
659 **
660 **	Can't convert to upper case here because might be a UUCP name.
661 **
662 **	Mark, you can change this to be anything you want......
663 */
664 
665 char **
666 myhostname(hostbuf, size)
667 	char hostbuf[];
668 	int size;
669 {
670 	register FILE *f;
671 
672 	hostbuf[0] = '\0';
673 	f = fopen("/usr/include/whoami", "r");
674 	if (f != NULL)
675 	{
676 		(void) fgets(hostbuf, size, f);
677 		fixcrlf(hostbuf, TRUE);
678 		(void) fclose(f);
679 	}
680 	return (NULL);
681 }
682 /*
683 **  GETREALHOSTNAME -- get the real host name asociated with a file descriptor
684 **
685 **	Parameters:
686 **		fd -- the descriptor
687 **
688 **	Returns:
689 **		The host name associated with this descriptor, if it can
690 **			be determined.
691 **		NULL otherwise.
692 **
693 **	Side Effects:
694 **		none
695 */
696 
697 char *
698 getrealhostname(fd)
699 	int fd;
700 {
701 	return NULL;
702 }
703 /*
704 **  MAPHOSTNAME -- turn a hostname into canonical form
705 **
706 **	Parameters:
707 **		map -- a pointer to the database map.
708 **		hbuf -- a buffer containing a hostname.
709 **		avp -- a pointer to a (cf file defined) argument vector.
710 **
711 **	Returns:
712 **		mapped host name
713 **		FALSE otherwise.
714 **
715 **	Side Effects:
716 **		Looks up the host specified in hbuf.  If it is not
717 **		the canonical name for that host, replace it with
718 **		the canonical name.  If the name is unknown, or it
719 **		is already the canonical name, leave it unchanged.
720 */
721 
722 /*ARGSUSED*/
723 char *
724 maphostname(map, hbuf, hbsize, avp)
725 	MAP *map;
726 	char *hbuf;
727 	int hbsize;
728 	char **avp;
729 {
730 	return NULL;
731 }
732 
733 #endif /* DAEMON */
734