File: comsat.c

package info (click to toggle)
biff 1%3A0.17.pre20000412-5
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, lenny, squeeze, stretch, wheezy
  • size: 120 kB
  • ctags: 28
  • sloc: ansic: 298; makefile: 82; sh: 27
file content (525 lines) | stat: -rw-r--r-- 13,804 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/*
 * Copyright (c) 1980 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

char copyright[] =
  "@(#) Copyright (c) 1980 Regents of the University of California.\n"
  "All rights reserved.\n";

/*
 * From: @(#)comsat.c	5.24 (Berkeley) 2/25/91
 */
char rcsid[] = 
  "$Id: comsat.c,v 1.17 1999/10/17 23:18:47 dholland Exp $";

#include <sys/param.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <sys/wait.h>

#include <netinet/in.h>

#include <stdio.h>
#include <utmp.h>
#include <termios.h>
#include <signal.h>
#include <errno.h>
#include <netdb.h>
#include <syslog.h>
#include <ctype.h>
#include <string.h>
#include <pwd.h>
#include <paths.h>   /* used for _PATH_MAILDIR, _PATH_UTMP, etc. */
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

#include "../version.h"

static int debug = 0;
#define	dsyslog	if (debug) syslog

#define MAXIDLE	120

static char hostname[MAXHOSTNAMELEN];
static struct utmp *utmp = NULL;
static time_t lastmsgtime;
static int nutmp;

static void mailfor(char *name);
static void notify(struct utmp *utp, off_t offset, const char *filename);
static void jkfprintf(FILE *, const char *name, off_t offset, const char *cr, const char *filename);
static void onalrm(int);

int main(void) {
	char msgbuf[100];          /* network input buffer */
	struct sockaddr_in from;   /* name of socket */
	socklen_t fromlen;         /* holds sizeof(from) */

	/* 
	 * Verify proper invocation: get the address of the local socket
	 * that's supposed to be our stdin. If it's not a socket (the only
	 * likely error) assume we were inadvertently run from someone's
	 * shell and quit out.
	 */
	fromlen = sizeof(from);
	if (getsockname(0, (struct sockaddr *)&from, &fromlen) < 0) {
		fprintf(stderr, "comsat: getsockname: %s.\n", strerror(errno));
		exit(1);
	}

	/*
	 * openlog() opens a connection to the system logger for comsat.
	 * We log as "comsat", with the process id, to the "LOG_DAEMON"
	 * log channel.
	 */
	openlog("comsat", LOG_PID, LOG_DAEMON);

	/*
	 * Schlep over to the system mail spool.
	 */
	if (chdir(_PATH_MAILDIR)) {
		syslog(LOG_ERR, "chdir: %s: %m", _PATH_MAILDIR);
		exit(1);
	}

	/*
	 * Record the time of the last message received (the one that
	 * caused us to be run) so we can idle out later.
	 */
	time(&lastmsgtime);

	/*
	 * Grab our hostname for spewing to the user's screen.
	 */
	gethostname(hostname, sizeof(hostname));

	/*
	 * Make sure we won't get stopped by scribbling on the user's screen.
	 */
	signal(SIGTTOU, SIG_IGN);

	/* 
	 * This declares that we're not interested in child processes' 
	 * exit codes, so they will go away on their own without needing
	 * to be wait()'d for.
	 */
	signal(SIGCHLD, SIG_IGN);

	/*
	 * Periodically reread the utmp, starting now.
	 */
	signal(SIGALRM, onalrm);
	onalrm(SIGALRM);

	/*
	 * Loop forever handling biff packets.
	 */
	for (;;) {
		sigset_t sigset;
		int cc;

		errno = 0;
		cc = recv(0, msgbuf, sizeof(msgbuf) - 1, 0);
		if (cc <= 0) {
			if (errno != EINTR) sleep(1);
			continue;
		}
		if (!nutmp) {
			/* utmp is empty: no one is logged in */ 
			continue;
		}

		/* Make sure we don't get SIGALRM while doing mailfor() */
		sigemptyset(&sigset);
		sigaddset(&sigset, SIGALRM);
		sigprocmask(SIG_BLOCK, &sigset, NULL);

		/* null-terminate input */
		msgbuf[cc] = 0;

		/* update time stamp */
		time(&lastmsgtime);

		/* biff the user */
		mailfor(msgbuf);

		/* allow SIGALRM again */
		sigprocmask(SIG_UNBLOCK, &sigset, NULL);
	}
}

/*
 * This function is called at startup and every fifteen seconds while 
 * we're running, via timer signals.
 */
static void onalrm(int signum) {
	static int utmpsize;		/* last malloced size for utmp */
	static time_t utmpmtime;	/* last modification time for utmp */

	struct stat statbuf;            /* scratch storage for stat() */
	struct utmp *uptr;
	int maxutmp;

	/*
	 * Defensive programming (this should not happen)
	 */
	if (signum!=SIGALRM) {
	    dsyslog(LOG_DEBUG, "wild signal %d\n", signum);
	    return;
	}

	/*
	 * If we've been sitting around doing nothing, go away.
	 */
	if (time(NULL) - lastmsgtime >= MAXIDLE) {
		exit(0);
	}

	/*
	 * Come back here in another fifteen seconds.
	 */
	alarm(15);

	/*
	 * Check the modification time of the utmp file.
	 */
	if (stat(_PATH_UTMP, &statbuf) < 0) {
		dsyslog(LOG_DEBUG, "fstat of utmp failed: %m\n");
		return;
	}

	if (statbuf.st_mtime > utmpmtime) {
		/*
		 * utmp has changed since we last came here; reread it and
		 * save the modification time.
		 */
		utmpmtime = statbuf.st_mtime;

		/*
		 * If it's now bigger than the space we have for it, 
		 * get more space.
		 */
		if (statbuf.st_size > utmpsize) {
			utmpsize = statbuf.st_size + 10 * sizeof(struct utmp);
			if (utmp) {
				utmp = realloc(utmp, utmpsize);
			}
			else {
				utmp = malloc(utmpsize);
			}
			if (!utmp) {
				syslog(LOG_ERR, "malloc failed: %m");
				exit(1);
			}
		}

		/* This is how many utmp entries we can possibly get */
		maxutmp = utmpsize / sizeof(struct utmp);

		/* Rewind the utmp file */
		setutent();

		/*
		 * Read the utmp file, via libc, copying each entry and
		 * counting how many we get.
		 */
		nutmp = 0;
		while ((uptr = getutent())!=NULL && nutmp < maxutmp) {
		    utmp[nutmp] = *uptr;
		    nutmp++;
		}

		/* Now done; close the utmp file. */
		endutent();
	}
}

/*
 * We get here when we have mail to announce for the specified user.
 * "name" holds a biff packet, which comes in the form
 *          username@fileoffset
 */
static void mailfor(char *name)
{
	struct utmp *utp;
	char *cp;
	off_t offset;
	char *filename;

	dsyslog(LOG_DEBUG, "mailfor: %s\n", name);

	/* Break off the file offset part and convert it to an integer. */
	cp = strchr(name, '@');
	if (!cp) return;
	*cp = 0;
	offset = strtol(cp + 1, &filename, 10);
	/* if(*filename != '\0')
		return; */

	if(*filename == ':')
		filename++;

	/* Look through the utmp and call notify() for each matching login. */
	utp = &utmp[nutmp];
	while (--utp >= utmp) {
		if (!strncmp(utp->ut_name, name, sizeof(utmp[0].ut_name)))
			notify(utp, offset, filename);
	}
}

/*
 * Check if a given tty name found in utmp is actually a legitimate tty.
 */
static int valid_tty(const char *line)
{
	const char *testline = line;

	/* 
	 * As of Linux 2.2 we can now sometimes have ttys in subdirs,
	 * but only /dev/pts. So if the name begins with pts/, skip that
	 * part. If there's a slash in anything else, complain loudly.
	 */
	if (!strncmp(testline, "pts/", 4)) testline += 4;

	if (strchr(testline, '/')) {
		/* A slash is an attempt to break security... */
		return 0;
	}
	return 1;
}

/*
 * This actually writes to the user's terminal.
 */
static void notify(struct utmp *utp, off_t offset, const char *filename)
{
	FILE *tp;                              /* file open on tty */
	struct stat stb;
	struct termios tbuf;
	char tty[sizeof(utp->ut_line)+sizeof(_PATH_DEV)+1]; /* full tty path */
	char name[sizeof(utp->ut_name) + 1];   /* user name */
	char line[sizeof(utp->ut_line) + 1];   /* tty name */
	const char *cr;                        /* line delimiter */
	sigset_t sigset;                       /* scratch signal mask */

#ifdef USER_PROCESS
	if (utp->ut_type != USER_PROCESS) {
		return;
	}
#endif

	/*
	 * Be careful in case we have a hostile utmp. (Remember sunos4 
	 * where it was mode 666?) Note that ut_line normally includes
	 * enough space for the null-terminator, but ut_name doesn't.
	 */
	strncpy(line, utp->ut_line, sizeof(utp->ut_line));
	line[sizeof(utp->ut_line)] = 0;

	strncpy(name, utp->ut_name, sizeof(utp->ut_name));
	name[sizeof(name) - 1] = '\0';

	/* Get the full path to the tty. */
	snprintf(tty, sizeof(tty), "%s%s", _PATH_DEV, line);

	/*
	 * Again, in case we have a hostile utmp, try to make sure we've
	 * got valid data and we're not being asked to write to, say,
	 * /etc/passwd.
	 */
	if (!valid_tty(line)) {
		syslog(LOG_AUTH | LOG_NOTICE, "invalid tty \"%s\" in utmp", 
		       tty);
		return;
	}

	/*
	 * If the user's tty isn't mode u+x, they don't want biffage;
	 * skip them.
	 */
	if (stat(tty, &stb) || !(stb.st_mode & S_IEXEC)) {
		dsyslog(LOG_DEBUG, "%s: wrong mode on %s", name, tty);
		return;
	}
	dsyslog(LOG_DEBUG, "notify %s on %s\n", name, tty);

	/*
	 * Fork a child process to do the tty I/O. There are, traditionally, 
	 * various ways for tty I/O to block indefinitely or otherwise hang.
	 * Also later down we're going to setuid to make sure we can't be
	 * used to read any file on the system.
	 *
	 * This of course makes a denial of service attack possible. So,
	 * in the parent process, wait a tenth of a second before continuing.
	 * This causes a primitive form of rate-limiting. It might be too 
	 * much delay for a busy system. But a busy system probably shouldn't
	 * be using comsat. If someone would like to make this smarter, feel
	 * free.
	 *
	 * Note: sleep with select() and NOT sleep() because on some systems
	 * at least sleep uses alarm(), which would interfere with our 
	 * reload/timeout logic.
	 */
	if (fork()) {
		/* parent process */
		struct timeval tv;
		tv.tv_sec = 0;
		tv.tv_usec = 100000;
		select(0, NULL, NULL, NULL, &tv);
		return;
	}
	/* child process */

	/*
	 * Turn off the alarm handler and instead exit in thirty seconds.
	 * Make sure SIGALRM isn't blocked.
	 */
	signal(SIGALRM, SIG_DFL);
	sigemptyset(&sigset);
	sigprocmask(SIG_SETMASK, &sigset, NULL);
	alarm(30);

	/*
	 * Open the tty.
	 */
	if ((tp = fopen(tty, "w")) == NULL) {
		dsyslog(LOG_ERR, "fopen of tty %s failed", tty);
		_exit(-1);
	}

	/* 
	 * Get the tty mode. Try to determine whether to use \n or \r\n 
	 * for linebreaks.
	 */
	tcgetattr(fileno(tp), &tbuf);
	if ((tbuf.c_oflag & OPOST) && (tbuf.c_oflag & ONLCR)) cr = "\n";
	else cr = "\r\n";

	/*
	 * Announce the mail.
	 */
	fprintf(tp, "%s\aNew mail for %s@%.*s\a has arrived:%s----%s",
		cr, name, (int)sizeof(hostname), hostname, cr, cr);

	/*
	 * Print the first few lines of the message.
	 */
	jkfprintf(tp, name, offset, cr, filename);

	/*
	 * Close up and quit the child process.
	 */
	fclose(tp);
	_exit(0);
}

/*
 * This prints a few lines from the mailbox of the user "name" at offset
 * "offset", using "cr" as the line break string, to the file "tp".
 */
static void jkfprintf(FILE *tp, const char *name, off_t offset, const char *cr, const char * filename)
{
	char *cp, ch;
	FILE *fi;
	int linecnt, charcnt, inheader;
	struct passwd *p;
	char line[BUFSIZ];

	/* 
	 * Set uid to user in case mail drop is on nfs 
	 * ...and also to prevent cute symlink to /etc/shadow games 
	 */
	if ((p = getpwnam(name)) == NULL) {
		/*
		 * If user is not in passwd file, assume that it's
		 * an attempt to break security...
		 */
		syslog(LOG_AUTH | LOG_NOTICE, "%s not in passwd file", name);
		return;
	}

	/* 
	 * This sets both real and effective uids and clears the saved uid 
	 * too (see posix) so it's a one-way trip.
	 */
	setuid(p->pw_uid);

	/*
	 * Open the user's mailbox (recall we're already in the mail spool dir)
	 */
	fi = fopen(filename, "r");
	if (fi == NULL)	{
	        dsyslog(LOG_DEBUG, "couldn't open mailbox %s\n", filename);
		return;
	}

	/* Move to requested offset */
	fseek(fi, offset, L_SET);
	/*
	 * Print the first 7 lines or 560 characters of the new mail
	 * (whichever comes first).  Skip header crap other than
	 * From and Subject.
	 */
	linecnt = 7;
	charcnt = 560;
	inheader = 1;
	while (fgets(line, sizeof(line), fi) != NULL) {
		if (inheader) {
			if (line[0] == '\n') {
				inheader = 0;
				continue;
			}
			if (line[0] == ' ' || line[0] == '\t' ||
			    (strncasecmp(line, "From:", 5) &&
			    strncasecmp(line, "Subject:", 8)))
				continue;
		}
		if (linecnt <= 0 || charcnt <= 0) {
			fprintf(tp, "...more...%s", cr);
			fclose(fi);
			return;
		}
		/* strip weird stuff so can't trojan horse stupid terminals */
		for (cp = line; (ch = *cp) && ch != '\n'; ++cp, --charcnt) {
			ch = toascii(ch);
			if (!isprint(ch) && !isspace(ch))
				ch |= 0x40;
			fputc(ch, tp);
		}
		fputs(cr, tp);
		--linecnt;
	}
	fprintf(tp, "----%s", cr);
	fclose(fi);
}