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