xref: /freebsd/usr.bin/msgs/msgs.c (revision a25896ca1270e25b657ceaa8d47d5699515f5c25)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1980, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #if 0
39 #ifndef lint
40 static char sccsid[] = "@(#)msgs.c	8.2 (Berkeley) 4/28/95";
41 #endif /* not lint */
42 #endif
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 /*
48  * msgs - a user bulletin board program
49  *
50  * usage:
51  *	msgs [fhlopq] [[-]number]	to read messages
52  *	msgs -s				to place messages
53  *	msgs -c [-days]			to clean up the bulletin board
54  *
55  * prompt commands are:
56  *	y	print message
57  *	n	flush message, go to next message
58  *	q	flush message, quit
59  *	p	print message, turn on 'pipe thru more' mode
60  *	P	print message, turn off 'pipe thru more' mode
61  *	-	reprint last message
62  *	s[-][<num>] [<filename>]	save message
63  *	m[-][<num>]	mail with message in temp mbox
64  *	x	exit without flushing this message
65  *	<num>	print message number <num>
66  */
67 
68 #define V7		/* will look for TERM in the environment */
69 #define OBJECT		/* will object to messages without Subjects */
70 /* #define REJECT */	/* will reject messages without Subjects
71 			   (OBJECT must be defined also) */
72 /* #define UNBUFFERED *//* use unbuffered output */
73 
74 #include <sys/param.h>
75 #include <sys/stat.h>
76 #include <ctype.h>
77 #include <dirent.h>
78 #include <err.h>
79 #include <errno.h>
80 #include <fcntl.h>
81 #include <locale.h>
82 #include <pwd.h>
83 #include <setjmp.h>
84 #include <termcap.h>
85 #include <termios.h>
86 #include <signal.h>
87 #include <stdio.h>
88 #include <stdlib.h>
89 #include <string.h>
90 #include <time.h>
91 #include <unistd.h>
92 #include "pathnames.h"
93 
94 #define	CMODE	0644		/* bounds file creation	mode */
95 #define NO	0
96 #define YES	1
97 #define SUPERUSER	0	/* superuser uid */
98 #define DAEMON		1	/* daemon uid */
99 #define NLINES	24		/* default number of lines/crt screen */
100 #define NDAYS	21		/* default keep time for messages */
101 #define DAYS	*24*60*60	/* seconds/day */
102 #define MSGSRC	".msgsrc"	/* user's rc file */
103 #define BOUNDS	"bounds"	/* message bounds file */
104 #define NEXT	"Next message? [yq]"
105 #define MORE	"More? [ynq]"
106 #define NOMORE	"(No more) [q] ?"
107 
108 typedef	char	bool;
109 
110 static FILE	*msgsrc;
111 static FILE	*newmsg;
112 static const char *sep = "-";
113 static char	inbuf[BUFSIZ];
114 static char	fname[MAXPATHLEN];
115 static char	cmdbuf[MAXPATHLEN + MAXPATHLEN];
116 static char	subj[128];
117 static char	from[128];
118 static char	date[128];
119 static char	*ptr;
120 static char	*in;
121 static bool	local;
122 static bool	ruptible;
123 static bool	totty;
124 static bool	seenfrom;
125 static bool	seensubj;
126 static bool	blankline;
127 static bool	printing = NO;
128 static bool	mailing = NO;
129 static bool	quitit = NO;
130 static bool	sending = NO;
131 static bool	intrpflg = NO;
132 static uid_t	uid;
133 static int	msg;
134 static int	prevmsg;
135 static int	lct;
136 static int	nlines;
137 static int	Lpp = 0;
138 static time_t	t;
139 static time_t	keep;
140 
141 /* option initialization */
142 static bool	hdrs = NO;
143 static bool	qopt = NO;
144 static bool	hush = NO;
145 static bool	send_msg = NO;
146 static bool	locomode = NO;
147 static bool	use_pager = NO;
148 static bool	clean = NO;
149 static bool	lastcmd = NO;
150 static jmp_buf	tstpbuf;
151 
152 static void	ask(const char *);
153 static void	gfrsub(FILE *);
154 static int	linecnt(FILE *);
155 static int	next(char *);
156 static char	*nxtfld(char *);
157 static void	onsusp(int);
158 static void	onintr(int);
159 static void	prmesg(int);
160 static void	usage(void);
161 
162 int
163 main(int argc, char *argv[])
164 {
165 	bool newrc, already;
166 	int rcfirst = 0;		/* first message to print (from .rc) */
167 	int rcback = 0;			/* amount to back off of rcfirst */
168 	int firstmsg = 0, nextmsg = 0, lastmsg = 0;
169 	int blast = 0;
170 	struct stat buf;		/* stat to check access of bounds */
171 	FILE *bounds;
172 	char *cp;
173 
174 #ifdef UNBUFFERED
175 	setbuf(stdout, NULL);
176 #endif
177 	setlocale(LC_ALL, "");
178 
179 	time(&t);
180 	if (setuid(uid = getuid()) != 0)
181 		err(1, "setuid failed");
182 	ruptible = (signal(SIGINT, SIG_IGN) == SIG_DFL);
183 	if (ruptible)
184 		signal(SIGINT, SIG_DFL);
185 
186 	argc--, argv++;
187 	while (argc > 0) {
188 		if (isdigit(argv[0][0])) {	/* starting message # */
189 			rcfirst = atoi(argv[0]);
190 		}
191 		else if (isdigit(argv[0][1])) {	/* backward offset */
192 			rcback = atoi( &( argv[0][1] ) );
193 		}
194 		else {
195 			ptr = *argv;
196 			while (*ptr) switch (*ptr++) {
197 
198 			case '-':
199 				break;
200 
201 			case 'c':
202 				if (uid != SUPERUSER && uid != DAEMON)
203 					errx(1,
204 				"only the super-user can use the c flag");
205 				clean = YES;
206 				break;
207 
208 			case 'f':		/* silently */
209 				hush = YES;
210 				break;
211 
212 			case 'h':		/* headers only */
213 				hdrs = YES;
214 				break;
215 
216 			case 'l':		/* local msgs only */
217 				locomode = YES;
218 				break;
219 
220 			case 'o':		/* option to save last message */
221 				lastcmd = YES;
222 				break;
223 
224 			case 'p':		/* pipe thru 'more' during long msgs */
225 				use_pager = YES;
226 				break;
227 
228 			case 'q':		/* query only */
229 				qopt = YES;
230 				break;
231 
232 			case 's':		/* sending TO msgs */
233 				send_msg = YES;
234 				break;
235 
236 			default:
237 				usage();
238 			}
239 		}
240 		argc--, argv++;
241 	}
242 
243 	/*
244 	 * determine current message bounds
245 	 */
246 	snprintf(fname, sizeof(fname), "%s/%s", _PATH_MSGS, BOUNDS);
247 
248 	/*
249 	 * Test access rights to the bounds file
250 	 * This can be a little tricky.  if(send_msg), then
251 	 * we will create it.  We assume that if(send_msg),
252 	 * then you have write permission there.
253 	 * Else, it better be there, or we bail.
254 	 */
255 	if (send_msg != YES) {
256 		if (stat(fname, &buf) < 0) {
257 			if (hush != YES) {
258 				err(errno, "%s", fname);
259 			} else {
260 				exit(1);
261 			}
262 		}
263 	}
264 	bounds = fopen(fname, "r");
265 
266 	if (bounds != NULL) {
267 		fscanf(bounds, "%d %d\n", &firstmsg, &lastmsg);
268 		fclose(bounds);
269 		blast = lastmsg;	/* save upper bound */
270 	}
271 
272 	if (clean)
273 		keep = t - (rcback? rcback : NDAYS) DAYS;
274 
275 	if (clean || bounds == NULL) {	/* relocate message bounds */
276 		struct dirent *dp;
277 		struct stat stbuf;
278 		bool seenany = NO;
279 		DIR	*dirp;
280 
281 		dirp = opendir(_PATH_MSGS);
282 		if (dirp == NULL)
283 			err(errno, "%s", _PATH_MSGS);
284 
285 		firstmsg = 32767;
286 		lastmsg = 0;
287 
288 		for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)){
289 			cp = dp->d_name;
290 			int i = 0;
291 
292 			if (dp->d_ino == 0)
293 				continue;
294 			if (dp->d_namlen == 0)
295 				continue;
296 
297 			if (clean)
298 				snprintf(inbuf, sizeof(inbuf), "%s/%s", _PATH_MSGS, cp);
299 
300 			while (isdigit(*cp))
301 				i = i * 10 + *cp++ - '0';
302 			if (*cp)
303 				continue;	/* not a message! */
304 
305 			if (clean) {
306 				if (stat(inbuf, &stbuf) != 0)
307 					continue;
308 				if (stbuf.st_mtime < keep
309 				    && stbuf.st_mode&S_IWRITE) {
310 					unlink(inbuf);
311 					continue;
312 				}
313 			}
314 
315 			if (i > lastmsg)
316 				lastmsg = i;
317 			if (i < firstmsg)
318 				firstmsg = i;
319 			seenany = YES;
320 		}
321 		closedir(dirp);
322 
323 		if (!seenany) {
324 			if (blast != 0)	/* never lower the upper bound! */
325 				lastmsg = blast;
326 			firstmsg = lastmsg + 1;
327 		}
328 		else if (blast > lastmsg)
329 			lastmsg = blast;
330 
331 		if (!send_msg) {
332 			bounds = fopen(fname, "w");
333 			if (bounds == NULL)
334 				err(errno, "%s", fname);
335 			chmod(fname, CMODE);
336 			fprintf(bounds, "%d %d\n", firstmsg, lastmsg);
337 			fclose(bounds);
338 		}
339 	}
340 
341 	if (send_msg) {
342 		/*
343 		 * Send mode - place msgs in _PATH_MSGS
344 		 */
345 		bounds = fopen(fname, "w");
346 		if (bounds == NULL)
347 			err(errno, "%s", fname);
348 
349 		nextmsg = lastmsg + 1;
350 		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, nextmsg);
351 		newmsg = fopen(fname, "w");
352 		if (newmsg == NULL)
353 			err(errno, "%s", fname);
354 		chmod(fname, CMODE);
355 
356 		fprintf(bounds, "%d %d\n", firstmsg, nextmsg);
357 		fclose(bounds);
358 
359 		sending = YES;
360 		if (ruptible)
361 			signal(SIGINT, onintr);
362 
363 		if (isatty(fileno(stdin))) {
364 			ptr = getpwuid(uid)->pw_name;
365 			printf("Message %d:\nFrom %s %sSubject: ",
366 				nextmsg, ptr, ctime(&t));
367 			fflush(stdout);
368 			fgets(inbuf, sizeof inbuf, stdin);
369 			putchar('\n');
370 			fflush(stdout);
371 			fprintf(newmsg, "From %s %sSubject: %s\n",
372 				ptr, ctime(&t), inbuf);
373 			blankline = seensubj = YES;
374 		}
375 		else
376 			blankline = seensubj = NO;
377 		for (;;) {
378 			fgets(inbuf, sizeof inbuf, stdin);
379 			if (feof(stdin) || ferror(stdin))
380 				break;
381 			blankline = (blankline || (inbuf[0] == '\n'));
382 			seensubj = (seensubj || (!blankline && (strncmp(inbuf, "Subj", 4) == 0)));
383 			fputs(inbuf, newmsg);
384 		}
385 #ifdef OBJECT
386 		if (!seensubj) {
387 			printf("NOTICE: Messages should have a Subject field!\n");
388 #ifdef REJECT
389 			unlink(fname);
390 #endif
391 			exit(1);
392 		}
393 #endif
394 		exit(ferror(stdin));
395 	}
396 	if (clean)
397 		exit(0);
398 
399 	/*
400 	 * prepare to display messages
401 	 */
402 	totty = (isatty(fileno(stdout)) != 0);
403 	use_pager = use_pager && totty;
404 
405 	if ((cp = getenv("HOME")) == NULL || *cp == '\0') {
406 		fprintf(stderr, "Error, no home directory!\n");
407 		exit(1);
408 	}
409 	snprintf(fname, sizeof(fname), "%s/%s", cp, MSGSRC);
410 	msgsrc = fopen(fname, "r");
411 	if (msgsrc) {
412 		newrc = NO;
413 		fscanf(msgsrc, "%d\n", &nextmsg);
414 		fclose(msgsrc);
415 		if (nextmsg > lastmsg+1) {
416 			printf("Warning: bounds have been reset (%d, %d)\n",
417 				firstmsg, lastmsg);
418 			truncate(fname, (off_t)0);
419 			newrc = YES;
420 		}
421 		else if (!rcfirst)
422 			rcfirst = nextmsg - rcback;
423 	}
424 	else
425 		newrc = YES;
426 	msgsrc = fopen(fname, "r+");
427 	if (msgsrc == NULL)
428 		msgsrc = fopen(fname, "w");
429 	if (msgsrc == NULL)
430 		err(errno, "%s", fname);
431 	if (rcfirst) {
432 		if (rcfirst > lastmsg+1) {
433 			printf("Warning: the last message is number %d.\n",
434 				lastmsg);
435 			rcfirst = nextmsg;
436 		}
437 		if (rcfirst > firstmsg)
438 			firstmsg = rcfirst;	/* don't set below first msg */
439 	}
440 	if (newrc) {
441 		nextmsg = firstmsg;
442 		rewind(msgsrc);
443 		fprintf(msgsrc, "%d\n", nextmsg);
444 		fflush(msgsrc);
445 	}
446 
447 #ifdef V7
448 	if (totty) {
449 		struct winsize win;
450 		if (ioctl(fileno(stdout), TIOCGWINSZ, &win) != -1)
451 			Lpp = win.ws_row;
452 		if (Lpp <= 0) {
453 			if (tgetent(inbuf, getenv("TERM")) <= 0
454 			    || (Lpp = tgetnum("li")) <= 0) {
455 				Lpp = NLINES;
456 			}
457 		}
458 	}
459 #endif
460 	Lpp -= 6;	/* for headers, etc. */
461 
462 	already = NO;
463 	prevmsg = firstmsg;
464 	printing = YES;
465 	if (ruptible)
466 		signal(SIGINT, onintr);
467 
468 	/*
469 	 * Main program loop
470 	 */
471 	for (msg = firstmsg; msg <= lastmsg; msg++) {
472 
473 		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, msg);
474 		newmsg = fopen(fname, "r");
475 		if (newmsg == NULL)
476 			continue;
477 
478 		gfrsub(newmsg);		/* get From and Subject fields */
479 		if (locomode && !local) {
480 			fclose(newmsg);
481 			continue;
482 		}
483 
484 		if (qopt) {	/* This has to be located here */
485 			printf("There are new messages.\n");
486 			exit(0);
487 		}
488 
489 		if (already && !hdrs)
490 			putchar('\n');
491 
492 		/*
493 		 * Print header
494 		 */
495 		if (totty)
496 			signal(SIGTSTP, onsusp);
497 		(void) setjmp(tstpbuf);
498 		already = YES;
499 		nlines = 2;
500 		if (seenfrom) {
501 			printf("Message %d:\nFrom %s %s", msg, from, date);
502 			nlines++;
503 		}
504 		if (seensubj) {
505 			printf("Subject: %s", subj);
506 			nlines++;
507 		}
508 		else {
509 			if (seenfrom) {
510 				putchar('\n');
511 				nlines++;
512 			}
513 			while (nlines < 6
514 			    && fgets(inbuf, sizeof inbuf, newmsg)
515 			    && inbuf[0] != '\n') {
516 				fputs(inbuf, stdout);
517 				nlines++;
518 			}
519 		}
520 
521 		lct = linecnt(newmsg);
522 		if (lct)
523 			printf("(%d%sline%s) ", lct, seensubj? " " : " more ",
524 			    (lct == 1) ? "" : "s");
525 
526 		if (hdrs) {
527 			printf("\n-----\n");
528 			fclose(newmsg);
529 			continue;
530 		}
531 
532 		/*
533 		 * Ask user for command
534 		 */
535 		if (totty)
536 			ask(lct? MORE : (msg==lastmsg? NOMORE : NEXT));
537 		else
538 			inbuf[0] = 'y';
539 		if (totty)
540 			signal(SIGTSTP, SIG_DFL);
541 cmnd:
542 		in = inbuf;
543 		switch (*in) {
544 			case 'x':
545 				/* FALLTHROUGH */
546 			case 'X':
547 				exit(0);
548 				/* NOTREACHED */
549 
550 			case 'q':
551 				/* FALLTHROUGH */
552 			case 'Q':
553 				quitit = YES;
554 				printf("--Postponed--\n");
555 				exit(0);
556 				/* NOTREACHED */
557 
558 			case 'n':
559 				/* FALLTHROUGH */
560 			case 'N':
561 				if (msg >= nextmsg) sep = "Flushed";
562 				prevmsg = msg;
563 				break;
564 
565 			case 'p':
566 				/* FALLTHROUGH */
567 			case 'P':
568 				use_pager = (*in++ == 'p');
569 				/* FALLTHROUGH */
570 			case '\n':
571 				/* FALLTHROUGH */
572 			case 'y':
573 			default:
574 				if (*in == '-') {
575 					msg = prevmsg-1;
576 					sep = "replay";
577 					break;
578 				}
579 				if (isdigit(*in)) {
580 					msg = next(in);
581 					sep = in;
582 					break;
583 				}
584 
585 				prmesg(nlines + lct + (seensubj? 1 : 0));
586 				prevmsg = msg;
587 
588 		}
589 
590 		printf("--%s--\n", sep);
591 		sep = "-";
592 		if (msg >= nextmsg) {
593 			nextmsg = msg + 1;
594 			rewind(msgsrc);
595 			fprintf(msgsrc, "%d\n", nextmsg);
596 			fflush(msgsrc);
597 		}
598 		if (newmsg)
599 			fclose(newmsg);
600 		if (quitit)
601 			break;
602 	}
603 
604 	/*
605 	 * Make sure .rc file gets updated
606 	 */
607 	if (--msg >= nextmsg) {
608 		nextmsg = msg + 1;
609 		rewind(msgsrc);
610 		fprintf(msgsrc, "%d\n", nextmsg);
611 		fflush(msgsrc);
612 	}
613 	if (already && !quitit && lastcmd && totty) {
614 		/*
615 		 * save or reply to last message?
616 		 */
617 		msg = prevmsg;
618 		ask(NOMORE);
619 		if (inbuf[0] == '-' || isdigit(inbuf[0]))
620 			goto cmnd;
621 	}
622 	if (!(already || hush || qopt))
623 		printf("No new messages.\n");
624 	exit(0);
625 	/* NOTREACHED */
626 }
627 
628 static void
629 usage(void)
630 {
631 	fprintf(stderr, "usage: msgs [fhlopq] [[-]number]\n");
632 	exit(1);
633 }
634 
635 static void
636 prmesg(int length)
637 {
638 	FILE *outf;
639 	char *env_pager;
640 
641 	if (use_pager && length > Lpp) {
642 		signal(SIGPIPE, SIG_IGN);
643 		signal(SIGQUIT, SIG_IGN);
644 		if ((env_pager = getenv("PAGER")) == NULL) {
645 			snprintf(cmdbuf, sizeof(cmdbuf), _PATH_PAGER, Lpp);
646 		} else {
647 			snprintf(cmdbuf, sizeof(cmdbuf), "%s", env_pager);
648 		}
649 		outf = popen(cmdbuf, "w");
650 		if (!outf)
651 			outf = stdout;
652 		else
653 			setbuf(outf, (char *)NULL);
654 	}
655 	else
656 		outf = stdout;
657 
658 	if (seensubj)
659 		putc('\n', outf);
660 
661 	while (fgets(inbuf, sizeof inbuf, newmsg)) {
662 		fputs(inbuf, outf);
663 		if (ferror(outf)) {
664 			clearerr(outf);
665 			break;
666 		}
667 	}
668 
669 	if (outf != stdout) {
670 		pclose(outf);
671 		signal(SIGPIPE, SIG_DFL);
672 		signal(SIGQUIT, SIG_DFL);
673 	}
674 	else {
675 		fflush(stdout);
676 	}
677 
678 	/* force wait on output */
679 	tcdrain(fileno(stdout));
680 }
681 
682 static void
683 onintr(int unused __unused)
684 {
685 	signal(SIGINT, onintr);
686 	if (mailing)
687 		unlink(fname);
688 	if (sending) {
689 		unlink(fname);
690 		puts("--Killed--");
691 		exit(1);
692 	}
693 	if (printing) {
694 		putchar('\n');
695 		if (hdrs)
696 			exit(0);
697 		sep = "Interrupt";
698 		if (newmsg)
699 			fseeko(newmsg, (off_t)0, SEEK_END);
700 		intrpflg = YES;
701 	}
702 }
703 
704 /*
705  * We have just gotten a susp.  Suspend and prepare to resume.
706  */
707 static void
708 onsusp(int unused __unused)
709 {
710 	signal(SIGTSTP, SIG_DFL);
711 	sigsetmask(0);
712 	kill(0, SIGTSTP);
713 	signal(SIGTSTP, onsusp);
714 	if (!mailing)
715 		longjmp(tstpbuf, 0);
716 }
717 
718 static int
719 linecnt(FILE *f)
720 {
721 	off_t oldpos = ftello(f);
722 	int l = 0;
723 	char lbuf[BUFSIZ];
724 
725 	while (fgets(lbuf, sizeof lbuf, f))
726 		l++;
727 	clearerr(f);
728 	fseeko(f, oldpos, SEEK_SET);
729 	return (l);
730 }
731 
732 static int
733 next(char *buf)
734 {
735 	int i;
736 	sscanf(buf, "%d", &i);
737 	sprintf(buf, "Goto %d", i);
738 	return(--i);
739 }
740 
741 static void
742 ask(const char *prompt)
743 {
744 	char	inch;
745 	int	n, cmsg, fd;
746 	off_t	oldpos;
747 	FILE	*cpfrom, *cpto;
748 
749 	printf("%s ", prompt);
750 	fflush(stdout);
751 	intrpflg = NO;
752 	(void) fgets(inbuf, sizeof inbuf, stdin);
753 	if ((n = strlen(inbuf)) > 0 && inbuf[n - 1] == '\n')
754 		inbuf[n - 1] = '\0';
755 	if (intrpflg)
756 		inbuf[0] = 'x';
757 
758 	/*
759 	 * Handle 'mail' and 'save' here.
760 	 */
761 	if ((inch = inbuf[0]) == 's' || inch == 'm') {
762 		if (inbuf[1] == '-')
763 			cmsg = prevmsg;
764 		else if (isdigit(inbuf[1]))
765 			cmsg = atoi(&inbuf[1]);
766 		else
767 			cmsg = msg;
768 		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, cmsg);
769 
770 		oldpos = ftello(newmsg);
771 
772 		cpfrom = fopen(fname, "r");
773 		if (!cpfrom) {
774 			printf("Message %d not found\n", cmsg);
775 			ask (prompt);
776 			return;
777 		}
778 
779 		if (inch == 's') {
780 			in = nxtfld(inbuf);
781 			if (*in) {
782 				for (n=0; in[n] > ' '; n++) { /* sizeof fname? */
783 					fname[n] = in[n];
784 				}
785 				fname[n] = '\0';
786 			}
787 			else
788 				strcpy(fname, "Messages");
789 			fd = open(fname, O_RDWR|O_EXCL|O_CREAT|O_APPEND);
790 		}
791 		else {
792 			strcpy(fname, _PATH_TMP);
793 			fd = mkstemp(fname);
794 			if (fd != -1) {
795 				snprintf(cmdbuf, sizeof(cmdbuf), _PATH_MAIL,
796 				    fname);
797 				mailing = YES;
798 			}
799 		}
800 		if (fd == -1 || (cpto = fdopen(fd, "a")) == NULL) {
801 			if (fd != -1)
802 				close(fd);
803 			warn("%s", fname);
804 			mailing = NO;
805 			fseeko(newmsg, oldpos, SEEK_SET);
806 			ask(prompt);
807 			fclose(cpfrom);
808 			return;
809 		}
810 
811 		while ((n = fread(inbuf, 1, sizeof inbuf, cpfrom)))
812 			fwrite(inbuf, 1, n, cpto);
813 
814 		fclose(cpfrom);
815 		fclose(cpto);
816 		fseeko(newmsg, oldpos, SEEK_SET);/* reposition current message */
817 		if (inch == 's')
818 			printf("Message %d saved in \"%s\"\n", cmsg, fname);
819 		else {
820 			system(cmdbuf);
821 			unlink(fname);
822 			mailing = NO;
823 		}
824 		ask(prompt);
825 	}
826 }
827 
828 static void
829 gfrsub(FILE *infile)
830 {
831 	off_t frompos;
832 	int count;
833 
834 	seensubj = seenfrom = NO;
835 	local = YES;
836 	subj[0] = from[0] = date[0] = '\0';
837 
838 	/*
839 	 * Is this a normal message?
840 	 */
841 	if (fgets(inbuf, sizeof inbuf, infile)) {
842 		if (strncmp(inbuf, "From", 4)==0) {
843 			/*
844 			 * expected form starts with From
845 			 */
846 			seenfrom = YES;
847 			frompos = ftello(infile);
848 			ptr = from;
849 			in = nxtfld(inbuf);
850 			if (*in) {
851 				count = sizeof(from) - 1;
852 				while (*in && *in > ' ' && count-- > 0) {
853 					if (*in == ':' || *in == '@' ||
854 					    *in == '!')
855 						local = NO;
856 					*ptr++ = *in++;
857 				}
858 			}
859 			*ptr = '\0';
860 			if (*(in = nxtfld(in)))
861 				strlcpy(date, in, sizeof date);
862 			else {
863 				date[0] = '\n';
864 				date[1] = '\0';
865 			}
866 		}
867 		else {
868 			/*
869 			 * not the expected form
870 			 */
871 			rewind(infile);
872 			return;
873 		}
874 	}
875 	else
876 		/*
877 		 * empty file ?
878 		 */
879 		return;
880 
881 	/*
882 	 * look for Subject line until EOF or a blank line
883 	 */
884 	while (fgets(inbuf, sizeof inbuf, infile)
885 	    && !(blankline = (inbuf[0] == '\n'))) {
886 		/*
887 		 * extract Subject line
888 		 */
889 		if (!seensubj && strncmp(inbuf, "Subj", 4)==0) {
890 			seensubj = YES;
891 			frompos = ftello(infile);
892 			strlcpy(subj, nxtfld(inbuf), sizeof subj);
893 		}
894 	}
895 	if (!blankline)
896 		/*
897 		 * ran into EOF
898 		 */
899 		fseeko(infile, frompos, SEEK_SET);
900 
901 	if (!seensubj)
902 		/*
903 		 * for possible use with Mail
904 		 */
905 		strlcpy(subj, "(No Subject)\n", sizeof subj);
906 }
907 
908 static char *
909 nxtfld(char *s)
910 {
911 	if (*s) while (*s && !isspace(*s)) s++;     /* skip over this field */
912 	if (*s) while (*s && isspace(*s)) s++;    /* find start of next field */
913 	return (s);
914 }
915