7813d55ad5889d9b03e6182f6fc56296e4fcbec5
[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       } else 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 or = 0;
702   int implicit = 1;             /* used to detect logical AND operator */
703   struct pattern_flags *entry;
704   char *p;
705   char *buf;
706   BUFFER ps;
707
708   memset (&ps, 0, sizeof (ps));
709   ps.dptr = s;
710   ps.dsize = str_len (s);
711
712   while (*ps.dptr) {
713     SKIPWS (ps.dptr);
714     switch (*ps.dptr) {
715     case '^':
716       ps.dptr++;
717       alladdr = !alladdr;
718       break;
719     case '!':
720       ps.dptr++;
721       not = !not;
722       break;
723     case '|':
724       if (!or) {
725         if (!curlist) {
726           snprintf (err->data, err->dsize, _("error in pattern at: %s"),
727                     ps.dptr);
728           return NULL;
729         }
730         if (curlist->next) {
731           /* A & B | C == (A & B) | C */
732           tmp = new_pattern ();
733           tmp->op = M_AND;
734           tmp->child = curlist;
735
736           curlist = tmp;
737           last = curlist;
738         }
739
740         or = 1;
741       }
742       ps.dptr++;
743       implicit = 0;
744       not = 0;
745       alladdr = 0;
746       break;
747     case '=':
748       /* fallthrough */
749     case '~':
750       if (implicit && or) {
751         /* A | B & C == (A | B) & C */
752         tmp = new_pattern ();
753         tmp->op = M_OR;
754         tmp->child = curlist;
755         curlist = tmp;
756         last = tmp;
757         or = 0;
758       }
759
760       tmp = new_pattern ();
761       tmp->not = not;
762       tmp->alladdr = alladdr;
763       tmp->stringmatch = (*ps.dptr == '=') ? 1 : 0;
764       not = 0;
765       alladdr = 0;
766
767       if (last)
768         last->next = tmp;
769       else
770         curlist = tmp;
771       last = tmp;
772
773       ps.dptr++;                /* move past the ~ */
774       if ((entry = lookup_tag (*ps.dptr)) == NULL) {
775         snprintf (err->data, err->dsize, _("%c: invalid command"), *ps.dptr);
776         mutt_pattern_free (&curlist);
777         return NULL;
778       }
779       if (entry->class && (flags & entry->class) == 0) {
780         snprintf (err->data, err->dsize, _("%c: not supported in this mode"),
781                   *ps.dptr);
782         mutt_pattern_free (&curlist);
783         return NULL;
784       }
785       tmp->op = entry->op;
786
787       ps.dptr++;                /* eat the operator and any optional whitespace */
788       SKIPWS (ps.dptr);
789
790       if (entry->eat_arg) {
791         if (!*ps.dptr) {
792           snprintf (err->data, err->dsize, _("missing parameter"));
793           mutt_pattern_free (&curlist);
794           return NULL;
795         }
796         if (entry->eat_arg (tmp, &ps, err) == -1) {
797           mutt_pattern_free (&curlist);
798           return NULL;
799         }
800       }
801       implicit = 1;
802       break;
803     case '(':
804       p = find_matching_paren (ps.dptr + 1);
805       if (*p != ')') {
806         snprintf (err->data, err->dsize, _("mismatched parenthesis: %s"),
807                   ps.dptr);
808         mutt_pattern_free (&curlist);
809         return NULL;
810       }
811       /* compile the sub-expression */
812       buf = str_substrdup (ps.dptr + 1, p);
813       if ((tmp = mutt_pattern_comp (buf, flags, err)) == NULL) {
814         mem_free (&buf);
815         mutt_pattern_free (&curlist);
816         return NULL;
817       }
818       mem_free (&buf);
819       if (last)
820         last->next = tmp;
821       else
822         curlist = tmp;
823       last = tmp;
824       tmp->not ^= not;
825       tmp->alladdr |= alladdr;
826       not = 0;
827       alladdr = 0;
828       ps.dptr = p + 1;          /* restore location */
829       break;
830     default:
831       snprintf (err->data, err->dsize, _("error in pattern at: %s"), ps.dptr);
832       mutt_pattern_free (&curlist);
833       return NULL;
834     }
835   }
836   if (!curlist) {
837     strfcpy (err->data, _("empty pattern"), err->dsize);
838     return NULL;
839   }
840   if (curlist->next) {
841     tmp = new_pattern ();
842     tmp->op = or ? M_OR : M_AND;
843     tmp->child = curlist;
844     curlist = tmp;
845   }
846   return (curlist);
847 }
848
849 static int
850 perform_and (pattern_t * pat, pattern_exec_flag flags, CONTEXT * ctx,
851              HEADER * hdr)
852 {
853   for (; pat; pat = pat->next)
854     if (mutt_pattern_exec (pat, flags, ctx, hdr) <= 0)
855       return 0;
856   return 1;
857 }
858
859 static int
860 perform_or (struct pattern_t *pat, pattern_exec_flag flags, CONTEXT * ctx,
861             HEADER * hdr)
862 {
863   for (; pat; pat = pat->next)
864     if (mutt_pattern_exec (pat, flags, ctx, hdr) > 0)
865       return 1;
866   return 0;
867 }
868
869 static int match_adrlist (pattern_t* pat, int match_personal, int alladdr,
870                           int n, ...)
871 {
872   va_list ap;
873   ADDRESS *a;
874
875   va_start (ap, n);
876   for (; n; n--) {
877     for (a = va_arg (ap, ADDRESS *); a; a = a->next) {
878       if (pat->alladdr ^
879           ((a->mailbox && patmatch (pat, a->mailbox) == 0) ||
880            (match_personal && a->personal &&
881             patmatch (pat, a->personal) == 0))) {
882         va_end (ap);
883         return (!pat->alladdr);      /* Found match, or non-match if alladdr */
884       }
885     }
886   }
887   va_end (ap);
888   return pat->alladdr;               /* No matches, or all matches if alladdr */
889 }
890
891 static int match_reference (pattern_t* pat, LIST * refs)
892 {
893   for (; refs; refs = refs->next)
894     if (patmatch (pat, refs->data) == 0)
895       return 1;
896   return 0;
897 }
898
899 int mutt_is_list_recipient (int alladdr, ADDRESS * a1, ADDRESS * a2)
900 {
901   for (; a1; a1 = a1->next)
902     if (alladdr ^ mutt_is_subscribed_list (a1))
903       return (!alladdr);
904   for (; a2; a2 = a2->next)
905     if (alladdr ^ mutt_is_subscribed_list (a2))
906       return (!alladdr);
907   return alladdr;
908 }
909
910 int mutt_is_list_cc (int alladdr, ADDRESS * a1, ADDRESS * a2)
911 {
912   for (; a1; a1 = a1->next)
913     if (alladdr ^ mutt_is_mail_list (a1))
914       return (!alladdr);
915   for (; a2; a2 = a2->next)
916     if (alladdr ^ mutt_is_mail_list (a2))
917       return (!alladdr);
918   return alladdr;
919 }
920
921 static int match_user (int alladdr, ADDRESS * a1, ADDRESS * a2)
922 {
923   for (; a1; a1 = a1->next)
924     if (alladdr ^ mutt_addr_is_user (a1))
925       return (!alladdr);
926   for (; a2; a2 = a2->next)
927     if (alladdr ^ mutt_addr_is_user (a2))
928       return (!alladdr);
929   return alladdr;
930 }
931
932 /* test if name is considered a real name, i.e. consists of at least 2
933  * space-separated words of which none may end in a dot
934  */
935 static int valid_realname (const char *name)
936 {
937   const char *p = name;
938   int ret = 0;
939
940   while (*p) {
941     if (isspace (*p))
942       ret++;
943     else if (*p == '.')
944       /* skip abbr. parts of names (e.g. 'J. User') */
945       ret--;
946     p++;
947   }
948   return (ret >= 1);
949 }
950
951 /* flags
952         M_MATCH_FULL_ADDRESS    match both personal and machine address */
953 int
954 mutt_pattern_exec (struct pattern_t *pat, pattern_exec_flag flags,
955                    CONTEXT * ctx, HEADER * h)
956 {
957   switch (pat->op) {
958   case M_AND:
959     return (pat->not ^ (perform_and (pat->child, flags, ctx, h) > 0));
960   case M_OR:
961     return (pat->not ^ (perform_or (pat->child, flags, ctx, h) > 0));
962   case M_ALL:
963     return (!pat->not);
964   case M_EXPIRED:
965     return (pat->not ^ h->expired);
966   case M_SUPERSEDED:
967     return (pat->not ^ h->superseded);
968   case M_FLAG:
969     return (pat->not ^ h->flagged);
970   case M_TAG:
971     return (pat->not ^ h->tagged);
972   case M_NEW:
973     return (pat->not ? h->old || h->read : !(h->old || h->read));
974   case M_UNREAD:
975     return (pat->not ? h->read : !h->read);
976   case M_REPLIED:
977     return (pat->not ^ h->replied);
978   case M_OLD:
979     return (pat->not ? (!h->old || h->read) : (h->old && !h->read));
980   case M_READ:
981     return (pat->not ^ h->read);
982   case M_DELETED:
983     return (pat->not ^ h->deleted);
984   case M_MESSAGE:
985     return (pat->not ^ (h->msgno >= pat->min - 1 && (pat->max == M_MAXRANGE ||
986                                                      h->msgno <=
987                                                      pat->max - 1)));
988   case M_DATE:
989     return (pat->
990             not ^ (h->date_sent >= pat->min && h->date_sent <= pat->max));
991   case M_DATE_RECEIVED:
992     return (pat->not ^ (h->received >= pat->min && h->received <= pat->max));
993   case M_BODY:
994   case M_HEADER:
995   case M_WHOLE_MSG:
996 #ifdef USE_IMAP
997     /* IMAP search sets h->matched at search compile time */
998     if (Context->magic == M_IMAP && pat->stringmatch)
999       return (h->matched);
1000 #endif
1001     return (pat->not ^ msg_search (ctx, pat, h->msgno));
1002   case M_SENDER:
1003     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1004                                       pat->alladdr, 1, h->env->sender));
1005   case M_FROM:
1006     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1007                                       pat->alladdr, 1, h->env->from));
1008   case M_TO:
1009     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1010                                       pat->alladdr, 1, h->env->to));
1011   case M_CC:
1012     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1013                                       pat->alladdr, 1, h->env->cc));
1014   case M_SUBJECT:
1015     return (pat->
1016             not ^ (h->env && h->env->subject
1017                    && patmatch (pat, h->env->subject) == 0));
1018   case M_ID:
1019     return (pat->
1020             not ^ (h->env && h->env->message_id
1021                    && patmatch (pat, h->env->message_id) == 0));
1022   case M_SCORE:
1023     return (pat->not ^ (h->score >= pat->min && (pat->max == M_MAXRANGE ||
1024                                                  h->score <= pat->max)));
1025   case M_SIZE:
1026     return (pat->
1027             not ^ (h->content->length >= pat->min
1028                    && (pat->max == M_MAXRANGE
1029                        || h->content->length <= pat->max)));
1030   case M_REFERENCE:
1031     return (pat->not ^ match_reference (pat, h->env->references));
1032   case M_ADDRESS:
1033     return (pat->
1034             not ^ (h->env
1035                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1036                                      pat->alladdr, 4, h->env->from,
1037                                      h->env->sender, h->env->to,
1038                                      h->env->cc)));
1039   case M_RECIPIENT:
1040     return (pat->
1041             not ^ (h->env
1042                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1043                                      pat->alladdr, 2, h->env->to,
1044                                      h->env->cc)));
1045   case M_LIST:
1046     return (pat->
1047             not ^ (h->env
1048                    && mutt_is_list_cc (pat->alladdr, h->env->to,
1049                                        h->env->cc)));
1050   case M_SUBSCRIBED_LIST:
1051     return (pat->
1052             not ^ (h->env
1053                    && mutt_is_list_recipient (pat->alladdr, h->env->to,
1054                                               h->env->cc)));
1055   case M_PERSONAL_RECIP:
1056     return (pat->
1057             not ^ (h->env
1058                    && match_user (pat->alladdr, h->env->to, h->env->cc)));
1059   case M_PERSONAL_FROM:
1060     return (pat->
1061             not ^ (h->env && match_user (pat->alladdr, h->env->from, NULL)));
1062   case M_COLLAPSED:
1063     return (pat->not ^ (h->collapsed && h->num_hidden > 1));
1064   case M_CRYPT_SIGN:
1065     if (!WithCrypto)
1066       break;
1067     return (pat->not ^ ((h->security & SIGN) ? 1 : 0));
1068   case M_CRYPT_VERIFIED:
1069     if (!WithCrypto)
1070       break;
1071     return (pat->not ^ ((h->security & GOODSIGN) ? 1 : 0));
1072   case M_CRYPT_ENCRYPT:
1073     if (!WithCrypto)
1074       break;
1075     return (pat->not ^ ((h->security & ENCRYPT) ? 1 : 0));
1076   case M_PGP_KEY:
1077     if (!(WithCrypto & APPLICATION_PGP))
1078       break;
1079     return (pat->not ^ ((h->security & APPLICATION_PGP)
1080                         && (h->security & PGPKEY)));
1081   case M_XLABEL:
1082     return (pat->
1083             not ^ (h->env->x_label
1084                    && patmatch (pat, h->env->x_label) == 0));
1085   case M_HORMEL:
1086     return (pat->
1087             not ^ (h->env->spam && h->env->spam->data
1088                    && patmatch (pat, h->env->spam->data) == 0));
1089   case M_DUPLICATED:
1090     return (pat->not ^ (h->thread && h->thread->duplicate_thread));
1091   case M_UNREFERENCED:
1092     return (pat->not ^ (h->thread && !h->thread->child));
1093   case M_MULTIPART:
1094     return (pat->not ^ (h->content && h->content->type == TYPEMULTIPART));
1095   case M_REALNAME:
1096     /* realname filter:
1097      * we have a match if
1098      * - From: matches $alternates
1099      * - or we have an alias for current address
1100      * - or From: contains valid email address _and_ name has >= 2 fields
1101      */
1102     return (pat->
1103             not ^ (h->env && h->env->from && (mutt_addr_is_user (h->env->from)
1104                                               ||
1105                                               (alias_reverse_lookup
1106                                                (h->env->from) != NULL)
1107                                               || (h->env->from->personal
1108                                                   && valid_realname (h->env->
1109                                                                      from->
1110                                                                      personal)
1111                                                   && h->env->from->mailbox)
1112                    )));
1113 #ifdef USE_NNTP
1114   case M_NEWSGROUPS:
1115     return (pat->
1116             not ^ (h->env->newsgroups
1117                    && patmatch (pat, h->env->newsgroups) == 0));
1118 #endif
1119   }
1120   mutt_error (_("error: unknown op %d (report this error)."), pat->op);
1121   return (-1);
1122 }
1123
1124 static void quote_simple (char *tmp, size_t len, const char *p)
1125 {
1126   int i = 0;
1127
1128   tmp[i++] = '"';
1129   while (*p && i < len - 3) {
1130     if (*p == '\\' || *p == '"')
1131       tmp[i++] = '\\';
1132     tmp[i++] = *p++;
1133   }
1134   tmp[i++] = '"';
1135   tmp[i] = 0;
1136 }
1137
1138 /* convert a simple search into a real request */
1139 void mutt_check_simple (char *s, size_t len, const char *simple)
1140 {
1141   char tmp[LONG_STRING];
1142
1143   /* XXX - is ascii_strcasecmp() right here, or should we use locale's
1144    * equivalences?
1145    */
1146
1147   if (!strchr (s, '~') && !strchr (s, '=')) {       /* yup, so spoof a real request */
1148     /* convert old tokens into the new format */
1149     if (ascii_strcasecmp ("all", s) == 0 || !str_cmp ("^", s) || !str_cmp (".", s))     /* ~A is more efficient */
1150       strfcpy (s, "~A", len);
1151     else if (ascii_strcasecmp ("del", s) == 0)
1152       strfcpy (s, "~D", len);
1153     else if (ascii_strcasecmp ("flag", s) == 0)
1154       strfcpy (s, "~F", len);
1155     else if (ascii_strcasecmp ("new", s) == 0)
1156       strfcpy (s, "~N", len);
1157     else if (ascii_strcasecmp ("old", s) == 0)
1158       strfcpy (s, "~O", len);
1159     else if (ascii_strcasecmp ("repl", s) == 0)
1160       strfcpy (s, "~Q", len);
1161     else if (ascii_strcasecmp ("read", s) == 0)
1162       strfcpy (s, "~R", len);
1163     else if (ascii_strcasecmp ("tag", s) == 0)
1164       strfcpy (s, "~T", len);
1165     else if (ascii_strcasecmp ("unread", s) == 0)
1166       strfcpy (s, "~U", len);
1167     else {
1168       quote_simple (tmp, sizeof (tmp), s);
1169       mutt_expand_fmt (s, len, simple, tmp);
1170     }
1171   }
1172 }
1173
1174 int mutt_pattern_func (int op, char *prompt)
1175 {
1176   pattern_t *pat;
1177   char buf[LONG_STRING] = "", *simple, error[STRING];
1178   BUFFER err;
1179   int i;
1180
1181   strfcpy (buf, NONULL (Context->pattern), sizeof (buf));
1182   if (prompt || op != M_LIMIT)
1183     if (mutt_get_field (prompt, buf, sizeof (buf), M_PATTERN | M_CLEAR) != 0)
1184       return (-1);
1185   if (!buf[0]) {
1186     if (op == M_LIMIT)
1187       strncpy (buf, "~A", sizeof (buf));
1188     else
1189       return (-1);
1190   }
1191
1192   mutt_message _("Compiling search pattern...");
1193
1194   simple = str_dup (buf);
1195   mutt_check_simple (buf, sizeof (buf), NONULL (SimpleSearch));
1196
1197   err.data = error;
1198   err.dsize = sizeof (error);
1199   if ((pat = mutt_pattern_comp (buf, M_FULL_MSG, &err)) == NULL) {
1200     mem_free (&simple);
1201     mutt_error ("%s", err.data);
1202     return (-1);
1203   }
1204
1205 #ifdef USE_IMAP
1206   if (Context->magic == M_IMAP && imap_search (Context, pat) < 0)
1207     return -1;
1208 #endif
1209
1210   mutt_message _("Executing command on matching messages...");
1211
1212 #define THIS_BODY Context->hdrs[i]->content
1213
1214   if (op == M_LIMIT) {
1215     Context->vcount = 0;
1216     Context->vsize = 0;
1217     Context->collapsed = 0;
1218
1219     for (i = 0; i < Context->msgcount; i++) {
1220       /* new limit pattern implicitly uncollapses all threads */
1221       Context->hdrs[i]->virtual = -1;
1222       Context->hdrs[i]->limited = 0;
1223       Context->hdrs[i]->collapsed = 0;
1224       Context->hdrs[i]->num_hidden = 0;
1225       if (mutt_pattern_exec
1226           (pat, M_MATCH_FULL_ADDRESS, Context, Context->hdrs[i])) {
1227         Context->hdrs[i]->virtual = Context->vcount;
1228         Context->hdrs[i]->limited = 1;
1229         Context->v2r[Context->vcount] = i;
1230         Context->vcount++;
1231         Context->vsize += THIS_BODY->length + THIS_BODY->offset -
1232           THIS_BODY->hdr_offset;
1233       }
1234     }
1235   }
1236   else {
1237     for (i = 0; i < Context->vcount; i++) {
1238       if (mutt_pattern_exec
1239           (pat, M_MATCH_FULL_ADDRESS, Context,
1240            Context->hdrs[Context->v2r[i]])) {
1241         switch (op) {
1242         case M_UNDELETE:
1243           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_PURGED,
1244                          0);
1245         case M_DELETE:
1246           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_DELETE,
1247                          (op == M_DELETE));
1248           break;
1249         case M_TAG:
1250         case M_UNTAG:
1251           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_TAG,
1252                          (op == M_TAG));
1253           break;
1254         }
1255       }
1256     }
1257   }
1258
1259 #undef THIS_BODY
1260
1261   mutt_clear_error ();
1262
1263   if (op == M_LIMIT) {
1264     /* drop previous limit pattern */
1265     mem_free (&Context->pattern);
1266     if (Context->limit_pattern)
1267       mutt_pattern_free (&Context->limit_pattern);
1268     if (Context->msgcount && !Context->vcount) {
1269       mutt_error _("No messages matched criteria.");
1270     }
1271
1272     /* record new limit pattern, unless match all */
1273     if (str_ncmp (buf, "~A", 2) != 0) {
1274       Context->pattern = simple;
1275       simple = NULL;            /* don't clobber it */
1276       Context->limit_pattern = mutt_pattern_comp (buf, M_FULL_MSG, &err);
1277     }
1278   }
1279   mem_free (&simple);
1280   mutt_pattern_free (&pat);
1281   return 0;
1282 }
1283
1284 int mutt_search_command (int cur, int op)
1285 {
1286   int i, j;
1287   char buf[STRING];
1288   char temp[LONG_STRING];
1289   char error[STRING];
1290   BUFFER err;
1291   int incr;
1292   HEADER *h;
1293
1294   if (op != OP_SEARCH_NEXT && op != OP_SEARCH_OPPOSITE) {
1295     strfcpy (buf, LastSearch, sizeof (buf));
1296     if (mutt_get_field ((op == OP_SEARCH) ? _("Search for: ") :
1297                         _("Reverse search for: "), buf, sizeof (buf),
1298                         M_CLEAR | M_PATTERN) != 0 || !buf[0])
1299       return (-1);
1300
1301     if (op == OP_SEARCH)
1302       unset_option (OPTSEARCHREVERSE);
1303     else
1304       set_option (OPTSEARCHREVERSE);
1305
1306     /* compare the *expanded* version of the search pattern in case 
1307        $simple_search has changed while we were searching */
1308     strfcpy (temp, buf, sizeof (temp));
1309     mutt_check_simple (temp, sizeof (temp), NONULL (SimpleSearch));
1310
1311     if (!SearchPattern || str_cmp (temp, LastSearchExpn)) {
1312       set_option (OPTSEARCHINVALID);
1313       strfcpy (LastSearch, buf, sizeof (LastSearch));
1314       mutt_message _("Compiling search pattern...");
1315
1316       mutt_pattern_free (&SearchPattern);
1317       err.data = error;
1318       err.dsize = sizeof (error);
1319       if ((SearchPattern =
1320            mutt_pattern_comp (temp, M_FULL_MSG, &err)) == NULL) {
1321         mutt_error ("%s", error);
1322         return (-1);
1323       }
1324       mutt_clear_error ();
1325     }
1326   }
1327   else if (!SearchPattern) {
1328     mutt_error _("No search pattern.");
1329
1330     return (-1);
1331   }
1332
1333   if (option (OPTSEARCHINVALID)) {
1334     for (i = 0; i < Context->msgcount; i++)
1335       Context->hdrs[i]->searched = 0;
1336 #ifdef USE_IMAP
1337     if (Context->magic == M_IMAP && imap_search (Context, SearchPattern) < 0)
1338       return -1;
1339 #endif
1340     unset_option (OPTSEARCHINVALID);
1341   }
1342
1343   incr = (option (OPTSEARCHREVERSE)) ? -1 : 1;
1344   if (op == OP_SEARCH_OPPOSITE)
1345     incr = -incr;
1346
1347   for (i = cur + incr, j = 0; j != Context->vcount; j++) {
1348     if (i > Context->vcount - 1) {
1349       i = 0;
1350       if (option (OPTWRAPSEARCH))
1351         mutt_message (_("Search wrapped to top."));
1352
1353       else {
1354         mutt_message _("Search hit bottom without finding match");
1355
1356         return (-1);
1357       }
1358     }
1359     else if (i < 0) {
1360       i = Context->vcount - 1;
1361       if (option (OPTWRAPSEARCH))
1362         mutt_message (_("Search wrapped to bottom."));
1363
1364       else {
1365         mutt_message _("Search hit top without finding match");
1366
1367         return (-1);
1368       }
1369     }
1370
1371     h = Context->hdrs[Context->v2r[i]];
1372     if (h->searched) {
1373       /* if we've already evaulated this message, use the cached value */
1374       if (h->matched)
1375         return i;
1376     }
1377     else {
1378       /* remember that we've already searched this message */
1379       h->searched = 1;
1380       if ((h->matched =
1381            (mutt_pattern_exec
1382             (SearchPattern, M_MATCH_FULL_ADDRESS, Context, h) > 0)))
1383         return i;
1384     }
1385
1386     if (SigInt) {
1387       mutt_error _("Search interrupted.");
1388
1389       SigInt = 0;
1390       return (-1);
1391     }
1392
1393     i += incr;
1394   }
1395
1396   mutt_error _("Not found.");
1397
1398   return (-1);
1399 }