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