xref: /original-bsd/usr.sbin/sendmail/src/daemon.c (revision 4670e840)
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.16 (Berkeley) 03/09/93 (with daemon mode)";
16 #else
17 static char sccsid[] = "@(#)daemon.c	6.16 (Berkeley) 03/09/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 	FILE *pidf;
83 	struct sockaddr_in srvraddr;
84 	extern void reapchild();
85 
86 	/*
87 	**  Set up the address for the mailer.
88 	*/
89 
90 	sp = getservbyname("smtp", "tcp");
91 	if (sp == NULL)
92 	{
93 		syserr("554 server \"smtp\" unknown");
94 		goto severe;
95 	}
96 	srvraddr.sin_family = AF_INET;
97 	srvraddr.sin_addr.s_addr = INADDR_ANY;
98 	srvraddr.sin_port = sp->s_port;
99 
100 	/*
101 	**  Try to actually open the connection.
102 	*/
103 
104 	if (tTd(15, 1))
105 		printf("getrequests: port 0x%x\n", srvraddr.sin_port);
106 
107 	/* get a socket for the SMTP connection */
108 	DaemonSocket = socket(AF_INET, SOCK_STREAM, 0);
109 	if (DaemonSocket < 0)
110 	{
111 		/* probably another daemon already */
112 		syserr("getrequests: can't create socket");
113 	  severe:
114 # ifdef LOG
115 		if (LogLevel > 0)
116 			syslog(LOG_ALERT, "problem creating SMTP socket");
117 # endif /* LOG */
118 		finis();
119 	}
120 
121 	/* turn on network debugging? */
122 	if (tTd(15, 101))
123 		(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG, (char *)&on, sizeof on);
124 
125 	(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof on);
126 	(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof on);
127 
128 	if (bind(DaemonSocket, (struct sockaddr *)&srvraddr, sizeof srvraddr) < 0)
129 	{
130 		syserr("getrequests: cannot bind");
131 		(void) close(DaemonSocket);
132 		goto severe;
133 	}
134 
135 	(void) signal(SIGCHLD, reapchild);
136 
137 	/* write the pid to the log file for posterity */
138 	pidf = fopen(PidFile, "w");
139 	if (pidf != NULL)
140 	{
141 		fprintf(pidf, "%d\n", getpid());
142 		fclose(pidf);
143 	}
144 
145 
146 	if (tTd(15, 1))
147 		printf("getrequests: %d\n", DaemonSocket);
148 
149 	for (;;)
150 	{
151 		register int pid;
152 		auto int lotherend;
153 		extern bool refuseconnections();
154 
155 		/* see if we are rejecting connections */
156 		CurrentLA = getla();
157 		if (refuseconnections())
158 		{
159 			if (!refusingconnections)
160 			{
161 				/* don't queue so peer will fail quickly */
162 				(void) listen(DaemonSocket, 0);
163 				refusingconnections = TRUE;
164 			}
165 			setproctitle("rejecting connections: load average: %d",
166 				CurrentLA);
167 			sleep(5);
168 			continue;
169 		}
170 
171 		if (refusingconnections)
172 		{
173 			/* start listening again */
174 			if (listen(DaemonSocket, 10) < 0)
175 			{
176 				syserr("getrequests: cannot listen");
177 				(void) close(DaemonSocket);
178 				goto severe;
179 			}
180 			setproctitle("accepting connections");
181 			refusingconnections = FALSE;
182 		}
183 
184 		/* wait for a connection */
185 		do
186 		{
187 			errno = 0;
188 			lotherend = sizeof RealHostAddr;
189 			t = accept(DaemonSocket,
190 			    (struct sockaddr *)&RealHostAddr, &lotherend);
191 		} while (t < 0 && errno == EINTR);
192 		if (t < 0)
193 		{
194 			syserr("getrequests: accept");
195 			sleep(5);
196 			continue;
197 		}
198 
199 		/*
200 		**  Create a subprocess to process the mail.
201 		*/
202 
203 		if (tTd(15, 2))
204 			printf("getrequests: forking (fd = %d)\n", t);
205 
206 		pid = fork();
207 		if (pid < 0)
208 		{
209 			syserr("daemon: cannot fork");
210 			sleep(10);
211 			(void) close(t);
212 			continue;
213 		}
214 
215 		if (pid == 0)
216 		{
217 			extern struct hostent *gethostbyaddr();
218 			register struct hostent *hp;
219 			char buf[MAXNAME];
220 			extern char *inet_ntoa();
221 
222 			/*
223 			**  CHILD -- return to caller.
224 			**	Collect verified idea of sending host.
225 			**	Verify calling user id if possible here.
226 			*/
227 
228 			(void) signal(SIGCHLD, SIG_DFL);
229 
230 			/* determine host name */
231 			hp = gethostbyaddr((char *) &RealHostAddr.sin_addr, sizeof RealHostAddr.sin_addr, AF_INET);
232 			if (hp != NULL)
233 				(void) strcpy(buf, hp->h_name);
234 			else
235 			{
236 				/* produce a dotted quad */
237 				(void) sprintf(buf, "[%s]",
238 					inet_ntoa(RealHostAddr.sin_addr));
239 			}
240 
241 #ifdef LOG
242 			if (LogLevel > 10)
243 			{
244 				/* log connection information */
245 				syslog(LOG_INFO, "connect from %s (%s)",
246 					buf, inet_ntoa(RealHostAddr.sin_addr));
247 			}
248 #endif
249 
250 			/* should we check for illegal connection here? XXX */
251 
252 			RealHostName = newstr(buf);
253 
254 			(void) close(DaemonSocket);
255 			InChannel = fdopen(t, "r");
256 			OutChannel = fdopen(dup(t), "w");
257 			if (tTd(15, 2))
258 				printf("getreq: returning\n");
259 # ifdef LOG
260 			if (LogLevel > 11)
261 				syslog(LOG_DEBUG, "connected, pid=%d", getpid());
262 # endif /* LOG */
263 			return;
264 		}
265 
266 		/* close the port so that others will hang (for a while) */
267 		(void) close(t);
268 	}
269 	/*NOTREACHED*/
270 }
271 /*
272 **  CLRDAEMON -- reset the daemon connection
273 **
274 **	Parameters:
275 **		none.
276 **
277 **	Returns:
278 **		none.
279 **
280 **	Side Effects:
281 **		releases any resources used by the passive daemon.
282 */
283 
284 clrdaemon()
285 {
286 	if (DaemonSocket >= 0)
287 		(void) close(DaemonSocket);
288 	DaemonSocket = -1;
289 }
290 /*
291 **  MAKECONNECTION -- make a connection to an SMTP socket on another machine.
292 **
293 **	Parameters:
294 **		host -- the name of the host.
295 **		port -- the port number to connect to.
296 **		mci -- a pointer to the mail connection information
297 **			structure to be filled in.
298 **		usesecureport -- if set, use a low numbered (reserved)
299 **			port to provide some rudimentary authentication.
300 **
301 **	Returns:
302 **		An exit code telling whether the connection could be
303 **			made and if not why not.
304 **
305 **	Side Effects:
306 **		none.
307 */
308 
309 struct sockaddr_in	CurHostAddr;		/* address of current host */
310 
311 int
312 makeconnection(host, port, mci, usesecureport)
313 	char *host;
314 	u_short port;
315 	register MCI *mci;
316 	bool usesecureport;
317 {
318 	register int i, s;
319 	register struct hostent *hp = (struct hostent *)NULL;
320 	struct sockaddr_in addr;
321 	int sav_errno;
322 	extern char *inet_ntoa();
323 #ifdef NAMED_BIND
324 	extern int h_errno;
325 #endif
326 
327 	/*
328 	**  Set up the address for the mailer.
329 	**	Accept "[a.b.c.d]" syntax for host name.
330 	*/
331 
332 #ifdef NAMED_BIND
333 	h_errno = 0;
334 #endif
335 	errno = 0;
336 
337 	if (host[0] == '[')
338 	{
339 		long hid;
340 		register char *p = strchr(host, ']');
341 
342 		if (p != NULL)
343 		{
344 			*p = '\0';
345 			hid = inet_addr(&host[1]);
346 			if (hid == -1)
347 			{
348 				/* try it as a host name (avoid MX lookup) */
349 				hp = gethostbyname(&host[1]);
350 				*p = ']';
351 				goto gothostent;
352 			}
353 			*p = ']';
354 		}
355 		if (p == NULL)
356 		{
357 			usrerr("553 Invalid numeric domain spec \"%s\"", host);
358 			return (EX_NOHOST);
359 		}
360 		addr.sin_addr.s_addr = hid;
361 	}
362 	else
363 	{
364 		hp = gethostbyname(host);
365 gothostent:
366 		if (hp == NULL)
367 		{
368 #ifdef NAMED_BIND
369 			if (errno == ETIMEDOUT || h_errno == TRY_AGAIN)
370 				return (EX_TEMPFAIL);
371 
372 			/* if name server is specified, assume temp fail */
373 			if (errno == ECONNREFUSED && UseNameServer)
374 				return (EX_TEMPFAIL);
375 #endif
376 			return (EX_NOHOST);
377 		}
378 		bcopy(hp->h_addr, (char *) &addr.sin_addr, hp->h_length);
379 		i = 1;
380 	}
381 
382 	/*
383 	**  Determine the port number.
384 	*/
385 
386 	if (port != 0)
387 		addr.sin_port = htons(port);
388 	else
389 	{
390 		register struct servent *sp = getservbyname("smtp", "tcp");
391 
392 		if (sp == NULL)
393 		{
394 			syserr("554 makeconnection: server \"smtp\" unknown");
395 			return (EX_OSERR);
396 		}
397 		addr.sin_port = sp->s_port;
398 	}
399 
400 	/*
401 	**  Try to actually open the connection.
402 	*/
403 
404 	for (;;)
405 	{
406 		if (tTd(16, 1))
407 			printf("makeconnection (%s [%s])\n", host,
408 			    inet_ntoa(addr.sin_addr));
409 
410 		/* save for logging */
411 		CurHostAddr = addr;
412 
413 		if (usesecureport)
414 		{
415 			int rport = IPPORT_RESERVED - 1;
416 
417 			s = rresvport(&rport);
418 		}
419 		else
420 		{
421 			s = socket(AF_INET, SOCK_STREAM, 0);
422 		}
423 		if (s < 0)
424 		{
425 			sav_errno = errno;
426 			syserr("makeconnection: no socket");
427 			goto failure;
428 		}
429 
430 		if (tTd(16, 1))
431 			printf("makeconnection: fd=%d\n", s);
432 
433 		/* turn on network debugging? */
434 		if (tTd(16, 101))
435 		{
436 			int on = 1;
437 			(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG,
438 					  (char *)&on, sizeof on);
439 		}
440 		if (CurEnv->e_xfp != NULL)
441 			(void) fflush(CurEnv->e_xfp);		/* for debugging */
442 		errno = 0;					/* for debugging */
443 		addr.sin_family = AF_INET;
444 		if (connect(s, (struct sockaddr *) &addr, sizeof addr) >= 0)
445 			break;
446 
447 		/* couldn't connect.... figure out why */
448 		sav_errno = errno;
449 		(void) close(s);
450 		if (hp && hp->h_addr_list[i])
451 		{
452 			if (tTd(16, 1))
453 				printf("Connect failed; trying new address....\n");
454 			bcopy(hp->h_addr_list[i++], (char *) &addr.sin_addr,
455 					hp->h_length);
456 			continue;
457 		}
458 
459 		/* failure, decide if temporary or not */
460 	failure:
461 		if (transienterror(sav_errno))
462 			return EX_TEMPFAIL;
463 		else if (sav_errno == EPERM)
464 		{
465 			/* why is this happening? */
466 			syserr("makeconnection: funny failure, addr=%lx, port=%x",
467 				addr.sin_addr.s_addr, addr.sin_port);
468 			return (EX_TEMPFAIL);
469 		}
470 		else
471 		{
472 			extern char *errstring();
473 
474 			message("%s", errstring(sav_errno));
475 			return (EX_UNAVAILABLE);
476 		}
477 	}
478 
479 	/* connection ok, put it into canonical form */
480 	mci->mci_out = fdopen(s, "w");
481 	mci->mci_in = fdopen(dup(s), "r");
482 
483 	return (EX_OK);
484 }
485 /*
486 **  MYHOSTNAME -- return the name of this host.
487 **
488 **	Parameters:
489 **		hostbuf -- a place to return the name of this host.
490 **		size -- the size of hostbuf.
491 **
492 **	Returns:
493 **		A list of aliases for this host.
494 **
495 **	Side Effects:
496 **		Sets the MyIpAddrs buffer to a list of my IP addresses.
497 */
498 
499 struct in_addr	MyIpAddrs[MAXIPADDR + 1];
500 
501 char **
502 myhostname(hostbuf, size)
503 	char hostbuf[];
504 	int size;
505 {
506 	register struct hostent *hp;
507 	extern struct hostent *gethostbyname();
508 
509 	if (gethostname(hostbuf, size) < 0)
510 	{
511 		(void) strcpy(hostbuf, "localhost");
512 	}
513 	hp = gethostbyname(hostbuf);
514 	if (hp != NULL)
515 	{
516 		(void) strncpy(hostbuf, hp->h_name, size - 1);
517 		hostbuf[size - 1] = '\0';
518 
519 		if (hp->h_addrtype == AF_INET && hp->h_length == 4)
520 		{
521 			register int i;
522 
523 			for (i = 0; i < MAXIPADDR; i++)
524 			{
525 				if (hp->h_addr_list[i] == NULL)
526 					break;
527 				MyIpAddrs[i].s_addr = *(u_long *) hp->h_addr_list[i];
528 			}
529 			MyIpAddrs[i].s_addr = 0;
530 		}
531 
532 		return (hp->h_aliases);
533 	}
534 	else
535 		return (NULL);
536 }
537 /*
538 **  GETREALHOSTNAME -- get the real host name asociated with a file descriptor
539 **
540 **	Parameters:
541 **		fd -- the descriptor
542 **
543 **	Returns:
544 **		The host name associated with this descriptor, if it can
545 **			be determined.
546 **		NULL otherwise.
547 **
548 **	Side Effects:
549 **		none
550 */
551 
552 char *
553 getrealhostname(fd)
554 	int fd;
555 {
556 	register struct hostent *hp;
557 	struct sockaddr_in sin;
558 	int sinlen;
559 	char hbuf[MAXNAME];
560 	extern struct hostent *gethostbyaddr();
561 	extern char *inet_ntoa();
562 
563 	if (getsockname(fd, (struct sockaddr *) &sin, &sinlen) < 0 ||
564 	    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