missing file
[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   SKIPWS (tmp);
363   s->dptr = tmp;
364   return 0;
365 }
366
367 static const char *getDate (const char *s, struct tm *t, BUFFER * err)
368 {
369   char *p;
370   time_t now = time (NULL);
371   struct tm *tm = localtime (&now);
372
373   t->tm_mday = strtol (s, &p, 10);
374   if (t->tm_mday < 1 || t->tm_mday > 31) {
375     snprintf (err->data, err->dsize, _("Invalid day of month: %s"), s);
376     return NULL;
377   }
378   if (*p != '/') {
379     /* fill in today's month and year */
380     t->tm_mon = tm->tm_mon;
381     t->tm_year = tm->tm_year;
382     return p;
383   }
384   p++;
385   t->tm_mon = strtol (p, &p, 10) - 1;
386   if (t->tm_mon < 0 || t->tm_mon > 11) {
387     snprintf (err->data, err->dsize, _("Invalid month: %s"), p);
388     return NULL;
389   }
390   if (*p != '/') {
391     t->tm_year = tm->tm_year;
392     return p;
393   }
394   p++;
395   t->tm_year = strtol (p, &p, 10);
396   if (t->tm_year < 70)          /* year 2000+ */
397     t->tm_year += 100;
398   else if (t->tm_year > 1900)
399     t->tm_year -= 1900;
400   return p;
401 }
402
403 /* Ny   years
404    Nm   months
405    Nw   weeks
406    Nd   days */
407 static const char *get_offset (struct tm *tm, const char *s, int sign)
408 {
409   char *ps;
410   int offset = strtol (s, &ps, 0);
411
412   if ((sign < 0 && offset > 0) || (sign > 0 && offset < 0))
413     offset = -offset;
414
415   switch (*ps) {
416   case 'y':
417     tm->tm_year += offset;
418     break;
419   case 'm':
420     tm->tm_mon += offset;
421     break;
422   case 'w':
423     tm->tm_mday += 7 * offset;
424     break;
425   case 'd':
426     tm->tm_mday += offset;
427     break;
428   default:
429     return s;
430   }
431   mutt_normalize_time (tm);
432   return (ps + 1);
433 }
434
435 static void adjust_date_range (struct tm *min, struct tm *max)
436 {
437   if (min->tm_year > max->tm_year
438       || (min->tm_year == max->tm_year && min->tm_mon > max->tm_mon)
439       || (min->tm_year == max->tm_year && min->tm_mon == max->tm_mon
440           && min->tm_mday > max->tm_mday)) {
441     int tmp;
442
443     tmp = min->tm_year;
444     min->tm_year = max->tm_year;
445     max->tm_year = tmp;
446
447     tmp = min->tm_mon;
448     min->tm_mon = max->tm_mon;
449     max->tm_mon = tmp;
450
451     tmp = min->tm_mday;
452     min->tm_mday = max->tm_mday;
453     max->tm_mday = tmp;
454
455     min->tm_hour = min->tm_min = min->tm_sec = 0;
456     max->tm_hour = 23;
457     max->tm_min = max->tm_sec = 59;
458   }
459 }
460
461 static const char *parse_date_range (const char *pc, struct tm *min,
462                                      struct tm *max, int haveMin,
463                                      struct tm *baseMin, BUFFER * err)
464 {
465   int flag = M_PDR_NONE;
466
467   while (*pc && ((flag & M_PDR_DONE) == 0)) {
468     const char *pt;
469     char ch = *pc++;
470
471     SKIPWS (pc);
472     switch (ch) {
473     case '-':
474       {
475         /* try a range of absolute date minus offset of Ndwmy */
476         pt = get_offset (min, pc, -1);
477         if (pc == pt) {
478           if (flag == M_PDR_NONE) {     /* nothing yet and no offset parsed => absolute date? */
479             if (!getDate (pc, max, err))
480               flag |= (M_PDR_ABSOLUTE | M_PDR_ERRORDONE);       /* done bad */
481             else {
482               /* reestablish initial base minimum if not specified */
483               if (!haveMin)
484                 memcpy (min, baseMin, sizeof (struct tm));
485               flag |= (M_PDR_ABSOLUTE | M_PDR_DONE);    /* done good */
486             }
487           }
488           else
489             flag |= M_PDR_ERRORDONE;
490         }
491         else {
492           pc = pt;
493           if (flag == M_PDR_NONE && !haveMin) { /* the very first "-3d" without a previous absolute date */
494             max->tm_year = min->tm_year;
495             max->tm_mon = min->tm_mon;
496             max->tm_mday = min->tm_mday;
497           }
498           flag |= M_PDR_MINUS;
499         }
500       }
501       break;
502     case '+':
503       {                         /* enlarge plusRange */
504         pt = get_offset (max, pc, 1);
505         if (pc == pt)
506           flag |= M_PDR_ERRORDONE;
507         else {
508           pc = pt;
509           flag |= M_PDR_PLUS;
510         }
511       }
512       break;
513     case '*':
514       {                         /* enlarge window in both directions */
515         pt = get_offset (min, pc, -1);
516         if (pc == pt)
517           flag |= M_PDR_ERRORDONE;
518         else {
519           pc = get_offset (max, pc, 1);
520           flag |= M_PDR_WINDOW;
521         }
522       }
523       break;
524     default:
525       flag |= M_PDR_ERRORDONE;
526     }
527     SKIPWS (pc);
528   }
529   if ((flag & M_PDR_ERROR) && !(flag & M_PDR_ABSOLUTE)) {       /* getDate has its own error message, don't overwrite it here */
530     snprintf (err->data, err->dsize, _("Invalid relative date: %s"), pc - 1);
531   }
532   return ((flag & M_PDR_ERROR) ? NULL : pc);
533 }
534
535 static int eat_date (pattern_t * pat, BUFFER * s, BUFFER * err)
536 {
537   BUFFER buffer;
538   struct tm min, max;
539
540   p_clear(&buffer, 1);
541   if (mutt_extract_token (&buffer, s, M_TOKEN_COMMENT | M_TOKEN_PATTERN) != 0
542       || !buffer.data) {
543     strfcpy (err->data, _("error in expression"), err->dsize);
544     return (-1);
545   }
546
547   p_clear(&min, 1);
548   /* the `0' time is Jan 1, 1970 UTC, so in order to prevent a negative time
549      when doing timezone conversion, we use Jan 2, 1970 UTC as the base
550      here */
551   min.tm_mday = 2;
552   min.tm_year = 70;
553
554   p_clear(&max, 1);
555
556   /* Arbitrary year in the future.  Don't set this too high
557      or mutt_mktime() returns something larger than will
558      fit in a time_t on some systems */
559   max.tm_year = 130;
560   max.tm_mon = 11;
561   max.tm_mday = 31;
562   max.tm_hour = 23;
563   max.tm_min = 59;
564   max.tm_sec = 59;
565
566   if (strchr ("<>=", buffer.data[0])) {
567     /* offset from current time
568        <3d      less than three days ago
569        >3d      more than three days ago
570        =3d      exactly three days ago */
571     time_t now = time (NULL);
572     struct tm *tm = localtime (&now);
573     int exact = 0;
574
575     if (buffer.data[0] == '<') {
576       memcpy (&min, tm, sizeof (min));
577       tm = &min;
578     }
579     else {
580       memcpy (&max, tm, sizeof (max));
581       tm = &max;
582
583       if (buffer.data[0] == '=')
584         exact++;
585     }
586     tm->tm_hour = 23;
587     tm->tm_min = tm->tm_sec = 59;
588
589     /* force negative offset */
590     get_offset (tm, buffer.data + 1, -1);
591
592     if (exact) {
593       /* start at the beginning of the day in question */
594       memcpy (&min, &max, sizeof (max));
595       min.tm_hour = min.tm_sec = min.tm_min = 0;
596     }
597   }
598   else {
599     const char *pc = buffer.data;
600
601     int haveMin = FALSE;
602     int untilNow = FALSE;
603
604     if (isdigit ((unsigned char) *pc)) {
605       /* mininum date specified */
606       if ((pc = getDate (pc, &min, err)) == NULL) {
607         p_delete(&buffer.data);
608         return (-1);
609       }
610       haveMin = TRUE;
611       SKIPWS (pc);
612       if (*pc == '-') {
613         const char *pt = pc + 1;
614
615         SKIPWS (pt);
616         untilNow = (*pt == '\0');
617       }
618     }
619
620     if (!untilNow) {            /* max date or relative range/window */
621
622       struct tm baseMin;
623
624       if (!haveMin) {           /* save base minimum and set current date, e.g. for "-3d+1d" */
625         time_t now = time (NULL);
626         struct tm *tm = localtime (&now);
627
628         memcpy (&baseMin, &min, sizeof (baseMin));
629         memcpy (&min, tm, sizeof (min));
630         min.tm_hour = min.tm_sec = min.tm_min = 0;
631       }
632
633       /* preset max date for relative offsets,
634          if nothing follows we search for messages on a specific day */
635       max.tm_year = min.tm_year;
636       max.tm_mon = min.tm_mon;
637       max.tm_mday = min.tm_mday;
638
639       if (!parse_date_range (pc, &min, &max, haveMin, &baseMin, err)) { /* bail out on any parsing error */
640         p_delete(&buffer.data);
641         return (-1);
642       }
643     }
644   }
645
646   /* Since we allow two dates to be specified we'll have to adjust that. */
647   adjust_date_range (&min, &max);
648
649   pat->min = mutt_mktime (&min, 1);
650   pat->max = mutt_mktime (&max, 1);
651
652   p_delete(&buffer.data);
653
654   return 0;
655 }
656
657 static struct pattern_flags *lookup_tag (char tag)
658 {
659   int i;
660
661   for (i = 0; Flags[i].tag; i++)
662     if (Flags[i].tag == tag)
663       return (&Flags[i]);
664   return NULL;
665 }
666
667 static /* const */ char *find_matching_paren ( /* const */ char *s)
668 {
669   int level = 1;
670
671   for (; *s; s++) {
672     if (*s == '(')
673       level++;
674     else if (*s == ')') {
675       level--;
676       if (!level)
677         break;
678     }
679   }
680   return s;
681 }
682
683 void mutt_pattern_free (pattern_t ** pat)
684 {
685   pattern_t *tmp;
686
687   while (*pat) {
688     tmp = *pat;
689     *pat = (*pat)->next;
690
691     if (tmp->rx) {
692       regfree (tmp->rx);
693       p_delete(&tmp->rx);
694     }
695     p_delete(&tmp->str);
696     if (tmp->child)
697       mutt_pattern_free (&tmp->child);
698     p_delete(&tmp);
699   }
700 }
701
702 pattern_t *mutt_pattern_comp ( /* const */ char *s, int flags, BUFFER * err)
703 {
704   pattern_t *curlist = NULL;
705   pattern_t *tmp;
706   pattern_t *last = NULL;
707   int not = 0;
708   int alladdr = 0;
709   int or = 0;
710   int implicit = 1;             /* used to detect logical AND operator */
711   struct pattern_flags *entry;
712   char *p;
713   char *buf;
714   BUFFER ps;
715
716   p_clear(&ps, 1);
717   ps.dptr = s;
718   ps.dsize = m_strlen(s);
719
720   while (*ps.dptr) {
721     SKIPWS (ps.dptr);
722     switch (*ps.dptr) {
723     case '^':
724       ps.dptr++;
725       alladdr = !alladdr;
726       break;
727     case '!':
728       ps.dptr++;
729       not = !not;
730       break;
731     case '|':
732       if (!or) {
733         if (!curlist) {
734           snprintf (err->data, err->dsize, _("error in pattern at: %s"),
735                     ps.dptr);
736           return NULL;
737         }
738         if (curlist->next) {
739           /* A & B | C == (A & B) | C */
740           tmp = new_pattern ();
741           tmp->op = M_AND;
742           tmp->child = curlist;
743
744           curlist = tmp;
745           last = curlist;
746         }
747
748         or = 1;
749       }
750       ps.dptr++;
751       implicit = 0;
752       not = 0;
753       alladdr = 0;
754       break;
755     case '=':
756       /* fallthrough */
757     case '~':
758       if (implicit && or) {
759         /* A | B & C == (A | B) & C */
760         tmp = new_pattern ();
761         tmp->op = M_OR;
762         tmp->child = curlist;
763         curlist = tmp;
764         last = tmp;
765         or = 0;
766       }
767
768       tmp = new_pattern ();
769       tmp->not = not;
770       tmp->alladdr = alladdr;
771       tmp->stringmatch = (*ps.dptr == '=') ? 1 : 0;
772       not = 0;
773       alladdr = 0;
774
775       if (last)
776         last->next = tmp;
777       else
778         curlist = tmp;
779       last = tmp;
780
781       ps.dptr++;                /* move past the ~ */
782       if ((entry = lookup_tag (*ps.dptr)) == NULL) {
783         snprintf (err->data, err->dsize, _("%c: invalid command"), *ps.dptr);
784         mutt_pattern_free (&curlist);
785         return NULL;
786       }
787       if (entry->class && (flags & entry->class) == 0) {
788         snprintf (err->data, err->dsize, _("%c: not supported in this mode"),
789                   *ps.dptr);
790         mutt_pattern_free (&curlist);
791         return NULL;
792       }
793       tmp->op = entry->op;
794
795       ps.dptr++;                /* eat the operator and any optional whitespace */
796       SKIPWS (ps.dptr);
797
798       if (entry->eat_arg) {
799         if (!*ps.dptr) {
800           snprintf (err->data, err->dsize, _("missing parameter"));
801           mutt_pattern_free (&curlist);
802           return NULL;
803         }
804         if (entry->eat_arg (tmp, &ps, err) == -1) {
805           mutt_pattern_free (&curlist);
806           return NULL;
807         }
808       }
809       implicit = 1;
810       break;
811     case '(':
812       p = find_matching_paren (ps.dptr + 1);
813       if (*p != ')') {
814         snprintf (err->data, err->dsize, _("mismatched parenthesis: %s"),
815                   ps.dptr);
816         mutt_pattern_free (&curlist);
817         return NULL;
818       }
819       /* compile the sub-expression */
820       buf = str_substrdup (ps.dptr + 1, p);
821       if ((tmp = mutt_pattern_comp (buf, flags, err)) == NULL) {
822         p_delete(&buf);
823         mutt_pattern_free (&curlist);
824         return NULL;
825       }
826       p_delete(&buf);
827       if (last)
828         last->next = tmp;
829       else
830         curlist = tmp;
831       last = tmp;
832       tmp->not ^= not;
833       tmp->alladdr |= alladdr;
834       not = 0;
835       alladdr = 0;
836       ps.dptr = p + 1;          /* restore location */
837       break;
838     default:
839       snprintf (err->data, err->dsize, _("error in pattern at: %s"), ps.dptr);
840       mutt_pattern_free (&curlist);
841       return NULL;
842     }
843   }
844   if (!curlist) {
845     strfcpy (err->data, _("empty pattern"), err->dsize);
846     return NULL;
847   }
848   if (curlist->next) {
849     tmp = new_pattern ();
850     tmp->op = or ? M_OR : M_AND;
851     tmp->child = curlist;
852     curlist = tmp;
853   }
854   return (curlist);
855 }
856
857 static int
858 perform_and (pattern_t * pat, pattern_exec_flag flags, CONTEXT * ctx,
859              HEADER * hdr)
860 {
861   for (; pat; pat = pat->next)
862     if (mutt_pattern_exec (pat, flags, ctx, hdr) <= 0)
863       return 0;
864   return 1;
865 }
866
867 static int
868 perform_or (struct pattern_t *pat, pattern_exec_flag flags, CONTEXT * ctx,
869             HEADER * hdr)
870 {
871   for (; pat; pat = pat->next)
872     if (mutt_pattern_exec (pat, flags, ctx, hdr) > 0)
873       return 1;
874   return 0;
875 }
876
877 static int match_adrlist (pattern_t* pat, int match_personal, int alladdr,
878                           int n, ...)
879 {
880   va_list ap;
881   ADDRESS *a;
882
883   va_start (ap, n);
884   for (; n; n--) {
885     for (a = va_arg (ap, ADDRESS *); a; a = a->next) {
886       if (pat->alladdr ^
887           ((a->mailbox && patmatch (pat, a->mailbox) == 0) ||
888            (match_personal && a->personal &&
889             patmatch (pat, a->personal) == 0))) {
890         va_end (ap);
891         return (!pat->alladdr);      /* Found match, or non-match if alladdr */
892       }
893     }
894   }
895   va_end (ap);
896   return pat->alladdr;               /* No matches, or all matches if alladdr */
897 }
898
899 static int match_reference (pattern_t* pat, LIST * refs)
900 {
901   for (; refs; refs = refs->next)
902     if (patmatch (pat, refs->data) == 0)
903       return 1;
904   return 0;
905 }
906
907 int mutt_is_list_recipient (int alladdr, ADDRESS * a1, ADDRESS * a2)
908 {
909   for (; a1; a1 = a1->next)
910     if (alladdr ^ mutt_is_subscribed_list (a1))
911       return (!alladdr);
912   for (; a2; a2 = a2->next)
913     if (alladdr ^ mutt_is_subscribed_list (a2))
914       return (!alladdr);
915   return alladdr;
916 }
917
918 int mutt_is_list_cc (int alladdr, ADDRESS * a1, ADDRESS * a2)
919 {
920   for (; a1; a1 = a1->next)
921     if (alladdr ^ mutt_is_mail_list (a1))
922       return (!alladdr);
923   for (; a2; a2 = a2->next)
924     if (alladdr ^ mutt_is_mail_list (a2))
925       return (!alladdr);
926   return alladdr;
927 }
928
929 static int match_user (int alladdr, ADDRESS * a1, ADDRESS * a2)
930 {
931   for (; a1; a1 = a1->next)
932     if (alladdr ^ mutt_addr_is_user (a1))
933       return (!alladdr);
934   for (; a2; a2 = a2->next)
935     if (alladdr ^ mutt_addr_is_user (a2))
936       return (!alladdr);
937   return alladdr;
938 }
939
940 /* test if name is considered a real name, i.e. consists of at least 2
941  * space-separated words of which none may end in a dot
942  */
943 static int valid_realname (const char *name)
944 {
945   const char *p = name;
946   int ret = 0;
947
948   while (*p) {
949     if (isspace (*p))
950       ret++;
951     else if (*p == '.')
952       /* skip abbr. parts of names (e.g. 'J. User') */
953       ret--;
954     p++;
955   }
956   return (ret >= 1);
957 }
958
959 /* flags
960         M_MATCH_FULL_ADDRESS    match both personal and machine address */
961 int
962 mutt_pattern_exec (struct pattern_t *pat, pattern_exec_flag flags,
963                    CONTEXT * ctx, HEADER * h)
964 {
965   switch (pat->op) {
966   case M_AND:
967     return (pat->not ^ (perform_and (pat->child, flags, ctx, h) > 0));
968   case M_OR:
969     return (pat->not ^ (perform_or (pat->child, flags, ctx, h) > 0));
970   case M_ALL:
971     return (!pat->not);
972   case M_EXPIRED:
973     return (pat->not ^ h->expired);
974   case M_SUPERSEDED:
975     return (pat->not ^ h->superseded);
976   case M_FLAG:
977     return (pat->not ^ h->flagged);
978   case M_TAG:
979     return (pat->not ^ h->tagged);
980   case M_NEW:
981     return (pat->not ? h->old || h->read : !(h->old || h->read));
982   case M_UNREAD:
983     return (pat->not ? h->read : !h->read);
984   case M_REPLIED:
985     return (pat->not ^ h->replied);
986   case M_OLD:
987     return (pat->not ? (!h->old || h->read) : (h->old && !h->read));
988   case M_READ:
989     return (pat->not ^ h->read);
990   case M_DELETED:
991     return (pat->not ^ h->deleted);
992   case M_MESSAGE:
993     return (pat->not ^ (h->msgno >= pat->min - 1 && (pat->max == M_MAXRANGE ||
994                                                      h->msgno <=
995                                                      pat->max - 1)));
996   case M_DATE:
997     return (pat->
998             not ^ (h->date_sent >= pat->min && h->date_sent <= pat->max));
999   case M_DATE_RECEIVED:
1000     return (pat->not ^ (h->received >= pat->min && h->received <= pat->max));
1001   case M_BODY:
1002   case M_HEADER:
1003   case M_WHOLE_MSG:
1004 #ifdef USE_IMAP
1005     /* IMAP search sets h->matched at search compile time */
1006     if (ctx->magic == M_IMAP && pat->stringmatch)
1007       return (h->matched);
1008 #endif
1009     return (pat->not ^ msg_search (ctx, pat, h->msgno));
1010   case M_SENDER:
1011     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1012                                       pat->alladdr, 1, h->env->sender));
1013   case M_FROM:
1014     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1015                                       pat->alladdr, 1, h->env->from));
1016   case M_TO:
1017     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1018                                       pat->alladdr, 1, h->env->to));
1019   case M_CC:
1020     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1021                                       pat->alladdr, 1, h->env->cc));
1022   case M_SUBJECT:
1023     return (pat->
1024             not ^ (h->env && h->env->subject
1025                    && patmatch (pat, h->env->subject) == 0));
1026   case M_ID:
1027     return (pat->
1028             not ^ (h->env && h->env->message_id
1029                    && patmatch (pat, h->env->message_id) == 0));
1030   case M_SCORE:
1031     return (pat->not ^ (h->score >= pat->min && (pat->max == M_MAXRANGE ||
1032                                                  h->score <= pat->max)));
1033   case M_SIZE:
1034     return (pat->
1035             not ^ (h->content->length >= pat->min
1036                    && (pat->max == M_MAXRANGE
1037                        || h->content->length <= pat->max)));
1038   case M_REFERENCE:
1039     return (pat->not ^ match_reference (pat, h->env->references));
1040   case M_ADDRESS:
1041     return (pat->
1042             not ^ (h->env
1043                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1044                                      pat->alladdr, 4, h->env->from,
1045                                      h->env->sender, h->env->to,
1046                                      h->env->cc)));
1047   case M_RECIPIENT:
1048     return (pat->
1049             not ^ (h->env
1050                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1051                                      pat->alladdr, 2, h->env->to,
1052                                      h->env->cc)));
1053   case M_LIST:
1054     return (pat->
1055             not ^ (h->env
1056                    && mutt_is_list_cc (pat->alladdr, h->env->to,
1057                                        h->env->cc)));
1058   case M_SUBSCRIBED_LIST:
1059     return (pat->
1060             not ^ (h->env
1061                    && mutt_is_list_recipient (pat->alladdr, h->env->to,
1062                                               h->env->cc)));
1063   case M_PERSONAL_RECIP:
1064     return (pat->
1065             not ^ (h->env
1066                    && match_user (pat->alladdr, h->env->to, h->env->cc)));
1067   case M_PERSONAL_FROM:
1068     return (pat->
1069             not ^ (h->env && match_user (pat->alladdr, h->env->from, NULL)));
1070   case M_COLLAPSED:
1071     return (pat->not ^ (h->collapsed && h->num_hidden > 1));
1072   case M_CRYPT_SIGN:
1073     if (!WithCrypto)
1074       break;
1075     return (pat->not ^ ((h->security & SIGN) ? 1 : 0));
1076   case M_CRYPT_VERIFIED:
1077     if (!WithCrypto)
1078       break;
1079     return (pat->not ^ ((h->security & GOODSIGN) ? 1 : 0));
1080   case M_CRYPT_ENCRYPT:
1081     if (!WithCrypto)
1082       break;
1083     return (pat->not ^ ((h->security & ENCRYPT) ? 1 : 0));
1084   case M_PGP_KEY:
1085     if (!(WithCrypto & APPLICATION_PGP))
1086       break;
1087     return (pat->not ^ ((h->security & APPLICATION_PGP)
1088                         && (h->security & PGPKEY)));
1089   case M_XLABEL:
1090     return (pat->
1091             not ^ (h->env->x_label
1092                    && patmatch (pat, h->env->x_label) == 0));
1093   case M_HORMEL:
1094     return (pat->
1095             not ^ (h->env->spam && h->env->spam->data
1096                    && patmatch (pat, h->env->spam->data) == 0));
1097   case M_DUPLICATED:
1098     return (pat->not ^ (h->thread && h->thread->duplicate_thread));
1099
1100   case M_MIMEATTACH:
1101     {
1102       int count;
1103       
1104       if (h->content->parts)
1105         count = mutt_count_body_parts(h, 0);
1106       else {
1107         mutt_parse_mime_message(ctx, h);
1108         count = mutt_count_body_parts(h, 0);
1109         mutt_free_body(&h->content->parts);
1110       }
1111       
1112       return (pat->not ^ (count >= pat->min && (pat->max == M_MAXRANGE ||
1113                                                 count <= pat->max)));
1114     }
1115
1116   case M_UNREFERENCED:
1117     return (pat->not ^ (h->thread && !h->thread->child));
1118   case M_MULTIPART:
1119     return (pat->not ^ (h->content && h->content->type == TYPEMULTIPART));
1120   case M_REALNAME:
1121     /* realname filter:
1122      * we have a match if
1123      * - From: matches $alternates
1124      * - or we have an alias for current address
1125      * - or From: contains valid email address _and_ name has >= 2 fields
1126      */
1127     return (pat->
1128             not ^ (h->env && h->env->from && (mutt_addr_is_user (h->env->from)
1129                                               ||
1130                                               (alias_reverse_lookup
1131                                                (h->env->from) != NULL)
1132                                               || (h->env->from->personal
1133                                                   && valid_realname (h->env->
1134                                                                      from->
1135                                                                      personal)
1136                                                   && h->env->from->mailbox)
1137                    )));
1138 #ifdef USE_NNTP
1139   case M_NEWSGROUPS:
1140     return (pat->
1141             not ^ (h->env->newsgroups
1142                    && patmatch (pat, h->env->newsgroups) == 0));
1143 #endif
1144   }
1145   mutt_error (_("error: unknown op %d (report this error)."), pat->op);
1146   return (-1);
1147 }
1148
1149 static void quote_simple (char *tmp, size_t len, const char *p)
1150 {
1151   int i = 0;
1152
1153   tmp[i++] = '"';
1154   while (*p && i < len - 3) {
1155     if (*p == '\\' || *p == '"')
1156       tmp[i++] = '\\';
1157     tmp[i++] = *p++;
1158   }
1159   tmp[i++] = '"';
1160   tmp[i] = 0;
1161 }
1162
1163 /* convert a simple search into a real request */
1164 void mutt_check_simple (char *s, size_t len, const char *simple)
1165 {
1166   char tmp[LONG_STRING];
1167
1168   /* XXX - is ascii_strcasecmp() right here, or should we use locale's
1169    * equivalences?
1170    */
1171
1172   if (!strchr (s, '~') && !strchr (s, '=')) {       /* yup, so spoof a real request */
1173     /* convert old tokens into the new format */
1174     if (ascii_strcasecmp ("all", s) == 0 || !m_strcmp("^", s) || !m_strcmp(".", s))     /* ~A is more efficient */
1175       strfcpy (s, "~A", len);
1176     else if (ascii_strcasecmp ("del", s) == 0)
1177       strfcpy (s, "~D", len);
1178     else if (ascii_strcasecmp ("flag", s) == 0)
1179       strfcpy (s, "~F", len);
1180     else if (ascii_strcasecmp ("new", s) == 0)
1181       strfcpy (s, "~N", len);
1182     else if (ascii_strcasecmp ("old", s) == 0)
1183       strfcpy (s, "~O", len);
1184     else if (ascii_strcasecmp ("repl", s) == 0)
1185       strfcpy (s, "~Q", len);
1186     else if (ascii_strcasecmp ("read", s) == 0)
1187       strfcpy (s, "~R", len);
1188     else if (ascii_strcasecmp ("tag", s) == 0)
1189       strfcpy (s, "~T", len);
1190     else if (ascii_strcasecmp ("unread", s) == 0)
1191       strfcpy (s, "~U", len);
1192     else {
1193       quote_simple (tmp, sizeof (tmp), s);
1194       mutt_expand_fmt (s, len, simple, tmp);
1195     }
1196   }
1197 }
1198
1199 int mutt_pattern_func (int op, char *prompt)
1200 {
1201   pattern_t *pat;
1202   char buf[LONG_STRING] = "", *simple, error[STRING];
1203   BUFFER err;
1204   int i;
1205
1206   strfcpy (buf, NONULL (Context->pattern), sizeof (buf));
1207   if (prompt || op != M_LIMIT)
1208     if (mutt_get_field (prompt, buf, sizeof (buf), M_PATTERN | M_CLEAR) != 0 || !buf[0])
1209       return (-1);
1210
1211   mutt_message _("Compiling search pattern...");
1212
1213   simple = m_strdup(buf);
1214   mutt_check_simple (buf, sizeof (buf), NONULL (SimpleSearch));
1215
1216   err.data = error;
1217   err.dsize = sizeof (error);
1218   if ((pat = mutt_pattern_comp (buf, M_FULL_MSG, &err)) == NULL) {
1219     p_delete(&simple);
1220     mutt_error ("%s", err.data);
1221     return (-1);
1222   }
1223
1224 #ifdef USE_IMAP
1225   if (Context->magic == M_IMAP && imap_search (Context, pat) < 0)
1226     return -1;
1227 #endif
1228
1229   mutt_message _("Executing command on matching messages...");
1230
1231 #define THIS_BODY Context->hdrs[i]->content
1232
1233   if (op == M_LIMIT) {
1234     Context->vcount = 0;
1235     Context->vsize = 0;
1236     Context->collapsed = 0;
1237
1238     for (i = 0; i < Context->msgcount; i++) {
1239       /* new limit pattern implicitly uncollapses all threads */
1240       Context->hdrs[i]->virtual = -1;
1241       Context->hdrs[i]->limited = 0;
1242       Context->hdrs[i]->collapsed = 0;
1243       Context->hdrs[i]->num_hidden = 0;
1244       if (mutt_pattern_exec
1245           (pat, M_MATCH_FULL_ADDRESS, Context, Context->hdrs[i])) {
1246         Context->hdrs[i]->virtual = Context->vcount;
1247         Context->hdrs[i]->limited = 1;
1248         Context->v2r[Context->vcount] = i;
1249         Context->vcount++;
1250         Context->vsize += THIS_BODY->length + THIS_BODY->offset -
1251           THIS_BODY->hdr_offset;
1252       }
1253     }
1254   }
1255   else {
1256     for (i = 0; i < Context->vcount; i++) {
1257       if (mutt_pattern_exec
1258           (pat, M_MATCH_FULL_ADDRESS, Context,
1259            Context->hdrs[Context->v2r[i]])) {
1260         switch (op) {
1261         case M_UNDELETE:
1262           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_PURGED,
1263                          0);
1264         case M_DELETE:
1265           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_DELETE,
1266                          (op == M_DELETE));
1267           break;
1268         case M_TAG:
1269         case M_UNTAG:
1270           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_TAG,
1271                          (op == M_TAG));
1272           break;
1273         }
1274       }
1275     }
1276   }
1277
1278 #undef THIS_BODY
1279
1280   mutt_clear_error ();
1281
1282   if (op == M_LIMIT) {
1283     /* drop previous limit pattern */
1284     p_delete(&Context->pattern);
1285     if (Context->limit_pattern)
1286       mutt_pattern_free (&Context->limit_pattern);
1287     if (Context->msgcount && !Context->vcount) {
1288       mutt_error _("No messages matched criteria.");
1289     }
1290
1291     /* record new limit pattern, unless match all */
1292     if (str_ncmp (buf, "~A", 2) != 0) {
1293       Context->pattern = simple;
1294       simple = NULL;            /* don't clobber it */
1295       Context->limit_pattern = mutt_pattern_comp (buf, M_FULL_MSG, &err);
1296     }
1297   }
1298   p_delete(&simple);
1299   mutt_pattern_free (&pat);
1300   return 0;
1301 }
1302
1303 int mutt_search_command (int cur, int op)
1304 {
1305   int i, j;
1306   char buf[STRING];
1307   char temp[LONG_STRING];
1308   char error[STRING];
1309   BUFFER err;
1310   int incr;
1311   HEADER *h;
1312
1313   if (op != OP_SEARCH_NEXT && op != OP_SEARCH_OPPOSITE) {
1314     strfcpy (buf, LastSearch, sizeof (buf));
1315     if (mutt_get_field ((op == OP_SEARCH) ? _("Search for: ") :
1316                         _("Reverse search for: "), buf, sizeof (buf),
1317                         M_CLEAR | M_PATTERN) != 0 || !buf[0])
1318       return (-1);
1319
1320     if (op == OP_SEARCH)
1321       unset_option (OPTSEARCHREVERSE);
1322     else
1323       set_option (OPTSEARCHREVERSE);
1324
1325     /* compare the *expanded* version of the search pattern in case 
1326        $simple_search has changed while we were searching */
1327     strfcpy (temp, buf, sizeof (temp));
1328     mutt_check_simple (temp, sizeof (temp), NONULL (SimpleSearch));
1329
1330     if (!SearchPattern || m_strcmp(temp, LastSearchExpn)) {
1331       set_option (OPTSEARCHINVALID);
1332       strfcpy (LastSearch, buf, sizeof (LastSearch));
1333       mutt_message _("Compiling search pattern...");
1334
1335       mutt_pattern_free (&SearchPattern);
1336       err.data = error;
1337       err.dsize = sizeof (error);
1338       if ((SearchPattern =
1339            mutt_pattern_comp (temp, M_FULL_MSG, &err)) == NULL) {
1340         mutt_error ("%s", error);
1341         return (-1);
1342       }
1343       mutt_clear_error ();
1344     }
1345   }
1346   else if (!SearchPattern) {
1347     mutt_error _("No search pattern.");
1348
1349     return (-1);
1350   }
1351
1352   if (option (OPTSEARCHINVALID)) {
1353     for (i = 0; i < Context->msgcount; i++)
1354       Context->hdrs[i]->searched = 0;
1355 #ifdef USE_IMAP
1356     if (Context->magic == M_IMAP && imap_search (Context, SearchPattern) < 0)
1357       return -1;
1358 #endif
1359     unset_option (OPTSEARCHINVALID);
1360   }
1361
1362   incr = (option (OPTSEARCHREVERSE)) ? -1 : 1;
1363   if (op == OP_SEARCH_OPPOSITE)
1364     incr = -incr;
1365
1366   for (i = cur + incr, j = 0; j != Context->vcount; j++) {
1367     if (i > Context->vcount - 1) {
1368       i = 0;
1369       if (option (OPTWRAPSEARCH))
1370         mutt_message (_("Search wrapped to top."));
1371
1372       else {
1373         mutt_message _("Search hit bottom without finding match");
1374
1375         return (-1);
1376       }
1377     }
1378     else if (i < 0) {
1379       i = Context->vcount - 1;
1380       if (option (OPTWRAPSEARCH))
1381         mutt_message (_("Search wrapped to bottom."));
1382
1383       else {
1384         mutt_message _("Search hit top without finding match");
1385
1386         return (-1);
1387       }
1388     }
1389
1390     h = Context->hdrs[Context->v2r[i]];
1391     if (h->searched) {
1392       /* if we've already evaulated this message, use the cached value */
1393       if (h->matched)
1394         return i;
1395     }
1396     else {
1397       /* remember that we've already searched this message */
1398       h->searched = 1;
1399       if ((h->matched =
1400            (mutt_pattern_exec
1401             (SearchPattern, M_MATCH_FULL_ADDRESS, Context, h) > 0)))
1402         return i;
1403     }
1404
1405     if (SigInt) {
1406       mutt_error _("Search interrupted.");
1407
1408       SigInt = 0;
1409       return (-1);
1410     }
1411
1412     i += incr;
1413   }
1414
1415   mutt_error _("Not found.");
1416
1417   return (-1);
1418 }