xref: /original-bsd/usr.sbin/sendmail/src/daemon.c (revision 2bd07fe6)
1 /*
2  * Copyright (c) 1983 Eric P. Allman
3  * Copyright (c) 1988 Regents of the University of California.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms are permitted
7  * provided that the above copyright notice and this paragraph are
8  * duplicated in all such forms and that any documentation,
9  * advertising materials, and other materials related to such
10  * distribution and use acknowledge that the software was developed
11  * by the University of California, Berkeley.  The name of the
12  * University may not be used to endorse or promote products derived
13  * from this software without specific prior written permission.
14  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
16  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
17  */
18 
19 #include <errno.h>
20 #include "sendmail.h"
21 
22 #ifndef lint
23 #ifdef DAEMON
24 static char sccsid[] = "@(#)daemon.c	5.35 (Berkeley) 04/19/90 (with daemon mode)";
25 #else
26 static char sccsid[] = "@(#)daemon.c	5.35 (Berkeley) 04/19/90 (without daemon mode)";
27 #endif
28 #endif /* not lint */
29 
30 int la;	/* load average */
31 
32 #ifdef DAEMON
33 
34 # include <netdb.h>
35 # include <sys/signal.h>
36 # include <sys/wait.h>
37 # include <sys/time.h>
38 # include <sys/resource.h>
39 
40 /*
41 **  DAEMON.C -- routines to use when running as a daemon.
42 **
43 **	This entire file is highly dependent on the 4.2 BSD
44 **	interprocess communication primitives.  No attempt has
45 **	been made to make this file portable to Version 7,
46 **	Version 6, MPX files, etc.  If you should try such a
47 **	thing yourself, I recommend chucking the entire file
48 **	and starting from scratch.  Basic semantics are:
49 **
50 **	getrequests()
51 **		Opens a port and initiates a connection.
52 **		Returns in a child.  Must set InChannel and
53 **		OutChannel appropriately.
54 **	clrdaemon()
55 **		Close any open files associated with getting
56 **		the connection; this is used when running the queue,
57 **		etc., to avoid having extra file descriptors during
58 **		the queue run and to avoid confusing the network
59 **		code (if it cares).
60 **	makeconnection(host, port, outfile, infile)
61 **		Make a connection to the named host on the given
62 **		port.  Set *outfile and *infile to the files
63 **		appropriate for communication.  Returns zero on
64 **		success, else an exit status describing the
65 **		error.
66 **	maphostname(hbuf, hbufsize)
67 **		Convert the entry in hbuf into a canonical form.  It
68 **		may not be larger than hbufsize.
69 */
70 /*
71 **  GETREQUESTS -- open mail IPC port and get requests.
72 **
73 **	Parameters:
74 **		none.
75 **
76 **	Returns:
77 **		none.
78 **
79 **	Side Effects:
80 **		Waits until some interesting activity occurs.  When
81 **		it does, a child is created to process it, and the
82 **		parent waits for completion.  Return from this
83 **		routine is always in the child.  The file pointers
84 **		"InChannel" and "OutChannel" should be set to point
85 **		to the communication channel.
86 */
87 
88 struct sockaddr_in	SendmailAddress;/* internet address of sendmail */
89 
90 int	DaemonSocket	= -1;		/* fd describing socket */
91 char	*NetName;			/* name of home (local?) network */
92 
93 getrequests()
94 {
95 	int t;
96 	register struct servent *sp;
97 	int on = 1;
98 	extern reapchild();
99 
100 	/*
101 	**  Set up the address for the mailer.
102 	*/
103 
104 	sp = getservbyname("smtp", "tcp");
105 	if (sp == NULL)
106 	{
107 		syserr("server \"smtp\" unknown");
108 		goto severe;
109 	}
110 	SendmailAddress.sin_family = AF_INET;
111 	SendmailAddress.sin_addr.s_addr = INADDR_ANY;
112 	SendmailAddress.sin_port = sp->s_port;
113 
114 	/*
115 	**  Try to actually open the connection.
116 	*/
117 
118 	if (tTd(15, 1))
119 		printf("getrequests: port 0x%x\n", SendmailAddress.sin_port);
120 
121 	/* get a socket for the SMTP connection */
122 	DaemonSocket = socket(AF_INET, SOCK_STREAM, 0);
123 	if (DaemonSocket < 0)
124 	{
125 		/* probably another daemon already */
126 		syserr("getrequests: can't create socket");
127 	  severe:
128 # ifdef LOG
129 		if (LogLevel > 0)
130 			syslog(LOG_ALERT, "cannot get connection");
131 # endif LOG
132 		finis();
133 	}
134 
135 	/* turn on network debugging? */
136 	if (tTd(15, 15))
137 		(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG, (char *)&on, sizeof on);
138 
139 	(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof on);
140 	(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof on);
141 
142 	if (bind(DaemonSocket, &SendmailAddress, sizeof SendmailAddress) < 0)
143 	{
144 		syserr("getrequests: cannot bind");
145 		(void) close(DaemonSocket);
146 		goto severe;
147 	}
148 	if (listen(DaemonSocket, 10) < 0)
149 	{
150 		syserr("getrequests: cannot listen");
151 		(void) close(DaemonSocket);
152 		goto severe;
153 	}
154 
155 	(void) signal(SIGCHLD, reapchild);
156 
157 	if (tTd(15, 1))
158 		printf("getrequests: %d\n", DaemonSocket);
159 
160 	for (;;)
161 	{
162 		register int pid;
163 		auto int lotherend;
164 		extern int RefuseLA;
165 
166 		/* see if we are rejecting connections */
167 		while ((la = getla()) > RefuseLA)
168 		{
169 			setproctitle("rejecting connections: load average: %.2f", (double)la);
170 			sleep(5);
171 		}
172 
173 		/* wait for a connection */
174 		setproctitle("accepting connections");
175 		do
176 		{
177 			errno = 0;
178 			lotherend = sizeof RealHostAddr;
179 			t = accept(DaemonSocket, &RealHostAddr, &lotherend);
180 		} while (t < 0 && errno == EINTR);
181 		if (t < 0)
182 		{
183 			syserr("getrequests: accept");
184 			sleep(5);
185 			continue;
186 		}
187 
188 		/*
189 		**  Create a subprocess to process the mail.
190 		*/
191 
192 		if (tTd(15, 2))
193 			printf("getrequests: forking (fd = %d)\n", t);
194 
195 		pid = fork();
196 		if (pid < 0)
197 		{
198 			syserr("daemon: cannot fork");
199 			sleep(10);
200 			(void) close(t);
201 			continue;
202 		}
203 
204 		if (pid == 0)
205 		{
206 			extern struct hostent *gethostbyaddr();
207 			register struct hostent *hp;
208 			char buf[MAXNAME];
209 
210 			/*
211 			**  CHILD -- return to caller.
212 			**	Collect verified idea of sending host.
213 			**	Verify calling user id if possible here.
214 			*/
215 
216 			(void) signal(SIGCHLD, SIG_DFL);
217 
218 			/* determine host name */
219 			hp = gethostbyaddr((char *) &RealHostAddr.sin_addr, sizeof RealHostAddr.sin_addr, AF_INET);
220 			if (hp != NULL)
221 				(void) strcpy(buf, hp->h_name);
222 			else
223 			{
224 				extern char *inet_ntoa();
225 
226 				/* produce a dotted quad */
227 				(void) sprintf(buf, "[%s]",
228 					inet_ntoa(RealHostAddr.sin_addr));
229 			}
230 
231 			/* should we check for illegal connection here? XXX */
232 
233 			RealHostName = newstr(buf);
234 
235 			(void) close(DaemonSocket);
236 			InChannel = fdopen(t, "r");
237 			OutChannel = fdopen(dup(t), "w");
238 			if (tTd(15, 2))
239 				printf("getreq: returning\n");
240 # ifdef LOG
241 			if (LogLevel > 11)
242 				syslog(LOG_DEBUG, "connected, pid=%d", getpid());
243 # endif LOG
244 			return;
245 		}
246 
247 		/* close the port so that others will hang (for a while) */
248 		(void) close(t);
249 	}
250 	/*NOTREACHED*/
251 }
252 /*
253 **  CLRDAEMON -- reset the daemon connection
254 **
255 **	Parameters:
256 **		none.
257 **
258 **	Returns:
259 **		none.
260 **
261 **	Side Effects:
262 **		releases any resources used by the passive daemon.
263 */
264 
265 clrdaemon()
266 {
267 	if (DaemonSocket >= 0)
268 		(void) close(DaemonSocket);
269 	DaemonSocket = -1;
270 }
271 /*
272 **  MAKECONNECTION -- make a connection to an SMTP socket on another machine.
273 **
274 **	Parameters:
275 **		host -- the name of the host.
276 **		port -- the port number to connect to.
277 **		outfile -- a pointer to a place to put the outfile
278 **			descriptor.
279 **		infile -- ditto for infile.
280 **
281 **	Returns:
282 **		An exit code telling whether the connection could be
283 **			made and if not why not.
284 **
285 **	Side Effects:
286 **		none.
287 */
288 
289 makeconnection(host, port, outfile, infile)
290 	char *host;
291 	u_short port;
292 	FILE **outfile;
293 	FILE **infile;
294 {
295 	register int i, s;
296 	register struct hostent *hp = (struct hostent *)NULL;
297 	extern char *inet_ntoa();
298 	int sav_errno;
299 #ifdef NAMED_BIND
300 	extern int h_errno;
301 #endif
302 
303 	/*
304 	**  Set up the address for the mailer.
305 	**	Accept "[a.b.c.d]" syntax for host name.
306 	*/
307 
308 #ifdef NAMED_BIND
309 	h_errno = 0;
310 #endif
311 	errno = 0;
312 
313 	if (host[0] == '[')
314 	{
315 		long hid;
316 		register char *p = index(host, ']');
317 
318 		if (p != NULL)
319 		{
320 			*p = '\0';
321 			hid = inet_addr(&host[1]);
322 			*p = ']';
323 		}
324 		if (p == NULL || hid == -1)
325 		{
326 			usrerr("Invalid numeric domain spec \"%s\"", host);
327 			return (EX_NOHOST);
328 		}
329 		SendmailAddress.sin_addr.s_addr = hid;
330 	}
331 	else
332 	{
333 		hp = gethostbyname(host);
334 		if (hp == NULL)
335 		{
336 #ifdef NAMED_BIND
337 			if (errno == ETIMEDOUT || h_errno == TRY_AGAIN)
338 				return (EX_TEMPFAIL);
339 
340 			/* if name server is specified, assume temp fail */
341 			if (errno == ECONNREFUSED && UseNameServer)
342 				return (EX_TEMPFAIL);
343 #endif
344 
345 			/*
346 			**  XXX Should look for mail forwarder record here
347 			**  XXX if (h_errno == NO_ADDRESS).
348 			*/
349 
350 			return (EX_NOHOST);
351 		}
352 		bcopy(hp->h_addr, (char *) &SendmailAddress.sin_addr, hp->h_length);
353 		i = 1;
354 	}
355 
356 	/*
357 	**  Determine the port number.
358 	*/
359 
360 	if (port != 0)
361 		SendmailAddress.sin_port = htons(port);
362 	else
363 	{
364 		register struct servent *sp = getservbyname("smtp", "tcp");
365 
366 		if (sp == NULL)
367 		{
368 			syserr("makeconnection: server \"smtp\" unknown");
369 			return (EX_OSFILE);
370 		}
371 		SendmailAddress.sin_port = sp->s_port;
372 	}
373 
374 	/*
375 	**  Try to actually open the connection.
376 	*/
377 
378 again:
379 	if (tTd(16, 1))
380 		printf("makeconnection (%s [%s])\n", host,
381 		    inet_ntoa(SendmailAddress.sin_addr.s_addr));
382 
383 	s = socket(AF_INET, SOCK_STREAM, 0);
384 	if (s < 0)
385 	{
386 		syserr("makeconnection: no socket");
387 		sav_errno = errno;
388 		goto failure;
389 	}
390 
391 	if (tTd(16, 1))
392 		printf("makeconnection: %d\n", s);
393 
394 	/* turn on network debugging? */
395 	if (tTd(16, 14))
396 	{
397 		int on = 1;
398 		(void) setsockopt(DaemonSocket, SOL_SOCKET, SO_DEBUG, (char *)&on, sizeof on);
399 	}
400 	if (CurEnv->e_xfp != NULL)
401 		(void) fflush(CurEnv->e_xfp);		/* for debugging */
402 	errno = 0;					/* for debugging */
403 	SendmailAddress.sin_family = AF_INET;
404 	if (connect(s, &SendmailAddress, sizeof SendmailAddress) < 0)
405 	{
406 		sav_errno = errno;
407 		(void) close(s);
408 		if (hp && hp->h_addr_list[i])
409 		{
410 			bcopy(hp->h_addr_list[i++],
411 			    (char *)&SendmailAddress.sin_addr, hp->h_length);
412 			goto again;
413 		}
414 
415 		/* failure, decide if temporary or not */
416 	failure:
417 		switch (sav_errno)
418 		{
419 		  case EISCONN:
420 		  case ETIMEDOUT:
421 		  case EINPROGRESS:
422 		  case EALREADY:
423 		  case EADDRINUSE:
424 		  case EHOSTDOWN:
425 		  case ENETDOWN:
426 		  case ENETRESET:
427 		  case ENOBUFS:
428 		  case ECONNREFUSED:
429 		  case ECONNRESET:
430 		  case EHOSTUNREACH:
431 		  case ENETUNREACH:
432 			/* there are others, I'm sure..... */
433 			return (EX_TEMPFAIL);
434 
435 		  case EPERM:
436 			/* why is this happening? */
437 			syserr("makeconnection: funny failure, addr=%lx, port=%x",
438 				SendmailAddress.sin_addr.s_addr, SendmailAddress.sin_port);
439 			return (EX_TEMPFAIL);
440 
441 		  default:
442 			{
443 				extern char *errstring();
444 
445 				message(Arpa_Info, "%s", errstring(sav_errno));
446 				return (EX_UNAVAILABLE);
447 			}
448 		}
449 	}
450 
451 	/* connection ok, put it into canonical form */
452 	*outfile = fdopen(s, "w");
453 	*infile = fdopen(dup(s), "r");
454 
455 	return (EX_OK);
456 }
457 /*
458 **  MYHOSTNAME -- return the name of this host.
459 **
460 **	Parameters:
461 **		hostbuf -- a place to return the name of this host.
462 **		size -- the size of hostbuf.
463 **
464 **	Returns:
465 **		A list of aliases for this host.
466 **
467 **	Side Effects:
468 **		none.
469 */
470 
471 char **
472 myhostname(hostbuf, size)
473 	char hostbuf[];
474 	int size;
475 {
476 	extern struct hostent *gethostbyname();
477 	struct hostent *hp;
478 
479 	if (gethostname(hostbuf, size) < 0)
480 	{
481 		(void) strcpy(hostbuf, "localhost");
482 	}
483 	hp = gethostbyname(hostbuf);
484 	if (hp != NULL)
485 	{
486 		(void) strcpy(hostbuf, hp->h_name);
487 		return (hp->h_aliases);
488 	}
489 	else
490 		return (NULL);
491 }
492 
493 /*
494  *  MAPHOSTNAME -- turn a hostname into canonical form
495  *
496  *	Parameters:
497  *		hbuf -- a buffer containing a hostname.
498  *		hbsize -- the size of hbuf.
499  *
500  *	Returns:
501  *		none.
502  *
503  *	Side Effects:
504  *		Looks up the host specified in hbuf.  If it is not
505  *		the canonical name for that host, replace it with
506  *		the canonical name.  If the name is unknown, or it
507  *		is already the canonical name, leave it unchanged.
508  */
509 maphostname(hbuf, hbsize)
510 	char *hbuf;
511 	int hbsize;
512 {
513 	register struct hostent *hp;
514 	u_long in_addr;
515 	char ptr[256], *cp;
516 	struct hostent *gethostbyaddr();
517 
518 	/*
519 	 * If first character is a bracket, then it is an address
520 	 * lookup.  Address is copied into a temporary buffer to
521 	 * strip the brackets and to preserve hbuf if address is
522 	 * unknown.
523 	 */
524 	if (*hbuf != '[') {
525 		getcanonname(hbuf, hbsize);
526 		return;
527 	}
528 	if ((cp = index(strcpy(ptr, hbuf), ']')) == NULL)
529 		return;
530 	*cp = '\0';
531 	in_addr = inet_addr(&ptr[1]);
532 	hp = gethostbyaddr((char *)&in_addr, sizeof(struct in_addr), AF_INET);
533 	if (hp == NULL)
534 		return;
535 	if (strlen(hp->h_name) >= hbsize)
536 		hp->h_name[hbsize - 1] = '\0';
537 	(void)strcpy(hbuf, hp->h_name);
538 }
539 
540 # else DAEMON
541 /* code for systems without sophisticated networking */
542 
543 /*
544 **  MYHOSTNAME -- stub version for case of no daemon code.
545 **
546 **	Can't convert to upper case here because might be a UUCP name.
547 **
548 **	Mark, you can change this to be anything you want......
549 */
550 
551 char **
552 myhostname(hostbuf, size)
553 	char hostbuf[];
554 	int size;
555 {
556 	register FILE *f;
557 
558 	hostbuf[0] = '\0';
559 	f = fopen("/usr/include/whoami", "r");
560 	if (f != NULL)
561 	{
562 		(void) fgets(hostbuf, size, f);
563 		fixcrlf(hostbuf, TRUE);
564 		(void) fclose(f);
565 	}
566 	return (NULL);
567 }
568 /*
569 **  MAPHOSTNAME -- turn a hostname into canonical form
570 **
571 **	Parameters:
572 **		hbuf -- a buffer containing a hostname.
573 **		hbsize -- the size of hbuf.
574 **
575 **	Returns:
576 **		none.
577 **
578 **	Side Effects:
579 **		Looks up the host specified in hbuf.  If it is not
580 **		the canonical name for that host, replace it with
581 **		the canonical name.  If the name is unknown, or it
582 **		is already the canonical name, leave it unchanged.
583 */
584 
585 /*ARGSUSED*/
586 maphostname(hbuf, hbsize)
587 	char *hbuf;
588 	int hbsize;
589 {
590 	return;
591 }
592 
593 #endif DAEMON
594