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