xref: /openbsd/libexec/comsat/comsat.c (revision 5b133f3f)
1 /*	$OpenBSD: comsat.c,v 1.51 2023/03/08 04:43:05 guenther 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
main(int argc,char * argv[])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 void
reapchildren(int signo)158 reapchildren(int signo)
159 {
160 	int save_errno = errno;
161 
162 	while (wait3(NULL, WNOHANG, NULL) > 0)
163 		;
164 	errno = save_errno;
165 }
166 
167 void
readutmp(int signo)168 readutmp(int signo)
169 {
170 	wantreadutmp = 1;
171 }
172 
173 void
doreadutmp(void)174 doreadutmp(void)
175 {
176 	static u_int utmpsize;		/* last malloced size for utmp */
177 	static time_t utmpmtime;	/* last modification time for utmp */
178 	struct stat statbf;
179 	int n;
180 
181 	if (time(NULL) - lastmsgtime >= MAXIDLE)
182 		exit(0);
183 	(void)fstat(uf, &statbf);
184 	if (statbf.st_mtime > utmpmtime) {
185 		utmpmtime = statbf.st_mtime;
186 		/* avoid int overflow */
187 		if (statbf.st_size > INT_MAX - 10 * sizeof(struct utmp)) {
188 			syslog(LOG_ALERT, "utmp file excessively large");
189 			exit(1);
190 		}
191 		if (statbf.st_size > utmpsize) {
192 			u_int nutmpsize = statbf.st_size + 10 *
193 			    sizeof(struct utmp);
194 			struct utmp *u;
195 
196 			if ((u = recallocarray(utmp, utmpsize,
197 			    nutmpsize, 1)) == NULL) {
198 				free(utmp);
199 				syslog(LOG_ERR, "%s", strerror(errno));
200 				exit(1);
201 			}
202 			utmp = u;
203 			utmpsize = nutmpsize;
204 		}
205 		n = pread(uf, utmp, statbf.st_size, 0);
206 		if (n == -1)
207 			n = 0;
208 		nutmp = n / sizeof(struct utmp);
209 		dsyslog(LOG_DEBUG, "read %d utmp entries", nutmp);
210 	}
211 	(void)alarm(15);
212 }
213 
214 void
mailfor(char * name)215 mailfor(char *name)
216 {
217 	struct utmp *utp = &utmp[nutmp];
218 	char utname[UT_NAMESIZE+1];
219 	const char *errstr;
220 	char *cp;
221 	off_t offset;
222 
223 	dsyslog(LOG_DEBUG, "mail for '%s'", name);
224 	if (!(cp = strchr(name, '@')))
225 		return;
226 	*cp++ = '\0';
227 	cp[strcspn(cp, " \t\n")] = '\0';
228 	offset = strtonum(cp, 0, LLONG_MAX, &errstr);
229 	if (errstr) {
230 		syslog(LOG_ERR, "'%s' is %s", cp + 1, errstr);
231 		return;
232 	}
233 	while (--utp >= utmp) {
234 		memcpy(utname, utp->ut_name, UT_NAMESIZE);
235 		utname[UT_NAMESIZE] = '\0';
236 		dsyslog(LOG_DEBUG, "check %s against %s", name, utname);
237 		if (!strncmp(utname, name, UT_NAMESIZE))
238 			notify(utp, offset);
239 	}
240 }
241 
242 static char *cr;
243 
244 void
notify(struct utmp * utp,off_t offset)245 notify(struct utmp *utp, off_t offset)
246 {
247 	int fd;
248 	FILE *tp;
249 	struct stat stb;
250 	struct termios ttybuf;
251 	char tty[PATH_MAX], name[UT_NAMESIZE + 1];
252 
253 	(void)snprintf(tty, sizeof(tty), "%s%.*s",
254 	    _PATH_DEV, (int)sizeof(utp->ut_line), utp->ut_line);
255 	if (strchr(tty + sizeof(_PATH_DEV) - 1, '/')) {
256 		/* A slash is an attempt to break security... */
257 		syslog(LOG_AUTH | LOG_NOTICE, "'/' in \"%s\"", tty);
258 		return;
259 	}
260 	if (stat(tty, &stb) || !(stb.st_mode & S_IEXEC)) {
261 		dsyslog(LOG_DEBUG, "%.*s: wrong mode on %s",
262 		    (int)sizeof(utp->ut_name), utp->ut_name, tty);
263 		return;
264 	}
265 	dsyslog(LOG_DEBUG, "notify %.*s on %s", (int)sizeof(utp->ut_name),
266 	    utp->ut_name, tty);
267 	if (fork())
268 		return;
269 	(void)signal(SIGALRM, SIG_DFL);
270 	(void)alarm(30);
271 	fd = open(tty, O_WRONLY);
272 	if (fd == -1 || (tp = fdopen(fd, "w")) == NULL) {
273 		dsyslog(LOG_ERR, "%s: %s", tty, strerror(errno));
274 		_exit(1);
275 	}
276 	(void)tcgetattr(fileno(tp), &ttybuf);
277 	cr = (ttybuf.c_oflag & ONLCR) && (ttybuf.c_oflag & OPOST) ?
278 	    "\n" : "\n\r";
279 	memcpy(name, utp->ut_name, UT_NAMESIZE);
280 	name[UT_NAMESIZE] = '\0';
281 	(void)fprintf(tp, "%s\007New mail for %s@%.*s\007 has arrived:%s----%s",
282 	    cr, name, (int)sizeof(hostname), hostname, cr, cr);
283 	jkfprintf(tp, name, offset);
284 	(void)fclose(tp);
285 	_exit(0);
286 }
287 
288 void
jkfprintf(FILE * tp,char name[],off_t offset)289 jkfprintf(FILE *tp, char name[], off_t offset)
290 {
291 	char *cp, ch;
292 	char visout[5], *s2;
293 	FILE *fi;
294 	int linecnt, charcnt, inheader;
295 	char line[BUFSIZ];
296 
297 	if ((fi = fopen(name, "r")) == NULL)
298 		return;
299 
300 	(void)fseeko(fi, offset, SEEK_SET);
301 	/*
302 	 * Print the first 7 lines or 560 characters of the new mail
303 	 * (whichever comes first).  Skip header crap other than
304 	 * From, Subject, To, and Date.
305 	 */
306 	linecnt = 7;
307 	charcnt = 560;
308 	inheader = 1;
309 	while (fgets(line, sizeof(line), fi) != NULL) {
310 		if (inheader) {
311 			if (line[0] == '\n') {
312 				inheader = 0;
313 				continue;
314 			}
315 			if (line[0] == ' ' || line[0] == '\t' ||
316 			    (strncmp(line, "From:", 5) &&
317 			    strncmp(line, "Subject:", 8)))
318 				continue;
319 		}
320 		if (linecnt <= 0 || charcnt <= 0) {
321 			(void)fprintf(tp, "...more...%s", cr);
322 			(void)fclose(fi);
323 			return;
324 		}
325 		/* strip weird stuff so can't trojan horse stupid terminals */
326 		for (cp = line; (ch = *cp) && ch != '\n'; ++cp, --charcnt) {
327 			ch = toascii(ch);
328 			vis(visout, ch, VIS_SAFE|VIS_NOSLASH, cp[1]);
329 			for (s2 = visout; *s2; s2++)
330 				(void)fputc(*s2, tp);
331 		}
332 		(void)fputs(cr, tp);
333 		--linecnt;
334 	}
335 	(void)fprintf(tp, "----%s\n", cr);
336 	(void)fclose(fi);
337 }
338