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