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