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