868d7abbcb2b409cb4834672d2fddc0a6b537275
[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 <lib-lib/mem.h>
15 #include <lib-lib/ascii.h>
16 #include <lib-lib/str.h>
17 #include <lib-lib/macros.h>
18 #include <lib-lib/file.h>
19 #include <lib-lib/buffer.h>
20 #include <lib-lib/mapping.h>
21
22 #include <lib-mime/mime.h>
23
24 #include <lib-ui/enter.h>
25
26 #include "mutt.h"
27 #include "handler.h"
28 #include "mx.h"
29 #include "keymap.h"
30 #include "copy.h"
31
32 #include <imap/imap.h>
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 <lib-crypt/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   'X', M_MIMEATTACH, 0, eat_range}, {
99   'y', M_XLABEL, 0, eat_regexp}, {
100   'z', M_SIZE, 0, eat_range}, {
101   '=', M_DUPLICATED, 0, NULL}, {
102   '$', M_UNREFERENCED, 0, NULL}, {
103   '*', M_REALNAME, 0, NULL}, {
104   0, 0, 0, NULL}
105 };
106
107 static pattern_t *SearchPattern = NULL; /* current search pattern */
108 static char LastSearch[STRING] = { 0 }; /* last pattern searched for */
109 static char LastSearchExpn[LONG_STRING] = { 0 };        /* expanded version of
110                                                            LastSearch */
111
112 #define M_MAXRANGE -1
113
114 /* constants for parse_date_range() */
115 #define M_PDR_NONE      0x0000
116 #define M_PDR_MINUS     0x0001
117 #define M_PDR_PLUS      0x0002
118 #define M_PDR_WINDOW    0x0004
119 #define M_PDR_ABSOLUTE  0x0008
120 #define M_PDR_DONE      0x0010
121 #define M_PDR_ERROR     0x0100
122 #define M_PDR_ERRORDONE (M_PDR_ERROR | M_PDR_DONE)
123
124
125 int mutt_getvaluebychar (char ch, struct mapping_t *table)
126 {
127   int i;
128
129   for (i = 0; table[i].name; i++) {
130     if (ch == table[i].name[0])
131       return table[i].value;
132   }
133
134   return (-1);
135 }
136
137 /* if no uppercase letters are given, do a case-insensitive search */
138 int mutt_which_case (const char *s)
139 {
140   while (*s) {
141     if (isalpha ((unsigned char) *s) && isupper ((unsigned char) *s))
142       return 0;                 /* case-sensitive */
143     s++;
144   }
145   return REG_ICASE;             /* case-insensitive */
146 }
147
148 static int
149 msg_search (CONTEXT *ctx, pattern_t* pat, int msgno)
150 {
151   char tempfile[_POSIX_PATH_MAX];
152   MESSAGE *msg = NULL;
153   STATE s;
154   struct stat st;
155   FILE *fp = NULL;
156   long lng = 0;
157   int match = 0;
158   HEADER *h = ctx->hdrs[msgno];
159   char* buf;
160   ssize_t blen;
161
162   if ((msg = mx_open_message (ctx, msgno)) != NULL) {
163     if (option (OPTTHOROUGHSRC)) {
164       /* decode the header / body */
165       p_clear(&s, 1);
166       s.fpin = msg->fp;
167       s.flags = M_CHARCONV;
168       mutt_mktemp (tempfile);
169       if ((s.fpout = safe_fopen (tempfile, "w+")) == NULL) {
170         mutt_perror (tempfile);
171         return (0);
172       }
173
174       if (pat->op != M_BODY)
175         mutt_copy_header (msg->fp, h, s.fpout, CH_FROM | CH_DECODE, NULL);
176
177       if (pat->op != M_HEADER) {
178         mutt_parse_mime_message (ctx, h);
179
180         if ((h->security & ENCRYPT) && !crypt_valid_passphrase (h->security))
181         {
182           mx_close_message (&msg);
183           if (fp) {
184             fclose (fp);
185             unlink (tempfile);
186           }
187           return (0);
188         }
189
190         fseeko (msg->fp, h->offset, 0);
191         mutt_body_handler (h->content, &s);
192       }
193
194       fp = s.fpout;
195       fflush (fp);
196       fseeko (fp, 0, 0);
197       fstat (fileno (fp), &st);
198       lng = (long) st.st_size;
199     }
200     else {
201       /* raw header / body */
202       fp = msg->fp;
203       if (pat->op != M_BODY) {
204         fseeko (fp, h->offset, 0);
205         lng = h->content->offset - h->offset;
206       }
207       if (pat->op != M_HEADER) {
208         if (pat->op == M_BODY)
209           fseeko (fp, h->content->offset, 0);
210         lng += h->content->length;
211       }
212     }
213
214     buf = p_new(char, blen = STRING);
215
216     /* search the file "fp" */
217     while (lng > 0) {
218       if (pat->op == M_HEADER) {
219         if (!mutt_read_rfc822_line(fp, &buf, &blen))
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 -= m_strlen(buf);
228     }
229
230     p_delete(&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   p_clear(&buf, 1);
249
250   if (mutt_extract_token (&buf, s, M_TOKEN_PATTERN | M_TOKEN_COMMENT) != 0 ||
251       !buf.data) {
252     snprintf (err->data, err->dsize, _("Error in expression: %s"), s->dptr);
253     return (-1);
254   }
255
256   if (!*buf.data) {
257     snprintf (err->data, err->dsize, _("Empty expression"));
258     return (-1);
259   }
260
261 #if 0
262  /* If there are no RE metacharacters, use simple search anyway */
263   if (!pat->stringmatch && !strpbrk (buf.data, "|[{.*+?^$"))
264     pat->stringmatch = 1;
265 #endif
266
267   if (pat->stringmatch) {
268     pat->str = m_strdup(buf.data);
269     p_delete(&buf.data);
270   } else {
271     pat->rx = p_new(regex_t, 1);
272     r = REGCOMP (pat->rx, buf.data, REG_NEWLINE | REG_NOSUB | mutt_which_case (buf.data));
273     p_delete(&buf.data);
274     if (r) {
275       regerror (r, pat->rx, err->data, err->dsize);
276       regfree (pat->rx);
277       p_delete(&pat->rx);
278       return (-1);
279     }
280   }
281   return 0;
282 }
283
284 static int patmatch (const pattern_t* pat, const char* buf) {
285   if (pat->stringmatch)
286     return !strstr (buf, pat->str);
287   else
288     return regexec (pat->rx, buf, 0, NULL, 0);
289 }
290
291 int eat_range (pattern_t * pat, BUFFER * s, BUFFER * err __attribute__ ((unused)))
292 {
293   char *tmp;
294   int do_exclusive = 0;
295   int skip_quote = 0;
296
297   /*
298    * If simple_search is set to "~m %s", the range will have double quotes 
299    * around it...
300    */
301   if (*s->dptr == '"') {
302     s->dptr++;
303     skip_quote = 1;
304   }
305   if (*s->dptr == '<')
306     do_exclusive = 1;
307   if ((*s->dptr != '-') && (*s->dptr != '<')) {
308     /* range minimum */
309     if (*s->dptr == '>') {
310       pat->max = M_MAXRANGE;
311       pat->min = strtol (s->dptr + 1, &tmp, 0) + 1;     /* exclusive range */
312     }
313     else
314       pat->min = strtol (s->dptr, &tmp, 0);
315     if (toupper ((unsigned char) *tmp) == 'K') {        /* is there a prefix? */
316       pat->min *= 1024;
317       tmp++;
318     }
319     else if (toupper ((unsigned char) *tmp) == 'M') {
320       pat->min *= 1048576;
321       tmp++;
322     }
323     if (*s->dptr == '>') {
324       s->dptr = tmp;
325       return 0;
326     }
327     if (*tmp != '-') {
328       /* exact value */
329       pat->max = pat->min;
330       s->dptr = tmp;
331       return 0;
332     }
333     tmp++;
334   }
335   else {
336     s->dptr++;
337     tmp = s->dptr;
338   }
339
340   if (isdigit ((unsigned char) *tmp)) {
341     /* range maximum */
342     pat->max = strtol (tmp, &tmp, 0);
343     if (toupper ((unsigned char) *tmp) == 'K') {
344       pat->max *= 1024;
345       tmp++;
346     }
347     else if (toupper ((unsigned char) *tmp) == 'M') {
348       pat->max *= 1048576;
349       tmp++;
350     }
351     if (do_exclusive)
352       (pat->max)--;
353   }
354   else
355     pat->max = M_MAXRANGE;
356
357   if (skip_quote && *tmp == '"')
358     tmp++;
359
360   s->dptr = vskipspaces(tmp);
361   return 0;
362 }
363
364 static const char *getDate (const char *s, struct tm *t, BUFFER * err)
365 {
366   char *p;
367   time_t now = time (NULL);
368   struct tm *tm = localtime (&now);
369
370   t->tm_mday = strtol (s, &p, 10);
371   if (t->tm_mday < 1 || t->tm_mday > 31) {
372     snprintf (err->data, err->dsize, _("Invalid day of month: %s"), s);
373     return NULL;
374   }
375   if (*p != '/') {
376     /* fill in today's month and year */
377     t->tm_mon = tm->tm_mon;
378     t->tm_year = tm->tm_year;
379     return p;
380   }
381   p++;
382   t->tm_mon = strtol (p, &p, 10) - 1;
383   if (t->tm_mon < 0 || t->tm_mon > 11) {
384     snprintf (err->data, err->dsize, _("Invalid month: %s"), p);
385     return NULL;
386   }
387   if (*p != '/') {
388     t->tm_year = tm->tm_year;
389     return p;
390   }
391   p++;
392   t->tm_year = strtol (p, &p, 10);
393   if (t->tm_year < 70)          /* year 2000+ */
394     t->tm_year += 100;
395   else if (t->tm_year > 1900)
396     t->tm_year -= 1900;
397   return p;
398 }
399
400 /* Ny   years
401    Nm   months
402    Nw   weeks
403    Nd   days */
404 static const char *get_offset (struct tm *tm, const char *s, int sign)
405 {
406   char *ps;
407   int offset = strtol (s, &ps, 0);
408
409   if ((sign < 0 && offset > 0) || (sign > 0 && offset < 0))
410     offset = -offset;
411
412   switch (*ps) {
413   case 'y':
414     tm->tm_year += offset;
415     break;
416   case 'm':
417     tm->tm_mon += offset;
418     break;
419   case 'w':
420     tm->tm_mday += 7 * offset;
421     break;
422   case 'd':
423     tm->tm_mday += offset;
424     break;
425   default:
426     return s;
427   }
428   mutt_normalize_time (tm);
429   return (ps + 1);
430 }
431
432 static void adjust_date_range (struct tm *min, struct tm *max)
433 {
434   if (min->tm_year > max->tm_year
435       || (min->tm_year == max->tm_year && min->tm_mon > max->tm_mon)
436       || (min->tm_year == max->tm_year && min->tm_mon == max->tm_mon
437           && min->tm_mday > max->tm_mday)) {
438     int tmp;
439
440     tmp = min->tm_year;
441     min->tm_year = max->tm_year;
442     max->tm_year = tmp;
443
444     tmp = min->tm_mon;
445     min->tm_mon = max->tm_mon;
446     max->tm_mon = tmp;
447
448     tmp = min->tm_mday;
449     min->tm_mday = max->tm_mday;
450     max->tm_mday = tmp;
451
452     min->tm_hour = min->tm_min = min->tm_sec = 0;
453     max->tm_hour = 23;
454     max->tm_min = max->tm_sec = 59;
455   }
456 }
457
458 static const char *parse_date_range (const char *pc, struct tm *min,
459                                      struct tm *max, int haveMin,
460                                      struct tm *baseMin, BUFFER * err)
461 {
462   int flag = M_PDR_NONE;
463
464   while (*pc && ((flag & M_PDR_DONE) == 0)) {
465     const char *pt;
466     char ch = *pc++;
467
468     pc = vskipspaces(pc);
469     switch (ch) {
470     case '-':
471       {
472         /* try a range of absolute date minus offset of Ndwmy */
473         pt = get_offset (min, pc, -1);
474         if (pc == pt) {
475           if (flag == M_PDR_NONE) {     /* nothing yet and no offset parsed => absolute date? */
476             if (!getDate (pc, max, err))
477               flag |= (M_PDR_ABSOLUTE | M_PDR_ERRORDONE);       /* done bad */
478             else {
479               /* reestablish initial base minimum if not specified */
480               if (!haveMin)
481                 memcpy (min, baseMin, sizeof (struct tm));
482               flag |= (M_PDR_ABSOLUTE | M_PDR_DONE);    /* done good */
483             }
484           }
485           else
486             flag |= M_PDR_ERRORDONE;
487         }
488         else {
489           pc = pt;
490           if (flag == M_PDR_NONE && !haveMin) { /* the very first "-3d" without a previous absolute date */
491             max->tm_year = min->tm_year;
492             max->tm_mon = min->tm_mon;
493             max->tm_mday = min->tm_mday;
494           }
495           flag |= M_PDR_MINUS;
496         }
497       }
498       break;
499     case '+':
500       {                         /* enlarge plusRange */
501         pt = get_offset (max, pc, 1);
502         if (pc == pt)
503           flag |= M_PDR_ERRORDONE;
504         else {
505           pc = pt;
506           flag |= M_PDR_PLUS;
507         }
508       }
509       break;
510     case '*':
511       {                         /* enlarge window in both directions */
512         pt = get_offset (min, pc, -1);
513         if (pc == pt)
514           flag |= M_PDR_ERRORDONE;
515         else {
516           pc = get_offset (max, pc, 1);
517           flag |= M_PDR_WINDOW;
518         }
519       }
520       break;
521     default:
522       flag |= M_PDR_ERRORDONE;
523     }
524     pc = vskipspaces(pc);
525   }
526   if ((flag & M_PDR_ERROR) && !(flag & M_PDR_ABSOLUTE)) {       /* getDate has its own error message, don't overwrite it here */
527     snprintf (err->data, err->dsize, _("Invalid relative date: %s"), pc - 1);
528   }
529   return ((flag & M_PDR_ERROR) ? NULL : pc);
530 }
531
532 static int eat_date (pattern_t * pat, BUFFER * s, BUFFER * err)
533 {
534   BUFFER buffer;
535   struct tm min, max;
536
537   p_clear(&buffer, 1);
538   if (mutt_extract_token (&buffer, s, M_TOKEN_COMMENT | M_TOKEN_PATTERN) != 0
539       || !buffer.data) {
540     m_strcpy(err->data, err->dsize, _("error in expression"));
541     return (-1);
542   }
543
544   p_clear(&min, 1);
545   /* the `0' time is Jan 1, 1970 UTC, so in order to prevent a negative time
546      when doing timezone conversion, we use Jan 2, 1970 UTC as the base
547      here */
548   min.tm_mday = 2;
549   min.tm_year = 70;
550
551   p_clear(&max, 1);
552
553   /* Arbitrary year in the future.  Don't set this too high
554      or mutt_mktime() returns something larger than will
555      fit in a time_t on some systems */
556   max.tm_year = 130;
557   max.tm_mon = 11;
558   max.tm_mday = 31;
559   max.tm_hour = 23;
560   max.tm_min = 59;
561   max.tm_sec = 59;
562
563   if (strchr ("<>=", buffer.data[0])) {
564     /* offset from current time
565        <3d      less than three days ago
566        >3d      more than three days ago
567        =3d      exactly three days ago */
568     time_t now = time (NULL);
569     struct tm *tm = localtime (&now);
570     int exact = 0;
571
572     if (buffer.data[0] == '<') {
573       memcpy (&min, tm, sizeof (min));
574       tm = &min;
575     }
576     else {
577       memcpy (&max, tm, sizeof (max));
578       tm = &max;
579
580       if (buffer.data[0] == '=')
581         exact++;
582     }
583     tm->tm_hour = 23;
584     tm->tm_min = tm->tm_sec = 59;
585
586     /* force negative offset */
587     get_offset (tm, buffer.data + 1, -1);
588
589     if (exact) {
590       /* start at the beginning of the day in question */
591       memcpy (&min, &max, sizeof (max));
592       min.tm_hour = min.tm_sec = min.tm_min = 0;
593     }
594   }
595   else {
596     const char *pc = buffer.data;
597
598     int haveMin = FALSE;
599     int untilNow = FALSE;
600
601     if (isdigit ((unsigned char) *pc)) {
602       /* mininum date specified */
603       if ((pc = getDate (pc, &min, err)) == NULL) {
604         p_delete(&buffer.data);
605         return (-1);
606       }
607       haveMin = TRUE;
608       pc = vskipspaces(pc);
609       if (*pc == '-') {
610         const char *pt;
611
612         pt = skipspaces(pc + 1);
613         untilNow = (*pt == '\0');
614       }
615     }
616
617     if (!untilNow) {            /* max date or relative range/window */
618
619       struct tm baseMin;
620
621       if (!haveMin) {           /* save base minimum and set current date, e.g. for "-3d+1d" */
622         time_t now = time (NULL);
623         struct tm *tm = localtime (&now);
624
625         memcpy (&baseMin, &min, sizeof (baseMin));
626         memcpy (&min, tm, sizeof (min));
627         min.tm_hour = min.tm_sec = min.tm_min = 0;
628       }
629
630       /* preset max date for relative offsets,
631          if nothing follows we search for messages on a specific day */
632       max.tm_year = min.tm_year;
633       max.tm_mon = min.tm_mon;
634       max.tm_mday = min.tm_mday;
635
636       if (!parse_date_range (pc, &min, &max, haveMin, &baseMin, err)) { /* bail out on any parsing error */
637         p_delete(&buffer.data);
638         return (-1);
639       }
640     }
641   }
642
643   /* Since we allow two dates to be specified we'll have to adjust that. */
644   adjust_date_range (&min, &max);
645
646   pat->min = mutt_mktime (&min, 1);
647   pat->max = mutt_mktime (&max, 1);
648
649   p_delete(&buffer.data);
650
651   return 0;
652 }
653
654 static struct pattern_flags *lookup_tag (char tag)
655 {
656   int i;
657
658   for (i = 0; Flags[i].tag; i++)
659     if (Flags[i].tag == tag)
660       return (&Flags[i]);
661   return NULL;
662 }
663
664 static /* const */ char *find_matching_paren ( /* const */ char *s)
665 {
666   int level = 1;
667
668   for (; *s; s++) {
669     if (*s == '(')
670       level++;
671     else if (*s == ')') {
672       level--;
673       if (!level)
674         break;
675     }
676   }
677   return s;
678 }
679
680 void mutt_pattern_free (pattern_t ** pat)
681 {
682   pattern_t *tmp;
683
684   while (*pat) {
685     tmp = *pat;
686     *pat = (*pat)->next;
687
688     if (tmp->rx) {
689       regfree (tmp->rx);
690       p_delete(&tmp->rx);
691     }
692     p_delete(&tmp->str);
693     if (tmp->child)
694       mutt_pattern_free (&tmp->child);
695     p_delete(&tmp);
696   }
697 }
698
699 pattern_t *mutt_pattern_comp ( /* const */ char *s, int flags, BUFFER * err)
700 {
701   pattern_t *curlist = NULL;
702   pattern_t *tmp;
703   pattern_t *last = NULL;
704   int not = 0;
705   int alladdr = 0;
706   int or = 0;
707   int implicit = 1;             /* used to detect logical AND operator */
708   struct pattern_flags *entry;
709   char *p;
710   char *buf;
711   BUFFER ps;
712
713   p_clear(&ps, 1);
714   ps.dptr = s;
715   ps.dsize = m_strlen(s);
716
717   while (*ps.dptr) {
718     ps.dptr = vskipspaces(ps.dptr);
719     switch (*ps.dptr) {
720     case '^':
721       ps.dptr++;
722       alladdr = !alladdr;
723       break;
724     case '!':
725       ps.dptr++;
726       not = !not;
727       break;
728     case '|':
729       if (!or) {
730         if (!curlist) {
731           snprintf (err->data, err->dsize, _("error in pattern at: %s"),
732                     ps.dptr);
733           return NULL;
734         }
735         if (curlist->next) {
736           /* A & B | C == (A & B) | C */
737           tmp = new_pattern ();
738           tmp->op = M_AND;
739           tmp->child = curlist;
740
741           curlist = tmp;
742           last = curlist;
743         }
744
745         or = 1;
746       }
747       ps.dptr++;
748       implicit = 0;
749       not = 0;
750       alladdr = 0;
751       break;
752     case '=':
753       /* fallthrough */
754     case '~':
755       if (implicit && or) {
756         /* A | B & C == (A | B) & C */
757         tmp = new_pattern ();
758         tmp->op = M_OR;
759         tmp->child = curlist;
760         curlist = tmp;
761         last = tmp;
762         or = 0;
763       }
764
765       tmp = new_pattern ();
766       tmp->not = not;
767       tmp->alladdr = alladdr;
768       tmp->stringmatch = (*ps.dptr == '=') ? 1 : 0;
769       not = 0;
770       alladdr = 0;
771
772       if (last)
773         last->next = tmp;
774       else
775         curlist = tmp;
776       last = tmp;
777
778       ps.dptr++;                /* move past the ~ */
779       if ((entry = lookup_tag (*ps.dptr)) == NULL) {
780         snprintf (err->data, err->dsize, _("%c: invalid command"), *ps.dptr);
781         mutt_pattern_free (&curlist);
782         return NULL;
783       }
784       if (entry->class && (flags & entry->class) == 0) {
785         snprintf (err->data, err->dsize, _("%c: not supported in this mode"),
786                   *ps.dptr);
787         mutt_pattern_free (&curlist);
788         return NULL;
789       }
790       tmp->op = entry->op;
791
792       ps.dptr = vskipspaces(ps.dptr + 1);
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 = p_dupstr(ps.dptr + 1, p - ps.dptr - 1);
817       if ((tmp = mutt_pattern_comp (buf, flags, err)) == NULL) {
818         p_delete(&buf);
819         mutt_pattern_free (&curlist);
820         return NULL;
821       }
822       p_delete(&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     m_strcpy(err->data, err->dsize, _("empty pattern"));
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 __attribute__ ((unused)),
874                           int n, ...)
875 {
876   va_list ap;
877   address_t *a;
878
879   va_start (ap, n);
880   for (; n; n--) {
881     for (a = va_arg (ap, address_t *); 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, string_list_t * 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_t * a1, address_t * 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_t * a1, address_t * 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_t * a1, address_t * 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     /* IMAP search sets h->matched at search compile time */
1001     if (ctx->magic == M_IMAP && pat->stringmatch)
1002       return (h->matched);
1003     return (pat->not ^ msg_search (ctx, pat, h->msgno));
1004   case M_SENDER:
1005     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1006                                       pat->alladdr, 1, h->env->sender));
1007   case M_FROM:
1008     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1009                                       pat->alladdr, 1, h->env->from));
1010   case M_TO:
1011     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1012                                       pat->alladdr, 1, h->env->to));
1013   case M_CC:
1014     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1015                                       pat->alladdr, 1, h->env->cc));
1016   case M_SUBJECT:
1017     return (pat->
1018             not ^ (h->env && h->env->subject
1019                    && patmatch (pat, h->env->subject) == 0));
1020   case M_ID:
1021     return (pat->
1022             not ^ (h->env && h->env->message_id
1023                    && patmatch (pat, h->env->message_id) == 0));
1024   case M_SCORE:
1025     return (pat->not ^ (h->score >= pat->min && (pat->max == M_MAXRANGE ||
1026                                                  h->score <= pat->max)));
1027   case M_SIZE:
1028     return (pat->
1029             not ^ (h->content->length >= pat->min
1030                    && (pat->max == M_MAXRANGE
1031                        || h->content->length <= pat->max)));
1032   case M_REFERENCE:
1033     return (pat->not ^ match_reference (pat, h->env->references));
1034   case M_ADDRESS:
1035     return (pat->
1036             not ^ (h->env
1037                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1038                                      pat->alladdr, 4, h->env->from,
1039                                      h->env->sender, h->env->to,
1040                                      h->env->cc)));
1041   case M_RECIPIENT:
1042     return (pat->
1043             not ^ (h->env
1044                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1045                                      pat->alladdr, 2, h->env->to,
1046                                      h->env->cc)));
1047   case M_LIST:
1048     return (pat->
1049             not ^ (h->env
1050                    && mutt_is_list_cc (pat->alladdr, h->env->to,
1051                                        h->env->cc)));
1052   case M_SUBSCRIBED_LIST:
1053     return (pat->
1054             not ^ (h->env
1055                    && mutt_is_list_recipient (pat->alladdr, h->env->to,
1056                                               h->env->cc)));
1057   case M_PERSONAL_RECIP:
1058     return (pat->
1059             not ^ (h->env
1060                    && match_user (pat->alladdr, h->env->to, h->env->cc)));
1061   case M_PERSONAL_FROM:
1062     return (pat->
1063             not ^ (h->env && match_user (pat->alladdr, h->env->from, NULL)));
1064   case M_COLLAPSED:
1065     return (pat->not ^ (h->collapsed && h->num_hidden > 1));
1066   case M_CRYPT_SIGN:
1067     return (pat->not ^ ((h->security & SIGN) ? 1 : 0));
1068   case M_CRYPT_VERIFIED:
1069     return (pat->not ^ ((h->security & GOODSIGN) ? 1 : 0));
1070   case M_CRYPT_ENCRYPT:
1071     return (pat->not ^ ((h->security & ENCRYPT) ? 1 : 0));
1072   case M_PGP_KEY:
1073     return (pat->not ^ ((h->security & APPLICATION_PGP)
1074                         && (h->security & PGPKEY)));
1075   case M_XLABEL:
1076     return (pat->
1077             not ^ (h->env->x_label
1078                    && patmatch (pat, h->env->x_label) == 0));
1079   case M_HORMEL:
1080     return (pat->
1081             not ^ (h->env->spam && h->env->spam->data
1082                    && patmatch (pat, h->env->spam->data) == 0));
1083   case M_DUPLICATED:
1084     return (pat->not ^ (h->thread && h->thread->duplicate_thread));
1085
1086   case M_MIMEATTACH:
1087     {
1088       int count;
1089       
1090       if (h->content->parts)
1091         count = mutt_count_body_parts(h, 0);
1092       else {
1093         mutt_parse_mime_message(ctx, h);
1094         count = mutt_count_body_parts(h, 0);
1095         mutt_free_body(&h->content->parts);
1096       }
1097       
1098       return (pat->not ^ (count >= pat->min && (pat->max == M_MAXRANGE ||
1099                                                 count <= pat->max)));
1100     }
1101
1102   case M_UNREFERENCED:
1103     return (pat->not ^ (h->thread && !h->thread->child));
1104   case M_MULTIPART:
1105     return (pat->not ^ (h->content && h->content->type == TYPEMULTIPART));
1106   case M_REALNAME:
1107     /* realname filter:
1108      * we have a match if
1109      * - From: matches $alternates
1110      * - or we have an alias for current address
1111      * - or From: contains valid email address _and_ name has >= 2 fields
1112      */
1113     return (h->env && h->env->from
1114         && (mutt_addr_is_user(h->env->from)
1115             || alias_reverse_lookup(Aliases, h->env->from)
1116             || (h->env->from->personal
1117                 && valid_realname(h->env-> from->personal)
1118                 && h->env->from->mailbox)
1119            )) ^ pat->not;
1120 #ifdef USE_NNTP
1121   case M_NEWSGROUPS:
1122     return (pat->
1123             not ^ (h->env->newsgroups
1124                    && patmatch (pat, h->env->newsgroups) == 0));
1125 #endif
1126   }
1127   mutt_error (_("error: unknown op %d (report this error)."), pat->op);
1128   return (-1);
1129 }
1130
1131 static void quote_simple (char *tmp, ssize_t len, const char *p)
1132 {
1133   ssize_t i = 0;
1134
1135   tmp[i++] = '"';
1136   while (*p && i < len - 3) {
1137     if (*p == '\\' || *p == '"')
1138       tmp[i++] = '\\';
1139     tmp[i++] = *p++;
1140   }
1141   tmp[i++] = '"';
1142   tmp[i] = 0;
1143 }
1144
1145 /* convert a simple search into a real request */
1146 void mutt_check_simple (char *s, size_t len, const char *simple)
1147 {
1148   char tmp[LONG_STRING];
1149
1150   /* XXX - is ascii_strcasecmp() right here, or should we use locale's
1151    * equivalences?
1152    */
1153
1154   if (!strchr (s, '~') && !strchr (s, '=')) {       /* yup, so spoof a real request */
1155     /* convert old tokens into the new format */
1156     if (ascii_strcasecmp ("all", s) == 0 || !m_strcmp("^", s) || !m_strcmp(".", s))     /* ~A is more efficient */
1157       m_strcpy(s, len, "~A");
1158     else if (ascii_strcasecmp ("del", s) == 0)
1159       m_strcpy(s, len, "~D");
1160     else if (ascii_strcasecmp ("flag", s) == 0)
1161       m_strcpy(s, len, "~F");
1162     else if (ascii_strcasecmp ("new", s) == 0)
1163       m_strcpy(s, len, "~N");
1164     else if (ascii_strcasecmp ("old", s) == 0)
1165       m_strcpy(s, len, "~O");
1166     else if (ascii_strcasecmp ("repl", s) == 0)
1167       m_strcpy(s, len, "~Q");
1168     else if (ascii_strcasecmp ("read", s) == 0)
1169       m_strcpy(s, len, "~R");
1170     else if (ascii_strcasecmp ("tag", s) == 0)
1171       m_strcpy(s, len, "~T");
1172     else if (ascii_strcasecmp ("unread", s) == 0)
1173       m_strcpy(s, len, "~U");
1174     else {
1175       quote_simple (tmp, sizeof (tmp), s);
1176       mutt_expand_fmt (s, len, simple, tmp);
1177     }
1178   }
1179 }
1180
1181 int mutt_pattern_func (int op, char *prompt)
1182 {
1183   pattern_t *pat;
1184   char buf[LONG_STRING] = "", *simple, error[STRING];
1185   BUFFER err;
1186   int i;
1187
1188   m_strcpy(buf, sizeof(buf), NONULL(Context->pattern));
1189   if (prompt || op != M_LIMIT)
1190     if (mutt_get_field (prompt, buf, sizeof (buf), M_PATTERN | M_CLEAR) != 0 || !buf[0])
1191       return (-1);
1192
1193   mutt_message _("Compiling search pattern...");
1194
1195   simple = m_strdup(buf);
1196   mutt_check_simple (buf, sizeof (buf), NONULL (SimpleSearch));
1197
1198   err.data = error;
1199   err.dsize = sizeof (error);
1200   if ((pat = mutt_pattern_comp (buf, M_FULL_MSG, &err)) == NULL) {
1201     p_delete(&simple);
1202     mutt_error ("%s", err.data);
1203     return (-1);
1204   }
1205
1206   if (Context->magic == M_IMAP && imap_search (Context, pat) < 0)
1207     return -1;
1208
1209   mutt_message _("Executing command on matching messages...");
1210
1211 #define THIS_BODY Context->hdrs[i]->content
1212
1213   if (op == M_LIMIT) {
1214     Context->vcount = 0;
1215     Context->vsize = 0;
1216     Context->collapsed = 0;
1217
1218     for (i = 0; i < Context->msgcount; i++) {
1219       /* new limit pattern implicitly uncollapses all threads */
1220       Context->hdrs[i]->virtual = -1;
1221       Context->hdrs[i]->limited = 0;
1222       Context->hdrs[i]->collapsed = 0;
1223       Context->hdrs[i]->num_hidden = 0;
1224       if (mutt_pattern_exec
1225           (pat, M_MATCH_FULL_ADDRESS, Context, Context->hdrs[i])) {
1226         Context->hdrs[i]->virtual = Context->vcount;
1227         Context->hdrs[i]->limited = 1;
1228         Context->v2r[Context->vcount] = i;
1229         Context->vcount++;
1230         Context->vsize += THIS_BODY->length + THIS_BODY->offset -
1231           THIS_BODY->hdr_offset;
1232       }
1233     }
1234   }
1235   else {
1236     for (i = 0; i < Context->vcount; i++) {
1237       if (mutt_pattern_exec
1238           (pat, M_MATCH_FULL_ADDRESS, Context,
1239            Context->hdrs[Context->v2r[i]])) {
1240         switch (op) {
1241         case M_UNDELETE:
1242           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_PURGED,
1243                          0);
1244         case M_DELETE:
1245           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_DELETE,
1246                          (op == M_DELETE));
1247           break;
1248         case M_TAG:
1249         case M_UNTAG:
1250           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_TAG,
1251                          (op == M_TAG));
1252           break;
1253         }
1254       }
1255     }
1256   }
1257
1258 #undef THIS_BODY
1259
1260   mutt_clear_error ();
1261
1262   if (op == M_LIMIT) {
1263     /* drop previous limit pattern */
1264     p_delete(&Context->pattern);
1265     if (Context->limit_pattern)
1266       mutt_pattern_free (&Context->limit_pattern);
1267     if (Context->msgcount && !Context->vcount) {
1268       mutt_error _("No messages matched criteria.");
1269     }
1270
1271     /* record new limit pattern, unless match all */
1272     if (m_strncmp(buf, "~A", 2) != 0) {
1273       Context->pattern = simple;
1274       simple = NULL;            /* don't clobber it */
1275       Context->limit_pattern = mutt_pattern_comp (buf, M_FULL_MSG, &err);
1276     }
1277   }
1278   p_delete(&simple);
1279   mutt_pattern_free (&pat);
1280   return 0;
1281 }
1282
1283 int mutt_search_command (int cur, int op)
1284 {
1285   int i, j;
1286   char buf[STRING];
1287   char temp[LONG_STRING];
1288   char error[STRING];
1289   BUFFER err;
1290   int incr;
1291   HEADER *h;
1292
1293   if (op != OP_SEARCH_NEXT && op != OP_SEARCH_OPPOSITE) {
1294     m_strcpy(buf, sizeof(buf), LastSearch);
1295     if (mutt_get_field ((op == OP_SEARCH) ? _("Search for: ") :
1296                         _("Reverse search for: "), buf, sizeof (buf),
1297                         M_CLEAR | M_PATTERN) != 0 || !buf[0])
1298       return (-1);
1299
1300     if (op == OP_SEARCH)
1301       unset_option (OPTSEARCHREVERSE);
1302     else
1303       set_option (OPTSEARCHREVERSE);
1304
1305     /* compare the *expanded* version of the search pattern in case 
1306        $simple_search has changed while we were searching */
1307     m_strcpy(temp, sizeof(temp), buf);
1308     mutt_check_simple (temp, sizeof (temp), NONULL (SimpleSearch));
1309
1310     if (!SearchPattern || m_strcmp(temp, LastSearchExpn)) {
1311       set_option (OPTSEARCHINVALID);
1312       m_strcpy(LastSearch, sizeof(LastSearch), buf);
1313       mutt_message _("Compiling search pattern...");
1314
1315       mutt_pattern_free (&SearchPattern);
1316       err.data = error;
1317       err.dsize = sizeof (error);
1318       if ((SearchPattern =
1319            mutt_pattern_comp (temp, M_FULL_MSG, &err)) == NULL) {
1320         mutt_error ("%s", error);
1321         return (-1);
1322       }
1323       mutt_clear_error ();
1324     }
1325   }
1326   else if (!SearchPattern) {
1327     mutt_error _("No search pattern.");
1328
1329     return (-1);
1330   }
1331
1332   if (option (OPTSEARCHINVALID)) {
1333     for (i = 0; i < Context->msgcount; i++)
1334       Context->hdrs[i]->searched = 0;
1335     if (Context->magic == M_IMAP && imap_search (Context, SearchPattern) < 0)
1336       return -1;
1337     unset_option (OPTSEARCHINVALID);
1338   }
1339
1340   incr = (option (OPTSEARCHREVERSE)) ? -1 : 1;
1341   if (op == OP_SEARCH_OPPOSITE)
1342     incr = -incr;
1343
1344   for (i = cur + incr, j = 0; j != Context->vcount; j++) {
1345     if (i > Context->vcount - 1) {
1346       i = 0;
1347       if (option (OPTWRAPSEARCH))
1348         mutt_message (_("Search wrapped to top."));
1349
1350       else {
1351         mutt_message _("Search hit bottom without finding match");
1352
1353         return (-1);
1354       }
1355     }
1356     else if (i < 0) {
1357       i = Context->vcount - 1;
1358       if (option (OPTWRAPSEARCH))
1359         mutt_message (_("Search wrapped to bottom."));
1360
1361       else {
1362         mutt_message _("Search hit top without finding match");
1363
1364         return (-1);
1365       }
1366     }
1367
1368     h = Context->hdrs[Context->v2r[i]];
1369     if (h->searched) {
1370       /* if we've already evaulated this message, use the cached value */
1371       if (h->matched)
1372         return i;
1373     }
1374     else {
1375       /* remember that we've already searched this message */
1376       h->searched = 1;
1377       if ((h->matched =
1378            (mutt_pattern_exec
1379             (SearchPattern, M_MATCH_FULL_ADDRESS, Context, h) > 0)))
1380         return i;
1381     }
1382
1383     if (SigInt) {
1384       mutt_error _("Search interrupted.");
1385
1386       SigInt = 0;
1387       return (-1);
1388     }
1389
1390     i += incr;
1391   }
1392
1393   mutt_error _("Not found.");
1394
1395   return (-1);
1396 }