1 /*-
2  * Copyright (c) 1990, 1993
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\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.1 (Berkeley) 06/04/93";
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 #include "pathnames.h"
43 
44 int eval = EX_OK;			/* sysexits.h error value. */
45 
46 void		deliver __P((int, char *));
47 void		e_to_sys __P((int));
48 __dead void	err __P((const char *, ...));
49 void		notifybiff __P((char *));
50 int		store __P((char *));
51 void		usage __P((void));
52 void		vwarn __P((const char *, _BSD_VA_LIST_));
53 void		warn __P((const char *, ...));
54 
55 int
56 main(argc, argv)
57 	int argc;
58 	char *argv[];
59 {
60 	struct passwd *pw;
61 	int ch, fd;
62 	uid_t uid;
63 	char *from;
64 
65 	openlog("mail.local", 0, LOG_MAIL);
66 
67 	from = NULL;
68 	while ((ch = getopt(argc, argv, "df:r:")) != EOF)
69 		switch(ch) {
70 		case 'd':		/* Backward compatible. */
71 			break;
72 		case 'f':
73 		case 'r':		/* Backward compatible. */
74 			if (from != NULL) {
75 				warn("multiple -f options");
76 				usage();
77 			}
78 			from = optarg;
79 			break;
80 		case '?':
81 		default:
82 			usage();
83 		}
84 	argc -= optind;
85 	argv += optind;
86 
87 	if (!*argv)
88 		usage();
89 
90 	/*
91 	 * If from not specified, use the name from getlogin() if the
92 	 * uid matches, otherwise, use the name from the password file
93 	 * corresponding to the uid.
94 	 */
95 	uid = getuid();
96 	if (!from && (!(from = getlogin()) ||
97 	    !(pw = getpwnam(from)) || pw->pw_uid != uid))
98 		from = (pw = getpwuid(uid)) ? pw->pw_name : "???";
99 
100 	/*
101 	 * There is no way to distinguish the error status of one delivery
102 	 * from the rest of the deliveries.  So, if we failed hard on one
103 	 * or more deliveries, but had no failures on any of the others, we
104 	 * return a hard failure.  If we failed temporarily on one or more
105 	 * deliveries, we return a temporary failure regardless of the other
106 	 * failures.  This results in the delivery being reattempted later
107 	 * at the expense of repeated failures and multiple deliveries.
108 	 */
109 	for (fd = store(from); *argv; ++argv)
110 		deliver(fd, *argv);
111 	exit(eval);
112 }
113 
114 int
115 store(from)
116 	char *from;
117 {
118 	FILE *fp;
119 	time_t tval;
120 	int fd, eline;
121 	char *tn, line[2048];
122 
123 	tn = strdup(_PATH_LOCTMP);
124 	if ((fd = mkstemp(tn)) == -1 || (fp = fdopen(fd, "w+")) == NULL) {
125 		e_to_sys(errno);
126 		err("unable to open temporary file");
127 	}
128 	(void)unlink(tn);
129 	free(tn);
130 
131 	(void)time(&tval);
132 	(void)fprintf(fp, "From %s %s", from, ctime(&tval));
133 
134 	line[0] = '\0';
135 	for (eline = 1; fgets(line, sizeof(line), stdin);) {
136 		if (line[0] == '\n')
137 			eline = 1;
138 		else {
139 			if (eline && line[0] == 'F' &&
140 			    !memcmp(line, "From ", 5))
141 				(void)putc('>', fp);
142 			eline = 0;
143 		}
144 		(void)fprintf(fp, "%s", line);
145 		if (ferror(fp)) {
146 			e_to_sys(errno);
147 			err("temporary file write error");
148 		}
149 	}
150 
151 	/* If message not newline terminated, need an extra. */
152 	if (!strchr(line, '\n'))
153 		(void)putc('\n', fp);
154 	/* Output a newline; note, empty messages are allowed. */
155 	(void)putc('\n', fp);
156 
157 	if (fflush(fp) == EOF || ferror(fp)) {
158 		e_to_sys(errno);
159 		err("temporary file write error");
160 	}
161 	return (fd);
162 }
163 
164 void
165 deliver(fd, name)
166 	int fd;
167 	char *name;
168 {
169 	struct stat sb;
170 	struct passwd *pw;
171 	int mbfd, nr, nw, off;
172 	char biffmsg[100], buf[8*1024], path[MAXPATHLEN];
173 	off_t curoff;
174 
175 	/*
176 	 * Disallow delivery to unknown names -- special mailboxes can be
177 	 * handled in the sendmail aliases file.
178 	 */
179 	if (!(pw = getpwnam(name))) {
180 		if (eval != EX_TEMPFAIL)
181 			eval = EX_UNAVAILABLE;
182 		warn("unknown name: %s", name);
183 		return;
184 	}
185 
186 	(void)snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR, name);
187 
188 	/*
189 	 * If the mailbox is a linked or a symlink, fail.
190 	 *
191 	 * If we created the mailbox, set the owner/group.  If that fails,
192 	 * just return.  Another process may have already opened it, so we
193 	 * can't unlink it.  Historically, binmail set the owner/group at
194 	 * each mail delivery.  We no longer do this, assuming that if the
195 	 * ownership or permissions were changed there was a reason.
196 	 *
197 	 * XXX
198 	 * open(2) should support flock'ing the file.
199 	 */
200 	if (lstat(path, &sb)) {
201 		if ((mbfd = open(path,
202 		    O_APPEND|O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR)) < 0)
203 			mbfd = open(path, O_APPEND|O_WRONLY, 0);
204 		else if (fchown(mbfd, pw->pw_uid, pw->pw_gid)) {
205 			e_to_sys(errno);
206 			warn("chown %u.%u: %s", pw->pw_uid, pw->pw_gid, name);
207 			return;
208 		}
209 	} else if (sb.st_nlink != 1 || S_ISLNK(sb.st_mode)) {
210 		e_to_sys(errno);
211 		warn("%s: linked file", path);
212 		return;
213 	} else
214 		mbfd = open(path, O_APPEND|O_WRONLY, 0);
215 
216 	if (mbfd == -1) {
217 		e_to_sys(errno);
218 		warn("%s: %s", path, strerror(errno));
219 		return;
220 	}
221 
222 	/* Wait until we can get a lock on the file. */
223 	if (flock(mbfd, LOCK_EX)) {
224 		e_to_sys(errno);
225 		warn("%s: %s", path, strerror(errno));
226 		goto err1;
227 	}
228 
229 	/* Get the starting offset of the new message for biff. */
230 	curoff = lseek(mbfd, (off_t)0, SEEK_END);
231 	(void)snprintf(biffmsg, sizeof(biffmsg), "%s@%qd\n", name, curoff);
232 
233 	/* Copy the message into the file. */
234 	if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
235 		e_to_sys(errno);
236 		warn("temporary file: %s", strerror(errno));
237 		goto err1;
238 	}
239 	while ((nr = read(fd, buf, sizeof(buf))) > 0)
240 		for (off = 0; off < nr; nr -= nw, off += nw)
241 			if ((nw = write(mbfd, buf + off, nr)) < 0) {
242 				e_to_sys(errno);
243 				warn("%s: %s", path, strerror(errno));
244 				goto err2;;
245 			}
246 	if (nr < 0) {
247 		e_to_sys(errno);
248 		warn("temporary file: %s", strerror(errno));
249 		goto err2;;
250 	}
251 
252 	/* Flush to disk, don't wait for update. */
253 	if (fsync(mbfd)) {
254 		e_to_sys(errno);
255 		warn("%s: %s", path, strerror(errno));
256 err2:		(void)ftruncate(mbfd, curoff);
257 err1:		(void)close(mbfd);
258 		return;
259 	}
260 
261 	/* Close and check -- NFS doesn't write until the close. */
262 	if (close(mbfd)) {
263 		e_to_sys(errno);
264 		warn("%s: %s", path, strerror(errno));
265 		return;
266 	}
267 
268 	notifybiff(biffmsg);
269 }
270 
271 void
272 notifybiff(msg)
273 	char *msg;
274 {
275 	static struct sockaddr_in addr;
276 	static int f = -1;
277 	struct hostent *hp;
278 	struct servent *sp;
279 	int len;
280 
281 	if (!addr.sin_family) {
282 		/* Be silent if biff service not available. */
283 		if (!(sp = getservbyname("biff", "udp")))
284 			return;
285 		if (!(hp = gethostbyname("localhost"))) {
286 			warn("localhost: %s", strerror(errno));
287 			return;
288 		}
289 		addr.sin_family = hp->h_addrtype;
290 		memmove(&addr.sin_addr, hp->h_addr, hp->h_length);
291 		addr.sin_port = sp->s_port;
292 	}
293 	if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
294 		warn("socket: %s", strerror(errno));
295 		return;
296 	}
297 	len = strlen(msg) + 1;
298 	if (sendto(f, msg, len, 0, (struct sockaddr *)&addr, sizeof(addr))
299 	    != len)
300 		warn("sendto biff: %s", strerror(errno));
301 }
302 
303 void
304 usage()
305 {
306 	eval = EX_USAGE;
307 	err("usage: mail.local [-f from] user ...");
308 }
309 
310 void
311 #if __STDC__
312 err(const char *fmt, ...)
313 #else
314 err(fmt, va_alist)
315 	const char *fmt;
316 	va_dcl
317 #endif
318 {
319 	va_list ap;
320 
321 #if __STDC__
322 	va_start(ap, fmt);
323 #else
324 	va_start(ap);
325 #endif
326 	vwarn(fmt, ap);
327 	va_end(ap);
328 
329 	exit(eval);
330 }
331 
332 void
333 #if __STDC__
334 warn(const char *fmt, ...)
335 #else
336 warn(fmt, va_alist)
337 	const char *fmt;
338 	va_dcl
339 #endif
340 {
341 	va_list ap;
342 
343 #if __STDC__
344 	va_start(ap, fmt);
345 #else
346 	va_start(ap);
347 #endif
348 	vwarn(fmt, ap);
349 	va_end(ap);
350 }
351 
352 void
353 vwarn(fmt, ap)
354 	const char *fmt;
355 	_BSD_VA_LIST_ ap;
356 {
357 	/*
358 	 * Log the message to stderr.
359 	 *
360 	 * Don't use LOG_PERROR as an openlog() flag to do this,
361 	 * it's not portable enough.
362 	 */
363 	if (eval != EX_USAGE)
364 		(void)fprintf(stderr, "mail.local: ");
365 	(void)vfprintf(stderr, fmt, ap);
366 	(void)fprintf(stderr, "\n");
367 
368 	/* Log the message to syslog. */
369 	vsyslog(LOG_ERR, fmt, ap);
370 }
371 
372 /*
373  * e_to_sys --
374  *	Guess which errno's are temporary.  Gag me.
375  */
376 void
377 e_to_sys(num)
378 	int num;
379 {
380 	/* Temporary failures override hard errors. */
381 	if (eval == EX_TEMPFAIL)
382 		return;
383 
384 	switch(num) {		/* Hopefully temporary errors. */
385 #ifdef EAGAIN
386 	case EAGAIN:		/* Resource temporarily unavailable */
387 #endif
388 #ifdef EDQUOT
389 	case EDQUOT:		/* Disc quota exceeded */
390 #endif
391 #ifdef EBUSY
392 	case EBUSY:		/* Device busy */
393 #endif
394 #ifdef EPROCLIM
395 	case EPROCLIM:		/* Too many processes */
396 #endif
397 #ifdef EUSERS
398 	case EUSERS:		/* Too many users */
399 #endif
400 #ifdef ECONNABORTED
401 	case ECONNABORTED:	/* Software caused connection abort */
402 #endif
403 #ifdef ECONNREFUSED
404 	case ECONNREFUSED:	/* Connection refused */
405 #endif
406 #ifdef ECONNRESET
407 	case ECONNRESET:	/* Connection reset by peer */
408 #endif
409 #ifdef EDEADLK
410 	case EDEADLK:		/* Resource deadlock avoided */
411 #endif
412 #ifdef EFBIG
413 	case EFBIG:		/* File too large */
414 #endif
415 #ifdef EHOSTDOWN
416 	case EHOSTDOWN:		/* Host is down */
417 #endif
418 #ifdef EHOSTUNREACH
419 	case EHOSTUNREACH:	/* No route to host */
420 #endif
421 #ifdef EMFILE
422 	case EMFILE:		/* Too many open files */
423 #endif
424 #ifdef ENETDOWN
425 	case ENETDOWN:		/* Network is down */
426 #endif
427 #ifdef ENETRESET
428 	case ENETRESET:		/* Network dropped connection on reset */
429 #endif
430 #ifdef ENETUNREACH
431 	case ENETUNREACH:	/* Network is unreachable */
432 #endif
433 #ifdef ENFILE
434 	case ENFILE:		/* Too many open files in system */
435 #endif
436 #ifdef ENOBUFS
437 	case ENOBUFS:		/* No buffer space available */
438 #endif
439 #ifdef ENOMEM
440 	case ENOMEM:		/* Cannot allocate memory */
441 #endif
442 #ifdef ENOSPC
443 	case ENOSPC:		/* No space left on device */
444 #endif
445 #ifdef EROFS
446 	case EROFS:		/* Read-only file system */
447 #endif
448 #ifdef ESTALE
449 	case ESTALE:		/* Stale NFS file handle */
450 #endif
451 #ifdef ETIMEDOUT
452 	case ETIMEDOUT:		/* Connection timed out */
453 #endif
454 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
455 	case EWOULDBLOCK:	/* Operation would block. */
456 #endif
457 		eval = EX_TEMPFAIL;
458 		break;
459 	default:
460 		eval = EX_UNAVAILABLE;
461 		break;
462 	}
463 }
464