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