xref: /openbsd/libexec/mail.local/mail.local.c (revision 891d7ab6)
1 /*	$OpenBSD: mail.local.c,v 1.32 2009/10/27 23:59:31 deraadt Exp $	*/
2 
3 /*-
4  * Copyright (c) 1996-1998 Theo de Raadt <deraadt@theos.com>
5  * Copyright (c) 1996-1998 David Mazieres <dm@lcs.mit.edu>
6  * Copyright (c) 1990 The Regents of the University of California.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include <sys/param.h>
35 #include <sys/stat.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <syslog.h>
39 #include <fcntl.h>
40 #include <netdb.h>
41 #include <pwd.h>
42 #include <time.h>
43 #include <unistd.h>
44 #include <errno.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include "pathnames.h"
49 #include "mail.local.h"
50 
51 int
52 main(int argc, char *argv[])
53 {
54 	struct passwd *pw;
55 	int ch, fd, eval, lockfile=1, holdme=0;
56 	uid_t uid;
57 	char *from;
58 
59 	openlog("mail.local", LOG_PERROR, LOG_MAIL);
60 
61 	from = NULL;
62 	while ((ch = getopt(argc, argv, "lLdf:r:H")) != -1)
63 		switch (ch) {
64 		case 'd':		/* backward compatible */
65 			break;
66 		case 'f':
67 		case 'r':		/* backward compatible */
68 			if (from)
69 				merr(FATAL, "multiple -f options");
70 			from = optarg;
71 			break;
72 		case 'l':
73 			lockfile=1;
74 			break;
75 		case 'L':
76 			lockfile=0;
77 			break;
78 		case 'H':
79 			holdme=1;
80 			break;
81 		default:
82 			usage();
83 		}
84 	argc -= optind;
85 	argv += optind;
86 
87 	/* Support -H flag for backwards compat */
88 	if (holdme) {
89 		execl(_PATH_LOCKSPOOL, "lockspool", (char *)NULL);
90 		merr(FATAL, "execl: lockspool: %s", strerror(errno));
91 	} else {
92 		if (!*argv)
93 			usage();
94 		if (geteuid() != 0)
95 			merr(FATAL, "may only be run by the superuser");
96 	}
97 
98 	/*
99 	 * If from not specified, use the name from getlogin() if the
100 	 * uid matches, otherwise, use the name from the password file
101 	 * corresponding to the uid.
102 	 */
103 	uid = getuid();
104 	if (!from && (!(from = getlogin()) ||
105 	    !(pw = getpwnam(from)) || pw->pw_uid != uid))
106 		from = (pw = getpwuid(uid)) ? pw->pw_name : "???";
107 
108 	fd = storemail(from);
109 	for (eval = 0; *argv; ++argv)
110 		eval |= deliver(fd, *argv, lockfile);
111 	exit(eval);
112 }
113 
114 int
115 storemail(char *from)
116 {
117 	FILE *fp = NULL;
118 	time_t tval;
119 	int fd, eline;
120 	size_t len;
121 	char *line, *tbuf;
122 
123 	if ((tbuf = strdup(_PATH_LOCTMP)) == NULL)
124 		merr(FATAL, "unable to allocate memory");
125 	if ((fd = mkstemp(tbuf)) == -1 || !(fp = fdopen(fd, "w+")))
126 		merr(FATAL, "unable to open temporary file");
127 	(void)unlink(tbuf);
128 	free(tbuf);
129 
130 	(void)time(&tval);
131 	(void)fprintf(fp, "From %s %s", from, ctime(&tval));
132 
133 	for (eline = 1, tbuf = NULL; (line = fgetln(stdin, &len));) {
134 		/* We have to NUL-terminate the line since fgetln does not */
135 		if (line[len - 1] == '\n')
136 			line[len - 1] = '\0';
137 		else {
138 			/* No trailing newline, so alloc space and copy */
139 			if ((tbuf = malloc(len + 1)) == NULL)
140 				merr(FATAL, "unable to allocate memory");
141 			memcpy(tbuf, line, len);
142 			tbuf[len] = '\0';
143 			line = tbuf;
144 		}
145 		if (line[0] == '\0')
146 			eline = 1;
147 		else {
148 			if (eline && line[0] == 'F' && len > 5 &&
149 			    !memcmp(line, "From ", 5))
150 				(void)putc('>', fp);
151 			eline = 0;
152 		}
153 		(void)fprintf(fp, "%s\n", line);
154 		if (ferror(fp))
155 			break;
156 	}
157 	if (tbuf)
158 		free(tbuf);
159 
160 	/* Output a newline; note, empty messages are allowed. */
161 	(void)putc('\n', fp);
162 	(void)fflush(fp);
163 	if (ferror(fp))
164 		merr(FATAL, "temporary file write error");
165 	return(fd);
166 }
167 
168 int
169 deliver(int fd, char *name, int lockfile)
170 {
171 	struct stat sb, fsb;
172 	struct passwd *pw;
173 	int mbfd=-1, rval=1, lfd=-1;
174 	char biffmsg[100], buf[8*1024], path[MAXPATHLEN];
175 	off_t curoff;
176 	size_t off;
177 	ssize_t nr, nw;
178 
179 	/*
180 	 * Disallow delivery to unknown names -- special mailboxes can be
181 	 * handled in the sendmail aliases file.
182 	 */
183 	if (!(pw = getpwnam(name))) {
184 		merr(NOTFATAL, "unknown name: %s", name);
185 		return(1);
186 	}
187 
188 	(void)snprintf(path, sizeof path, "%s/%s", _PATH_MAILDIR, name);
189 
190 	if (lockfile) {
191 		lfd = getlock(name, pw);
192 		if (lfd == -1)
193 			return (1);
194 	}
195 
196 	/* after this point, always exit via bad to remove lockfile */
197 retry:
198 	if (lstat(path, &sb)) {
199 		if (errno != ENOENT) {
200 			merr(NOTFATAL, "%s: %s", path, strerror(errno));
201 			goto bad;
202 		}
203 		if ((mbfd = open(path, O_APPEND|O_CREAT|O_EXCL|O_WRONLY|O_EXLOCK,
204 		    S_IRUSR|S_IWUSR)) < 0) {
205 			if (errno == EEXIST) {
206 				/* file appeared since lstat */
207 				goto retry;
208 			} else {
209 				merr(NOTFATAL, "%s: %s", path, strerror(errno));
210 				goto bad;
211 			}
212 		}
213 		/*
214 		 * Set the owner and group.  Historically, binmail repeated
215 		 * this at each mail delivery.  We no longer do this, assuming
216 		 * that if the ownership or permissions were changed there
217 		 * was a reason for doing so.
218 		 */
219 		if (fchown(mbfd, pw->pw_uid, pw->pw_gid) < 0) {
220 			merr(NOTFATAL, "chown %u:%u: %s",
221 			    pw->pw_uid, pw->pw_gid, name);
222 			goto bad;
223 		}
224 	} else {
225 		if (sb.st_nlink != 1 || !S_ISREG(sb.st_mode)) {
226 			merr(NOTFATAL, "%s: linked or special file", path);
227 			goto bad;
228 		}
229 		if ((mbfd = open(path, O_APPEND|O_WRONLY|O_EXLOCK,
230 		    S_IRUSR|S_IWUSR)) < 0) {
231 			merr(NOTFATAL, "%s: %s", path, strerror(errno));
232 			goto bad;
233 		}
234 		if (fstat(mbfd, &fsb)) {
235 			/* relating error to path may be bad style */
236 			merr(NOTFATAL, "%s: %s", path, strerror(errno));
237 			goto bad;
238 		}
239 		if (sb.st_dev != fsb.st_dev || sb.st_ino != fsb.st_ino) {
240 			merr(NOTFATAL, "%s: changed after open", path);
241 			goto bad;
242 		}
243 		/* paranoia? */
244 		if (fsb.st_nlink != 1 || !S_ISREG(fsb.st_mode)) {
245 			merr(NOTFATAL, "%s: linked or special file", path);
246 			goto bad;
247 		}
248 	}
249 
250 	curoff = lseek(mbfd, 0, SEEK_END);
251 	(void)snprintf(biffmsg, sizeof biffmsg, "%s@%qd\n", name, curoff);
252 	if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
253 		merr(NOTFATAL, "temporary file: %s", strerror(errno));
254 		goto bad;
255 	}
256 
257 	while ((nr = read(fd, buf, sizeof(buf))) > 0)
258 		for (off = 0; off < nr;  off += nw)
259 			if ((nw = write(mbfd, buf + off, nr - off)) < 0) {
260 				merr(NOTFATAL, "%s: %s", path, strerror(errno));
261 				(void)ftruncate(mbfd, curoff);
262 				goto bad;
263 			}
264 
265 	if (nr == 0) {
266 		rval = 0;
267 	} else {
268 		(void)ftruncate(mbfd, curoff);
269 		merr(FATAL, "temporary file: %s", strerror(errno));
270 	}
271 
272 bad:
273 	if (lfd != -1) {
274 		rellock();
275 		close(lfd);
276 	}
277 
278 	if (mbfd != -1) {
279 		(void)fsync(mbfd);		/* Don't wait for update. */
280 		(void)close(mbfd);		/* Implicit unlock. */
281 	}
282 
283 	if (!rval)
284 		notifybiff(biffmsg);
285 	return(rval);
286 }
287 
288 void
289 notifybiff(char *msg)
290 {
291 	static struct sockaddr_in addr;
292 	static int f = -1;
293 	struct hostent *hp;
294 	struct servent *sp;
295 	size_t len;
296 
297 	if (!addr.sin_family) {
298 		/* Be silent if biff service not available. */
299 		if (!(sp = getservbyname("biff", "udp")))
300 			return;
301 		if (!(hp = gethostbyname("localhost"))) {
302 			merr(NOTFATAL, "localhost: %s", strerror(errno));
303 			return;
304 		}
305 		addr.sin_len = sizeof(struct sockaddr_in);
306 		addr.sin_family = hp->h_addrtype;
307 		addr.sin_port = sp->s_port;
308 		bcopy(hp->h_addr, &addr.sin_addr, (size_t)hp->h_length);
309 	}
310 	if (f < 0 && (f = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
311 		merr(NOTFATAL, "socket: %s", strerror(errno));
312 		return;
313 	}
314 	len = strlen(msg) + 1;
315 	if (sendto(f, msg, len, 0, (struct sockaddr *)&addr, sizeof(addr))
316 	    != len)
317 		merr(NOTFATAL, "sendto biff: %s", strerror(errno));
318 }
319 
320 void
321 usage(void)
322 {
323 	merr(FATAL, "usage: mail.local [-Ll] [-f from] user ...");
324 }
325