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