Rocco Rutte:
[apps/madmutt.git] / pattern.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>, and others
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 #if HAVE_CONFIG_H
11 # include "config.h"
12 #endif
13
14 #include "mutt.h"
15 #include "buffer.h"
16 #include "handler.h"
17 #include "enter.h"
18 #include "ascii.h"
19 #include "mx.h"
20 #include "mapping.h"
21 #include "keymap.h"
22 #include "copy.h"
23 #include "mime.h"
24
25 #include "lib/mem.h"
26 #include "lib/intl.h"
27 #include "lib/str.h"
28
29 #ifdef USE_IMAP
30 #include "mx.h"
31 #include "imap/imap.h"
32 #endif
33
34 #include <string.h>
35 #include <stdlib.h>
36 #include <ctype.h>
37 #include <sys/stat.h>
38 #include <unistd.h>
39 #include <stdarg.h>
40
41 #include "mutt_crypt.h"
42
43 static int eat_regexp (pattern_t * pat, BUFFER *, BUFFER *);
44 static int eat_date (pattern_t * pat, BUFFER *, BUFFER *);
45 static int eat_range (pattern_t * pat, BUFFER *, BUFFER *);
46 static int patmatch (const pattern_t* pat, const char* buf);
47
48 struct pattern_flags {
49   int tag;                      /* character used to represent this op */
50   int op;                       /* operation to perform */
51   int class;
52   int (*eat_arg) (pattern_t *, BUFFER *, BUFFER *);
53 } Flags[] = {
54   {
55   'A', M_ALL, 0, NULL}, {
56   'b', M_BODY, M_FULL_MSG, eat_regexp}, {
57   'B', M_WHOLE_MSG, M_FULL_MSG, eat_regexp}, {
58   'c', M_CC, 0, eat_regexp}, {
59   'C', M_RECIPIENT, 0, eat_regexp}, {
60   'd', M_DATE, 0, eat_date}, {
61   'D', M_DELETED, 0, NULL}, {
62   'e', M_SENDER, 0, eat_regexp}, {
63   'E', M_EXPIRED, 0, NULL}, {
64   'f', M_FROM, 0, eat_regexp}, {
65   'F', M_FLAG, 0, NULL}, {
66   'g', M_CRYPT_SIGN, 0, NULL}, {
67   'G', M_CRYPT_ENCRYPT, 0, NULL}, {
68   'h', M_HEADER, M_FULL_MSG, eat_regexp}, {
69   'H', M_HORMEL, 0, eat_regexp}, {
70   'i', M_ID, 0, eat_regexp}, {
71   'k', M_PGP_KEY, 0, NULL}, {
72   'L', M_ADDRESS, 0, eat_regexp}, {
73   'l', M_LIST, 0, NULL}, {
74   'm', M_MESSAGE, 0, eat_range}, {
75   'M', M_MULTIPART, 0, NULL}, {
76   'n', M_SCORE, 0, eat_range}, {
77   'N', M_NEW, 0, NULL}, {
78   'O', M_OLD, 0, NULL}, {
79   'p', M_PERSONAL_RECIP, 0, NULL}, {
80   'P', M_PERSONAL_FROM, 0, NULL}, {
81   'Q', M_REPLIED, 0, NULL}, {
82   'R', M_READ, 0, NULL}, {
83   'r', M_DATE_RECEIVED, 0, eat_date}, {
84   's', M_SUBJECT, 0, eat_regexp}, {
85   'S', M_SUPERSEDED, 0, NULL}, {
86   'T', M_TAG, 0, NULL}, {
87   't', M_TO, 0, eat_regexp}, {
88   'U', M_UNREAD, 0, NULL}, {
89   'u', M_SUBSCRIBED_LIST, 0, NULL}, {
90   'v', M_COLLAPSED, 0, NULL}, {
91   'V', M_CRYPT_VERIFIED, 0, NULL},
92 #ifdef USE_NNTP
93   {
94   'w', M_NEWSGROUPS, 0, eat_regexp},
95 #endif
96   {
97   'x', M_REFERENCE, 0, eat_regexp}, {
98   'y', M_XLABEL, 0, eat_regexp}, {
99   'z', M_SIZE, 0, eat_range}, {
100   '=', M_DUPLICATED, 0, NULL}, {
101   '$', M_UNREFERENCED, 0, NULL}, {
102   '*', M_REALNAME, 0, NULL}, {
103   0}
104 };
105
106 static pattern_t *SearchPattern = NULL; /* current search pattern */
107 static char LastSearch[STRING] = { 0 }; /* last pattern searched for */
108 static char LastSearchExpn[LONG_STRING] = { 0 };        /* expanded version of
109                                                            LastSearch */
110
111 #define M_MAXRANGE -1
112
113 /* constants for parse_date_range() */
114 #define M_PDR_NONE      0x0000
115 #define M_PDR_MINUS     0x0001
116 #define M_PDR_PLUS      0x0002
117 #define M_PDR_WINDOW    0x0004
118 #define M_PDR_ABSOLUTE  0x0008
119 #define M_PDR_DONE      0x0010
120 #define M_PDR_ERROR     0x0100
121 #define M_PDR_ERRORDONE (M_PDR_ERROR | M_PDR_DONE)
122
123
124 int mutt_getvaluebychar (char ch, struct mapping_t *table)
125 {
126   int i;
127
128   for (i = 0; table[i].name; i++) {
129     if (ch == table[i].name[0])
130       return table[i].value;
131   }
132
133   return (-1);
134 }
135
136 /* if no uppercase letters are given, do a case-insensitive search */
137 int mutt_which_case (const char *s)
138 {
139   while (*s) {
140     if (isalpha ((unsigned char) *s) && isupper ((unsigned char) *s))
141       return 0;                 /* case-sensitive */
142     s++;
143   }
144   return REG_ICASE;             /* case-insensitive */
145 }
146
147 static int
148 msg_search (CONTEXT *ctx, pattern_t* pat, int msgno)
149 {
150   char tempfile[_POSIX_PATH_MAX];
151   MESSAGE *msg = NULL;
152   STATE s;
153   struct stat st;
154   FILE *fp = NULL;
155   long lng = 0;
156   int match = 0;
157   HEADER *h = ctx->hdrs[msgno];
158   char* buf;
159   size_t blen;
160
161   if ((msg = mx_open_message (ctx, msgno)) != NULL) {
162     if (option (OPTTHOROUGHSRC)) {
163       /* decode the header / body */
164       memset (&s, 0, sizeof (s));
165       s.fpin = msg->fp;
166       s.flags = M_CHARCONV;
167       mutt_mktemp (tempfile);
168       if ((s.fpout = safe_fopen (tempfile, "w+")) == NULL) {
169         mutt_perror (tempfile);
170         return (0);
171       }
172
173       if (pat->op != M_BODY)
174         mutt_copy_header (msg->fp, h, s.fpout, CH_FROM | CH_DECODE, NULL);
175
176       if (pat->op != M_HEADER) {
177         mutt_parse_mime_message (ctx, h);
178
179         if (WithCrypto && (h->security & ENCRYPT)
180             && !crypt_valid_passphrase (h->security)) {
181           mx_close_message (&msg);
182           if (fp) {
183             fclose (fp);
184             unlink (tempfile);
185           }
186           return (0);
187         }
188
189         fseek (msg->fp, h->offset, 0);
190         mutt_body_handler (h->content, &s);
191       }
192
193       fp = s.fpout;
194       fflush (fp);
195       fseek (fp, 0, 0);
196       fstat (fileno (fp), &st);
197       lng = (long) st.st_size;
198     }
199     else {
200       /* raw header / body */
201       fp = msg->fp;
202       if (pat->op != M_BODY) {
203         fseek (fp, h->offset, 0);
204         lng = h->content->offset - h->offset;
205       }
206       if (pat->op != M_HEADER) {
207         if (pat->op == M_BODY)
208           fseek (fp, h->content->offset, 0);
209         lng += h->content->length;
210       }
211     }
212
213     blen = STRING;
214     buf = mem_malloc (blen);
215
216     /* search the file "fp" */
217     while (lng > 0) {
218       if (pat->op == M_HEADER) {
219         if (*(buf = mutt_read_rfc822_line (fp, buf, &blen)) == '\0')
220           break;
221       } if (fgets (buf, blen - 1, fp) == NULL)
222         break;                  /* don't loop forever */
223       if (patmatch (pat, buf) == 0) {
224         match = 1;
225         break;
226       }
227       lng -= str_len (buf);
228     }
229
230     mem_free (&buf);
231
232     mx_close_message (&msg);
233
234     if (option (OPTTHOROUGHSRC)) {
235       fclose (fp);
236       unlink (tempfile);
237     }
238   }
239
240   return match;
241 }
242
243 int eat_regexp (pattern_t * pat, BUFFER * s, BUFFER * err)
244 {
245   BUFFER buf;
246   int r;
247
248   memset (&buf, 0, sizeof (buf));
249   if (mutt_extract_token (&buf, s, M_TOKEN_PATTERN | M_TOKEN_COMMENT) != 0 ||
250       !buf.data) {
251     snprintf (err->data, err->dsize, _("Error in expression: %s"), s->dptr);
252     return (-1);
253   }
254
255 #if 0
256  /* If there are no RE metacharacters, use simple search anyway */
257   if (!pat->stringmatch && !strpbrk (buf.data, "|[{.*+?^$"))
258     pat->stringmatch = 1;
259 #endif
260
261   if (pat->stringmatch) {
262     pat->str = str_dup (buf.data);
263     mem_free (&buf.data);
264   } else {
265     pat->rx = mem_malloc (sizeof (regex_t));
266     r = REGCOMP (pat->rx, buf.data, REG_NEWLINE | REG_NOSUB | mutt_which_case (buf.data));
267     mem_free (&buf.data);
268     if (r) {
269       regerror (r, pat->rx, err->data, err->dsize);
270       regfree (pat->rx);
271       mem_free (&pat->rx);
272       return (-1);
273     }
274   }
275   return 0;
276 }
277
278 static int patmatch (const pattern_t* pat, const char* buf) {
279   if (pat->stringmatch)
280     return !strstr (buf, pat->str);
281   else
282     return regexec (pat->rx, buf, 0, NULL, 0);
283 }
284
285 int eat_range (pattern_t * pat, BUFFER * s, BUFFER * err)
286 {
287   char *tmp;
288   int do_exclusive = 0;
289   int skip_quote = 0;
290
291   /*
292    * If simple_search is set to "~m %s", the range will have double quotes 
293    * around it...
294    */
295   if (*s->dptr == '"') {
296     s->dptr++;
297     skip_quote = 1;
298   }
299   if (*s->dptr == '<')
300     do_exclusive = 1;
301   if ((*s->dptr != '-') && (*s->dptr != '<')) {
302     /* range minimum */
303     if (*s->dptr == '>') {
304       pat->max = M_MAXRANGE;
305       pat->min = strtol (s->dptr + 1, &tmp, 0) + 1;     /* exclusive range */
306     }
307     else
308       pat->min = strtol (s->dptr, &tmp, 0);
309     if (toupper ((unsigned char) *tmp) == 'K') {        /* is there a prefix? */
310       pat->min *= 1024;
311       tmp++;
312     }
313     else if (toupper ((unsigned char) *tmp) == 'M') {
314       pat->min *= 1048576;
315       tmp++;
316     }
317     if (*s->dptr == '>') {
318       s->dptr = tmp;
319       return 0;
320     }
321     if (*tmp != '-') {
322       /* exact value */
323       pat->max = pat->min;
324       s->dptr = tmp;
325       return 0;
326     }
327     tmp++;
328   }
329   else {
330     s->dptr++;
331     tmp = s->dptr;
332   }
333
334   if (isdigit ((unsigned char) *tmp)) {
335     /* range maximum */
336     pat->max = strtol (tmp, &tmp, 0);
337     if (toupper ((unsigned char) *tmp) == 'K') {
338       pat->max *= 1024;
339       tmp++;
340     }
341     else if (toupper ((unsigned char) *tmp) == 'M') {
342       pat->max *= 1048576;
343       tmp++;
344     }
345     if (do_exclusive)
346       (pat->max)--;
347   }
348   else
349     pat->max = M_MAXRANGE;
350
351   if (skip_quote && *tmp == '"')
352     tmp++;
353
354   SKIPWS (tmp);
355   s->dptr = tmp;
356   return 0;
357 }
358
359 static const char *getDate (const char *s, struct tm *t, BUFFER * err)
360 {
361   char *p;
362   time_t now = time (NULL);
363   struct tm *tm = localtime (&now);
364
365   t->tm_mday = strtol (s, &p, 10);
366   if (t->tm_mday < 1 || t->tm_mday > 31) {
367     snprintf (err->data, err->dsize, _("Invalid day of month: %s"), s);
368     return NULL;
369   }
370   if (*p != '/') {
371     /* fill in today's month and year */
372     t->tm_mon = tm->tm_mon;
373     t->tm_year = tm->tm_year;
374     return p;
375   }
376   p++;
377   t->tm_mon = strtol (p, &p, 10) - 1;
378   if (t->tm_mon < 0 || t->tm_mon > 11) {
379     snprintf (err->data, err->dsize, _("Invalid month: %s"), p);
380     return NULL;
381   }
382   if (*p != '/') {
383     t->tm_year = tm->tm_year;
384     return p;
385   }
386   p++;
387   t->tm_year = strtol (p, &p, 10);
388   if (t->tm_year < 70)          /* year 2000+ */
389     t->tm_year += 100;
390   else if (t->tm_year > 1900)
391     t->tm_year -= 1900;
392   return p;
393 }
394
395 /* Ny   years
396    Nm   months
397    Nw   weeks
398    Nd   days */
399 static const char *get_offset (struct tm *tm, const char *s, int sign)
400 {
401   char *ps;
402   int offset = strtol (s, &ps, 0);
403
404   if ((sign < 0 && offset > 0) || (sign > 0 && offset < 0))
405     offset = -offset;
406
407   switch (*ps) {
408   case 'y':
409     tm->tm_year += offset;
410     break;
411   case 'm':
412     tm->tm_mon += offset;
413     break;
414   case 'w':
415     tm->tm_mday += 7 * offset;
416     break;
417   case 'd':
418     tm->tm_mday += offset;
419     break;
420   default:
421     return s;
422   }
423   mutt_normalize_time (tm);
424   return (ps + 1);
425 }
426
427 static void adjust_date_range (struct tm *min, struct tm *max)
428 {
429   if (min->tm_year > max->tm_year
430       || (min->tm_year == max->tm_year && min->tm_mon > max->tm_mon)
431       || (min->tm_year == max->tm_year && min->tm_mon == max->tm_mon
432           && min->tm_mday > max->tm_mday)) {
433     int tmp;
434
435     tmp = min->tm_year;
436     min->tm_year = max->tm_year;
437     max->tm_year = tmp;
438
439     tmp = min->tm_mon;
440     min->tm_mon = max->tm_mon;
441     max->tm_mon = tmp;
442
443     tmp = min->tm_mday;
444     min->tm_mday = max->tm_mday;
445     max->tm_mday = tmp;
446
447     min->tm_hour = min->tm_min = min->tm_sec = 0;
448     max->tm_hour = 23;
449     max->tm_min = max->tm_sec = 59;
450   }
451 }
452
453 static const char *parse_date_range (const char *pc, struct tm *min,
454                                      struct tm *max, int haveMin,
455                                      struct tm *baseMin, BUFFER * err)
456 {
457   int flag = M_PDR_NONE;
458
459   while (*pc && ((flag & M_PDR_DONE) == 0)) {
460     const char *pt;
461     char ch = *pc++;
462
463     SKIPWS (pc);
464     switch (ch) {
465     case '-':
466       {
467         /* try a range of absolute date minus offset of Ndwmy */
468         pt = get_offset (min, pc, -1);
469         if (pc == pt) {
470           if (flag == M_PDR_NONE) {     /* nothing yet and no offset parsed => absolute date? */
471             if (!getDate (pc, max, err))
472               flag |= (M_PDR_ABSOLUTE | M_PDR_ERRORDONE);       /* done bad */
473             else {
474               /* reestablish initial base minimum if not specified */
475               if (!haveMin)
476                 memcpy (min, baseMin, sizeof (struct tm));
477               flag |= (M_PDR_ABSOLUTE | M_PDR_DONE);    /* done good */
478             }
479           }
480           else
481             flag |= M_PDR_ERRORDONE;
482         }
483         else {
484           pc = pt;
485           if (flag == M_PDR_NONE && !haveMin) { /* the very first "-3d" without a previous absolute date */
486             max->tm_year = min->tm_year;
487             max->tm_mon = min->tm_mon;
488             max->tm_mday = min->tm_mday;
489           }
490           flag |= M_PDR_MINUS;
491         }
492       }
493       break;
494     case '+':
495       {                         /* enlarge plusRange */
496         pt = get_offset (max, pc, 1);
497         if (pc == pt)
498           flag |= M_PDR_ERRORDONE;
499         else {
500           pc = pt;
501           flag |= M_PDR_PLUS;
502         }
503       }
504       break;
505     case '*':
506       {                         /* enlarge window in both directions */
507         pt = get_offset (min, pc, -1);
508         if (pc == pt)
509           flag |= M_PDR_ERRORDONE;
510         else {
511           pc = get_offset (max, pc, 1);
512           flag |= M_PDR_WINDOW;
513         }
514       }
515       break;
516     default:
517       flag |= M_PDR_ERRORDONE;
518     }
519     SKIPWS (pc);
520   }
521   if ((flag & M_PDR_ERROR) && !(flag & M_PDR_ABSOLUTE)) {       /* getDate has its own error message, don't overwrite it here */
522     snprintf (err->data, err->dsize, _("Invalid relative date: %s"), pc - 1);
523   }
524   return ((flag & M_PDR_ERROR) ? NULL : pc);
525 }
526
527 static int eat_date (pattern_t * pat, BUFFER * s, BUFFER * err)
528 {
529   BUFFER buffer;
530   struct tm min, max;
531
532   memset (&buffer, 0, sizeof (buffer));
533   if (mutt_extract_token (&buffer, s, M_TOKEN_COMMENT | M_TOKEN_PATTERN) != 0
534       || !buffer.data) {
535     strfcpy (err->data, _("error in expression"), err->dsize);
536     return (-1);
537   }
538
539   memset (&min, 0, sizeof (min));
540   /* the `0' time is Jan 1, 1970 UTC, so in order to prevent a negative time
541      when doing timezone conversion, we use Jan 2, 1970 UTC as the base
542      here */
543   min.tm_mday = 2;
544   min.tm_year = 70;
545
546   memset (&max, 0, sizeof (max));
547
548   /* Arbitrary year in the future.  Don't set this too high
549      or mutt_mktime() returns something larger than will
550      fit in a time_t on some systems */
551   max.tm_year = 130;
552   max.tm_mon = 11;
553   max.tm_mday = 31;
554   max.tm_hour = 23;
555   max.tm_min = 59;
556   max.tm_sec = 59;
557
558   if (strchr ("<>=", buffer.data[0])) {
559     /* offset from current time
560        <3d      less than three days ago
561        >3d      more than three days ago
562        =3d      exactly three days ago */
563     time_t now = time (NULL);
564     struct tm *tm = localtime (&now);
565     int exact = 0;
566
567     if (buffer.data[0] == '<') {
568       memcpy (&min, tm, sizeof (min));
569       tm = &min;
570     }
571     else {
572       memcpy (&max, tm, sizeof (max));
573       tm = &max;
574
575       if (buffer.data[0] == '=')
576         exact++;
577     }
578     tm->tm_hour = 23;
579     tm->tm_min = tm->tm_sec = 59;
580
581     /* force negative offset */
582     get_offset (tm, buffer.data + 1, -1);
583
584     if (exact) {
585       /* start at the beginning of the day in question */
586       memcpy (&min, &max, sizeof (max));
587       min.tm_hour = min.tm_sec = min.tm_min = 0;
588     }
589   }
590   else {
591     const char *pc = buffer.data;
592
593     int haveMin = FALSE;
594     int untilNow = FALSE;
595
596     if (isdigit ((unsigned char) *pc)) {
597       /* mininum date specified */
598       if ((pc = getDate (pc, &min, err)) == NULL) {
599         mem_free (&buffer.data);
600         return (-1);
601       }
602       haveMin = TRUE;
603       SKIPWS (pc);
604       if (*pc == '-') {
605         const char *pt = pc + 1;
606
607         SKIPWS (pt);
608         untilNow = (*pt == '\0');
609       }
610     }
611
612     if (!untilNow) {            /* max date or relative range/window */
613
614       struct tm baseMin;
615
616       if (!haveMin) {           /* save base minimum and set current date, e.g. for "-3d+1d" */
617         time_t now = time (NULL);
618         struct tm *tm = localtime (&now);
619
620         memcpy (&baseMin, &min, sizeof (baseMin));
621         memcpy (&min, tm, sizeof (min));
622         min.tm_hour = min.tm_sec = min.tm_min = 0;
623       }
624
625       /* preset max date for relative offsets,
626          if nothing follows we search for messages on a specific day */
627       max.tm_year = min.tm_year;
628       max.tm_mon = min.tm_mon;
629       max.tm_mday = min.tm_mday;
630
631       if (!parse_date_range (pc, &min, &max, haveMin, &baseMin, err)) { /* bail out on any parsing error */
632         mem_free (&buffer.data);
633         return (-1);
634       }
635     }
636   }
637
638   /* Since we allow two dates to be specified we'll have to adjust that. */
639   adjust_date_range (&min, &max);
640
641   pat->min = mutt_mktime (&min, 1);
642   pat->max = mutt_mktime (&max, 1);
643
644   mem_free (&buffer.data);
645
646   return 0;
647 }
648
649 static struct pattern_flags *lookup_tag (char tag)
650 {
651   int i;
652
653   for (i = 0; Flags[i].tag; i++)
654     if (Flags[i].tag == tag)
655       return (&Flags[i]);
656   return NULL;
657 }
658
659 static /* const */ char *find_matching_paren ( /* const */ char *s)
660 {
661   int level = 1;
662
663   for (; *s; s++) {
664     if (*s == '(')
665       level++;
666     else if (*s == ')') {
667       level--;
668       if (!level)
669         break;
670     }
671   }
672   return s;
673 }
674
675 void mutt_pattern_free (pattern_t ** pat)
676 {
677   pattern_t *tmp;
678
679   while (*pat) {
680     tmp = *pat;
681     *pat = (*pat)->next;
682
683     if (tmp->rx) {
684       regfree (tmp->rx);
685       mem_free (&tmp->rx);
686     }
687     mem_free (tmp->str);
688     if (tmp->child)
689       mutt_pattern_free (&tmp->child);
690     mem_free (&tmp);
691   }
692 }
693
694 pattern_t *mutt_pattern_comp ( /* const */ char *s, int flags, BUFFER * err)
695 {
696   pattern_t *curlist = NULL;
697   pattern_t *tmp;
698   pattern_t *last = NULL;
699   int not = 0;
700   int alladdr = 0;
701   int stringmatch = 0;
702   int or = 0;
703   int implicit = 1;             /* used to detect logical AND operator */
704   struct pattern_flags *entry;
705   char *p;
706   char *buf;
707   BUFFER ps;
708
709   memset (&ps, 0, sizeof (ps));
710   ps.dptr = s;
711   ps.dsize = str_len (s);
712
713   while (*ps.dptr) {
714     SKIPWS (ps.dptr);
715     switch (*ps.dptr) {
716     case '^':
717       ps.dptr++;
718       alladdr = !alladdr;
719       break;
720     case '!':
721       ps.dptr++;
722       not = !not;
723       break;
724     case '|':
725       if (!or) {
726         if (!curlist) {
727           snprintf (err->data, err->dsize, _("error in pattern at: %s"),
728                     ps.dptr);
729           return NULL;
730         }
731         if (curlist->next) {
732           /* A & B | C == (A & B) | C */
733           tmp = new_pattern ();
734           tmp->op = M_AND;
735           tmp->child = curlist;
736
737           curlist = tmp;
738           last = curlist;
739         }
740
741         or = 1;
742       }
743       ps.dptr++;
744       implicit = 0;
745       not = 0;
746       alladdr = 0;
747       stringmatch = 0;
748       break;
749     case '=':
750       stringmatch = 1;
751       /* fallthrough */
752     case '~':
753       if (implicit && or) {
754         /* A | B & C == (A | B) & C */
755         tmp = new_pattern ();
756         tmp->op = M_OR;
757         tmp->child = curlist;
758         curlist = tmp;
759         last = tmp;
760         or = 0;
761       }
762
763       tmp = new_pattern ();
764       tmp->not = not;
765       tmp->alladdr = alladdr;
766       tmp->stringmatch = stringmatch;
767       not = 0;
768       alladdr = 0;
769       stringmatch = 0;
770
771       if (last)
772         last->next = tmp;
773       else
774         curlist = tmp;
775       last = tmp;
776
777       ps.dptr++;                /* move past the ~ */
778       if ((entry = lookup_tag (*ps.dptr)) == NULL) {
779         snprintf (err->data, err->dsize, _("%c: invalid command"), *ps.dptr);
780         mutt_pattern_free (&curlist);
781         return NULL;
782       }
783       if (entry->class && (flags & entry->class) == 0) {
784         snprintf (err->data, err->dsize, _("%c: not supported in this mode"),
785                   *ps.dptr);
786         mutt_pattern_free (&curlist);
787         return NULL;
788       }
789       tmp->op = entry->op;
790
791       ps.dptr++;                /* eat the operator and any optional whitespace */
792       SKIPWS (ps.dptr);
793
794       if (entry->eat_arg) {
795         if (!*ps.dptr) {
796           snprintf (err->data, err->dsize, _("missing parameter"));
797           mutt_pattern_free (&curlist);
798           return NULL;
799         }
800         if (entry->eat_arg (tmp, &ps, err) == -1) {
801           mutt_pattern_free (&curlist);
802           return NULL;
803         }
804       }
805       implicit = 1;
806       break;
807     case '(':
808       p = find_matching_paren (ps.dptr + 1);
809       if (*p != ')') {
810         snprintf (err->data, err->dsize, _("mismatched parenthesis: %s"),
811                   ps.dptr);
812         mutt_pattern_free (&curlist);
813         return NULL;
814       }
815       /* compile the sub-expression */
816       buf = str_substrdup (ps.dptr + 1, p);
817       if ((tmp = mutt_pattern_comp (buf, flags, err)) == NULL) {
818         mem_free (&buf);
819         mutt_pattern_free (&curlist);
820         return NULL;
821       }
822       mem_free (&buf);
823       if (last)
824         last->next = tmp;
825       else
826         curlist = tmp;
827       last = tmp;
828       tmp->not ^= not;
829       tmp->alladdr |= alladdr;
830       not = 0;
831       alladdr = 0;
832       ps.dptr = p + 1;          /* restore location */
833       break;
834     default:
835       snprintf (err->data, err->dsize, _("error in pattern at: %s"), ps.dptr);
836       mutt_pattern_free (&curlist);
837       return NULL;
838     }
839   }
840   if (!curlist) {
841     strfcpy (err->data, _("empty pattern"), err->dsize);
842     return NULL;
843   }
844   if (curlist->next) {
845     tmp = new_pattern ();
846     tmp->op = or ? M_OR : M_AND;
847     tmp->child = curlist;
848     curlist = tmp;
849   }
850   return (curlist);
851 }
852
853 static int
854 perform_and (pattern_t * pat, pattern_exec_flag flags, CONTEXT * ctx,
855              HEADER * hdr)
856 {
857   for (; pat; pat = pat->next)
858     if (mutt_pattern_exec (pat, flags, ctx, hdr) <= 0)
859       return 0;
860   return 1;
861 }
862
863 static int
864 perform_or (struct pattern_t *pat, pattern_exec_flag flags, CONTEXT * ctx,
865             HEADER * hdr)
866 {
867   for (; pat; pat = pat->next)
868     if (mutt_pattern_exec (pat, flags, ctx, hdr) > 0)
869       return 1;
870   return 0;
871 }
872
873 static int match_adrlist (pattern_t* pat, int match_personal, int alladdr,
874                           int n, ...)
875 {
876   va_list ap;
877   ADDRESS *a;
878
879   va_start (ap, n);
880   for (; n; n--) {
881     for (a = va_arg (ap, ADDRESS *); a; a = a->next) {
882       if (pat->alladdr ^
883           ((a->mailbox && patmatch (pat, a->mailbox) == 0) ||
884            (match_personal && a->personal &&
885             patmatch (pat, a->personal) == 0))) {
886         va_end (ap);
887         return (!pat->alladdr);      /* Found match, or non-match if alladdr */
888       }
889     }
890   }
891   va_end (ap);
892   return pat->alladdr;               /* No matches, or all matches if alladdr */
893 }
894
895 static int match_reference (pattern_t* pat, LIST * refs)
896 {
897   for (; refs; refs = refs->next)
898     if (patmatch (pat, refs->data) == 0)
899       return 1;
900   return 0;
901 }
902
903 int mutt_is_list_recipient (int alladdr, ADDRESS * a1, ADDRESS * a2)
904 {
905   for (; a1; a1 = a1->next)
906     if (alladdr ^ mutt_is_subscribed_list (a1))
907       return (!alladdr);
908   for (; a2; a2 = a2->next)
909     if (alladdr ^ mutt_is_subscribed_list (a2))
910       return (!alladdr);
911   return alladdr;
912 }
913
914 int mutt_is_list_cc (int alladdr, ADDRESS * a1, ADDRESS * a2)
915 {
916   for (; a1; a1 = a1->next)
917     if (alladdr ^ mutt_is_mail_list (a1))
918       return (!alladdr);
919   for (; a2; a2 = a2->next)
920     if (alladdr ^ mutt_is_mail_list (a2))
921       return (!alladdr);
922   return alladdr;
923 }
924
925 static int match_user (int alladdr, ADDRESS * a1, ADDRESS * a2)
926 {
927   for (; a1; a1 = a1->next)
928     if (alladdr ^ mutt_addr_is_user (a1))
929       return (!alladdr);
930   for (; a2; a2 = a2->next)
931     if (alladdr ^ mutt_addr_is_user (a2))
932       return (!alladdr);
933   return alladdr;
934 }
935
936 /* test if name is considered a real name, i.e. consists of at least 2
937  * space-separated words of which none may end in a dot
938  */
939 static int valid_realname (const char *name)
940 {
941   const char *p = name;
942   int ret = 0;
943
944   while (*p) {
945     if (isspace (*p))
946       ret++;
947     else if (*p == '.')
948       /* skip abbr. parts of names (e.g. 'J. User') */
949       ret--;
950     p++;
951   }
952   return (ret >= 1);
953 }
954
955 /* flags
956         M_MATCH_FULL_ADDRESS    match both personal and machine address */
957 int
958 mutt_pattern_exec (struct pattern_t *pat, pattern_exec_flag flags,
959                    CONTEXT * ctx, HEADER * h)
960 {
961   switch (pat->op) {
962   case M_AND:
963     return (pat->not ^ (perform_and (pat->child, flags, ctx, h) > 0));
964   case M_OR:
965     return (pat->not ^ (perform_or (pat->child, flags, ctx, h) > 0));
966   case M_ALL:
967     return (!pat->not);
968   case M_EXPIRED:
969     return (pat->not ^ h->expired);
970   case M_SUPERSEDED:
971     return (pat->not ^ h->superseded);
972   case M_FLAG:
973     return (pat->not ^ h->flagged);
974   case M_TAG:
975     return (pat->not ^ h->tagged);
976   case M_NEW:
977     return (pat->not ? h->old || h->read : !(h->old || h->read));
978   case M_UNREAD:
979     return (pat->not ? h->read : !h->read);
980   case M_REPLIED:
981     return (pat->not ^ h->replied);
982   case M_OLD:
983     return (pat->not ? (!h->old || h->read) : (h->old && !h->read));
984   case M_READ:
985     return (pat->not ^ h->read);
986   case M_DELETED:
987     return (pat->not ^ h->deleted);
988   case M_MESSAGE:
989     return (pat->not ^ (h->msgno >= pat->min - 1 && (pat->max == M_MAXRANGE ||
990                                                      h->msgno <=
991                                                      pat->max - 1)));
992   case M_DATE:
993     return (pat->
994             not ^ (h->date_sent >= pat->min && h->date_sent <= pat->max));
995   case M_DATE_RECEIVED:
996     return (pat->not ^ (h->received >= pat->min && h->received <= pat->max));
997   case M_BODY:
998   case M_HEADER:
999   case M_WHOLE_MSG:
1000 #ifdef USE_IMAP
1001     /* IMAP search sets h->matched at search compile time */
1002     if (Context->magic == M_IMAP && pat->stringmatch)
1003       return (h->matched);
1004 #endif
1005     return (pat->not ^ msg_search (ctx, pat, h->msgno));
1006   case M_SENDER:
1007     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1008                                       pat->alladdr, 1, h->env->sender));
1009   case M_FROM:
1010     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1011                                       pat->alladdr, 1, h->env->from));
1012   case M_TO:
1013     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1014                                       pat->alladdr, 1, h->env->to));
1015   case M_CC:
1016     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1017                                       pat->alladdr, 1, h->env->cc));
1018   case M_SUBJECT:
1019     return (pat->
1020             not ^ (h->env && h->env->subject
1021                    && patmatch (pat, h->env->subject) == 0));
1022   case M_ID:
1023     return (pat->
1024             not ^ (h->env && h->env->message_id
1025                    && patmatch (pat, h->env->message_id) == 0));
1026   case M_SCORE:
1027     return (pat->not ^ (h->score >= pat->min && (pat->max == M_MAXRANGE ||
1028                                                  h->score <= pat->max)));
1029   case M_SIZE:
1030     return (pat->
1031             not ^ (h->content->length >= pat->min
1032                    && (pat->max == M_MAXRANGE
1033                        || h->content->length <= pat->max)));
1034   case M_REFERENCE:
1035     return (pat->not ^ match_reference (pat, h->env->references));
1036   case M_ADDRESS:
1037     return (pat->
1038             not ^ (h->env
1039                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1040                                      pat->alladdr, 4, h->env->from,
1041                                      h->env->sender, h->env->to,
1042                                      h->env->cc)));
1043   case M_RECIPIENT:
1044     return (pat->
1045             not ^ (h->env
1046                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1047                                      pat->alladdr, 2, h->env->to,
1048                                      h->env->cc)));
1049   case M_LIST:
1050     return (pat->
1051             not ^ (h->env
1052                    && mutt_is_list_cc (pat->alladdr, h->env->to,
1053                                        h->env->cc)));
1054   case M_SUBSCRIBED_LIST:
1055     return (pat->
1056             not ^ (h->env
1057                    && mutt_is_list_recipient (pat->alladdr, h->env->to,
1058                                               h->env->cc)));
1059   case M_PERSONAL_RECIP:
1060     return (pat->
1061             not ^ (h->env
1062                    && match_user (pat->alladdr, h->env->to, h->env->cc)));
1063   case M_PERSONAL_FROM:
1064     return (pat->
1065             not ^ (h->env && match_user (pat->alladdr, h->env->from, NULL)));
1066   case M_COLLAPSED:
1067     return (pat->not ^ (h->collapsed && h->num_hidden > 1));
1068   case M_CRYPT_SIGN:
1069     if (!WithCrypto)
1070       break;
1071     return (pat->not ^ ((h->security & SIGN) ? 1 : 0));
1072   case M_CRYPT_VERIFIED:
1073     if (!WithCrypto)
1074       break;
1075     return (pat->not ^ ((h->security & GOODSIGN) ? 1 : 0));
1076   case M_CRYPT_ENCRYPT:
1077     if (!WithCrypto)
1078       break;
1079     return (pat->not ^ ((h->security & ENCRYPT) ? 1 : 0));
1080   case M_PGP_KEY:
1081     if (!(WithCrypto & APPLICATION_PGP))
1082       break;
1083     return (pat->not ^ ((h->security & APPLICATION_PGP)
1084                         && (h->security & PGPKEY)));
1085   case M_XLABEL:
1086     return (pat->
1087             not ^ (h->env->x_label
1088                    && patmatch (pat, h->env->x_label) == 0));
1089   case M_HORMEL:
1090     return (pat->
1091             not ^ (h->env->spam && h->env->spam->data
1092                    && patmatch (pat, h->env->spam->data) == 0));
1093   case M_DUPLICATED:
1094     return (pat->not ^ (h->thread && h->thread->duplicate_thread));
1095   case M_UNREFERENCED:
1096     return (pat->not ^ (h->thread && !h->thread->child));
1097   case M_MULTIPART:
1098     return (pat->not ^ (h->content && h->content->type == TYPEMULTIPART));
1099   case M_REALNAME:
1100     /* realname filter:
1101      * we have a match if
1102      * - From: matches $alternates
1103      * - or we have an alias for current address
1104      * - or From: contains valid email address _and_ name has >= 2 fields
1105      */
1106     return (pat->
1107             not ^ (h->env && h->env->from && (mutt_addr_is_user (h->env->from)
1108                                               ||
1109                                               (alias_reverse_lookup
1110                                                (h->env->from) != NULL)
1111                                               || (h->env->from->personal
1112                                                   && valid_realname (h->env->
1113                                                                      from->
1114                                                                      personal)
1115                                                   && h->env->from->mailbox)
1116                    )));
1117 #ifdef USE_NNTP
1118   case M_NEWSGROUPS:
1119     return (pat->
1120             not ^ (h->env->newsgroups
1121                    && patmatch (pat, h->env->newsgroups) == 0));
1122 #endif
1123   }
1124   mutt_error (_("error: unknown op %d (report this error)."), pat->op);
1125   return (-1);
1126 }
1127
1128 static void quote_simple (char *tmp, size_t len, const char *p)
1129 {
1130   int i = 0;
1131
1132   tmp[i++] = '"';
1133   while (*p && i < len - 3) {
1134     if (*p == '\\' || *p == '"')
1135       tmp[i++] = '\\';
1136     tmp[i++] = *p++;
1137   }
1138   tmp[i++] = '"';
1139   tmp[i] = 0;
1140 }
1141
1142 /* convert a simple search into a real request */
1143 void mutt_check_simple (char *s, size_t len, const char *simple)
1144 {
1145   char tmp[LONG_STRING];
1146
1147   /* XXX - is ascii_strcasecmp() right here, or should we use locale's
1148    * equivalences?
1149    */
1150
1151   if (!strchr (s, '~') && !strchr (s, '=')) {       /* yup, so spoof a real request */
1152     /* convert old tokens into the new format */
1153     if (ascii_strcasecmp ("all", s) == 0 || !str_cmp ("^", s) || !str_cmp (".", s))     /* ~A is more efficient */
1154       strfcpy (s, "~A", len);
1155     else if (ascii_strcasecmp ("del", s) == 0)
1156       strfcpy (s, "~D", len);
1157     else if (ascii_strcasecmp ("flag", s) == 0)
1158       strfcpy (s, "~F", len);
1159     else if (ascii_strcasecmp ("new", s) == 0)
1160       strfcpy (s, "~N", len);
1161     else if (ascii_strcasecmp ("old", s) == 0)
1162       strfcpy (s, "~O", len);
1163     else if (ascii_strcasecmp ("repl", s) == 0)
1164       strfcpy (s, "~Q", len);
1165     else if (ascii_strcasecmp ("read", s) == 0)
1166       strfcpy (s, "~R", len);
1167     else if (ascii_strcasecmp ("tag", s) == 0)
1168       strfcpy (s, "~T", len);
1169     else if (ascii_strcasecmp ("unread", s) == 0)
1170       strfcpy (s, "~U", len);
1171     else {
1172       quote_simple (tmp, sizeof (tmp), s);
1173       mutt_expand_fmt (s, len, simple, tmp);
1174     }
1175   }
1176 }
1177
1178 int mutt_pattern_func (int op, char *prompt)
1179 {
1180   pattern_t *pat;
1181   char buf[LONG_STRING] = "", *simple, error[STRING];
1182   BUFFER err;
1183   int i;
1184
1185   strfcpy (buf, NONULL (Context->pattern), sizeof (buf));
1186   if (prompt || op != M_LIMIT)
1187     if (mutt_get_field (prompt, buf, sizeof (buf), M_PATTERN | M_CLEAR) != 0)
1188       return (-1);
1189   if (!buf[0]) {
1190     if (op == M_LIMIT)
1191       strncpy (buf, "~A", sizeof (buf));
1192     else
1193       return (-1);
1194   }
1195
1196   mutt_message _("Compiling search pattern...");
1197
1198   simple = str_dup (buf);
1199   mutt_check_simple (buf, sizeof (buf), NONULL (SimpleSearch));
1200
1201   err.data = error;
1202   err.dsize = sizeof (error);
1203   if ((pat = mutt_pattern_comp (buf, M_FULL_MSG, &err)) == NULL) {
1204     mem_free (&simple);
1205     mutt_error ("%s", err.data);
1206     return (-1);
1207   }
1208
1209 #ifdef USE_IMAP
1210   if (Context->magic == M_IMAP && imap_search (Context, pat) < 0)
1211     return -1;
1212 #endif
1213
1214   mutt_message _("Executing command on matching messages...");
1215
1216 #define THIS_BODY Context->hdrs[i]->content
1217
1218   if (op == M_LIMIT) {
1219     Context->vcount = 0;
1220     Context->vsize = 0;
1221     Context->collapsed = 0;
1222
1223     for (i = 0; i < Context->msgcount; i++) {
1224       /* new limit pattern implicitly uncollapses all threads */
1225       Context->hdrs[i]->virtual = -1;
1226       Context->hdrs[i]->limited = 0;
1227       Context->hdrs[i]->collapsed = 0;
1228       Context->hdrs[i]->num_hidden = 0;
1229       if (mutt_pattern_exec
1230           (pat, M_MATCH_FULL_ADDRESS, Context, Context->hdrs[i])) {
1231         Context->hdrs[i]->virtual = Context->vcount;
1232         Context->hdrs[i]->limited = 1;
1233         Context->v2r[Context->vcount] = i;
1234         Context->vcount++;
1235         Context->vsize += THIS_BODY->length + THIS_BODY->offset -
1236           THIS_BODY->hdr_offset;
1237       }
1238     }
1239   }
1240   else {
1241     for (i = 0; i < Context->vcount; i++) {
1242       if (mutt_pattern_exec
1243           (pat, M_MATCH_FULL_ADDRESS, Context,
1244            Context->hdrs[Context->v2r[i]])) {
1245         switch (op) {
1246         case M_UNDELETE:
1247           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_PURGED,
1248                          0);
1249         case M_DELETE:
1250           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_DELETE,
1251                          (op == M_DELETE));
1252           break;
1253         case M_TAG:
1254         case M_UNTAG:
1255           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_TAG,
1256                          (op == M_TAG));
1257           break;
1258         }
1259       }
1260     }
1261   }
1262
1263 #undef THIS_BODY
1264
1265   mutt_clear_error ();
1266
1267   if (op == M_LIMIT) {
1268     /* drop previous limit pattern */
1269     mem_free (&Context->pattern);
1270     if (Context->limit_pattern)
1271       mutt_pattern_free (&Context->limit_pattern);
1272     if (Context->msgcount && !Context->vcount) {
1273       mutt_error _("No messages matched criteria.");
1274     }
1275
1276     /* record new limit pattern, unless match all */
1277     if (str_ncmp (buf, "~A", 2) != 0) {
1278       Context->pattern = simple;
1279       simple = NULL;            /* don't clobber it */
1280       Context->limit_pattern = mutt_pattern_comp (buf, M_FULL_MSG, &err);
1281     }
1282   }
1283   mem_free (&simple);
1284   mutt_pattern_free (&pat);
1285   return 0;
1286 }
1287
1288 int mutt_search_command (int cur, int op)
1289 {
1290   int i, j;
1291   char buf[STRING];
1292   char temp[LONG_STRING];
1293   char error[STRING];
1294   BUFFER err;
1295   int incr;
1296   HEADER *h;
1297
1298   if (op != OP_SEARCH_NEXT && op != OP_SEARCH_OPPOSITE) {
1299     strfcpy (buf, LastSearch, sizeof (buf));
1300     if (mutt_get_field ((op == OP_SEARCH) ? _("Search for: ") :
1301                         _("Reverse search for: "), buf, sizeof (buf),
1302                         M_CLEAR | M_PATTERN) != 0 || !buf[0])
1303       return (-1);
1304
1305     if (op == OP_SEARCH)
1306       unset_option (OPTSEARCHREVERSE);
1307     else
1308       set_option (OPTSEARCHREVERSE);
1309
1310     /* compare the *expanded* version of the search pattern in case 
1311        $simple_search has changed while we were searching */
1312     strfcpy (temp, buf, sizeof (temp));
1313     mutt_check_simple (temp, sizeof (temp), NONULL (SimpleSearch));
1314
1315     if (!SearchPattern || str_cmp (temp, LastSearchExpn)) {
1316       set_option (OPTSEARCHINVALID);
1317       strfcpy (LastSearch, buf, sizeof (LastSearch));
1318       mutt_message _("Compiling search pattern...");
1319
1320       mutt_pattern_free (&SearchPattern);
1321       err.data = error;
1322       err.dsize = sizeof (error);
1323       if ((SearchPattern =
1324            mutt_pattern_comp (temp, M_FULL_MSG, &err)) == NULL) {
1325         mutt_error ("%s", error);
1326         return (-1);
1327       }
1328       mutt_clear_error ();
1329     }
1330   }
1331   else if (!SearchPattern) {
1332     mutt_error _("No search pattern.");
1333
1334     return (-1);
1335   }
1336
1337   if (option (OPTSEARCHINVALID)) {
1338     for (i = 0; i < Context->msgcount; i++)
1339       Context->hdrs[i]->searched = 0;
1340 #ifdef USE_IMAP
1341     if (Context->magic == M_IMAP && imap_search (Context, SearchPattern) < 0)
1342       return -1;
1343 #endif
1344     unset_option (OPTSEARCHINVALID);
1345   }
1346
1347   incr = (option (OPTSEARCHREVERSE)) ? -1 : 1;
1348   if (op == OP_SEARCH_OPPOSITE)
1349     incr = -incr;
1350
1351   for (i = cur + incr, j = 0; j != Context->vcount; j++) {
1352     if (i > Context->vcount - 1) {
1353       i = 0;
1354       if (option (OPTWRAPSEARCH))
1355         mutt_message (_("Search wrapped to top."));
1356
1357       else {
1358         mutt_message _("Search hit bottom without finding match");
1359
1360         return (-1);
1361       }
1362     }
1363     else if (i < 0) {
1364       i = Context->vcount - 1;
1365       if (option (OPTWRAPSEARCH))
1366         mutt_message (_("Search wrapped to bottom."));
1367
1368       else {
1369         mutt_message _("Search hit top without finding match");
1370
1371         return (-1);
1372       }
1373     }
1374
1375     h = Context->hdrs[Context->v2r[i]];
1376     if (h->searched) {
1377       /* if we've already evaulated this message, use the cached value */
1378       if (h->matched)
1379         return i;
1380     }
1381     else {
1382       /* remember that we've already searched this message */
1383       h->searched = 1;
1384       if ((h->matched =
1385            (mutt_pattern_exec
1386             (SearchPattern, M_MATCH_FULL_ADDRESS, Context, h) > 0)))
1387         return i;
1388     }
1389
1390     if (SigInt) {
1391       mutt_error _("Search interrupted.");
1392
1393       SigInt = 0;
1394       return (-1);
1395     }
1396
1397     i += incr;
1398   }
1399
1400   mutt_error _("Not found.");
1401
1402   return (-1);
1403 }