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