xref: /netbsd-src/libexec/comsat/comsat.c (revision 9c1da17e908379b8a470f1117a6395bd6a0ca559)
1 /*	$NetBSD: comsat.c,v 1.34 2005/07/18 04:01:33 christos 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.34 2005/07/18 04:01:33 christos 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 <err.h>
57 #include <signal.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <syslog.h>
62 #include <termios.h>
63 #include <time.h>
64 #include <vis.h>
65 #include <unistd.h>
66 #ifdef SUPPORT_UTMP
67 #include <utmp.h>
68 #endif
69 #ifdef SUPPORT_UTMPX
70 #include <utmpx.h>
71 #endif
72 
73 #include "utmpentry.h"
74 
75 #if !defined(SUPPORT_UTMP) && !defined(SUPPORT_UTMPX)
76 	#error "SUPPORT_UTMP and/or SUPPORT_UTMPX must be defined"
77 #endif
78 
79 #define	dsyslog	if (debug) syslog
80 
81 #define MAXIDLE	120
82 
83 static int	logging;
84 static int	debug;
85 static char	hostname[MAXHOSTNAMELEN + 1];
86 static time_t	utmpmtime;		/* last modification time for utmp/x */
87 static int	nutmp;
88 static struct	utmpentry *utmp = NULL;
89 static time_t	lastmsgtime;
90 static volatile sig_atomic_t needupdate;
91 
92 int main(int, char *[]);
93 static void jkfprintf(FILE *, const char *, off_t, const char *);
94 static void mailfor(const char *);
95 static void notify(const struct utmpentry *, off_t);
96 static void onalrm(int);
97 static void checkutmp(void);
98 
99 int
100 main(int argc, char *argv[])
101 {
102 	struct sockaddr_storage from;
103 	int cc, ch;
104 	socklen_t fromlen;
105 	char msgbuf[100];
106 	sigset_t nsigset, osigset;
107 
108 	/* verify proper invocation */
109 	fromlen = sizeof(from);
110 	if (getsockname(0, (struct sockaddr *)(void *)&from, &fromlen) == -1)
111 		err(1, "getsockname");
112 
113 	openlog("comsat", LOG_PID, LOG_DAEMON);
114 	while ((ch = getopt(argc, argv, "l")) != -1)
115 		switch (ch) {
116 		case 'l':
117 			logging = 1;
118 			break;
119 		default:
120 			syslog(LOG_ERR, "Usage: %s [-l]", getprogname());
121 			exit(1);
122 		}
123 	if (chdir(_PATH_MAILDIR) == -1) {
124 		syslog(LOG_ERR, "chdir: %s: %m", _PATH_MAILDIR);
125 		(void)recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
126 		exit(1);
127 	}
128 	(void)time(&lastmsgtime);
129 	(void)gethostname(hostname, sizeof(hostname));
130 	hostname[sizeof(hostname) - 1] = '\0';
131 	(void)signal(SIGALRM, onalrm);
132 	(void)signal(SIGTTOU, SIG_IGN);
133 	(void)signal(SIGCHLD, SIG_IGN);
134 	(void)sigemptyset(&nsigset);
135 	(void)sigaddset(&nsigset, SIGALRM);
136 	if (sigprocmask(SIG_SETMASK, NULL, &osigset) == -1) {
137 		syslog(LOG_ERR, "sigprocmask get failed (%m)");
138 		exit(1);
139 	}
140 	needupdate++;
141 	for (;;) {
142 		cc = recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
143 		if (cc <= 0) {
144 			if (errno != EINTR)
145 				sleep(1);
146 			errno = 0;
147 			checkutmp();
148 			continue;
149 		} else
150 			checkutmp();
151 		if (!nutmp)		/* no one has logged in yet */
152 			continue;
153 		if (sigprocmask(SIG_SETMASK, &nsigset, NULL) == -1) {
154 			syslog(LOG_ERR, "sigprocmask set failed (%m)");
155 			exit(1);
156 		}
157 		msgbuf[cc] = '\0';
158 		(void)time(&lastmsgtime);
159 		mailfor(msgbuf);
160 		if (sigprocmask(SIG_SETMASK, &osigset, NULL) == -1) {
161 			syslog(LOG_ERR, "sigprocmask restore failed (%m)");
162 			exit(1);
163 		}
164 	}
165 }
166 
167 static void
168 /*ARGSUSED*/
169 onalrm(int signo)
170 {
171 	needupdate++;
172 }
173 
174 static void
175 checkutmp(void)
176 {
177 	struct stat statbf;
178 	time_t newtime = 0;
179 
180 	if (!needupdate)
181 		return;
182 	needupdate = 0;
183 
184 	if (time(NULL) - lastmsgtime >= MAXIDLE)
185 		exit(0);
186 	(void)alarm((u_int)15);
187 #ifdef SUPPORT_UTMP
188 	if (stat(_PATH_UTMP, &statbf) != -1)
189 		if (statbf.st_mtime > newtime)
190 			newtime = statbf.st_mtime;
191 #endif
192 #ifdef SUPPORT_UTMPX
193 	if (stat(_PATH_UTMPX, &statbf) != -1)
194 		if (statbf.st_mtime > newtime)
195 			newtime = statbf.st_mtime;
196 #endif
197 	if (newtime > utmpmtime) {
198 		freeutentries(utmp);
199 		nutmp = getutentries(NULL, &utmp);
200 		utmpmtime = newtime;
201 	}
202 }
203 
204 static void
205 mailfor(const char *name)
206 {
207 	struct utmpentry *ep;
208 	char *cp, *fn;
209 	off_t offset;
210 	intmax_t val;
211 
212 	if (!(cp = strchr(name, '@')))
213 		return;
214 	*cp = '\0';
215 	errno = 0;
216 	offset = val = strtoimax(cp + 1, &fn, 10);
217 	if (errno == ERANGE || offset != val)
218 		return;
219 	if (fn && *fn && *fn != '\n') {
220 		/*
221 		 * Procmail sends messages to comsat with a trailing colon
222 		 * and a pathname to the folder where the new message was
223 		 * deposited.  Since we can't reliably open only regular
224 		 * files, we need to ignore these.  With one exception:
225 		 * if it mentions the user's system mailbox.
226 		 */
227 		char maildir[MAXPATHLEN];
228 		int l = snprintf(maildir, sizeof(maildir), ":%s/%s",
229 		    _PATH_MAILDIR, name);
230 		if (l >= sizeof(maildir) || strcmp(maildir, fn) != 0)
231 			return;
232 	}
233 	for (ep = utmp; ep != NULL; ep = ep->next)
234 		if (strcmp(ep->name, name) == 0)
235 			notify(ep, offset);
236 }
237 
238 static void
239 notify(const struct utmpentry *ep, off_t offset)
240 {
241 	FILE *tp;
242 	struct passwd *p;
243 	struct stat stb;
244 	struct termios ttybuf;
245 	char tty[sizeof(_PATH_DEV) + sizeof(ep->line) + 1];
246 	const char *cr = ep->line;
247 
248 	if (strncmp(cr, "pts/", 4) == 0)
249 		cr += 4;
250 	if (strchr(cr, '/')) {
251 		/* A slash is an attempt to break security... */
252 		syslog(LOG_AUTH | LOG_NOTICE, "Unexpected `/' in `%s'",
253 		    ep->line);
254 		return;
255 	}
256 	(void)snprintf(tty, sizeof(tty), "%s%s", _PATH_DEV, ep->line);
257 	if (stat(tty, &stb) == -1 || !(stb.st_mode & S_IEXEC)) {
258 		dsyslog(LOG_DEBUG, "%s: wrong mode on %s", ep->name, tty);
259 		return;
260 	}
261 	dsyslog(LOG_DEBUG, "notify %s on %s", ep->name, tty);
262 	switch (fork()) {
263 	case -1:
264 		syslog(LOG_NOTICE, "fork failed (%m)");
265 		return;
266 	case 0:
267 		break;
268 	default:
269 		return;
270 	}
271 	(void)signal(SIGALRM, SIG_DFL);
272 	(void)alarm((u_int)30);
273 	if ((tp = fopen(tty, "w")) == NULL) {
274 		dsyslog(LOG_ERR, "open `%s' (%s)", tty, strerror(errno));
275 		_exit(1);
276 	}
277 	if (tcgetattr(fileno(tp), &ttybuf) == -1) {
278 		dsyslog(LOG_ERR, "tcgetattr `%s' (%s)", tty, strerror(errno));
279 		_exit(1);
280 	}
281 	cr = (ttybuf.c_oflag & ONLCR) && (ttybuf.c_oflag & OPOST) ?
282 	    "\n" : "\n\r";
283 	/* Set uid/gid/groups to users in case mail drop is on nfs */
284 	if ((p = getpwnam(ep->name)) == NULL ||
285 	    initgroups(p->pw_name, p->pw_gid) == -1 ||
286 	    setgid(p->pw_gid) == -1 ||
287 	    setuid(p->pw_uid) == -1)
288 		_exit(1);
289 
290 	if (logging)
291 		syslog(LOG_INFO, "biff message for %s", ep->name);
292 
293 	(void)fprintf(tp, "%s\007New mail for %s@%.*s\007 has arrived:%s----%s",
294 	    cr, ep->name, (int)sizeof(hostname), hostname, cr, cr);
295 	jkfprintf(tp, ep->name, offset, cr);
296 	(void)fclose(tp);
297 	_exit(0);
298 }
299 
300 static void
301 jkfprintf(FILE *tp, const char *name, off_t offset, const char *cr)
302 {
303 	FILE *fi;
304 	int linecnt, charcnt, inheader;
305 	char line[BUFSIZ], visline[BUFSIZ * 4 + 1], *nl;
306 
307 	if ((fi = fopen(name, "r")) == NULL)
308 		return;
309 
310 	(void)fseeko(fi, offset, SEEK_SET);
311 	/*
312 	 * Print the first 7 lines or 560 characters of the new mail
313 	 * (whichever comes first).  Skip header crap other than
314 	 * From, Subject, To, and Date.
315 	 */
316 	linecnt = 7;
317 	charcnt = 560;
318 	inheader = 1;
319 	while (fgets(line, sizeof(line), fi) != NULL) {
320 		line[sizeof(line) - 1] = '\0';
321 		if (inheader) {
322 			if (line[0] == '\n') {
323 				inheader = 0;
324 				continue;
325 			}
326 			if (line[0] == ' ' || line[0] == '\t' ||
327 			    (strncasecmp(line, "From:", 5) &&
328 			    strncasecmp(line, "Subject:", 8)))
329 				continue;
330 		}
331 		if (strncmp(line, "From ", 5) == 0) {
332 			(void)fprintf(tp, "----%s", cr);
333 			(void)fclose(fi);
334 			return;
335 		}
336 		if (linecnt <= 0 || charcnt <= 0) {
337 			(void)fprintf(tp, "...more...%s", cr);
338 			(void)fclose(fi);
339 			return;
340 		}
341 		if ((nl = strchr(line, '\n')) != NULL)
342 			*nl = '\0';
343 		/* strip weird stuff so can't trojan horse stupid terminals */
344 		(void)strvis(visline, line, VIS_CSTYLE);
345 		(void)fputs(visline, tp);
346 		(void)fputs(cr, tp);
347 		--linecnt;
348 	}
349 	(void)fprintf(tp, "----%s\n", cr);
350 	(void)fclose(fi);
351 }
352