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