1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1990 The Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)mail.local.c	5.12 (Berkeley) 04/30/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' && !bcmp(line, "From ", 5))
140 				(void)putc('>', fp);
141 			eline = 0;
142 		}
143 		(void)fprintf(fp, "%s", line);
144 		if (ferror(fp)) {
145 			e_to_sys(errno);
146 			err("temporary file write error");
147 		}
148 	}
149 
150 	/* If message not newline terminated, need an extra. */
151 	if (!strchr(line, '\n'))
152 		(void)putc('\n', fp);
153 	/* Output a newline; note, empty messages are allowed. */
154 	(void)putc('\n', fp);
155 
156 	if (fflush(fp) == EOF || ferror(fp)) {
157 		e_to_sys(errno);
158 		err("temporary file write error");
159 	}
160 	return (fd);
161 }
162 
163 void
164 deliver(fd, name)
165 	int fd;
166 	char *name;
167 {
168 	struct stat sb;
169 	struct passwd *pw;
170 	int mbfd, nr, nw, off;
171 	char biffmsg[100], buf[8*1024], path[MAXPATHLEN];
172 	off_t curoff;
173 
174 	/*
175 	 * Disallow delivery to unknown names -- special mailboxes can be
176 	 * handled in the sendmail aliases file.
177 	 */
178 	if (!(pw = getpwnam(name))) {
179 		if (eval != EX_TEMPFAIL)
180 			eval = EX_UNAVAILABLE;
181 		warn("unknown name: %s", name);
182 		return;
183 	}
184 
185 	(void)snprintf(path, sizeof(path), "%s/%s", _PATH_MAILDIR, name);
186 
187 	/*
188 	 * If the mailbox is a linked or a symlink, fail.
189 	 *
190 	 * If we created the mailbox, set the owner/group.  If that fails,
191 	 * just return.  Another process may have already opened it, so we
192 	 * can't unlink it.  Historically, binmail set the owner/group at
193 	 * each mail delivery.  We no longer do this, assuming that if the
194 	 * ownership or permissions were changed there was a reason.
195 	 *
196 	 * XXX
197 	 * open(2) should support flock'ing the file.
198 	 */
199 	if (lstat(path, &sb)) {
200 		if ((mbfd = open(path,
201 		    O_APPEND|O_CREAT|O_EXCL|O_WRONLY, S_IRUSR|S_IWUSR)) < 0)
202 			mbfd = open(path, O_APPEND|O_WRONLY, 0);
203 		else if (fchown(mbfd, pw->pw_uid, pw->pw_gid)) {
204 			e_to_sys(errno);
205 			warn("chown %u.%u: %s", pw->pw_uid, pw->pw_gid, name);
206 			return;
207 		}
208 	} else if (sb.st_nlink != 1 || S_ISLNK(sb.st_mode)) {
209 		e_to_sys(errno);
210 		warn("%s: linked file", path);
211 		return;
212 	} else
213 		mbfd = open(path, O_APPEND|O_WRONLY, 0);
214 
215 	if (mbfd == -1) {
216 		e_to_sys(errno);
217 		warn("%s: %s", path, strerror(errno));
218 		return;
219 	}
220 
221 	/* Wait until we can get a lock on the file. */
222 	if (flock(mbfd, LOCK_EX)) {
223 		e_to_sys(errno);
224 		warn("%s: %s", path, strerror(errno));
225 		goto err1;
226 	}
227 
228 	/* Get the starting offset of the new message for biff. */
229 	curoff = lseek(mbfd, (off_t)0, SEEK_END);
230 	(void)snprintf(biffmsg, sizeof(biffmsg), "%s@%qd\n", name, curoff);
231 
232 	/* Copy the message into the file. */
233 	if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
234 		e_to_sys(errno);
235 		warn("temporary file: %s", strerror(errno));
236 		goto err1;
237 	}
238 	while ((nr = read(fd, buf, sizeof(buf))) > 0)
239 		for (off = 0; off < nr; nr -= nw, off += nw)
240 			if ((nw = write(mbfd, buf + off, nr)) < 0) {
241 				e_to_sys(errno);
242 				warn("%s: %s", path, strerror(errno));
243 				goto err2;;
244 			}
245 	if (nr < 0) {
246 		e_to_sys(errno);
247 		warn("temporary file: %s", strerror(errno));
248 		goto err2;;
249 	}
250 
251 	/* Flush to disk, don't wait for update. */
252 	if (fsync(mbfd)) {
253 		e_to_sys(errno);
254 		warn("%s: %s", path, strerror(errno));
255 err2:		(void)ftruncate(mbfd, curoff);
256 err1:		(void)close(mbfd);
257 		return;
258 	}
259 
260 	/* Close and check -- NFS doesn't write until the close. */
261 	if (close(mbfd)) {
262 		e_to_sys(errno);
263 		warn("%s: %s", path, strerror(errno));
264 		return;
265 	}
266 
267 	notifybiff(biffmsg);
268 }
269 
270 void
271 notifybiff(msg)
272 	char *msg;
273 {
274 	static struct sockaddr_in addr;
275 	static int f = -1;
276 	struct hostent *hp;
277 	struct servent *sp;
278 	int len;
279 
280 	if (!addr.sin_family) {
281 		/* Be silent if biff service not available. */
282 		if (!(sp = getservbyname("biff", "udp")))
283 			return;
284 		if (!(hp = gethostbyname("localhost"))) {
285 			warn("localhost: %s", strerror(errno));
286 			return;
287 		}
288 		addr.sin_family = hp->h_addrtype;
289 		bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);
290 		addr.sin_port = sp->s_port;
291 	}
292 	if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
293 		warn("socket: %s", strerror(errno));
294 		return;
295 	}
296 	len = strlen(msg) + 1;
297 	if (sendto(f, msg, len, 0, (struct sockaddr *)&addr, sizeof(addr))
298 	    != len)
299 		warn("sendto biff: %s", strerror(errno));
300 }
301 
302 void
303 usage()
304 {
305 	eval = EX_USAGE;
306 	err("usage: mail.local [-f from] user ...");
307 }
308 
309 void
310 #if __STDC__
311 err(const char *fmt, ...)
312 #else
313 err(fmt, va_alist)
314 	const char *fmt;
315 	va_dcl
316 #endif
317 {
318 	va_list ap;
319 
320 #if __STDC__
321 	va_start(ap, fmt);
322 #else
323 	va_start(ap);
324 #endif
325 	vwarn(fmt, ap);
326 	va_end(ap);
327 
328 	exit(eval);
329 }
330 
331 void
332 #if __STDC__
333 warn(const char *fmt, ...)
334 #else
335 warn(fmt, va_alist)
336 	const char *fmt;
337 	va_dcl
338 #endif
339 {
340 	va_list ap;
341 
342 #if __STDC__
343 	va_start(ap, fmt);
344 #else
345 	va_start(ap);
346 #endif
347 	vwarn(fmt, ap);
348 	va_end(ap);
349 }
350 
351 void
352 vwarn(fmt, ap)
353 	const char *fmt;
354 	_BSD_VA_LIST_ ap;
355 {
356 	/*
357 	 * Log the message to stderr.
358 	 *
359 	 * Don't use LOG_PERROR as an openlog() flag to do this,
360 	 * it's not portable enough.
361 	 */
362 	if (eval != EX_USAGE)
363 		(void)fprintf(stderr, "mail.local: ");
364 	(void)vfprintf(stderr, fmt, ap);
365 	(void)fprintf(stderr, "\n");
366 
367 	/* Log the message to syslog. */
368 	vsyslog(LOG_ERR, fmt, ap);
369 }
370 
371 /*
372  * e_to_sys --
373  *	Guess which errno's are temporary.  Gag me.
374  */
375 void
376 e_to_sys(num)
377 	int num;
378 {
379 	/* Temporary failures override hard errors. */
380 	if (eval == EX_TEMPFAIL)
381 		return;
382 
383 	switch(num) {		/* Hopefully temporary errors. */
384 #ifdef EAGAIN
385 	case EAGAIN:		/* Resource temporarily unavailable */
386 #endif
387 #ifdef EDQUOT
388 	case EDQUOT:		/* Disc quota exceeded */
389 #endif
390 #ifdef EBUSY
391 	case EBUSY:		/* Device busy */
392 #endif
393 #ifdef EPROCLIM
394 	case EPROCLIM:		/* Too many processes */
395 #endif
396 #ifdef EUSERS
397 	case EUSERS:		/* Too many users */
398 #endif
399 #ifdef ECONNABORTED
400 	case ECONNABORTED:	/* Software caused connection abort */
401 #endif
402 #ifdef ECONNREFUSED
403 	case ECONNREFUSED:	/* Connection refused */
404 #endif
405 #ifdef ECONNRESET
406 	case ECONNRESET:	/* Connection reset by peer */
407 #endif
408 #ifdef EDEADLK
409 	case EDEADLK:		/* Resource deadlock avoided */
410 #endif
411 #ifdef EFBIG
412 	case EFBIG:		/* File too large */
413 #endif
414 #ifdef EHOSTDOWN
415 	case EHOSTDOWN:		/* Host is down */
416 #endif
417 #ifdef EHOSTUNREACH
418 	case EHOSTUNREACH:	/* No route to host */
419 #endif
420 #ifdef EMFILE
421 	case EMFILE:		/* Too many open files */
422 #endif
423 #ifdef ENETDOWN
424 	case ENETDOWN:		/* Network is down */
425 #endif
426 #ifdef ENETRESET
427 	case ENETRESET:		/* Network dropped connection on reset */
428 #endif
429 #ifdef ENETUNREACH
430 	case ENETUNREACH:	/* Network is unreachable */
431 #endif
432 #ifdef ENFILE
433 	case ENFILE:		/* Too many open files in system */
434 #endif
435 #ifdef ENOBUFS
436 	case ENOBUFS:		/* No buffer space available */
437 #endif
438 #ifdef ENOMEM
439 	case ENOMEM:		/* Cannot allocate memory */
440 #endif
441 #ifdef ENOSPC
442 	case ENOSPC:		/* No space left on device */
443 #endif
444 #ifdef EROFS
445 	case EROFS:		/* Read-only file system */
446 #endif
447 #ifdef ESTALE
448 	case ESTALE:		/* Stale NFS file handle */
449 #endif
450 #ifdef ETIMEDOUT
451 	case ETIMEDOUT:		/* Connection timed out */
452 #endif
453 #if defined(EWOULDBLOCK) && (EWOULDBLOCK != EAGAIN)
454 	case EWOULDBLOCK:	/* Operation would block. */
455 #endif
456 		eval = EX_TEMPFAIL;
457 		break;
458 	default:
459 		eval = EX_UNAVAILABLE;
460 		break;
461 	}
462 }
463