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