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