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