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