Merge branch 'vendor/CVS'
[dragonfly.git] / usr.bin / mail / lex.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  * @(#)lex.c    8.2 (Berkeley) 4/20/95
34  * $FreeBSD: src/usr.bin/mail/lex.c,v 1.5.6.5 2003/01/06 05:46:03 mikeh Exp $
35  * $DragonFly: src/usr.bin/mail/lex.c,v 1.6 2004/09/08 03:01:11 joerg Exp $
36  */
37
38 #include "rcv.h"
39 #include <errno.h>
40 #include <fcntl.h>
41 #include "extern.h"
42
43 /*
44  * Mail -- a mail program
45  *
46  * Lexical processing of commands.
47  */
48
49 const char      *prompt = "& ";
50
51 extern const struct cmd cmdtab[];
52 extern const char *version;     
53
54 /*
55  * Set up editing on the given file name.
56  * If the first character of name is %, we are considered to be
57  * editing the file, otherwise we are reading our mail which has
58  * signficance for mbox and so forth.
59  *
60  * If the -e option is passed to mail, this function has a
61  * tri-state return code: -1 on error, 0 on no mail, 1 if there is
62  * mail.
63  */
64 int
65 setfile(char *name)
66 {
67         FILE *ibuf;
68         int checkmode, i, fd;
69         struct stat stb;
70         char isedit = *name != '%' || getuserid(myname) != getuid();
71         char *who = name[1] ? name + 1 : myname;
72         char tempname[PATHSIZE];
73         static int shudclob;
74
75         checkmode = value("checkmode") != NULL;
76
77         if ((name = expand(name)) == NULL)
78                 return (-1);
79
80         if ((ibuf = Fopen(name, "r")) == NULL) {
81                 if (!isedit && errno == ENOENT)
82                         goto nomail;
83                 warn("%s", name);
84                 return (-1);
85         }
86
87         if (fstat(fileno(ibuf), &stb) < 0) {
88                 warn("fstat");
89                 Fclose(ibuf);
90                 return (-1);
91         }
92
93         if (S_ISDIR(stb.st_mode) || !S_ISREG(stb.st_mode)) {
94                 Fclose(ibuf);
95                 errno = S_ISDIR(stb.st_mode) ? EISDIR : EINVAL;
96                 warn("%s", name);
97                 return (-1);
98         }
99
100         /*
101          * Looks like all will be well.  We must now relinquish our
102          * hold on the current set of stuff.  Must hold signals
103          * while we are reading the new file, else we will ruin
104          * the message[] data structure.
105          */
106
107         holdsigs();
108         if (shudclob)
109                 quit();
110
111         /*
112          * Copy the messages into /tmp
113          * and set pointers.
114          */
115
116         readonly = 0;
117         if ((i = open(name, 1)) < 0)
118                 readonly++;
119         else
120                 close(i);
121         if (shudclob) {
122                 fclose(itf);
123                 fclose(otf);
124         }
125         shudclob = 1;
126         edit = isedit;
127         strlcpy(prevfile, mailname, sizeof(prevfile));
128         if (name != mailname)
129                 strlcpy(mailname, name, sizeof(mailname));
130         mailsize = fsize(ibuf);
131         snprintf(tempname, sizeof(tempname), "%s/mail.RxXXXXXXXXXX", tmpdir);
132         if ((fd = mkstemp(tempname)) == -1 || (otf = fdopen(fd, "w")) == NULL)
133                 err(1, "%s", tempname);
134         fcntl(fileno(otf), F_SETFD, 1);
135         if ((itf = fopen(tempname, "r")) == NULL)
136                 err(1, "%s", tempname);
137         fcntl(fileno(itf), F_SETFD, 1);
138         rm(tempname);
139         setptr(ibuf, 0);
140         setmsize(msgCount);
141         /*
142          * New mail may have arrived while we were reading
143          * the mail file, so reset mailsize to be where
144          * we really are in the file...
145          */
146         mailsize = ftello(ibuf);
147         Fclose(ibuf);
148         relsesigs();
149         sawcom = 0;
150         if ((checkmode || !edit) && msgCount == 0) {
151 nomail:
152                 if (!checkmode) {
153                         fprintf(stderr, "No mail for %s\n", who);
154                         return (-1);
155                 } else {
156                         return (0);
157                 }
158         }
159         return (checkmode ? 1 : 0);
160 }
161
162 /*
163  * Incorporate any new mail that has arrived since we first
164  * started reading mail.
165  */
166 int
167 incfile(void)
168 {
169         off_t newsize;
170         int omsgCount = msgCount;
171         FILE *ibuf;
172
173         ibuf = Fopen(mailname, "r");
174         if (ibuf == NULL)
175                 return (-1);
176         holdsigs();
177         newsize = fsize(ibuf);
178         if (newsize == 0)
179                 return (-1);            /* mail box is now empty??? */
180         if (newsize < mailsize)
181                 return (-1);            /* mail box has shrunk??? */
182         if (newsize == mailsize)
183                 return (0);             /* no new mail */
184         setptr(ibuf, mailsize);
185         setmsize(msgCount);
186         mailsize = ftello(ibuf);
187         Fclose(ibuf);
188         relsesigs();
189         return (msgCount - omsgCount);
190 }
191
192 int     *msgvec;
193 int     reset_on_stop;                  /* do a reset() if stopped */
194
195 /*
196  * Interpret user commands one by one.  If standard input is not a tty,
197  * print no prompt.
198  */
199 void
200 commands(void)
201 {
202         int n, eofloop = 0;
203         char linebuf[LINESIZE];
204
205         if (!sourcing) {
206                 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
207                         signal(SIGINT, intr);
208                 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
209                         signal(SIGHUP, hangup);
210                 signal(SIGTSTP, stop);
211                 signal(SIGTTOU, stop);
212                 signal(SIGTTIN, stop);
213         }
214         setexit();
215         for (;;) {
216                 /*
217                  * Print the prompt, if needed.  Clear out
218                  * string space, and flush the output.
219                  */
220                 if (!sourcing && value("interactive") != NULL) {
221                         if ((value("autoinc") != NULL) && (incfile() > 0))
222                                 printf("New mail has arrived.\n");
223                         reset_on_stop = 1;
224                         printf("%s", prompt);
225                 }
226                 fflush(stdout);
227                 sreset();
228                 /*
229                  * Read a line of commands from the current input
230                  * and handle end of file specially.
231                  */
232                 n = 0;
233                 for (;;) {
234                         if (readline(input, &linebuf[n], LINESIZE - n) < 0) {
235                                 if (n == 0)
236                                         n = -1;
237                                 break;
238                         }
239                         if ((n = strlen(linebuf)) == 0)
240                                 break;
241                         n--;
242                         if (linebuf[n] != '\\')
243                                 break;
244                         linebuf[n++] = ' ';
245                 }
246                 reset_on_stop = 0;
247                 if (n < 0) {
248                                 /* eof */
249                         if (loading)
250                                 break;
251                         if (sourcing) {
252                                 unstack();
253                                 continue;
254                         }
255                         if (value("interactive") != NULL &&
256                             value("ignoreeof") != NULL &&
257                             ++eofloop < 25) {
258                                 printf("Use \"quit\" to quit.\n");
259                                 continue;
260                         }
261                         break;
262                 }
263                 eofloop = 0;
264                 if (execute(linebuf, 0))
265                         break;
266         }
267 }
268
269 /*
270  * Execute a single command.
271  * Command functions return 0 for success, 1 for error, and -1
272  * for abort.  A 1 or -1 aborts a load or source.  A -1 aborts
273  * the interactive command loop.
274  * Contxt is non-zero if called while composing mail.
275  */
276 int
277 execute(char *linebuf, int contxt)
278 {
279         char word[LINESIZE];
280         char *arglist[MAXARGC];
281         const struct cmd *com;
282         char *cp, *cp2;
283         int c, muvec[2];
284         int e = 1;
285
286         /*
287          * Strip the white space away from the beginning
288          * of the command, then scan out a word, which
289          * consists of anything except digits and white space.
290          *
291          * Handle ! escapes differently to get the correct
292          * lexical conventions.
293          */
294
295         for (cp = linebuf; isspace((unsigned char)*cp); cp++)
296                 ;
297         if (*cp == '!') {
298                 if (sourcing) {
299                         printf("Can't \"!\" while sourcing\n");
300                         goto out;
301                 }
302                 shell(cp+1);
303                 return (0);
304         }
305         cp2 = word;
306         while (*cp != '\0' && strchr(" \t0123456789$^.:/-+*'\"", *cp) == NULL)
307                 *cp2++ = *cp++;
308         *cp2 = '\0';
309
310         /*
311          * Look up the command; if not found, bitch.
312          * Normally, a blank command would map to the
313          * first command in the table; while sourcing,
314          * however, we ignore blank lines to eliminate
315          * confusion.
316          */
317
318         if (sourcing && *word == '\0')
319                 return (0);
320         com = lex(word);
321         if (com == NULL) {
322                 printf("Unknown command: \"%s\"\n", word);
323                 goto out;
324         }
325
326         /*
327          * See if we should execute the command -- if a conditional
328          * we always execute it, otherwise, check the state of cond.
329          */
330
331         if ((com->c_argtype & F) == 0)
332                 if ((cond == CRCV && !rcvmode) || (cond == CSEND && rcvmode))
333                         return (0);
334
335         /*
336          * Process the arguments to the command, depending
337          * on the type he expects.  Default to an error.
338          * If we are sourcing an interactive command, it's
339          * an error.
340          */
341
342         if (!rcvmode && (com->c_argtype & M) == 0) {
343                 printf("May not execute \"%s\" while sending\n",
344                     com->c_name);
345                 goto out;
346         }
347         if (sourcing && com->c_argtype & I) {
348                 printf("May not execute \"%s\" while sourcing\n",
349                     com->c_name);
350                 goto out;
351         }
352         if (readonly && com->c_argtype & W) {
353                 printf("May not execute \"%s\" -- message file is read only\n",
354                    com->c_name);
355                 goto out;
356         }
357         if (contxt && com->c_argtype & R) {
358                 printf("Cannot recursively invoke \"%s\"\n", com->c_name);
359                 goto out;
360         }
361         switch (com->c_argtype & ~(F|P|I|M|T|W|R)) {
362         case MSGLIST:
363                 /*
364                  * A message list defaulting to nearest forward
365                  * legal message.
366                  */
367                 if (msgvec == 0) {
368                         printf("Illegal use of \"message list\"\n");
369                         break;
370                 }
371                 if ((c = getmsglist(cp, msgvec, com->c_msgflag)) < 0)
372                         break;
373                 if (c  == 0) {
374                         *msgvec = first(com->c_msgflag, com->c_msgmask);
375                         msgvec[1] = 0;
376                 }
377                 if (*msgvec == 0) {
378                         printf("No applicable messages\n");
379                         break;
380                 }
381                 e = (*com->c_func)(msgvec);
382                 break;
383
384         case NDMLIST:
385                 /*
386                  * A message list with no defaults, but no error
387                  * if none exist.
388                  */
389                 if (msgvec == 0) {
390                         printf("Illegal use of \"message list\"\n");
391                         break;
392                 }
393                 if (getmsglist(cp, msgvec, com->c_msgflag) < 0)
394                         break;
395                 e = (*com->c_func)(msgvec);
396                 break;
397
398         case STRLIST:
399                 /*
400                  * Just the straight string, with
401                  * leading blanks removed.
402                  */
403                 while (isspace((unsigned char)*cp))
404                         cp++;
405                 e = (*com->c_func)(cp);
406                 break;
407
408         case RAWLIST:
409                 /*
410                  * A vector of strings, in shell style.
411                  */
412                 if ((c = getrawlist(cp, arglist,
413                     sizeof(arglist) / sizeof(*arglist))) < 0)
414                         break;
415                 if (c < com->c_minargs) {
416                         printf("%s requires at least %d arg(s)\n",
417                             com->c_name, com->c_minargs);
418                         break;
419                 }
420                 if (c > com->c_maxargs) {
421                         printf("%s takes no more than %d arg(s)\n",
422                             com->c_name, com->c_maxargs);
423                         break;
424                 }
425                 e = (*com->c_func)(arglist);
426                 break;
427
428         case NOLIST:
429                 /*
430                  * Just the constant zero, for exiting,
431                  * eg.
432                  */
433                 e = (*com->c_func)(0);
434                 break;
435
436         default:
437                 errx(1, "Unknown argtype");
438         }
439
440 out:
441         /*
442          * Exit the current source file on
443          * error.
444          */
445         if (e) {
446                 if (e < 0)
447                         return (1);
448                 if (loading)
449                         return (1);
450                 if (sourcing)
451                         unstack();
452                 return (0);
453         }
454         if (com == NULL)
455                 return (0);
456         if (value("autoprint") != NULL && com->c_argtype & P)
457                 if ((dot->m_flag & MDELETED) == 0) {
458                         muvec[0] = dot - &message[0] + 1;
459                         muvec[1] = 0;
460                         type(muvec);
461                 }
462         if (!sourcing && (com->c_argtype & T) == 0)
463                 sawcom = 1;
464         return (0);
465 }
466
467 /*
468  * Set the size of the message vector used to construct argument
469  * lists to message list functions.
470  */
471 void
472 setmsize(int sz)
473 {
474         if (msgvec != NULL)
475                 free(msgvec);
476         msgvec = calloc((unsigned)(sz + 1), sizeof(*msgvec));
477 }
478
479 /*
480  * Find the correct command in the command table corresponding
481  * to the passed command "word"
482  */
483
484 const struct cmd *
485 lex(char *word)
486 {
487         const struct cmd *cp;
488
489         /*
490          * ignore trailing chars after `#'
491          *
492          * lines with beginning `#' are comments
493          * spaces before `#' are ignored in execute()
494          */
495
496         if (*word == '#')
497             *(word+1) = '\0';
498
499
500         for (cp = &cmdtab[0]; cp->c_name != NULL; cp++)
501                 if (isprefix(word, cp->c_name))
502                         return (cp);
503         return (NULL);
504 }
505
506 /*
507  * Determine if as1 is a valid prefix of as2.
508  * Return true if yep.
509  */
510 int
511 isprefix(const char *as1, const char *as2)
512 {
513         const char *s1, *s2;
514
515         s1 = as1;
516         s2 = as2;
517         while (*s1++ == *s2)
518                 if (*s2++ == '\0')
519                         return (1);
520         return (*--s1 == '\0');
521 }
522
523 /*
524  * The following gets called on receipt of an interrupt.  This is
525  * to abort printout of a command, mainly.
526  * Dispatching here when command() is inactive crashes rcv.
527  * Close all open files except 0, 1, 2, and the temporary.
528  * Also, unstack all source files.
529  */
530
531 int     inithdr;                        /* am printing startup headers */
532
533 /*ARGSUSED*/
534 void
535 intr(int s)
536 {
537         noreset = 0;
538         if (!inithdr)
539                 sawcom++;
540         inithdr = 0;
541         while (sourcing)
542                 unstack();
543
544         close_all_files();
545
546         if (image >= 0) {
547                 close(image);
548                 image = -1;
549         }
550         fprintf(stderr, "Interrupt\n");
551         reset(0);
552 }
553
554 /*
555  * When we wake up after ^Z, reprint the prompt.
556  */
557 void
558 stop(int s)
559 {
560         sig_t old_action = signal(s, SIG_DFL);
561         sigset_t nset;
562
563         sigemptyset(&nset);
564         sigaddset(&nset, s);
565         sigprocmask(SIG_UNBLOCK, &nset, NULL);
566         kill(0, s);
567         sigprocmask(SIG_BLOCK, &nset, NULL);
568         signal(s, old_action);
569         if (reset_on_stop) {
570                 reset_on_stop = 0;
571                 reset(0);
572         }
573 }
574
575 /*
576  * Branch here on hangup signal and simulate "exit".
577  */
578 /*ARGSUSED*/
579 void
580 hangup(int s)
581 {
582         /* nothing to do? */
583         exit(1);
584 }
585
586 /*
587  * Announce the presence of the current Mail version,
588  * give the message count, and print a header listing.
589  */
590 void
591 announce(void)
592 {
593         int vec[2], mdot;
594
595         mdot = newfileinfo(0);
596         vec[0] = mdot;
597         vec[1] = 0;
598         dot = &message[mdot - 1];
599         if (msgCount > 0 && value("noheader") == NULL) {
600                 inithdr++;
601                 headers(vec);
602                 inithdr = 0;
603         }
604 }
605
606 /*
607  * Announce information about the file we are editing.
608  * Return a likely place to set dot.
609  */
610 int
611 newfileinfo(int omsgCount)
612 {
613         struct message *mp;
614         int u, n, mdot, d, s;
615         char fname[PATHSIZE+1], zname[PATHSIZE+1], *ename;
616
617         for (mp = &message[omsgCount]; mp < &message[msgCount]; mp++)
618                 if (mp->m_flag & MNEW)
619                         break;
620         if (mp >= &message[msgCount])
621                 for (mp = &message[omsgCount]; mp < &message[msgCount]; mp++)
622                         if ((mp->m_flag & MREAD) == 0)
623                                 break;
624         if (mp < &message[msgCount])
625                 mdot = mp - &message[0] + 1;
626         else
627                 mdot = omsgCount + 1;
628         s = d = 0;
629         for (mp = &message[0], n = 0, u = 0; mp < &message[msgCount]; mp++) {
630                 if (mp->m_flag & MNEW)
631                         n++;
632                 if ((mp->m_flag & MREAD) == 0)
633                         u++;
634                 if (mp->m_flag & MDELETED)
635                         d++;
636                 if (mp->m_flag & MSAVED)
637                         s++;
638         }
639         ename = mailname;
640         if (getfold(fname, sizeof(fname) - 1) >= 0) {
641                 strcat(fname, "/");
642                 if (strncmp(fname, mailname, strlen(fname)) == 0) {
643                         snprintf(zname, sizeof(zname), "+%s",
644                             mailname + strlen(fname));
645                         ename = zname;
646                 }
647         }
648         printf("\"%s\": ", ename);
649         if (msgCount == 1)
650                 printf("1 message");
651         else
652                 printf("%d messages", msgCount);
653         if (n > 0)
654                 printf(" %d new", n);
655         if (u-n > 0)
656                 printf(" %d unread", u);
657         if (d > 0)
658                 printf(" %d deleted", d);
659         if (s > 0)
660                 printf(" %d saved", s);
661         if (readonly)
662                 printf(" [Read only]");
663         printf("\n");
664         return (mdot);
665 }
666
667 /*
668  * Print the current version number.
669  */
670
671 /*ARGSUSED*/
672 int
673 pversion(int e)
674 {
675         printf("Version %s\n", version);
676         return (0);
677 }
678
679 /*
680  * Load a file of user definitions.
681  */
682 void
683 load(char *name)
684 {
685         FILE *in, *oldin;
686
687         if ((in = Fopen(name, "r")) == NULL)
688                 return;
689         oldin = input;
690         input = in;
691         loading = 1;
692         sourcing = 1;
693         commands();
694         loading = 0;
695         sourcing = 0;
696         input = oldin;
697         Fclose(in);
698 }