Rocco Rutte:
[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 "mutt.h"
15 #include "mx.h"
16 #include "mapping.h"
17 #include "keymap.h"
18 #include "copy.h"
19
20 #include "lib/mem.h"
21 #include "lib/intl.h"
22 #include "lib/str.h"
23
24 #include <string.h>
25 #include <stdlib.h>
26 #include <ctype.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <stdarg.h>
30
31 #include "mutt_crypt.h"
32
33 static int eat_regexp (pattern_t * pat, BUFFER *, BUFFER *);
34 static int eat_date (pattern_t * pat, BUFFER *, BUFFER *);
35 static int eat_range (pattern_t * pat, BUFFER *, BUFFER *);
36
37 struct pattern_flags {
38   int tag;                      /* character used to represent this op */
39   int op;                       /* operation to perform */
40   int class;
41   int (*eat_arg) (pattern_t *, BUFFER *, BUFFER *);
42 } Flags[] = {
43   {
44   'A', M_ALL, 0, NULL}, {
45   'b', M_BODY, M_FULL_MSG, eat_regexp}, {
46   'B', M_WHOLE_MSG, M_FULL_MSG, eat_regexp}, {
47   'c', M_CC, 0, eat_regexp}, {
48   'C', M_RECIPIENT, 0, eat_regexp}, {
49   'd', M_DATE, 0, eat_date}, {
50   'D', M_DELETED, 0, NULL}, {
51   'e', M_SENDER, 0, eat_regexp}, {
52   'E', M_EXPIRED, 0, NULL}, {
53   'f', M_FROM, 0, eat_regexp}, {
54   'F', M_FLAG, 0, NULL}, {
55   'g', M_CRYPT_SIGN, 0, NULL}, {
56   'G', M_CRYPT_ENCRYPT, 0, NULL}, {
57   'h', M_HEADER, M_FULL_MSG, eat_regexp}, {
58   'H', M_HORMEL, 0, eat_regexp}, {
59   'i', M_ID, 0, eat_regexp}, {
60   'k', M_PGP_KEY, 0, NULL}, {
61   'L', M_ADDRESS, 0, eat_regexp}, {
62   'l', M_LIST, 0, NULL}, {
63   'm', M_MESSAGE, 0, eat_range}, {
64   'n', M_SCORE, 0, eat_range}, {
65   'N', M_NEW, 0, NULL}, {
66   'O', M_OLD, 0, NULL}, {
67   'p', M_PERSONAL_RECIP, 0, NULL}, {
68   'P', M_PERSONAL_FROM, 0, NULL}, {
69   'Q', M_REPLIED, 0, NULL}, {
70   'R', M_READ, 0, NULL}, {
71   'r', M_DATE_RECEIVED, 0, eat_date}, {
72   's', M_SUBJECT, 0, eat_regexp}, {
73   'S', M_SUPERSEDED, 0, NULL}, {
74   'T', M_TAG, 0, NULL}, {
75   't', M_TO, 0, eat_regexp}, {
76   'U', M_UNREAD, 0, NULL}, {
77   'v', M_COLLAPSED, 0, NULL}, {
78   'V', M_CRYPT_VERIFIED, 0, NULL},
79 #ifdef USE_NNTP
80   {
81   'w', M_NEWSGROUPS, 0, eat_regexp},
82 #endif
83   {
84   'x', M_REFERENCE, 0, eat_regexp}, {
85   'y', M_XLABEL, 0, eat_regexp}, {
86   'z', M_SIZE, 0, eat_range}, {
87   '=', M_DUPLICATED, 0, NULL}, {
88   '$', M_UNREFERENCED, 0, NULL}, {
89   '*', M_REALNAME, 0, NULL}, {
90   0}
91 };
92
93 static pattern_t *SearchPattern = NULL; /* current search pattern */
94 static char LastSearch[STRING] = { 0 }; /* last pattern searched for */
95 static char LastSearchExpn[LONG_STRING] = { 0 };        /* expanded version of
96                                                            LastSearch */
97
98 #define M_MAXRANGE -1
99
100 /* constants for parse_date_range() */
101 #define M_PDR_NONE      0x0000
102 #define M_PDR_MINUS     0x0001
103 #define M_PDR_PLUS      0x0002
104 #define M_PDR_WINDOW    0x0004
105 #define M_PDR_ABSOLUTE  0x0008
106 #define M_PDR_DONE      0x0010
107 #define M_PDR_ERROR     0x0100
108 #define M_PDR_ERRORDONE (M_PDR_ERROR | M_PDR_DONE)
109
110
111 int mutt_getvaluebychar (char ch, struct mapping_t *table)
112 {
113   int i;
114
115   for (i = 0; table[i].name; i++) {
116     if (ch == table[i].name[0])
117       return table[i].value;
118   }
119
120   return (-1);
121 }
122
123 /* if no uppercase letters are given, do a case-insensitive search */
124 int mutt_which_case (const char *s)
125 {
126   while (*s) {
127     if (isalpha ((unsigned char) *s) && isupper ((unsigned char) *s))
128       return 0;                 /* case-sensitive */
129     s++;
130   }
131   return REG_ICASE;             /* case-insensitive */
132 }
133
134 static int
135 msg_search (CONTEXT * ctx, regex_t * rx, char *buf, size_t blen, int op,
136             int msgno)
137 {
138   char tempfile[_POSIX_PATH_MAX];
139   MESSAGE *msg = NULL;
140   STATE s;
141   struct stat st;
142   FILE *fp = NULL;
143   long lng = 0;
144   int match = 0;
145   HEADER *h = ctx->hdrs[msgno];
146
147   if ((msg = mx_open_message (ctx, msgno)) != NULL) {
148     if (option (OPTTHOROUGHSRC)) {
149       /* decode the header / body */
150       memset (&s, 0, sizeof (s));
151       s.fpin = msg->fp;
152       s.flags = M_CHARCONV;
153       mutt_mktemp (tempfile);
154       if ((s.fpout = safe_fopen (tempfile, "w+")) == NULL) {
155         mutt_perror (tempfile);
156         return (0);
157       }
158
159       if (op != M_BODY)
160         mutt_copy_header (msg->fp, h, s.fpout, CH_FROM | CH_DECODE, NULL);
161
162       if (op != M_HEADER) {
163         mutt_parse_mime_message (ctx, h);
164
165         if (WithCrypto && (h->security & ENCRYPT)
166             && !crypt_valid_passphrase (h->security)) {
167           mx_close_message (&msg);
168           if (fp) {
169             fclose (fp);
170             unlink (tempfile);
171           }
172           return (0);
173         }
174
175         fseek (msg->fp, h->offset, 0);
176         mutt_body_handler (h->content, &s);
177       }
178
179       fp = s.fpout;
180       fflush (fp);
181       fseek (fp, 0, 0);
182       fstat (fileno (fp), &st);
183       lng = (long) st.st_size;
184     }
185     else {
186       /* raw header / body */
187       fp = msg->fp;
188       if (op != M_BODY) {
189         fseek (fp, h->offset, 0);
190         lng = h->content->offset - h->offset;
191       }
192       if (op != M_HEADER) {
193         if (op == M_BODY)
194           fseek (fp, h->content->offset, 0);
195         lng += h->content->length;
196       }
197     }
198
199     /* search the file "fp" */
200     while (lng > 0) {
201       if (fgets (buf, blen - 1, fp) == NULL)
202         break;                  /* don't loop forever */
203       if (regexec (rx, buf, 0, NULL, 0) == 0) {
204         match = 1;
205         break;
206       }
207       lng -= str_len (buf);
208     }
209
210     mx_close_message (&msg);
211
212     if (option (OPTTHOROUGHSRC)) {
213       fclose (fp);
214       unlink (tempfile);
215     }
216   }
217
218   return match;
219 }
220
221 int eat_regexp (pattern_t * pat, BUFFER * s, BUFFER * err)
222 {
223   BUFFER buf;
224   int r;
225
226   memset (&buf, 0, sizeof (buf));
227   if (mutt_extract_token (&buf, s, M_TOKEN_PATTERN | M_TOKEN_COMMENT) != 0 ||
228       !buf.data) {
229     snprintf (err->data, err->dsize, _("Error in expression: %s"), s->dptr);
230     return (-1);
231   }
232   pat->rx = mem_malloc (sizeof (regex_t));
233   r =
234     REGCOMP (pat->rx, buf.data,
235              REG_NEWLINE | REG_NOSUB | mutt_which_case (buf.data));
236   mem_free (&buf.data);
237   if (r) {
238     regerror (r, pat->rx, err->data, err->dsize);
239     regfree (pat->rx);
240     mem_free (&pat->rx);
241     return (-1);
242   }
243   return 0;
244 }
245
246 int eat_range (pattern_t * pat, BUFFER * s, BUFFER * err)
247 {
248   char *tmp;
249   int do_exclusive = 0;
250   int skip_quote = 0;
251
252   /*
253    * If simple_search is set to "~m %s", the range will have double quotes 
254    * around it...
255    */
256   if (*s->dptr == '"') {
257     s->dptr++;
258     skip_quote = 1;
259   }
260   if (*s->dptr == '<')
261     do_exclusive = 1;
262   if ((*s->dptr != '-') && (*s->dptr != '<')) {
263     /* range minimum */
264     if (*s->dptr == '>') {
265       pat->max = M_MAXRANGE;
266       pat->min = strtol (s->dptr + 1, &tmp, 0) + 1;     /* exclusive range */
267     }
268     else
269       pat->min = strtol (s->dptr, &tmp, 0);
270     if (toupper ((unsigned char) *tmp) == 'K') {        /* is there a prefix? */
271       pat->min *= 1024;
272       tmp++;
273     }
274     else if (toupper ((unsigned char) *tmp) == 'M') {
275       pat->min *= 1048576;
276       tmp++;
277     }
278     if (*s->dptr == '>') {
279       s->dptr = tmp;
280       return 0;
281     }
282     if (*tmp != '-') {
283       /* exact value */
284       pat->max = pat->min;
285       s->dptr = tmp;
286       return 0;
287     }
288     tmp++;
289   }
290   else {
291     s->dptr++;
292     tmp = s->dptr;
293   }
294
295   if (isdigit ((unsigned char) *tmp)) {
296     /* range maximum */
297     pat->max = strtol (tmp, &tmp, 0);
298     if (toupper ((unsigned char) *tmp) == 'K') {
299       pat->max *= 1024;
300       tmp++;
301     }
302     else if (toupper ((unsigned char) *tmp) == 'M') {
303       pat->max *= 1048576;
304       tmp++;
305     }
306     if (do_exclusive)
307       (pat->max)--;
308   }
309   else
310     pat->max = M_MAXRANGE;
311
312   if (skip_quote && *tmp == '"')
313     tmp++;
314
315   SKIPWS (tmp);
316   s->dptr = 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   mutt_normalize_time (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     SKIPWS (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     SKIPWS (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   memset (&buffer, 0, sizeof (buffer));
494   if (mutt_extract_token (&buffer, s, M_TOKEN_COMMENT | M_TOKEN_PATTERN) != 0
495       || !buffer.data) {
496     strfcpy (err->data, _("error in expression"), err->dsize);
497     return (-1);
498   }
499
500   memset (&min, 0, sizeof (min));
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   memset (&max, 0, sizeof (max));
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         mem_free (&buffer.data);
561         return (-1);
562       }
563       haveMin = TRUE;
564       SKIPWS (pc);
565       if (*pc == '-') {
566         const char *pt = pc + 1;
567
568         SKIPWS (pt);
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         mem_free (&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 = mutt_mktime (&min, 1);
603   pat->max = mutt_mktime (&max, 1);
604
605   mem_free (&buffer.data);
606
607   return 0;
608 }
609
610 static 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     if (*s == '(')
626       level++;
627     else if (*s == ')') {
628       level--;
629       if (!level)
630         break;
631     }
632   }
633   return s;
634 }
635
636 void mutt_pattern_free (pattern_t ** pat)
637 {
638   pattern_t *tmp;
639
640   while (*pat) {
641     tmp = *pat;
642     *pat = (*pat)->next;
643
644     if (tmp->rx) {
645       regfree (tmp->rx);
646       mem_free (&tmp->rx);
647     }
648     if (tmp->child)
649       mutt_pattern_free (&tmp->child);
650     mem_free (&tmp);
651   }
652 }
653
654 pattern_t *mutt_pattern_comp ( /* const */ char *s, int flags, BUFFER * err)
655 {
656   pattern_t *curlist = NULL;
657   pattern_t *tmp;
658   pattern_t *last = NULL;
659   int not = 0;
660   int alladdr = 0;
661   int or = 0;
662   int implicit = 1;             /* used to detect logical AND operator */
663   struct pattern_flags *entry;
664   char *p;
665   char *buf;
666   BUFFER ps;
667
668   memset (&ps, 0, sizeof (ps));
669   ps.dptr = s;
670   ps.dsize = str_len (s);
671
672   while (*ps.dptr) {
673     SKIPWS (ps.dptr);
674     switch (*ps.dptr) {
675     case '^':
676       ps.dptr++;
677       alladdr = !alladdr;
678       break;
679     case '!':
680       ps.dptr++;
681       not = !not;
682       break;
683     case '|':
684       if (!or) {
685         if (!curlist) {
686           snprintf (err->data, err->dsize, _("error in pattern at: %s"),
687                     ps.dptr);
688           return NULL;
689         }
690         if (curlist->next) {
691           /* A & B | C == (A & B) | C */
692           tmp = new_pattern ();
693           tmp->op = M_AND;
694           tmp->child = curlist;
695
696           curlist = tmp;
697           last = curlist;
698         }
699
700         or = 1;
701       }
702       ps.dptr++;
703       implicit = 0;
704       not = 0;
705       alladdr = 0;
706       break;
707     case '~':
708       if (implicit && or) {
709         /* A | B & C == (A | B) & C */
710         tmp = new_pattern ();
711         tmp->op = M_OR;
712         tmp->child = curlist;
713         curlist = tmp;
714         last = tmp;
715         or = 0;
716       }
717
718       tmp = new_pattern ();
719       tmp->not = not;
720       tmp->alladdr = alladdr;
721       not = 0;
722       alladdr = 0;
723
724       if (last)
725         last->next = tmp;
726       else
727         curlist = tmp;
728       last = tmp;
729
730       ps.dptr++;                /* move past the ~ */
731       if ((entry = lookup_tag (*ps.dptr)) == NULL) {
732         snprintf (err->data, err->dsize, _("%c: invalid command"), *ps.dptr);
733         mutt_pattern_free (&curlist);
734         return NULL;
735       }
736       if (entry->class && (flags & entry->class) == 0) {
737         snprintf (err->data, err->dsize, _("%c: not supported in this mode"),
738                   *ps.dptr);
739         mutt_pattern_free (&curlist);
740         return NULL;
741       }
742       tmp->op = entry->op;
743
744       ps.dptr++;                /* eat the operator and any optional whitespace */
745       SKIPWS (ps.dptr);
746
747       if (entry->eat_arg) {
748         if (!*ps.dptr) {
749           snprintf (err->data, err->dsize, _("missing parameter"));
750           mutt_pattern_free (&curlist);
751           return NULL;
752         }
753         if (entry->eat_arg (tmp, &ps, err) == -1) {
754           mutt_pattern_free (&curlist);
755           return NULL;
756         }
757       }
758       implicit = 1;
759       break;
760     case '(':
761       p = find_matching_paren (ps.dptr + 1);
762       if (*p != ')') {
763         snprintf (err->data, err->dsize, _("mismatched parenthesis: %s"),
764                   ps.dptr);
765         mutt_pattern_free (&curlist);
766         return NULL;
767       }
768       /* compile the sub-expression */
769       buf = str_substrdup (ps.dptr + 1, p);
770       if ((tmp = mutt_pattern_comp (buf, flags, err)) == NULL) {
771         mem_free (&buf);
772         mutt_pattern_free (&curlist);
773         return NULL;
774       }
775       mem_free (&buf);
776       if (last)
777         last->next = tmp;
778       else
779         curlist = tmp;
780       last = tmp;
781       tmp->not ^= not;
782       tmp->alladdr |= alladdr;
783       not = 0;
784       alladdr = 0;
785       ps.dptr = p + 1;          /* restore location */
786       break;
787     default:
788       snprintf (err->data, err->dsize, _("error in pattern at: %s"), ps.dptr);
789       mutt_pattern_free (&curlist);
790       return NULL;
791     }
792   }
793   if (!curlist) {
794     strfcpy (err->data, _("empty pattern"), err->dsize);
795     return NULL;
796   }
797   if (curlist->next) {
798     tmp = new_pattern ();
799     tmp->op = or ? M_OR : M_AND;
800     tmp->child = curlist;
801     curlist = tmp;
802   }
803   return (curlist);
804 }
805
806 static int
807 perform_and (pattern_t * pat, pattern_exec_flag flags, CONTEXT * ctx,
808              HEADER * hdr)
809 {
810   for (; pat; pat = pat->next)
811     if (mutt_pattern_exec (pat, flags, ctx, hdr) <= 0)
812       return 0;
813   return 1;
814 }
815
816 static int
817 perform_or (struct pattern_t *pat, pattern_exec_flag flags, CONTEXT * ctx,
818             HEADER * hdr)
819 {
820   for (; pat; pat = pat->next)
821     if (mutt_pattern_exec (pat, flags, ctx, hdr) > 0)
822       return 1;
823   return 0;
824 }
825
826 static int match_adrlist (regex_t * rx, int match_personal, int alladdr,
827                           int n, ...)
828 {
829   va_list ap;
830   ADDRESS *a;
831
832   va_start (ap, n);
833   for (; n; n--) {
834     for (a = va_arg (ap, ADDRESS *); a; a = a->next) {
835       if (alladdr ^
836           ((a->mailbox && regexec (rx, a->mailbox, 0, NULL, 0) == 0) ||
837            (match_personal && a->personal &&
838             regexec (rx, a->personal, 0, NULL, 0) == 0))) {
839         va_end (ap);
840         return (!alladdr);      /* Found match, or non-match if alladdr */
841       }
842     }
843   }
844   va_end (ap);
845   return alladdr;               /* No matches, or all matches if alladdr */
846 }
847
848 static int match_reference (regex_t * rx, LIST * refs)
849 {
850   for (; refs; refs = refs->next)
851     if (regexec (rx, refs->data, 0, NULL, 0) == 0)
852       return 1;
853   return 0;
854 }
855
856 int mutt_is_list_recipient (int alladdr, ADDRESS * a1, ADDRESS * a2)
857 {
858   for (; a1; a1 = a1->next)
859     if (alladdr ^ mutt_is_subscribed_list (a1))
860       return (!alladdr);
861   for (; a2; a2 = a2->next)
862     if (alladdr ^ mutt_is_subscribed_list (a2))
863       return (!alladdr);
864   return alladdr;
865 }
866
867 int mutt_is_list_cc (int alladdr, ADDRESS * a1, ADDRESS * a2)
868 {
869   for (; a1; a1 = a1->next)
870     if (alladdr ^ mutt_is_mail_list (a1))
871       return (!alladdr);
872   for (; a2; a2 = a2->next)
873     if (alladdr ^ mutt_is_mail_list (a2))
874       return (!alladdr);
875   return alladdr;
876 }
877
878 static int match_user (int alladdr, ADDRESS * a1, ADDRESS * a2)
879 {
880   for (; a1; a1 = a1->next)
881     if (alladdr ^ mutt_addr_is_user (a1))
882       return (!alladdr);
883   for (; a2; a2 = a2->next)
884     if (alladdr ^ mutt_addr_is_user (a2))
885       return (!alladdr);
886   return alladdr;
887 }
888
889 /* test if name is considered a real name, i.e. consists of at least 2
890  * space-separated words of which none may end in a dot
891  */
892 static int valid_realname (const char *name)
893 {
894   const char *p = name;
895   int ret = 0;
896
897   while (*p) {
898     if (isspace (*p))
899       ret++;
900     else if (*p == '.')
901       /* skip abbr. parts of names (e.g. 'J. User') */
902       ret--;
903     p++;
904   }
905   return (ret >= 1);
906 }
907
908 /* flags
909         M_MATCH_FULL_ADDRESS    match both personal and machine address */
910 int
911 mutt_pattern_exec (struct pattern_t *pat, pattern_exec_flag flags,
912                    CONTEXT * ctx, HEADER * h)
913 {
914   char buf[STRING];
915
916   switch (pat->op) {
917   case M_AND:
918     return (pat->not ^ (perform_and (pat->child, flags, ctx, h) > 0));
919   case M_OR:
920     return (pat->not ^ (perform_or (pat->child, flags, ctx, h) > 0));
921   case M_ALL:
922     return (!pat->not);
923   case M_EXPIRED:
924     return (pat->not ^ h->expired);
925   case M_SUPERSEDED:
926     return (pat->not ^ h->superseded);
927   case M_FLAG:
928     return (pat->not ^ h->flagged);
929   case M_TAG:
930     return (pat->not ^ h->tagged);
931   case M_NEW:
932     return (pat->not ? h->old || h->read : !(h->old || h->read));
933   case M_UNREAD:
934     return (pat->not ? h->read : !h->read);
935   case M_REPLIED:
936     return (pat->not ^ h->replied);
937   case M_OLD:
938     return (pat->not ? (!h->old || h->read) : (h->old && !h->read));
939   case M_READ:
940     return (pat->not ^ h->read);
941   case M_DELETED:
942     return (pat->not ^ h->deleted);
943   case M_MESSAGE:
944     return (pat->not ^ (h->msgno >= pat->min - 1 && (pat->max == M_MAXRANGE ||
945                                                      h->msgno <=
946                                                      pat->max - 1)));
947   case M_DATE:
948     return (pat->
949             not ^ (h->date_sent >= pat->min && h->date_sent <= pat->max));
950   case M_DATE_RECEIVED:
951     return (pat->not ^ (h->received >= pat->min && h->received <= pat->max));
952   case M_BODY:
953   case M_HEADER:
954   case M_WHOLE_MSG:
955     return (pat->
956             not ^ msg_search (ctx, pat->rx, buf, sizeof (buf), pat->op,
957                               h->msgno));
958   case M_SENDER:
959     return (pat->not ^ match_adrlist (pat->rx, flags & M_MATCH_FULL_ADDRESS,
960                                       pat->alladdr, 1, h->env->sender));
961   case M_FROM:
962     return (pat->not ^ match_adrlist (pat->rx, flags & M_MATCH_FULL_ADDRESS,
963                                       pat->alladdr, 1, h->env->from));
964   case M_TO:
965     return (pat->not ^ match_adrlist (pat->rx, flags & M_MATCH_FULL_ADDRESS,
966                                       pat->alladdr, 1, h->env->to));
967   case M_CC:
968     return (pat->not ^ match_adrlist (pat->rx, flags & M_MATCH_FULL_ADDRESS,
969                                       pat->alladdr, 1, h->env->cc));
970   case M_SUBJECT:
971     return (pat->
972             not ^ (h->env && h->env->subject
973                    && regexec (pat->rx, h->env->subject, 0, NULL, 0) == 0));
974   case M_ID:
975     return (pat->
976             not ^ (h->env && h->env->message_id
977                    && regexec (pat->rx, h->env->message_id, 0, NULL,
978                                0) == 0));
979   case M_SCORE:
980     return (pat->not ^ (h->score >= pat->min && (pat->max == M_MAXRANGE ||
981                                                  h->score <= pat->max)));
982   case M_SIZE:
983     return (pat->
984             not ^ (h->content->length >= pat->min
985                    && (pat->max == M_MAXRANGE
986                        || h->content->length <= pat->max)));
987   case M_REFERENCE:
988     return (pat->not ^ match_reference (pat->rx, h->env->references));
989   case M_ADDRESS:
990     return (pat->
991             not ^ (h->env
992                    && match_adrlist (pat->rx, flags & M_MATCH_FULL_ADDRESS,
993                                      pat->alladdr, 4, h->env->from,
994                                      h->env->sender, h->env->to,
995                                      h->env->cc)));
996   case M_RECIPIENT:
997     return (pat->
998             not ^ (h->env
999                    && match_adrlist (pat->rx, flags & M_MATCH_FULL_ADDRESS,
1000                                      pat->alladdr, 2, h->env->to,
1001                                      h->env->cc)));
1002   case M_LIST:
1003     return (pat->
1004             not ^ (h->env
1005                    && mutt_is_list_recipient (pat->alladdr, h->env->to,
1006                                               h->env->cc)));
1007   case M_PERSONAL_RECIP:
1008     return (pat->
1009             not ^ (h->env
1010                    && match_user (pat->alladdr, h->env->to, h->env->cc)));
1011   case M_PERSONAL_FROM:
1012     return (pat->
1013             not ^ (h->env && match_user (pat->alladdr, h->env->from, NULL)));
1014   case M_COLLAPSED:
1015     return (pat->not ^ (h->collapsed && h->num_hidden > 1));
1016   case M_CRYPT_SIGN:
1017     if (!WithCrypto)
1018       break;
1019     return (pat->not ^ ((h->security & SIGN) ? 1 : 0));
1020   case M_CRYPT_VERIFIED:
1021     if (!WithCrypto)
1022       break;
1023     return (pat->not ^ ((h->security & GOODSIGN) ? 1 : 0));
1024   case M_CRYPT_ENCRYPT:
1025     if (!WithCrypto)
1026       break;
1027     return (pat->not ^ ((h->security & ENCRYPT) ? 1 : 0));
1028   case M_PGP_KEY:
1029     if (!(WithCrypto & APPLICATION_PGP))
1030       break;
1031     return (pat->not ^ ((h->security & APPLICATION_PGP)
1032                         && (h->security & PGPKEY)));
1033   case M_XLABEL:
1034     return (pat->
1035             not ^ (h->env->x_label
1036                    && regexec (pat->rx, h->env->x_label, 0, NULL, 0) == 0));
1037   case M_HORMEL:
1038     return (pat->
1039             not ^ (h->env->spam && h->env->spam->data
1040                    && regexec (pat->rx, h->env->spam->data, 0, NULL,
1041                                0) == 0));
1042   case M_DUPLICATED:
1043     return (pat->not ^ (h->thread && h->thread->duplicate_thread));
1044   case M_UNREFERENCED:
1045     return (pat->not ^ (h->thread && !h->thread->child));
1046   case M_REALNAME:
1047     /* realname filter:
1048      * we have a match if
1049      * - From: matches $alternates
1050      * - or we have an alias for current address
1051      * - or From: contains valid email address _and_ name has >= 2 fields
1052      */
1053     return (pat->
1054             not ^ (h->env && h->env->from && (mutt_addr_is_user (h->env->from)
1055                                               ||
1056                                               (alias_reverse_lookup
1057                                                (h->env->from) != NULL)
1058                                               || (h->env->from->personal
1059                                                   && valid_realname (h->env->
1060                                                                      from->
1061                                                                      personal)
1062                                                   && h->env->from->mailbox)
1063                    )));
1064 #ifdef USE_NNTP
1065   case M_NEWSGROUPS:
1066     return (pat->
1067             not ^ (h->env->newsgroups
1068                    && regexec (pat->rx, h->env->newsgroups, 0, NULL,
1069                                0) == 0));
1070 #endif
1071   }
1072   mutt_error (_("error: unknown op %d (report this error)."), pat->op);
1073   return (-1);
1074 }
1075
1076 static void quote_simple (char *tmp, size_t len, const char *p)
1077 {
1078   int i = 0;
1079
1080   tmp[i++] = '"';
1081   while (*p && i < len - 3) {
1082     if (*p == '\\' || *p == '"')
1083       tmp[i++] = '\\';
1084     tmp[i++] = *p++;
1085   }
1086   tmp[i++] = '"';
1087   tmp[i] = 0;
1088 }
1089
1090 /* convert a simple search into a real request */
1091 void mutt_check_simple (char *s, size_t len, const char *simple)
1092 {
1093   char tmp[LONG_STRING];
1094
1095   /* XXX - is ascii_strcasecmp() right here, or should we use locale's
1096    * equivalences?
1097    */
1098
1099   if (!strchr (s, '~')) {       /* yup, so spoof a real request */
1100     /* convert old tokens into the new format */
1101     if (ascii_strcasecmp ("all", s) == 0 || !str_cmp ("^", s) || !str_cmp (".", s))     /* ~A is more efficient */
1102       strfcpy (s, "~A", len);
1103     else if (ascii_strcasecmp ("del", s) == 0)
1104       strfcpy (s, "~D", len);
1105     else if (ascii_strcasecmp ("flag", s) == 0)
1106       strfcpy (s, "~F", len);
1107     else if (ascii_strcasecmp ("new", s) == 0)
1108       strfcpy (s, "~N", len);
1109     else if (ascii_strcasecmp ("old", s) == 0)
1110       strfcpy (s, "~O", len);
1111     else if (ascii_strcasecmp ("repl", s) == 0)
1112       strfcpy (s, "~Q", len);
1113     else if (ascii_strcasecmp ("read", s) == 0)
1114       strfcpy (s, "~R", len);
1115     else if (ascii_strcasecmp ("tag", s) == 0)
1116       strfcpy (s, "~T", len);
1117     else if (ascii_strcasecmp ("unread", s) == 0)
1118       strfcpy (s, "~U", len);
1119     else {
1120       quote_simple (tmp, sizeof (tmp), s);
1121       mutt_expand_fmt (s, len, simple, tmp);
1122     }
1123   }
1124 }
1125
1126 int mutt_pattern_func (int op, char *prompt)
1127 {
1128   pattern_t *pat;
1129   char buf[LONG_STRING] = "", *simple, error[STRING];
1130   BUFFER err;
1131   int i;
1132
1133   strfcpy (buf, NONULL (Context->pattern), sizeof (buf));
1134   if (prompt || op != M_LIMIT)
1135     if (mutt_get_field (prompt, buf, sizeof (buf), M_PATTERN | M_CLEAR) != 0)
1136       return (-1);
1137   if (!buf[0]) {
1138     if (op == M_LIMIT)
1139       strncpy (buf, "~A", sizeof (buf));
1140     else
1141       return (-1);
1142   }
1143
1144   mutt_message _("Compiling search pattern...");
1145
1146   simple = str_dup (buf);
1147   mutt_check_simple (buf, sizeof (buf), NONULL (SimpleSearch));
1148
1149   err.data = error;
1150   err.dsize = sizeof (error);
1151   if ((pat = mutt_pattern_comp (buf, M_FULL_MSG, &err)) == NULL) {
1152     mem_free (&simple);
1153     mutt_error ("%s", err.data);
1154     return (-1);
1155   }
1156
1157   mutt_message _("Executing command on matching messages...");
1158
1159 #define THIS_BODY Context->hdrs[i]->content
1160
1161   if (op == M_LIMIT) {
1162     Context->vcount = 0;
1163     Context->vsize = 0;
1164     Context->collapsed = 0;
1165
1166     for (i = 0; i < Context->msgcount; i++) {
1167       /* new limit pattern implicitly uncollapses all threads */
1168       Context->hdrs[i]->virtual = -1;
1169       Context->hdrs[i]->limited = 0;
1170       Context->hdrs[i]->collapsed = 0;
1171       Context->hdrs[i]->num_hidden = 0;
1172       if (mutt_pattern_exec
1173           (pat, M_MATCH_FULL_ADDRESS, Context, Context->hdrs[i])) {
1174         Context->hdrs[i]->virtual = Context->vcount;
1175         Context->hdrs[i]->limited = 1;
1176         Context->v2r[Context->vcount] = i;
1177         Context->vcount++;
1178         Context->vsize += THIS_BODY->length + THIS_BODY->offset -
1179           THIS_BODY->hdr_offset;
1180       }
1181     }
1182   }
1183   else {
1184     for (i = 0; i < Context->vcount; i++) {
1185       if (mutt_pattern_exec
1186           (pat, M_MATCH_FULL_ADDRESS, Context,
1187            Context->hdrs[Context->v2r[i]])) {
1188         switch (op) {
1189         case M_UNDELETE:
1190           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_PURGED,
1191                          0);
1192         case M_DELETE:
1193           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_DELETE,
1194                          (op == M_DELETE));
1195           break;
1196         case M_TAG:
1197         case M_UNTAG:
1198           mutt_set_flag (Context, Context->hdrs[Context->v2r[i]], M_TAG,
1199                          (op == M_TAG));
1200           break;
1201         }
1202       }
1203     }
1204   }
1205
1206 #undef THIS_BODY
1207
1208   mutt_clear_error ();
1209
1210   if (op == M_LIMIT) {
1211     mem_free (&Context->pattern);
1212     if (Context->limit_pattern)
1213       mutt_pattern_free (&Context->limit_pattern);
1214     if (!Context->vcount) {
1215       mutt_error _("No messages matched criteria.");
1216
1217 #if 0
1218       Context->vcount = Context->msgcount;
1219       /* restore full display */
1220       for (i = 0; i < Context->msgcount; i++) {
1221         Context->hdrs[i]->virtual = i;
1222         Context->v2r[i] = i;
1223       }
1224 #endif
1225     }
1226     else if (str_ncmp (buf, "~A", 2) != 0) {
1227       Context->pattern = simple;
1228       simple = NULL;            /* don't clobber it */
1229       Context->limit_pattern = mutt_pattern_comp (buf, M_FULL_MSG, &err);
1230     }
1231   }
1232   mem_free (&simple);
1233   mutt_pattern_free (&pat);
1234   return 0;
1235 }
1236
1237 int mutt_search_command (int cur, int op)
1238 {
1239   int i, j;
1240   char buf[STRING];
1241   char temp[LONG_STRING];
1242   char error[STRING];
1243   BUFFER err;
1244   int incr;
1245   HEADER *h;
1246
1247   if (op != OP_SEARCH_NEXT && op != OP_SEARCH_OPPOSITE) {
1248     strfcpy (buf, LastSearch, sizeof (buf));
1249     if (mutt_get_field ((op == OP_SEARCH) ? _("Search for: ") :
1250                         _("Reverse search for: "), buf, sizeof (buf),
1251                         M_CLEAR | M_PATTERN) != 0 || !buf[0])
1252       return (-1);
1253
1254     if (op == OP_SEARCH)
1255       unset_option (OPTSEARCHREVERSE);
1256     else
1257       set_option (OPTSEARCHREVERSE);
1258
1259     /* compare the *expanded* version of the search pattern in case 
1260        $simple_search has changed while we were searching */
1261     strfcpy (temp, buf, sizeof (temp));
1262     mutt_check_simple (temp, sizeof (temp), NONULL (SimpleSearch));
1263
1264     if (!SearchPattern || str_cmp (temp, LastSearchExpn)) {
1265       set_option (OPTSEARCHINVALID);
1266       strfcpy (LastSearch, buf, sizeof (LastSearch));
1267       mutt_message _("Compiling search pattern...");
1268
1269       mutt_pattern_free (&SearchPattern);
1270       err.data = error;
1271       err.dsize = sizeof (error);
1272       if ((SearchPattern =
1273            mutt_pattern_comp (temp, M_FULL_MSG, &err)) == NULL) {
1274         mutt_error ("%s", error);
1275         return (-1);
1276       }
1277       mutt_clear_error ();
1278     }
1279   }
1280   else if (!SearchPattern) {
1281     mutt_error _("No search pattern.");
1282
1283     return (-1);
1284   }
1285
1286   if (option (OPTSEARCHINVALID)) {
1287     for (i = 0; i < Context->msgcount; i++)
1288       Context->hdrs[i]->searched = 0;
1289     unset_option (OPTSEARCHINVALID);
1290   }
1291
1292   incr = (option (OPTSEARCHREVERSE)) ? -1 : 1;
1293   if (op == OP_SEARCH_OPPOSITE)
1294     incr = -incr;
1295
1296   for (i = cur + incr, j = 0; j != Context->vcount; j++) {
1297     if (i > Context->vcount - 1) {
1298       i = 0;
1299       if (option (OPTWRAPSEARCH))
1300         mutt_message (_("Search wrapped to top."));
1301
1302       else {
1303         mutt_message _("Search hit bottom without finding match");
1304
1305         return (-1);
1306       }
1307     }
1308     else if (i < 0) {
1309       i = Context->vcount - 1;
1310       if (option (OPTWRAPSEARCH))
1311         mutt_message (_("Search wrapped to bottom."));
1312
1313       else {
1314         mutt_message _("Search hit top without finding match");
1315
1316         return (-1);
1317       }
1318     }
1319
1320     h = Context->hdrs[Context->v2r[i]];
1321     if (h->searched) {
1322       /* if we've already evaulated this message, use the cached value */
1323       if (h->matched)
1324         return i;
1325     }
1326     else {
1327       /* remember that we've already searched this message */
1328       h->searched = 1;
1329       if ((h->matched =
1330            (mutt_pattern_exec
1331             (SearchPattern, M_MATCH_FULL_ADDRESS, Context, h) > 0)))
1332         return i;
1333     }
1334
1335     if (SigInt) {
1336       mutt_error _("Search interrupted.");
1337
1338       SigInt = 0;
1339       return (-1);
1340     }
1341
1342     i += incr;
1343   }
1344
1345   mutt_error _("Not found.");
1346
1347   return (-1);
1348 }