xref: /netbsd-src/libexec/comsat/comsat.c (revision 4b896b232495b7a9b8b94a1cf1e21873296d53b8)
1 /*	$NetBSD: comsat.c,v 1.26 2003/09/19 05:33:15 itojun Exp $	*/
2 
3 /*
4  * Copyright (c) 1980, 1993
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. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1980, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n");
36 #if 0
37 static char sccsid[] = "from: @(#)comsat.c	8.1 (Berkeley) 6/4/93";
38 #else
39 __RCSID("$NetBSD: comsat.c,v 1.26 2003/09/19 05:33:15 itojun Exp $");
40 #endif
41 #endif /* not lint */
42 
43 #include <sys/param.h>
44 #include <sys/socket.h>
45 #include <sys/stat.h>
46 #include <sys/file.h>
47 #include <sys/wait.h>
48 
49 #include <netinet/in.h>
50 
51 #include <ctype.h>
52 #include <errno.h>
53 #include <netdb.h>
54 #include <paths.h>
55 #include <pwd.h>
56 #include <signal.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <syslog.h>
61 #include <termios.h>
62 #include <time.h>
63 #include <vis.h>
64 #include <unistd.h>
65 #include <utmp.h>
66 
67 int	logging;
68 int	debug = 0;
69 #define	dsyslog	if (debug) syslog
70 
71 #define MAXIDLE	120
72 
73 char	hostname[MAXHOSTNAMELEN+1];
74 struct	utmp *utmp = NULL;
75 time_t	lastmsgtime;
76 int	nutmp, uf;
77 
78 void jkfprintf (FILE *, char[], off_t);
79 void mailfor (char *);
80 void notify (struct utmp *, off_t);
81 void onalrm (int);
82 void reapchildren (int);
83 
84 int
85 main(int argc, char *argv[])
86 {
87 	struct sockaddr_storage from;
88 	int cc, ch;
89 	int fromlen;
90 	char msgbuf[100];
91 	sigset_t nsigset;
92 
93 	/* verify proper invocation */
94 	fromlen = sizeof(from);
95 	if (getsockname(0, (struct sockaddr *)&from, &fromlen) < 0) {
96 		(void)fprintf(stderr,
97 		    "comsat: getsockname: %s.\n", strerror(errno));
98 		exit(1);
99 	}
100 
101 	openlog("comsat", LOG_PID, LOG_DAEMON);
102 	while ((ch = getopt(argc, argv, "l")) != -1)
103 		switch (ch) {
104 		case 'l':
105 			logging = 1;
106 			break;
107 		default:
108 			syslog(LOG_ERR, "Usage: %s [-l]", getprogname());
109 			exit(1);
110 		}
111 	if (chdir(_PATH_MAILDIR)) {
112 		syslog(LOG_ERR, "chdir: %s: %m", _PATH_MAILDIR);
113 		(void)recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
114 		exit(1);
115 	}
116 	if ((uf = open(_PATH_UTMP, O_RDONLY, 0)) < 0) {
117 		syslog(LOG_ERR, "open: %s: %m", _PATH_UTMP);
118 		(void)recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
119 		exit(1);
120 	}
121 	(void)time(&lastmsgtime);
122 	(void)gethostname(hostname, sizeof(hostname));
123 	hostname[sizeof(hostname) - 1] = '\0';
124 	onalrm(0);
125 	(void)signal(SIGALRM, onalrm);
126 	(void)signal(SIGTTOU, SIG_IGN);
127 	(void)signal(SIGCHLD, reapchildren);
128 	for (;;) {
129 		cc = recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
130 		if (cc <= 0) {
131 			if (errno != EINTR)
132 				sleep(1);
133 			errno = 0;
134 			continue;
135 		}
136 		if (!nutmp)		/* no one has logged in yet */
137 			continue;
138 		sigemptyset(&nsigset);
139 		sigaddset(&nsigset, SIGALRM);
140 		sigprocmask(SIG_SETMASK, &nsigset, NULL);
141 		msgbuf[cc] = '\0';
142 		(void)time(&lastmsgtime);
143 		mailfor(msgbuf);
144 		sigemptyset(&nsigset);
145 		sigprocmask(SIG_SETMASK, &nsigset, NULL);
146 	}
147 }
148 
149 void
150 reapchildren(int signo)
151 {
152 
153 	while (wait3(NULL, WNOHANG, NULL) > 0);
154 }
155 
156 void
157 onalrm(int signo)
158 {
159 	static u_int utmpsize;		/* last malloced size for utmp */
160 	static u_int utmpmtime;		/* last modification time for utmp */
161 	struct stat statbf;
162 	struct utmp *u;
163 
164 	if (time(NULL) - lastmsgtime >= MAXIDLE)
165 		exit(0);
166 	(void)alarm((u_int)15);
167 	(void)fstat(uf, &statbf);
168 	if (statbf.st_mtime > utmpmtime) {
169 		utmpmtime = statbf.st_mtime;
170 		if (statbf.st_size > utmpsize) {
171 			if ((u = realloc(utmp,
172 			    statbf.st_size + 10 * sizeof(struct utmp))) == NULL) {
173 				syslog(LOG_ERR, "%s", strerror(errno));
174 				exit(1);
175 			}
176 			utmp = u;
177 			utmpsize = statbf.st_size + 10 * sizeof(struct utmp);
178 		}
179 		(void)lseek(uf, (off_t)0, SEEK_SET);
180 		nutmp = read(uf, utmp, (int)statbf.st_size)/sizeof(struct utmp);
181 	}
182 }
183 
184 void
185 mailfor(char *name)
186 {
187 	struct utmp *utp = &utmp[nutmp];
188 	char *cp, *fn;
189 	off_t offset;
190 
191 	if (!(cp = strchr(name, '@')))
192 		return;
193 	*cp = '\0';
194 	errno = 0;
195 	offset = strtol(cp + 1, &fn, 10);
196 	if (errno == ERANGE)
197 		return;
198 	if (fn && *fn && *fn != '\n') {
199 		/*
200 		 * Procmail sends messages to comsat with a trailing colon
201 		 * and a pathname to the folder where the new message was
202 		 * deposited.  Since we can't reliably open only regular
203 		 * files, we need to ignore these.  With one exception:
204 		 * if it mentions the user's system mailbox.
205 		 */
206 		char maildir[128];
207 		int l = snprintf(maildir, sizeof(maildir), ":%s/%s",
208 				 _PATH_MAILDIR, name);
209 		if (l > sizeof(maildir) || strcmp(maildir, fn) != 0)
210 			return;
211 	}
212 	while (--utp >= utmp)
213 		if (!strncmp(utp->ut_name, name, sizeof(utmp[0].ut_name)))
214 			notify(utp, offset);
215 }
216 
217 static char *cr;
218 
219 void
220 notify(struct utmp *utp, off_t offset)
221 {
222 	FILE *tp;
223 	struct passwd *p;
224 	struct stat stb;
225 	struct termios ttybuf;
226 	char tty[20], name[sizeof(utmp[0].ut_name) + 1];
227 
228 	(void)snprintf(tty, sizeof(tty), "%s%.*s",
229 	    _PATH_DEV, (int)sizeof(utp->ut_line), utp->ut_line);
230 	if (strchr(tty + sizeof(_PATH_DEV) - 1, '/')) {
231 		/* A slash is an attempt to break security... */
232 		/*
233 		 * XXX but what about something like "/dev/pts/5"
234 		 * that we may one day "support". ?
235 		 */
236 		syslog(LOG_AUTH | LOG_NOTICE, "'/' in \"%s\"", tty);
237 		return;
238 	}
239 	if (stat(tty, &stb) || !(stb.st_mode & S_IEXEC)) {
240 		dsyslog(LOG_DEBUG, "%s: wrong mode on %s", utp->ut_name, tty);
241 		return;
242 	}
243 	dsyslog(LOG_DEBUG, "notify %s on %s", utp->ut_name, tty);
244 	if (fork())
245 		return;
246 	(void)signal(SIGALRM, SIG_DFL);
247 	(void)alarm((u_int)30);
248 	if ((tp = fopen(tty, "w")) == NULL) {
249 		dsyslog(LOG_ERR, "%s: %s", tty, strerror(errno));
250 		_exit(1);
251 	}
252 	(void)tcgetattr(fileno(tp), &ttybuf);
253 	cr = (ttybuf.c_oflag & ONLCR) && (ttybuf.c_oflag & OPOST) ?
254 	    "\n" : "\n\r";
255 	(void)strlcpy(name, utp->ut_name, sizeof(name));
256 
257 	/* Set uid/gid/groups to users in case mail drop is on nfs */
258 	if ((p = getpwnam(name)) == NULL ||
259 	    initgroups(p->pw_name, p->pw_gid) < 0 ||
260 	    setgid(p->pw_gid) < 0 ||
261 	    setuid(p->pw_uid) < 0)
262 		_exit(1);
263 
264 	if (logging)
265 		syslog(LOG_INFO, "biff message for %s", name);
266 
267 	(void)fprintf(tp, "%s\007New mail for %s@%.*s\007 has arrived:%s----%s",
268 	    cr, name, (int)sizeof(hostname), hostname, cr, cr);
269 	jkfprintf(tp, name, offset);
270 	(void)fclose(tp);
271 	_exit(0);
272 }
273 
274 void
275 jkfprintf(FILE *tp, char name[], off_t offset)
276 {
277 	FILE *fi;
278 	int linecnt, charcnt, inheader;
279 	char line[BUFSIZ], visline[BUFSIZ*4], *nl;
280 
281 	if ((fi = fopen(name, "r")) == NULL)
282 		return;
283 
284 	(void)fseek(fi, offset, SEEK_SET);
285 	/*
286 	 * Print the first 7 lines or 560 characters of the new mail
287 	 * (whichever comes first).  Skip header crap other than
288 	 * From, Subject, To, and Date.
289 	 */
290 	linecnt = 7;
291 	charcnt = 560;
292 	inheader = 1;
293 	while (fgets(line, sizeof(line), fi) != NULL) {
294 		line[sizeof(line) - 1] = '\0';
295 		if (inheader) {
296 			if (line[0] == '\n') {
297 				inheader = 0;
298 				continue;
299 			}
300 			if (line[0] == ' ' || line[0] == '\t' ||
301 			    (strncasecmp(line, "From:", 5) &&
302 			    strncasecmp(line, "Subject:", 8)))
303 				continue;
304 		}
305 		if (strncmp(line, "From ", 5) == 0) {
306 			(void)fprintf(tp, "----%s", cr);
307 			(void)fclose(fi);
308 			return;
309 		}
310 		if (linecnt <= 0 || charcnt <= 0) {
311 			(void)fprintf(tp, "...more...%s", cr);
312 			(void)fclose(fi);
313 			return;
314 		}
315 		if ((nl = strchr(line, '\n')) != NULL)
316 			*nl = '\0';
317 		/* strip weird stuff so can't trojan horse stupid terminals */
318 		(void)strvis(visline, line, VIS_CSTYLE);
319 		(void)fputs(visline, tp);
320 		(void)fputs(cr, tp);
321 		--linecnt;
322 	}
323 	(void)fprintf(tp, "----%s\n", cr);
324 	(void)fclose(fi);
325 }
326