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