1 /*-
2  * Copyright (c) 1990, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 static char copyright[] =
10 "@(#) Copyright (c) 1990, 1993, 1994\n\
11 	The Regents of the University of California.  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)mail.local.c	8.7 (Berkeley) 10/17/94";
16 #endif /* not lint */
17 
18 #include <sys/param.h>
19 #include <sys/stat.h>
20 #include <sys/socket.h>
21 
22 #include <netinet/in.h>
23 
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <netdb.h>
27 #include <pwd.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sysexits.h>
32 #include <syslog.h>
33 #include <time.h>
34 #include <unistd.h>
35 
36 #if __STDC__
37 #include <stdarg.h>
38 #else
39 #include <varargs.h>
40 #endif
41 
42 #ifndef LOCK_EX
43 # include <sys/file.h>
44 #endif
45 
46 #ifdef BSD4_4
47 # include "pathnames.h"
48 #endif
49 
50 #ifndef __P
51 # ifdef __STDC__
52 #  define __P(protos)	protos
53 # else
54 #  define __P(protos)	()
55 #  define const
56 # endif
57 #endif
58 #ifndef __dead
59 # if defined(__GNUC__) && (__GNUC__ < 2 || __GNUC_MINOR__ < 5) && !defined(__STRICT_ANSI__)
60 #  define __dead	__volatile
61 # else
62 #  define __dead
63 # endif
64 #endif
65 
66 #ifndef BSD4_4
67 # define _BSD_VA_LIST_	va_list
68 extern char	*strerror __P((int));
69 #endif
70 
71 #ifndef _PATH_LOCTMP
72 # define _PATH_LOCTMP	"/tmp/local.XXXXXX"
73 #endif
74 #ifndef _PATH_MAILDIR
75 # define _PATH_MAILDIR	"/var/spool/mail"
76 #endif
77 
78 #ifndef S_ISLNK
79 # define S_ISLNK(mode)	(((mode) & _S_IFMT) == S_IFLNK)
80 #endif
81 
82 int eval = EX_OK;			/* sysexits.h error value. */
83 
84 void		deliver __P((int, char *));
85 void		e_to_sys __P((int));
86 __dead void	err __P((const char *, ...));
87 void		notifybiff __P((char *));
88 int		store __P((char *));
89 void		usage __P((void));
90 void		vwarn __P((const char *, _BSD_VA_LIST_));
91 void		warn __P((const char *, ...));
92 
93 int
94 main(argc, argv)
95 	int argc;
96 	char *argv[];
97 {
98 	struct passwd *pw;
99 	int ch, fd;
100 	uid_t uid;
101 	char *from;
102 	extern char *optarg;
103 	extern int optind;
104 
105 #ifdef LOG_MAIL
106 	openlog("mail.local", 0, LOG_MAIL);
107 #else
108 	openlog("mail.local", 0);
109 #endif
110 
111 	from = NULL;
112 	while ((ch = getopt(argc, argv, "df:r:")) != EOF)
113 		switch(ch) {
114 		case 'd':		/* Backward compatible. */
115 			break;
116 		case 'f':
117 		case 'r':		/* Backward compatible. */
118 			if (from != NULL) {
119 				warn("multiple -f options");
120 				usage();
121 			}
122 			from = optarg;
123 			break;
124 		case '?':
125 		default:
126 			usage();
127 		}
128 	argc -= optind;
129 	argv += optind;
130 
131 	if (!*argv)
132 		usage();
133 
134 	/*
135 	 * If from not specified, use the name from getlogin() if the
136 	 * uid matches, otherwise, use the name from the password file
137 	 * corresponding to the uid.
138 	 */
139 	uid = getuid();
140 	if (!from && (!(from = getlogin()) ||
141 	    !(pw = getpwnam(from)) || pw->pw_uid != uid))
142 		from = (pw = getpwuid(uid)) ? pw->pw_name : "???";
143 
144 	/*
145 	 * There is no way to distinguish the error status of one delivery
146 	 * from the rest of the deliveries.  So, if we failed hard on one
147 	 * or more deliveries, but had no failures on any of the others, we
148 	 * return a hard failure.  If we failed temporarily on one or more
149 	 * deliveries, we return a temporary failure regardless of the other
150 	 * failures.  This results in the delivery being reattempted later
151 	 * at the expense of repeated failures and multiple deliveries.
152 	 */
153 	for (fd = store(from); *argv; ++argv)
154 		deliver(fd, *argv);
155 	exit(eval);
156 }
157 
158 int
159 store(from)
160 	char *from;
161 {
162 	FILE *fp;
163 	time_t tval;
164 	int fd, eline;
165 	char line[2048];
166 	char tmpbuf[sizeof _PATH_LOCTMP + 1];
167 
168 	strcpy(tmpbuf, _PATH_LOCTMP);
169 	if ((fd = mkstemp(tmpbuf)) == -1 || (fp = fdopen(fd, "w+")) == NULL) {
170 		e_to_sys(errno);
171 		err("unable to open temporary file");
172 	}
173 	(void)unlink(tmpbuf);
174 
175 	(void)time(&tval);
176 	(void)fprintf(fp, "From %s %s", from, ctime(&tval));
177 
178 	line[0] = '\0';
179 	for (eline = 1; fgets(line, sizeof(line), stdin);) {
180 		if (line[0] == '\n')
181 			eline = 1;
182 		else {
183 			if (eline && line[0] == 'F' &&
184 			    !memcmp(line, "From ", 5))
185 				(void)putc('>', fp);
186 			eline = 0;
187 		}
188 		(void)fprintf(fp, "%s", line);
189 		if (ferror(fp)) {
190 			e_to_sys(errno);
191 			err("temporary file write error");
192 		}
193 	}
194 
195 	/* If message not newline terminated, need an extra. */
196 	if (!strchr(line, '\n'))
197 		(void)putc('\n', fp);
198 	/* Output a newline; note, empty messages are allowed. */
199 	(void)putc('\n', fp);
200 
201 	if (fflush(fp) == EOF || ferror(fp)) {
202 		e_to_sys(errno);
203 		err("temporary file write error");
204 	}
205 	return (fd);
206 }
207 
208 void
209 deliver(fd, name)
210 	int fd;
211 	char *name;
212 {
213 	struct stat fsb, sb;
214 	struct passwd *pw;
215 	int mbfd, nr, nw, off;
216 	char biffmsg[100], buf[8*1024], path[MAXPATHLEN];
217 	off_t curoff;
218 
219 	/*
220 	 * Disallow delivery to unknown names -- special mailboxes can be
221 	 * handled in the sendmail aliases file.
222 	 */
223 	if (!(pw = getpwnam(name))) {
224 		if (eval != EX_TEMPFAIL)
225 			eval = EX_UNAVAILABLE;
226 		warn("unknown name: %s", name);
227 		return;
228 	}
229 
230 	(void)snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR, name);
231 
232 	/*
233 	 * If the mailbox is linked or a symlink, fail.  There's an obvious
234 	 * race here, that the file was replaced with a symbolic link after
235 	 * the lstat returned, but before the open.  We attempt to detect
236 	 * this by comparing the original stat information and information
237 	 * returned by an fstat of the file descriptor returned by the open.
238 	 *
239 	 * NB: this is a symptom of a larger problem, that the mail spooling
240 	 * directory is writeable by the wrong users.  If that directory is
241 	 * writeable, system security is compromised for other reasons, and
242 	 * it cannot be fixed here.
243 	 *
244 	 * If we created the mailbox, set the owner/group.  If that fails,
245 	 * just return.  Another process may have already opened it, so we
246 	 * can't unlink it.  Historically, binmail set the owner/group at
247 	 * each mail delivery.  We no longer do this, assuming that if the
248 	 * ownership or permissions were changed there was a reason.
249 	 *
250 	 * XXX
251 	 * open(2) should support flock'ing the file.
252 	 */
253 tryagain:
254 	if (lstat(path, &sb)) {
255 		mbfd = open(path,
256 		    O_APPEND|O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR);
257 		if (mbfd == -1) {
258 			if (errno == EEXIST)
259 				goto tryagain;
260 		} else if (fchown(mbfd, pw->pw_uid, pw->pw_gid)) {
261 			e_to_sys(errno);
262 			warn("chown %u.%u: %s", pw->pw_uid, pw->pw_gid, name);
263 			return;
264 		}
265 	} else if (sb.st_nlink != 1 || S_ISLNK(sb.st_mode)) {
266 		e_to_sys(errno);
267 		warn("%s: linked file", path);
268 		return;
269 	} else {
270 		mbfd = open(path, O_APPEND|O_WRONLY, 0);
271 		if (mbfd != -1 &&
272 		    (fstat(mbfd, &fsb) || fsb.st_nlink != 1 ||
273 		    S_ISLNK(fsb.st_mode) || sb.st_dev != fsb.st_dev ||
274 		    sb.st_ino != fsb.st_ino)) {
275 			warn("%s: file changed after open", path);
276 			(void)close(mbfd);
277 			return;
278 		}
279 	}
280 
281 	if (mbfd == -1) {
282 		e_to_sys(errno);
283 		warn("%s: %s", path, strerror(errno));
284 		return;
285 	}
286 
287 	/* Wait until we can get a lock on the file. */
288 	if (flock(mbfd, LOCK_EX)) {
289 		e_to_sys(errno);
290 		warn("%s: %s", path, strerror(errno));
291 		goto err1;
292 	}
293 
294 	/* Get the starting offset of the new message for biff. */
295 	curoff = lseek(mbfd, (off_t)0, SEEK_END);
296 	(void)snprintf(biffmsg, sizeof(biffmsg), "%s@%qd\n", name, curoff);
297 
298 	/* Copy the message into the file. */
299 	if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
300 		e_to_sys(errno);
301 		warn("temporary file: %s", strerror(errno));
302 		goto err1;
303 	}
304 	while ((nr = read(fd, buf, sizeof(buf))) > 0)
305 		for (off = 0; off < nr; nr -= nw, off += nw)
306 			if ((nw = write(mbfd, buf + off, nr)) < 0) {
307 				e_to_sys(errno);
308 				warn("%s: %s", path, strerror(errno));
309 				goto err2;;
310 			}
311 	if (nr < 0) {
312 		e_to_sys(errno);
313 		warn("temporary file: %s", strerror(errno));
314 		goto err2;;
315 	}
316 
317 	/* Flush to disk, don't wait for update. */
318 	if (fsync(mbfd)) {
319 		e_to_sys(errno);
320 		warn("%s: %s", path, strerror(errno));
321 err2:		(void)ftruncate(mbfd, curoff);
322 err1:		(void)close(mbfd);
323 		return;
324 	}
325 
326 	/* Close and check -- NFS doesn't write until the close. */
327 	if (close(mbfd)) {
328 		e_to_sys(errno);
329 		warn("%s: %s", path, strerror(errno));
330 		return;
331 	}
332 
333 	notifybiff(biffmsg);
334 }
335 
336 void
337 notifybiff(msg)
338 	char *msg;
339 {
340 	static struct sockaddr_in addr;
341 	static int f = -1;
342 	struct hostent *hp;
343 	struct servent *sp;
344 	int len;
345 
346 	if (!addr.sin_family) {
347 		/* Be silent if biff service not available. */
348 		if (!(sp = getservbyname("biff", "udp")))
349 			return;
350 		if (!(hp = gethostbyname("localhost"))) {
351 			warn("localhost: %s", strerror(errno));
352 			return;
353 		}
354 		addr.sin_family = hp->h_addrtype;
355 		memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
356 		addr.sin_port = sp->s_port;
357 	}
358 	if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
359 		warn("socket: %s", strerror(errno));
360 		return;
361 	}
362 	len = strlen(msg) + 1;
363 	if (sendto(f, msg, len, 0, (struct sockaddr *)&addr, sizeof(addr))
364 	    != len)
365 		warn("sendto biff: %s", strerror(errno));
366 }
367 
368 void
369 usage()
370 {
371 	eval = EX_USAGE;
372 	err("usage: mail.local [-f from] user ...");
373 }
374 
375 #if __STDC__
376 void
377 err(const char *fmt, ...)
378 #else
379 void
380 err(fmt, va_alist)
381 	const char *fmt;
382 	va_dcl
383 #endif
384 {
385 	va_list ap;
386 
387 #if __STDC__
388 	va_start(ap, fmt);
389 #else
390 	va_start(ap);
391 #endif
392 	vwarn(fmt, ap);
393 	va_end(ap);
394 
395 	exit(eval);
396 }
397 
398 void
399 #if __STDC__
400 warn(const char *fmt, ...)
401 #else
402 warn(fmt, va_alist)
403 	const char *fmt;
404 	va_dcl
405 #endif
406 {
407 	va_list ap;
408 
409 #if __STDC__
410 	va_start(ap, fmt);
411 #else
412 	va_start(ap);
413 #endif
414 	vwarn(fmt, ap);
415 	va_end(ap);
416 }
417 
418 void
419 vwarn(fmt, ap)
420 	const char *fmt;
421 	_BSD_VA_LIST_ ap;
422 {
423 	/*
424 	 * Log the message to stderr.
425 	 *
426 	 * Don't use LOG_PERROR as an openlog() flag to do this,
427 	 * it's not portable enough.
428 	 */
429 	if (eval != EX_USAGE)
430 		(void)fprintf(stderr, "mail.local: ");
431 	(void)vfprintf(stderr, fmt, ap);
432 	(void)fprintf(stderr, "\n");
433 
434 #ifndef ultrix
435 	/* Log the message to syslog. */
436 	vsyslog(LOG_ERR, fmt, ap);
437 #else
438 	{
439 		char fmtbuf[10240];
440 
441 		(void) sprintf(fmtbuf, fmt, ap);
442 		syslog(LOG_ERR, "%s", fmtbuf);
443 	}
444 #endif
445 }
446 
447 /*
448  * e_to_sys --
449  *	Guess which errno's are temporary.  Gag me.
450  */
451 void
452 e_to_sys(num)
453 	int num;
454 {
455 	/* Temporary failures override hard errors. */
456 	if (eval == EX_TEMPFAIL)
457 		return;
458 
459 	switch(num) {		/* Hopefully temporary errors. */
460 #ifdef EAGAIN
461 	case EAGAIN:		/* Resource temporarily unavailable */
462 #endif
463 #ifdef EDQUOT
464 	case EDQUOT:		/* Disc quota exceeded */
465 #endif
466 #ifdef EBUSY
467 	case EBUSY:		/* Device busy */
468 #endif
469 #ifdef EPROCLIM
470 	case EPROCLIM:		/* Too many processes */
471 #endif
472 #ifdef EUSERS
473 	case EUSERS:		/* Too many users */
474 #endif
475 #ifdef ECONNABORTED
476 	case ECONNABORTED:	/* Software caused connection abort */
477 #endif
478 #ifdef ECONNREFUSED
479 	case ECONNREFUSED:	/* Connection refused */
480 #endif
481 #ifdef ECONNRESET
482 	case ECONNRESET:	/* Connection reset by peer */
483 #endif
484 #ifdef EDEADLK
485 	case EDEADLK:		/* Resource deadlock avoided */
486 #endif
487 #ifdef EFBIG
488 	case EFBIG:		/* File too large */
489 #endif
490 #ifdef EHOSTDOWN
491 	case EHOSTDOWN:		/* Host is down */
492 #endif
493 #ifdef EHOSTUNREACH
494 	case EHOSTUNREACH:	/* No route to host */
495 #endif
496 #ifdef EMFILE
497 	case EMFILE:		/* Too many open files */
498 #endif
499 #ifdef ENETDOWN
500 	case ENETDOWN:		/* Network is down */
501 #endif
502 #ifdef ENETRESET
503 	case ENETRESET:		/* Network dropped connection on reset */
504 #endif
505 #ifdef ENETUNREACH
506 	case ENETUNREACH:	/* Network is unreachable */
507 #endif
508 #ifdef ENFILE
509 	case ENFILE:		/* Too many open files in system */
510 #endif
511 #ifdef ENOBUFS
512 	case ENOBUFS:		/* No buffer space available */
513 #endif
514 #ifdef ENOMEM
515 	case ENOMEM:		/* Cannot allocate memory */
516 #endif
517 #ifdef ENOSPC
518 	case ENOSPC:		/* No space left on device */
519 #endif
520 #ifdef EROFS
521 	case EROFS:		/* Read-only file system */
522 #endif
523 #ifdef ESTALE
524 	case ESTALE:		/* Stale NFS file handle */
525 #endif
526 #ifdef ETIMEDOUT
527 	case ETIMEDOUT:		/* Connection timed out */
528 #endif
529 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN && EWOULDBLOCK != EDEADLK
530 	case EWOULDBLOCK:	/* Operation would block. */
531 #endif
532 		eval = EX_TEMPFAIL;
533 		break;
534 	default:
535 		eval = EX_UNAVAILABLE;
536 		break;
537 	}
538 }
539 
540 #ifndef BSD4_4
541 
542 char *
543 strerror(eno)
544 	int eno;
545 {
546 	extern int sys_nerr;
547 	extern char *sys_errlist[];
548 	static char ebuf[60];
549 
550 	if (eno >= 0 && eno <= sys_nerr)
551 		return sys_errlist[eno];
552 	(void) sprintf(ebuf, "Error %d", eno);
553 	return ebuf;
554 }
555 
556 #if __STDC__
557 snprintf(char *buf, int bufsiz, const char *fmt, ...)
558 #else
559 snprintf(buf, bufsiz, fmt, va_alist)
560 	char *buf;
561 	int bufsiz;
562 	const char *fmt;
563 	va_dcl
564 #endif
565 {
566 	va_list ap;
567 
568 #if __STDC__
569 	va_start(ap, fmt);
570 #else
571 	va_start(ap);
572 #endif
573 	vsprintf(buf, fmt, ap);
574 	va_end(ap);
575 }
576 
577 #endif
578 
579 #ifdef ultrix
580 
581 int
582 mkstemp(template)
583 	char *template;
584 {
585 	int fd;
586 
587 	return open(mktemp(template), O_RDWR|O_CREAT|O_EXCL, 0600);
588 }
589 
590 #endif
591