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