xref: /openbsd/libexec/comsat/comsat.c (revision 73471bf0)
1 /*	$OpenBSD: comsat.c,v 1.50 2021/07/12 15:09:18 beck 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/limits.h>
33 #include <sys/socket.h>
34 #include <sys/stat.h>
35 #include <sys/wait.h>
36 
37 #include <netinet/in.h>
38 
39 #include <ctype.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #include <netdb.h>
43 #include <limits.h>
44 #include <paths.h>
45 #include <pwd.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <syslog.h>
51 #include <termios.h>
52 #include <unistd.h>
53 #include <utmp.h>
54 #include <vis.h>
55 #include <err.h>
56 
57 int	debug = 0;
58 #define	dsyslog	if (debug) syslog
59 
60 #define MAXIDLE	120
61 
62 char	hostname[HOST_NAME_MAX+1];
63 struct	utmp *utmp = NULL;
64 time_t	lastmsgtime;
65 int	nutmp, uf;
66 
67 void jkfprintf(FILE *, char[], off_t);
68 void mailfor(char *);
69 void notify(struct utmp *, off_t);
70 void readutmp(int);
71 void doreadutmp(void);
72 void reapchildren(int);
73 
74 volatile sig_atomic_t wantreadutmp;
75 
76 int
77 main(int argc, char *argv[])
78 {
79 	struct sockaddr_storage from;
80 	struct sigaction sa;
81 	ssize_t cc;
82 	socklen_t fromlen;
83 	char msgbuf[100];
84 	sigset_t sigset;
85 
86 	/* verify proper invocation */
87 	fromlen = sizeof(from);
88 	if (getsockname(0, (struct sockaddr *)&from, &fromlen) == -1) {
89 		(void)fprintf(stderr,
90 		    "comsat: getsockname: %s.\n", strerror(errno));
91 		exit(1);
92 	}
93 
94 	if (unveil(_PATH_MAILDIR, "r") == -1)
95 		err(1, "unveil %s", _PATH_MAILDIR);
96 	if (unveil(_PATH_UTMP, "r") == -1)
97 		err(1, "unveil %s", _PATH_UTMP);
98 	if (unveil("/tmp", "w") == -1)
99 		err(1, "unveil /tmp");
100 	if (unveil(_PATH_DEV, "rw") == -1)
101 		err(1, "unveil %s", _PATH_DEV);
102 	if (pledge("stdio rpath wpath proc tty", NULL) == -1)
103 		err(1, "pledge");
104 
105 	openlog("comsat", LOG_PID, LOG_DAEMON);
106 	if (chdir(_PATH_MAILDIR)) {
107 		syslog(LOG_ERR, "chdir: %s: %m", _PATH_MAILDIR);
108 		(void) recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
109 		exit(1);
110 	}
111 	if ((uf = open(_PATH_UTMP, O_RDONLY)) == -1) {
112 		syslog(LOG_ERR, "open: %s: %m", _PATH_UTMP);
113 		(void) recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
114 		exit(1);
115 	}
116 	(void)time(&lastmsgtime);
117 	(void)gethostname(hostname, sizeof(hostname));
118 	doreadutmp();
119 
120 	(void)signal(SIGTTOU, SIG_IGN);
121 
122 	bzero(&sa, sizeof sa);
123 	sigemptyset(&sa.sa_mask);
124 	sa.sa_handler = readutmp;
125 	sa.sa_flags = 0;			/* no SA_RESTART */
126 	(void)sigaction(SIGALRM, &sa, NULL);
127 
128 	sa.sa_handler = reapchildren;
129 	sa.sa_flags = SA_RESTART;
130 	(void)sigaction(SIGCHLD, &sa, NULL);
131 
132 	for (;;) {
133 		if (wantreadutmp) {
134 			wantreadutmp = 0;
135 			doreadutmp();
136 		}
137 
138 		cc = recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
139 		if (cc <= 0) {
140 			if (errno != EINTR)
141 				sleep(1);
142 			continue;
143 		}
144 		if (!nutmp)		/* no one has logged in yet */
145 			continue;
146 		sigemptyset(&sigset);
147 		sigaddset(&sigset, SIGALRM);
148 		sigprocmask(SIG_SETMASK, &sigset, NULL);
149 		msgbuf[cc] = '\0';
150 		(void)time(&lastmsgtime);
151 		mailfor(msgbuf);
152 		sigemptyset(&sigset);
153 		sigprocmask(SIG_SETMASK, &sigset, NULL);
154 	}
155 }
156 
157 /* ARGSUSED */
158 void
159 reapchildren(int signo)
160 {
161 	int save_errno = errno;
162 
163 	while (wait3(NULL, WNOHANG, NULL) > 0)
164 		;
165 	errno = save_errno;
166 }
167 
168 /* ARGSUSED */
169 void
170 readutmp(int signo)
171 {
172 	wantreadutmp = 1;
173 }
174 
175 void
176 doreadutmp(void)
177 {
178 	static u_int utmpsize;		/* last malloced size for utmp */
179 	static time_t utmpmtime;	/* last modification time for utmp */
180 	struct stat statbf;
181 	int n;
182 
183 	if (time(NULL) - lastmsgtime >= MAXIDLE)
184 		exit(0);
185 	(void)fstat(uf, &statbf);
186 	if (statbf.st_mtime > utmpmtime) {
187 		utmpmtime = statbf.st_mtime;
188 		/* avoid int overflow */
189 		if (statbf.st_size > INT_MAX - 10 * sizeof(struct utmp)) {
190 			syslog(LOG_ALERT, "utmp file excessively large");
191 			exit(1);
192 		}
193 		if (statbf.st_size > utmpsize) {
194 			u_int nutmpsize = statbf.st_size + 10 *
195 			    sizeof(struct utmp);
196 			struct utmp *u;
197 
198 			if ((u = recallocarray(utmp, utmpsize,
199 			    nutmpsize, 1)) == NULL) {
200 				free(utmp);
201 				syslog(LOG_ERR, "%s", strerror(errno));
202 				exit(1);
203 			}
204 			utmp = u;
205 			utmpsize = nutmpsize;
206 		}
207 		n = pread(uf, utmp, statbf.st_size, 0);
208 		if (n == -1)
209 			n = 0;
210 		nutmp = n / sizeof(struct utmp);
211 		dsyslog(LOG_DEBUG, "read %d utmp entries", nutmp);
212 	}
213 	(void)alarm(15);
214 }
215 
216 void
217 mailfor(char *name)
218 {
219 	struct utmp *utp = &utmp[nutmp];
220 	char utname[UT_NAMESIZE+1];
221 	const char *errstr;
222 	char *cp;
223 	off_t offset;
224 
225 	dsyslog(LOG_DEBUG, "mail for '%s'", name);
226 	if (!(cp = strchr(name, '@')))
227 		return;
228 	*cp++ = '\0';
229 	cp[strcspn(cp, " \t\n")] = '\0';
230 	offset = strtonum(cp, 0, LLONG_MAX, &errstr);
231 	if (errstr) {
232 		syslog(LOG_ERR, "'%s' is %s", cp + 1, errstr);
233 		return;
234 	}
235 	while (--utp >= utmp) {
236 		memcpy(utname, utp->ut_name, UT_NAMESIZE);
237 		utname[UT_NAMESIZE] = '\0';
238 		dsyslog(LOG_DEBUG, "check %s against %s", name, utname);
239 		if (!strncmp(utname, name, UT_NAMESIZE))
240 			notify(utp, offset);
241 	}
242 }
243 
244 static char *cr;
245 
246 void
247 notify(struct utmp *utp, off_t offset)
248 {
249 	int fd;
250 	FILE *tp;
251 	struct stat stb;
252 	struct termios ttybuf;
253 	char tty[PATH_MAX], name[UT_NAMESIZE + 1];
254 
255 	(void)snprintf(tty, sizeof(tty), "%s%.*s",
256 	    _PATH_DEV, (int)sizeof(utp->ut_line), utp->ut_line);
257 	if (strchr(tty + sizeof(_PATH_DEV) - 1, '/')) {
258 		/* A slash is an attempt to break security... */
259 		syslog(LOG_AUTH | LOG_NOTICE, "'/' in \"%s\"", tty);
260 		return;
261 	}
262 	if (stat(tty, &stb) || !(stb.st_mode & S_IEXEC)) {
263 		dsyslog(LOG_DEBUG, "%.*s: wrong mode on %s",
264 		    (int)sizeof(utp->ut_name), utp->ut_name, tty);
265 		return;
266 	}
267 	dsyslog(LOG_DEBUG, "notify %.*s on %s", (int)sizeof(utp->ut_name),
268 	    utp->ut_name, tty);
269 	if (fork())
270 		return;
271 	(void)signal(SIGALRM, SIG_DFL);
272 	(void)alarm(30);
273 	fd = open(tty, O_WRONLY);
274 	if (fd == -1 || (tp = fdopen(fd, "w")) == NULL) {
275 		dsyslog(LOG_ERR, "%s: %s", tty, strerror(errno));
276 		_exit(1);
277 	}
278 	(void)tcgetattr(fileno(tp), &ttybuf);
279 	cr = (ttybuf.c_oflag & ONLCR) && (ttybuf.c_oflag & OPOST) ?
280 	    "\n" : "\n\r";
281 	memcpy(name, utp->ut_name, UT_NAMESIZE);
282 	name[UT_NAMESIZE] = '\0';
283 	(void)fprintf(tp, "%s\007New mail for %s@%.*s\007 has arrived:%s----%s",
284 	    cr, name, (int)sizeof(hostname), hostname, cr, cr);
285 	jkfprintf(tp, name, offset);
286 	(void)fclose(tp);
287 	_exit(0);
288 }
289 
290 void
291 jkfprintf(FILE *tp, char name[], off_t offset)
292 {
293 	char *cp, ch;
294 	char visout[5], *s2;
295 	FILE *fi;
296 	int linecnt, charcnt, inheader;
297 	char line[BUFSIZ];
298 
299 	if ((fi = fopen(name, "r")) == NULL)
300 		return;
301 
302 	(void)fseeko(fi, offset, SEEK_SET);
303 	/*
304 	 * Print the first 7 lines or 560 characters of the new mail
305 	 * (whichever comes first).  Skip header crap other than
306 	 * From, Subject, To, and Date.
307 	 */
308 	linecnt = 7;
309 	charcnt = 560;
310 	inheader = 1;
311 	while (fgets(line, sizeof(line), fi) != NULL) {
312 		if (inheader) {
313 			if (line[0] == '\n') {
314 				inheader = 0;
315 				continue;
316 			}
317 			if (line[0] == ' ' || line[0] == '\t' ||
318 			    (strncmp(line, "From:", 5) &&
319 			    strncmp(line, "Subject:", 8)))
320 				continue;
321 		}
322 		if (linecnt <= 0 || charcnt <= 0) {
323 			(void)fprintf(tp, "...more...%s", cr);
324 			(void)fclose(fi);
325 			return;
326 		}
327 		/* strip weird stuff so can't trojan horse stupid terminals */
328 		for (cp = line; (ch = *cp) && ch != '\n'; ++cp, --charcnt) {
329 			ch = toascii(ch);
330 			vis(visout, ch, VIS_SAFE|VIS_NOSLASH, cp[1]);
331 			for (s2 = visout; *s2; s2++)
332 				(void)fputc(*s2, tp);
333 		}
334 		(void)fputs(cr, tp);
335 		--linecnt;
336 	}
337 	(void)fprintf(tp, "----%s\n", cr);
338 	(void)fclose(fi);
339 }
340