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