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