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