less and less cruft: always compile socket support in
[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 #include <lib-lib/mapping.h>
21
22 #include <lib-mime/mime.h>
23
24 #include "mutt.h"
25 #include "handler.h"
26 #include "enter.h"
27 #include "mx.h"
28 #include "keymap.h"
29 #include "copy.h"
30
31
32 #ifdef USE_IMAP
33 #include "mx.h"
34 #include "imap/imap.h"
35 #endif
36
37 #include <string.h>
38 #include <stdlib.h>
39 #include <ctype.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
42 #include <stdarg.h>
43
44 #include "mutt_crypt.h"
45
46 static int eat_regexp (pattern_t * pat, BUFFER *, BUFFER *);
47 static int eat_date (pattern_t * pat, BUFFER *, BUFFER *);
48 static int eat_range (pattern_t * pat, BUFFER *, BUFFER *);
49 static int patmatch (const pattern_t* pat, const char* buf);
50
51 struct pattern_flags {
52   int tag;                      /* character used to represent this op */
53   int op;                       /* operation to perform */
54   int class;
55   int (*eat_arg) (pattern_t *, BUFFER *, BUFFER *);
56 } Flags[] = {
57   {
58   'A', M_ALL, 0, NULL}, {
59   'b', M_BODY, M_FULL_MSG, eat_regexp}, {
60   'B', M_WHOLE_MSG, M_FULL_MSG, eat_regexp}, {
61   'c', M_CC, 0, eat_regexp}, {
62   'C', M_RECIPIENT, 0, eat_regexp}, {
63   'd', M_DATE, 0, eat_date}, {
64   'D', M_DELETED, 0, NULL}, {
65   'e', M_SENDER, 0, eat_regexp}, {
66   'E', M_EXPIRED, 0, NULL}, {
67   'f', M_FROM, 0, eat_regexp}, {
68   'F', M_FLAG, 0, NULL}, {
69   'g', M_CRYPT_SIGN, 0, NULL}, {
70   'G', M_CRYPT_ENCRYPT, 0, NULL}, {
71   'h', M_HEADER, M_FULL_MSG, eat_regexp}, {
72   'H', M_HORMEL, 0, eat_regexp}, {
73   'i', M_ID, 0, eat_regexp}, {
74   'k', M_PGP_KEY, 0, NULL}, {
75   'L', M_ADDRESS, 0, eat_regexp}, {
76   'l', M_LIST, 0, NULL}, {
77   'm', M_MESSAGE, 0, eat_range}, {
78   'M', M_MULTIPART, 0, NULL}, {
79   'n', M_SCORE, 0, eat_range}, {
80   'N', M_NEW, 0, NULL}, {
81   'O', M_OLD, 0, NULL}, {
82   'p', M_PERSONAL_RECIP, 0, NULL}, {
83   'P', M_PERSONAL_FROM, 0, NULL}, {
84   'Q', M_REPLIED, 0, NULL}, {
85   'R', M_READ, 0, NULL}, {
86   'r', M_DATE_RECEIVED, 0, eat_date}, {
87   's', M_SUBJECT, 0, eat_regexp}, {
88   'S', M_SUPERSEDED, 0, NULL}, {
89   'T', M_TAG, 0, NULL}, {
90   't', M_TO, 0, eat_regexp}, {
91   'U', M_UNREAD, 0, NULL}, {
92   'u', M_SUBSCRIBED_LIST, 0, NULL}, {
93   'v', M_COLLAPSED, 0, NULL}, {
94   'V', M_CRYPT_VERIFIED, 0, NULL},
95 #ifdef USE_NNTP
96   {
97   'w', M_NEWSGROUPS, 0, eat_regexp},
98 #endif
99   {
100   'x', M_REFERENCE, 0, eat_regexp}, {
101   'X', M_MIMEATTACH, 0, eat_range}, {
102   'y', M_XLABEL, 0, eat_regexp}, {
103   'z', M_SIZE, 0, eat_range}, {
104   '=', M_DUPLICATED, 0, NULL}, {
105   '$', M_UNREFERENCED, 0, NULL}, {
106   '*', M_REALNAME, 0, NULL}, {
107   0, 0, 0, NULL}
108 };
109
110 static pattern_t *SearchPattern = NULL; /* current search pattern */
111 static char LastSearch[STRING] = { 0 }; /* last pattern searched for */
112 static char LastSearchExpn[LONG_STRING] = { 0 };        /* expanded version of
113                                                            LastSearch */
114
115 #define M_MAXRANGE -1
116
117 /* constants for parse_date_range() */
118 #define M_PDR_NONE      0x0000
119 #define M_PDR_MINUS     0x0001
120 #define M_PDR_PLUS      0x0002
121 #define M_PDR_WINDOW    0x0004
122 #define M_PDR_ABSOLUTE  0x0008
123 #define M_PDR_DONE      0x0010
124 #define M_PDR_ERROR     0x0100
125 #define M_PDR_ERRORDONE (M_PDR_ERROR | M_PDR_DONE)
126
127
128 int mutt_getvaluebychar (char ch, struct mapping_t *table)
129 {
130   int i;
131
132   for (i = 0; table[i].name; i++) {
133     if (ch == table[i].name[0])
134       return table[i].value;
135   }
136
137   return (-1);
138 }
139
140 /* if no uppercase letters are given, do a case-insensitive search */
141 int mutt_which_case (const char *s)
142 {
143   while (*s) {
144     if (isalpha ((unsigned char) *s) && isupper ((unsigned char) *s))
145       return 0;                 /* case-sensitive */
146     s++;
147   }
148   return REG_ICASE;             /* case-insensitive */
149 }
150
151 static int
152 msg_search (CONTEXT *ctx, pattern_t* pat, int msgno)
153 {
154   char tempfile[_POSIX_PATH_MAX];
155   MESSAGE *msg = NULL;
156   STATE s;
157   struct stat st;
158   FILE *fp = NULL;
159   long lng = 0;
160   int match = 0;
161   HEADER *h = ctx->hdrs[msgno];
162   char* buf;
163   size_t blen;
164
165   if ((msg = mx_open_message (ctx, msgno)) != NULL) {
166     if (option (OPTTHOROUGHSRC)) {
167       /* decode the header / body */
168       p_clear(&s, 1);
169       s.fpin = msg->fp;
170       s.flags = M_CHARCONV;
171       mutt_mktemp (tempfile);
172       if ((s.fpout = safe_fopen (tempfile, "w+")) == NULL) {
173         mutt_perror (tempfile);
174         return (0);
175       }
176
177       if (pat->op != M_BODY)
178         mutt_copy_header (msg->fp, h, s.fpout, CH_FROM | CH_DECODE, NULL);
179
180       if (pat->op != M_HEADER) {
181         mutt_parse_mime_message (ctx, h);
182
183         if ((h->security & ENCRYPT) && !crypt_valid_passphrase (h->security))
184         {
185           mx_close_message (&msg);
186           if (fp) {
187             fclose (fp);
188             unlink (tempfile);
189           }
190           return (0);
191         }
192
193         fseeko (msg->fp, h->offset, 0);
194         mutt_body_handler (h->content, &s);
195       }
196
197       fp = s.fpout;
198       fflush (fp);
199       fseeko (fp, 0, 0);
200       fstat (fileno (fp), &st);
201       lng = (long) st.st_size;
202     }
203     else {
204       /* raw header / body */
205       fp = msg->fp;
206       if (pat->op != M_BODY) {
207         fseeko (fp, h->offset, 0);
208         lng = h->content->offset - h->offset;
209       }
210       if (pat->op != M_HEADER) {
211         if (pat->op == M_BODY)
212           fseeko (fp, h->content->offset, 0);
213         lng += h->content->length;
214       }
215     }
216
217     buf = p_new(char, blen = STRING);
218
219     /* search the file "fp" */
220     while (lng > 0) {
221       if (pat->op == M_HEADER) {
222         if (*(buf = mutt_read_rfc822_line (fp, buf, &blen)) == '\0')
223           break;
224       } else if (fgets (buf, blen - 1, fp) == NULL)
225         break;                  /* don't loop forever */
226       if (patmatch (pat, buf) == 0) {
227         match = 1;
228         break;
229       }
230       lng -= m_strlen(buf);
231     }
232
233     p_delete(&buf);
234
235     mx_close_message (&msg);
236
237     if (option (OPTTHOROUGHSRC)) {
238       fclose (fp);
239       unlink (tempfile);
240     }
241   }
242
243   return match;
244 }
245
246 int eat_regexp (pattern_t * pat, BUFFER * s, BUFFER * err)
247 {
248   BUFFER buf;
249   int r;
250
251   p_clear(&buf, 1);
252
253   if (mutt_extract_token (&buf, s, M_TOKEN_PATTERN | M_TOKEN_COMMENT) != 0 ||
254       !buf.data) {
255     snprintf (err->data, err->dsize, _("Error in expression: %s"), s->dptr);
256     return (-1);
257   }
258
259   if (!*buf.data) {
260     snprintf (err->data, err->dsize, _("Empty expression"));
261     return (-1);
262   }
263
264 #if 0
265  /* If there are no RE metacharacters, use simple search anyway */
266   if (!pat->stringmatch && !strpbrk (buf.data, "|[{.*+?^$"))
267     pat->stringmatch = 1;
268 #endif
269
270   if (pat->stringmatch) {
271     pat->str = m_strdup(buf.data);
272     p_delete(&buf.data);
273   } else {
274     pat->rx = p_new(regex_t, 1);
275     r = REGCOMP (pat->rx, buf.data, REG_NEWLINE | REG_NOSUB | mutt_which_case (buf.data));
276     p_delete(&buf.data);
277     if (r) {
278       regerror (r, pat->rx, err->data, err->dsize);
279       regfree (pat->rx);
280       p_delete(&pat->rx);
281       return (-1);
282     }
283   }
284   return 0;
285 }
286
287 static int patmatch (const pattern_t* pat, const char* buf) {
288   if (pat->stringmatch)
289     return !strstr (buf, pat->str);
290   else
291     return regexec (pat->rx, buf, 0, NULL, 0);
292 }
293
294 int eat_range (pattern_t * pat, BUFFER * s, BUFFER * err)
295 {
296   char *tmp;
297   int do_exclusive = 0;
298   int skip_quote = 0;
299
300   /*
301    * If simple_search is set to "~m %s", the range will have double quotes 
302    * around it...
303    */
304   if (*s->dptr == '"') {
305     s->dptr++;
306     skip_quote = 1;
307   }
308   if (*s->dptr == '<')
309     do_exclusive = 1;
310   if ((*s->dptr != '-') && (*s->dptr != '<')) {
311     /* range minimum */
312     if (*s->dptr == '>') {
313       pat->max = M_MAXRANGE;
314       pat->min = strtol (s->dptr + 1, &tmp, 0) + 1;     /* exclusive range */
315     }
316     else
317       pat->min = strtol (s->dptr, &tmp, 0);
318     if (toupper ((unsigned char) *tmp) == 'K') {        /* is there a prefix? */
319       pat->min *= 1024;
320       tmp++;
321     }
322     else if (toupper ((unsigned char) *tmp) == 'M') {
323       pat->min *= 1048576;
324       tmp++;
325     }
326     if (*s->dptr == '>') {
327       s->dptr = tmp;
328       return 0;
329     }
330     if (*tmp != '-') {
331       /* exact value */
332       pat->max = pat->min;
333       s->dptr = tmp;
334       return 0;
335     }
336     tmp++;
337   }
338   else {
339     s->dptr++;
340     tmp = s->dptr;
341   }
342
343   if (isdigit ((unsigned char) *tmp)) {
344     /* range maximum */
345     pat->max = strtol (tmp, &tmp, 0);
346     if (toupper ((unsigned char) *tmp) == 'K') {
347       pat->max *= 1024;
348       tmp++;
349     }
350     else if (toupper ((unsigned char) *tmp) == 'M') {
351       pat->max *= 1048576;
352       tmp++;
353     }
354     if (do_exclusive)
355       (pat->max)--;
356   }
357   else
358     pat->max = M_MAXRANGE;
359
360   if (skip_quote && *tmp == '"')
361     tmp++;
362
363   s->dptr = vskipspaces(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     pc = vskipspaces(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     pc = vskipspaces(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     m_strcpy(err->data, err->dsize, _("error in expression"));
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       pc = vskipspaces(pc);
612       if (*pc == '-') {
613         const char *pt;
614
615         pt = skipspaces(pc + 1);
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     ps.dptr = vskipspaces(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 = vskipspaces(ps.dptr + 1);
796
797       if (entry->eat_arg) {
798         if (!*ps.dptr) {
799           snprintf (err->data, err->dsize, _("missing parameter"));
800           mutt_pattern_free (&curlist);
801           return NULL;
802         }
803         if (entry->eat_arg (tmp, &ps, err) == -1) {
804           mutt_pattern_free (&curlist);
805           return NULL;
806         }
807       }
808       implicit = 1;
809       break;
810     case '(':
811       p = find_matching_paren (ps.dptr + 1);
812       if (*p != ')') {
813         snprintf (err->data, err->dsize, _("mismatched parenthesis: %s"),
814                   ps.dptr);
815         mutt_pattern_free (&curlist);
816         return NULL;
817       }
818       /* compile the sub-expression */
819       buf = p_dupstr(ps.dptr + 1, p - ps.dptr - 1);
820       if ((tmp = mutt_pattern_comp (buf, flags, err)) == NULL) {
821         p_delete(&buf);
822         mutt_pattern_free (&curlist);
823         return NULL;
824       }
825       p_delete(&buf);
826       if (last)
827         last->next = tmp;
828       else
829         curlist = tmp;
830       last = tmp;
831       tmp->not ^= not;
832       tmp->alladdr |= alladdr;
833       not = 0;
834       alladdr = 0;
835       ps.dptr = p + 1;          /* restore location */
836       break;
837     default:
838       snprintf (err->data, err->dsize, _("error in pattern at: %s"), ps.dptr);
839       mutt_pattern_free (&curlist);
840       return NULL;
841     }
842   }
843   if (!curlist) {
844     m_strcpy(err->data, err->dsize, _("empty pattern"));
845     return NULL;
846   }
847   if (curlist->next) {
848     tmp = new_pattern ();
849     tmp->op = or ? M_OR : M_AND;
850     tmp->child = curlist;
851     curlist = tmp;
852   }
853   return (curlist);
854 }
855
856 static int
857 perform_and (pattern_t * pat, pattern_exec_flag flags, CONTEXT * ctx,
858              HEADER * hdr)
859 {
860   for (; pat; pat = pat->next)
861     if (mutt_pattern_exec (pat, flags, ctx, hdr) <= 0)
862       return 0;
863   return 1;
864 }
865
866 static int
867 perform_or (struct pattern_t *pat, pattern_exec_flag flags, CONTEXT * ctx,
868             HEADER * hdr)
869 {
870   for (; pat; pat = pat->next)
871     if (mutt_pattern_exec (pat, flags, ctx, hdr) > 0)
872       return 1;
873   return 0;
874 }
875
876 static int match_adrlist (pattern_t* pat, int match_personal, int alladdr,
877                           int n, ...)
878 {
879   va_list ap;
880   address_t *a;
881
882   va_start (ap, n);
883   for (; n; n--) {
884     for (a = va_arg (ap, address_t *); a; a = a->next) {
885       if (pat->alladdr ^
886           ((a->mailbox && patmatch (pat, a->mailbox) == 0) ||
887            (match_personal && a->personal &&
888             patmatch (pat, a->personal) == 0))) {
889         va_end (ap);
890         return (!pat->alladdr);      /* Found match, or non-match if alladdr */
891       }
892     }
893   }
894   va_end (ap);
895   return pat->alladdr;               /* No matches, or all matches if alladdr */
896 }
897
898 static int match_reference (pattern_t* pat, LIST * refs)
899 {
900   for (; refs; refs = refs->next)
901     if (patmatch (pat, refs->data) == 0)
902       return 1;
903   return 0;
904 }
905
906 int mutt_is_list_recipient (int alladdr, address_t * a1, address_t * a2)
907 {
908   for (; a1; a1 = a1->next)
909     if (alladdr ^ mutt_is_subscribed_list (a1))
910       return (!alladdr);
911   for (; a2; a2 = a2->next)
912     if (alladdr ^ mutt_is_subscribed_list (a2))
913       return (!alladdr);
914   return alladdr;
915 }
916
917 int mutt_is_list_cc (int alladdr, address_t * a1, address_t * a2)
918 {
919   for (; a1; a1 = a1->next)
920     if (alladdr ^ mutt_is_mail_list (a1))
921       return (!alladdr);
922   for (; a2; a2 = a2->next)
923     if (alladdr ^ mutt_is_mail_list (a2))
924       return (!alladdr);
925   return alladdr;
926 }
927
928 static int match_user (int alladdr, address_t * a1, address_t * a2)
929 {
930   for (; a1; a1 = a1->next)
931     if (alladdr ^ mutt_addr_is_user (a1))
932       return (!alladdr);
933   for (; a2; a2 = a2->next)
934     if (alladdr ^ mutt_addr_is_user (a2))
935       return (!alladdr);
936   return alladdr;
937 }
938
939 /* test if name is considered a real name, i.e. consists of at least 2
940  * space-separated words of which none may end in a dot
941  */
942 static int valid_realname (const char *name)
943 {
944   const char *p = name;
945   int ret = 0;
946
947   while (*p) {
948     if (isspace (*p))
949       ret++;
950     else if (*p == '.')
951       /* skip abbr. parts of names (e.g. 'J. User') */
952       ret--;
953     p++;
954   }
955   return (ret >= 1);
956 }
957
958 /* flags
959         M_MATCH_FULL_ADDRESS    match both personal and machine address */
960 int
961 mutt_pattern_exec (struct pattern_t *pat, pattern_exec_flag flags,
962                    CONTEXT * ctx, HEADER * h)
963 {
964   switch (pat->op) {
965   case M_AND:
966     return (pat->not ^ (perform_and (pat->child, flags, ctx, h) > 0));
967   case M_OR:
968     return (pat->not ^ (perform_or (pat->child, flags, ctx, h) > 0));
969   case M_ALL:
970     return (!pat->not);
971   case M_EXPIRED:
972     return (pat->not ^ h->expired);
973   case M_SUPERSEDED:
974     return (pat->not ^ h->superseded);
975   case M_FLAG:
976     return (pat->not ^ h->flagged);
977   case M_TAG:
978     return (pat->not ^ h->tagged);
979   case M_NEW:
980     return (pat->not ? h->old || h->read : !(h->old || h->read));
981   case M_UNREAD:
982     return (pat->not ? h->read : !h->read);
983   case M_REPLIED:
984     return (pat->not ^ h->replied);
985   case M_OLD:
986     return (pat->not ? (!h->old || h->read) : (h->old && !h->read));
987   case M_READ:
988     return (pat->not ^ h->read);
989   case M_DELETED:
990     return (pat->not ^ h->deleted);
991   case M_MESSAGE:
992     return (pat->not ^ (h->msgno >= pat->min - 1 && (pat->max == M_MAXRANGE ||
993                                                      h->msgno <=
994                                                      pat->max - 1)));
995   case M_DATE:
996     return (pat->
997             not ^ (h->date_sent >= pat->min && h->date_sent <= pat->max));
998   case M_DATE_RECEIVED:
999     return (pat->not ^ (h->received >= pat->min && h->received <= pat->max));
1000   case M_BODY:
1001   case M_HEADER:
1002   case M_WHOLE_MSG:
1003 #ifdef USE_IMAP
1004     /* IMAP search sets h->matched at search compile time */
1005     if (ctx->magic == M_IMAP && pat->stringmatch)
1006       return (h->matched);
1007 #endif
1008     return (pat->not ^ msg_search (ctx, pat, h->msgno));
1009   case M_SENDER:
1010     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1011                                       pat->alladdr, 1, h->env->sender));
1012   case M_FROM:
1013     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1014                                       pat->alladdr, 1, h->env->from));
1015   case M_TO:
1016     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1017                                       pat->alladdr, 1, h->env->to));
1018   case M_CC:
1019     return (pat->not ^ match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1020                                       pat->alladdr, 1, h->env->cc));
1021   case M_SUBJECT:
1022     return (pat->
1023             not ^ (h->env && h->env->subject
1024                    && patmatch (pat, h->env->subject) == 0));
1025   case M_ID:
1026     return (pat->
1027             not ^ (h->env && h->env->message_id
1028                    && patmatch (pat, h->env->message_id) == 0));
1029   case M_SCORE:
1030     return (pat->not ^ (h->score >= pat->min && (pat->max == M_MAXRANGE ||
1031                                                  h->score <= pat->max)));
1032   case M_SIZE:
1033     return (pat->
1034             not ^ (h->content->length >= pat->min
1035                    && (pat->max == M_MAXRANGE
1036                        || h->content->length <= pat->max)));
1037   case M_REFERENCE:
1038     return (pat->not ^ match_reference (pat, h->env->references));
1039   case M_ADDRESS:
1040     return (pat->
1041             not ^ (h->env
1042                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1043                                      pat->alladdr, 4, h->env->from,
1044                                      h->env->sender, h->env->to,
1045                                      h->env->cc)));
1046   case M_RECIPIENT:
1047     return (pat->
1048             not ^ (h->env
1049                    && match_adrlist (pat, flags & M_MATCH_FULL_ADDRESS,
1050                                      pat->alladdr, 2, h->env->to,
1051                                      h->env->cc)));
1052   case M_LIST:
1053     return (pat->
1054             not ^ (h->env
1055                    && mutt_is_list_cc (pat->alladdr, h->env->to,
1056                                        h->env->cc)));
1057   case M_SUBSCRIBED_LIST:
1058     return (pat->
1059             not ^ (h->env
1060                    && mutt_is_list_recipient (pat->alladdr, h->env->to,
1061                                               h->env->cc)));
1062   case M_PERSONAL_RECIP:
1063     return (pat->
1064             not ^ (h->env
1065                    && match_user (pat->alladdr, h->env->to, h->env->cc)));
1066   case M_PERSONAL_FROM:
1067     return (pat->
1068             not ^ (h->env && match_user (pat->alladdr, h->env->from, NULL)));
1069   case M_COLLAPSED:
1070     return (pat->not ^ (h->collapsed && h->num_hidden > 1));
1071   case M_CRYPT_SIGN:
1072     return (pat->not ^ ((h->security & SIGN) ? 1 : 0));
1073   case M_CRYPT_VERIFIED:
1074     return (pat->not ^ ((h->security & GOODSIGN) ? 1 : 0));
1075   case M_CRYPT_ENCRYPT:
1076     return (pat->not ^ ((h->security & ENCRYPT) ? 1 : 0));
1077   case M_PGP_KEY:
1078     return (pat->not ^ ((h->security & APPLICATION_PGP)
1079                         && (h->security & PGPKEY)));
1080   case M_XLABEL:
1081     return (pat->
1082             not ^ (h->env->x_label
1083                    && patmatch (pat, h->env->x_label) == 0));
1084   case M_HORMEL:
1085     return (pat->
1086             not ^ (h->env->spam && h->env->spam->data
1087                    && patmatch (pat, h->env->spam->data) == 0));
1088   case M_DUPLICATED:
1089     return (pat->not ^ (h->thread && h->thread->duplicate_thread));
1090
1091   case M_MIMEATTACH:
1092     {
1093       int count;
1094       
1095       if (h->content->parts)
1096         count = mutt_count_body_parts(h, 0);
1097       else {
1098         mutt_parse_mime_message(ctx, h);
1099         count = mutt_count_body_parts(h, 0);
1100         mutt_free_body(&h->content->parts);
1101       }
1102       
1103       return (pat->not ^ (count >= pat->min && (pat->max == M_MAXRANGE ||
1104                                                 count <= pat->max)));
1105     }
1106
1107   case M_UNREFERENCED:
1108     return (pat->not ^ (h->thread && !h->thread->child));
1109   case M_MULTIPART:
1110     return (pat->not ^ (h->content && h->content->type == TYPEMULTIPART));
1111   case M_REALNAME:
1112     /* realname filter:
1113      * we have a match if
1114      * - From: matches $alternates
1115      * - or we have an alias for current address
1116      * - or From: contains valid email address _and_ name has >= 2 fields
1117      */
1118     return (pat->
1119             not ^ (h->env && h->env->from && (mutt_addr_is_user (h->env->from)
1120                                               ||
1121                                               (alias_reverse_lookup
1122                                                (h->env->from) != NULL)
1123                                               || (h->env->from->personal
1124                                                   && valid_realname (h->env->
1125                                                                      from->
1126                                                                      personal)
1127                                                   && h->env->from->mailbox)
1128                    )));
1129 #ifdef USE_NNTP
1130   case M_NEWSGROUPS:
1131     return (pat->
1132             not ^ (h->env->newsgroups
1133                    && patmatch (pat, h->env->newsgroups) == 0));
1134 #endif
1135   }
1136   mutt_error (_("error: unknown op %d (report this error)."), pat->op);
1137   return (-1);
1138 }
1139
1140 static void quote_simple (char *tmp, size_t len, const char *p)
1141 {
1142   int i = 0;
1143
1144   tmp[i++] = '"';
1145   while (*p && i < len - 3) {
1146     if (*p == '\\' || *p == '"')
1147       tmp[i++] = '\\';
1148     tmp[i++] = *p++;
1149   }
1150   tmp[i++] = '"';
1151   tmp[i] = 0;
1152 }
1153
1154 /* convert a simple search into a real request */
1155 void mutt_check_simple (char *s, size_t len, const char *simple)
1156 {
1157   char tmp[LONG_STRING];
1158
1159   /* XXX - is ascii_strcasecmp() right here, or should we use locale's
1160    * equivalences?
1161    */
1162
1163   if (!strchr (s, '~') && !strchr (s, '=')) {       /* yup, so spoof a real request */
1164     /* convert old tokens into the new format */
1165     if (ascii_strcasecmp ("all", s) == 0 || !m_strcmp("^", s) || !m_strcmp(".", s))     /* ~A is more efficient */
1166       m_strcpy(s, len, "~A");
1167     else if (ascii_strcasecmp ("del", s) == 0)
1168       m_strcpy(s, len, "~D");
1169     else if (ascii_strcasecmp ("flag", s) == 0)
1170       m_strcpy(s, len, "~F");
1171     else if (ascii_strcasecmp ("new", s) == 0)
1172       m_strcpy(s, len, "~N");
1173     else if (ascii_strcasecmp ("old", s) == 0)
1174       m_strcpy(s, len, "~O");
1175     else if (ascii_strcasecmp ("repl", s) == 0)
1176       m_strcpy(s, len, "~Q");
1177     else if (ascii_strcasecmp ("read", s) == 0)
1178       m_strcpy(s, len, "~R");
1179     else if (ascii_strcasecmp ("tag", s) == 0)
1180       m_strcpy(s, len, "~T");
1181     else if (ascii_strcasecmp ("unread", s) == 0)
1182       m_strcpy(s, len, "~U");
1183     else {
1184       quote_simple (tmp, sizeof (tmp), s);
1185       mutt_expand_fmt (s, len, simple, tmp);
1186     }
1187   }
1188 }
1189
1190 int mutt_pattern_func (int op, char *prompt)
1191 {
1192   pattern_t *pat;
1193   char buf[LONG_STRING] = "", *simple, error[STRING];
1194   BUFFER err;
1195   int i;
1196
1197   m_strcpy(buf, sizeof(buf), NONULL(Context->pattern));
1198   if (prompt || op != M_LIMIT)
1199     if (mutt_get_field (prompt, buf, sizeof (buf), M_PATTERN | M_CLEAR) != 0 || !buf[0])
1200       return (-1);
1201
1202   mutt_message _("Compiling search pattern...");
1203
1204   simple = m_strdup(buf);
1205   mutt_check_simple (buf, sizeof (buf), NONULL (SimpleSearch));
1206
1207   err.data = error;
1208   err.dsize = sizeof (error);
1209   if ((pat = mutt_pattern_comp (buf, M_FULL_MSG, &err)) == NULL) {
1210     p_delete(&simple);
1211     mutt_error ("%s", err.data);
1212     return (-1);
1213   }
1214
1215 #ifdef USE_IMAP
1216   if (Context->magic == M_IMAP && imap_search (Context, pat) < 0)
1217     return -1;
1218 #endif
1219
1220   mutt_message _("Executing command on matching messages...");
1221
1222 #define THIS_BODY Context->hdrs[i]->content
1223
1224   if (op == M_LIMIT) {
1225     Context->vcount = 0;
1226     Context->vsize = 0;
1227     Context->collapsed = 0;
1228
1229     for (i = 0; i < Context->msgcount; i++) {
1230       /* new limit pattern implicitly uncollapses all threads */
1231       Context->hdrs[i]->virtual = -1;
1232       Context->hdrs[i]->limited = 0;
1233       Context->hdrs[i]->collapsed = 0;
1234       Context->hdrs[i]->num_hidden = 0;
1235       if (mutt_pattern_exec
1236           (pat, M_MATCH_FULL_ADDRESS, Context, Context->hdrs[i])) {
1237         Context->hdrs[i]->virtual = Context->vcount;
1238         Context->hdrs[i]->limited = 1;
1239         Context->v2r[Context->vcount] = i;
1240         Context->vcount++;
1241         Context->vsize += THIS_BODY->length + THIS_BODY->offset -
1242           THIS_BODY->hdr_offset;
1243       }
1244     }
1245   }
1246   else {
1247     for (i = 0; i < Context->vcount; i++) {
1248       if (mutt_pattern_exec
1249           (pat, M_MATCH_FULL_ADDRESS, Context,
1250            Context->hdrs[Context->v2r[i]])) {
1251         switch (op) {
1252         case M_UNDELETE:
1253           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_PURGED,
1254                          0);
1255         case M_DELETE:
1256           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_DELETE,
1257                          (op == M_DELETE));
1258           break;
1259         case M_TAG:
1260         case M_UNTAG:
1261           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_TAG,
1262                          (op == M_TAG));
1263           break;
1264         }
1265       }
1266     }
1267   }
1268
1269 #undef THIS_BODY
1270
1271   mutt_clear_error ();
1272
1273   if (op == M_LIMIT) {
1274     /* drop previous limit pattern */
1275     p_delete(&Context->pattern);
1276     if (Context->limit_pattern)
1277       mutt_pattern_free (&Context->limit_pattern);
1278     if (Context->msgcount && !Context->vcount) {
1279       mutt_error _("No messages matched criteria.");
1280     }
1281
1282     /* record new limit pattern, unless match all */
1283     if (m_strncmp(buf, "~A", 2) != 0) {
1284       Context->pattern = simple;
1285       simple = NULL;            /* don't clobber it */
1286       Context->limit_pattern = mutt_pattern_comp (buf, M_FULL_MSG, &err);
1287     }
1288   }
1289   p_delete(&simple);
1290   mutt_pattern_free (&pat);
1291   return 0;
1292 }
1293
1294 int mutt_search_command (int cur, int op)
1295 {
1296   int i, j;
1297   char buf[STRING];
1298   char temp[LONG_STRING];
1299   char error[STRING];
1300   BUFFER err;
1301   int incr;
1302   HEADER *h;
1303
1304   if (op != OP_SEARCH_NEXT && op != OP_SEARCH_OPPOSITE) {
1305     m_strcpy(buf, sizeof(buf), LastSearch);
1306     if (mutt_get_field ((op == OP_SEARCH) ? _("Search for: ") :
1307                         _("Reverse search for: "), buf, sizeof (buf),
1308                         M_CLEAR | M_PATTERN) != 0 || !buf[0])
1309       return (-1);
1310
1311     if (op == OP_SEARCH)
1312       unset_option (OPTSEARCHREVERSE);
1313     else
1314       set_option (OPTSEARCHREVERSE);
1315
1316     /* compare the *expanded* version of the search pattern in case 
1317        $simple_search has changed while we were searching */
1318     m_strcpy(temp, sizeof(temp), buf);
1319     mutt_check_simple (temp, sizeof (temp), NONULL (SimpleSearch));
1320
1321     if (!SearchPattern || m_strcmp(temp, LastSearchExpn)) {
1322       set_option (OPTSEARCHINVALID);
1323       m_strcpy(LastSearch, sizeof(LastSearch), buf);
1324       mutt_message _("Compiling search pattern...");
1325
1326       mutt_pattern_free (&SearchPattern);
1327       err.data = error;
1328       err.dsize = sizeof (error);
1329       if ((SearchPattern =
1330            mutt_pattern_comp (temp, M_FULL_MSG, &err)) == NULL) {
1331         mutt_error ("%s", error);
1332         return (-1);
1333       }
1334       mutt_clear_error ();
1335     }
1336   }
1337   else if (!SearchPattern) {
1338     mutt_error _("No search pattern.");
1339
1340     return (-1);
1341   }
1342
1343   if (option (OPTSEARCHINVALID)) {
1344     for (i = 0; i < Context->msgcount; i++)
1345       Context->hdrs[i]->searched = 0;
1346 #ifdef USE_IMAP
1347     if (Context->magic == M_IMAP && imap_search (Context, SearchPattern) < 0)
1348       return -1;
1349 #endif
1350     unset_option (OPTSEARCHINVALID);
1351   }
1352
1353   incr = (option (OPTSEARCHREVERSE)) ? -1 : 1;
1354   if (op == OP_SEARCH_OPPOSITE)
1355     incr = -incr;
1356
1357   for (i = cur + incr, j = 0; j != Context->vcount; j++) {
1358     if (i > Context->vcount - 1) {
1359       i = 0;
1360       if (option (OPTWRAPSEARCH))
1361         mutt_message (_("Search wrapped to top."));
1362
1363       else {
1364         mutt_message _("Search hit bottom without finding match");
1365
1366         return (-1);
1367       }
1368     }
1369     else if (i < 0) {
1370       i = Context->vcount - 1;
1371       if (option (OPTWRAPSEARCH))
1372         mutt_message (_("Search wrapped to bottom."));
1373
1374       else {
1375         mutt_message _("Search hit top without finding match");
1376
1377         return (-1);
1378       }
1379     }
1380
1381     h = Context->hdrs[Context->v2r[i]];
1382     if (h->searched) {
1383       /* if we've already evaulated this message, use the cached value */
1384       if (h->matched)
1385         return i;
1386     }
1387     else {
1388       /* remember that we've already searched this message */
1389       h->searched = 1;
1390       if ((h->matched =
1391            (mutt_pattern_exec
1392             (SearchPattern, M_MATCH_FULL_ADDRESS, Context, h) > 0)))
1393         return i;
1394     }
1395
1396     if (SigInt) {
1397       mutt_error _("Search interrupted.");
1398
1399       SigInt = 0;
1400       return (-1);
1401     }
1402
1403     i += incr;
1404   }
1405
1406   mutt_error _("Not found.");
1407
1408   return (-1);
1409 }