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