pick matching rework
[mmh] / uip / pick.c
1 /*
2 ** pick.c -- search for messages by content
3 **
4 ** This code is Copyright (c) 2002, 2008, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <h/tws.h>
11 #include <h/utils.h>
12 #include <h/scansbr.h>
13 #include <h/fmt_scan.h>
14 #include <unistd.h>
15 #include <locale.h>
16 #include <sysexits.h>
17 #include <ctype.h>
18 #include <regex.h>
19 #include <libgen.h>
20
21 #ifdef HAVE_SYS_TIME_H
22 # include <sys/time.h>
23 #endif
24 #include <time.h>
25
26 static struct swit switches[] = {
27 #define ANDSW  0
28         { "and", 0 },
29 #define ORSW  1
30         { "or", 0 },
31 #define NOTSW  2
32         { "not", 0 },
33 #define LBRSW  3
34         { "lbrace", 0 },
35 #define RBRSW  4
36         { "rbrace", 0 },
37 #define CCSW  5
38         { "cc  pattern", 0 },
39 #define DATESW  6
40         { "date  pattern", 0 },
41 #define FROMSW  7
42         { "from  pattern", 0 },
43 #define SRCHSW  8
44         { "search  pattern", 0 },
45 #define SUBJSW  9
46         { "subject  pattern", 0 },
47 #define TOSW  10
48         { "to  pattern", 0 },
49 #define OTHRSW  11
50         { "-othercomponent  pattern", 0 },
51 #define AFTRSW  12
52         { "after date", 0 },
53 #define BEFRSW  13
54         { "before date", 0 },
55 #define DATFDSW  14
56         { "datefield field", 5 },  /* 5 chars required to differ from -date */
57 #define SEQSW  15
58         { "sequence name", 0 },
59 #define PUBLSW  16
60         { "public", 0 },
61 #define NPUBLSW  17
62         { "nopublic", 2 },
63 #define ZEROSW  18
64         { "zero", 0 },
65 #define NZEROSW  19
66         { "nozero", 2 },
67 #define LISTSW  20
68         { "list", 0 },
69 #define NLISTSW  21
70         { "nolist", 2 },
71 #define FORMATSW  22
72         { "format format", 0 },
73 #define WIDTHSW  23
74     { "width columns", 0 },
75 #define THREADSW  24
76         { "thread", 0 },
77 #define FILESW  25
78         { "file file", 0 },
79 #define VERSIONSW  26
80         { "Version", 0 },
81 #define HELPSW  27
82         { "help", 0 },
83         { NULL, 0 }
84 };
85
86 char *version=VERSION;
87
88 enum nexus_type {
89         noop_t = 0,
90         not_t,
91         and_t,
92         or_t,
93         date_t,
94         grep_t
95 };
96
97 struct bin_data {
98         struct nexus *left;
99         struct nexus *right;
100 };
101
102 struct date_data {
103         char *datef;
104         boolean after;
105         struct tws tws;
106 };
107
108 struct grep_data {
109         char *header;
110         char *pattern;
111         regex_t *preg;
112 };
113
114 struct nexus {
115         enum nexus_type t;
116         boolean match;
117         union {
118                 struct bin_data b;
119                 struct date_data d;
120                 struct grep_data g;
121         } data;
122 };
123
124 static struct nexus *head;
125 static boolean body = FALSE;
126
127 /*
128 ** static prototypes
129 */
130 static int pcompile(char **, char *);
131 static int pmatches(FILE *, int);
132 static boolean nexus_match(struct field *, int, struct nexus *);
133 static void nexus_free(struct nexus **);
134 static void nexus_clear(struct nexus *);
135 static void nexus_debug(struct nexus *, size_t);
136 static void nexus_debug_grep(struct grep_data *);
137 static void print_debug_level(size_t);
138 static struct nexus * createonethread(char *);
139 static struct nexus * createpickthread(char *);
140 static void scan_mbox(char *, char *, int);
141
142
143 static int listsw = -1;
144
145 void putzero_done();
146
147 static void printmsg(FILE *, struct msgs *, int, char *, int);
148
149 int
150 main(int argc, char **argv)
151 {
152         int publicsw = -1, zerosw = 1, vecp = 0, width = 0;
153         unsigned int seqp = 0;
154         int lo, hi, msgnum;
155         char *maildir, *folder = NULL, buf[100];
156         char *cp, **argp, **arguments;
157         char *seqs[NUMATTRS + 1], *vec[MAXARGS];
158         struct msgs_array msgs = { 0, 0, NULL };
159         struct msgs *mp;
160         char *form = NULL;
161         char *fmtstr;
162         FILE *fp;
163         char *file = NULL;
164
165         if (atexit(putzero_done) != 0) {
166                 adios(EX_OSERR, NULL, "atexit failed");
167         }
168
169         setlocale(LC_ALL, "");
170         invo_name = mhbasename(argv[0]);
171
172         /* read user profile/context */
173         context_read();
174
175         arguments = getarguments(invo_name, argc, argv, 1);
176         argp = arguments;
177
178         if (strcmp(invo_name, "scan")==0) {
179                 form = scanformat;
180         }
181
182         while ((cp = *argp++)) {
183                 if (*cp == '-') {
184                         if (*++cp == '-') {
185                                 vec[vecp++] = --cp;
186                                 goto pattern;
187                         }
188                         switch (smatch(cp, switches)) {
189                         case AMBIGSW:
190                                 ambigsw(cp, switches);
191                                 listsw = 0;  /* HACK */
192                                 exit(EX_USAGE);
193                         case UNKWNSW:
194                                 adios(EX_USAGE, NULL, "-%s unknown", cp);
195
196                         case HELPSW:
197                                 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", invo_name);
198                                 print_help(buf, switches, 1);
199                                 listsw = 0;  /* HACK */
200                                 exit(argc == 2 ? EX_OK : EX_USAGE);
201                         case VERSIONSW:
202                                 print_version(invo_name);
203                                 listsw = 0;  /* HACK */
204                                 exit(argc == 2 ? EX_OK : EX_USAGE);
205
206                         case CCSW:
207                         case DATESW:
208                         case FROMSW:
209                         case SUBJSW:
210                         case TOSW:
211                         case DATFDSW:
212                         case AFTRSW:
213                         case BEFRSW:
214                         case SRCHSW:
215                         case THREADSW:
216                                 vec[vecp++] = --cp;
217                         pattern:
218                                 if (!(cp = *argp++)) /* allow -xyz arguments */
219                                         adios(EX_USAGE, NULL, "missing argument to %s",
220                                                         argp[-2]);
221                                 vec[vecp++] = cp;
222                                 continue;
223                         case OTHRSW:
224                                 adios(EX_SOFTWARE, NULL, "internal error!");
225
226                         case ANDSW:
227                         case ORSW:
228                         case NOTSW:
229                         case LBRSW:
230                         case RBRSW:
231                                 vec[vecp++] = --cp;
232                                 continue;
233
234                         case SEQSW:
235                                 if (!(cp = *argp++) || *cp == '-')
236                                         adios(EX_USAGE, NULL, "missing argument to %s",
237                                                         argp[-2]);
238
239                                 /* check if too many sequences specified */
240                                 if (seqp >= NUMATTRS)
241                                         adios(EX_USAGE, NULL, "too many sequences (more than %d) specified", NUMATTRS);
242
243                                 if (!seq_nameok(cp))
244                                         exit(EX_USAGE);
245
246                                 seqs[seqp++] = cp;
247                                 continue;
248                         case PUBLSW:
249                                 publicsw = 1;
250                                 continue;
251                         case NPUBLSW:
252                                 publicsw = 0;
253                                 continue;
254                         case ZEROSW:
255                                 zerosw++;
256                                 continue;
257                         case NZEROSW:
258                                 zerosw = 0;
259                                 continue;
260
261                         case LISTSW:
262                                 listsw = 1;
263                                 continue;
264                         case NLISTSW:
265                                 listsw = 0;
266                                 continue;
267                         case FORMATSW:
268                                 if (!(form = *argp++) || *form == '-') {
269                                         adios(EX_USAGE, NULL, "missing argument to %s", argp[-2]);
270                                 }
271                                 continue;
272                         case WIDTHSW:
273                                 if (!(cp = *argp++) || *cp == '-') {
274                                         adios(EX_USAGE, NULL, "missing argument to %s",
275                                                         argp[-2]);
276                                 }
277                                 width = atoi(cp);
278                                 continue;
279                         case FILESW:
280                                 if (!(cp = *argp++) || (cp[0] == '-' && cp[1])) {
281                                         adios(EX_USAGE, NULL, "missing argument to %s",
282                                                         argp[-2]);
283                                 }
284                                 if (strcmp(file = cp, "-")!=0) {
285                                         file = mh_xstrdup(expanddir(cp));
286                                 }
287                                 continue;
288                         }
289                 }
290                 if (*cp == '+' || *cp == '@') {
291                         if (folder)
292                                 adios(EX_USAGE, NULL, "only one folder at a time!");
293                         else
294                                 folder = mh_xstrdup(expandfol(cp));
295                 } else
296                         app_msgarg(&msgs, cp);
297         }
298         vec[vecp] = NULL;
299
300         fmtstr = new_fs(form, "pick.default");
301
302         if (file) {
303                 if (folder) {
304                         adios(EX_USAGE, NULL, "\"+folder\" not allowed with -file");
305                 }
306                 if (msgs.size) {
307                         adios(EX_USAGE, NULL, "\"msgs\" not allowed with -file");
308                 }
309                 if (vecp) {
310                         adios(EX_USAGE, NULL, "section arguments not allowed with -file");
311                 }
312
313                 scan_mbox(file, fmtstr, width);
314                 exit(EX_OK);
315         }
316
317         /*
318         ** If we didn't specify which messages to search,
319         ** then search the whole folder.
320         */
321         if (!msgs.size)
322                 app_msgarg(&msgs, seq_all);
323
324         if (!folder)
325                 folder = getcurfol();
326         maildir = toabsdir(folder);
327
328         if (chdir(maildir) == NOTOK)
329                 adios(EX_OSERR, maildir, "unable to change directory to");
330
331         /* read folder and create message structure */
332         if (!(mp = folder_read(folder)))
333                 adios(EX_IOERR, NULL, "unable to read folder %s", folder);
334
335         /* check for empty folder */
336         if (mp->nummsg == 0)
337                 adios(EX_DATAERR, NULL, "no messages in %s", folder);
338
339         /* parse all the message ranges/sequences and set SELECTED */
340         for (msgnum = 0; msgnum < msgs.size; msgnum++)
341                 if (!m_convert(mp, msgs.msgs[msgnum]))
342                         exit(EX_USAGE);
343         seq_setprev(mp);  /* set the previous-sequence */
344
345         /*
346         ** If we aren't saving the results to a sequence,
347         ** we default to list the results.
348         */
349         if (listsw == -1)
350                 listsw = !seqp;
351
352         if (publicsw == 1 && is_readonly(mp))
353                 adios(EX_NOPERM, NULL, "folder %s is read-only, so -public not allowed",
354                                 folder);
355
356         if (!pcompile(vec, NULL))
357                 exit(EX_SOFTWARE);
358
359         lo = mp->lowsel;
360         hi = mp->hghsel;
361
362         /*
363         ** If printing message numbers to standard out,
364         ** force line buffering on.
365         */
366         if (listsw)
367                 setvbuf(stdout, NULL, _IOLBF, 0);
368
369         /*
370         ** Scan through all the SELECTED messages and check for a
371         ** match.  If the message does not match, then unselect it.
372         */
373         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
374                 if (is_selected(mp, msgnum)) {
375                         if ((fp = fopen(cp = m_name(msgnum), "r")) == NULL)
376                                 admonish(cp, "unable to read message");
377                         if (fp && pmatches(fp, msgnum)) {
378                                 if (msgnum < lo)
379                                         lo = msgnum;
380                                 if (msgnum > hi)
381                                         hi = msgnum;
382
383                                 if (listsw) {
384                                         printmsg(fp, mp, msgnum, fmtstr, width);
385                                 }
386                         } else {
387                                 /* if it doesn't match, then unselect it */
388                                 unset_selected(mp, msgnum);
389                         }
390                         if (fp)
391                                 fclose(fp);
392                 }
393         }
394
395         nexus_free(&head);
396
397         mp->lowsel = lo;
398         mp->hghsel = hi;
399
400         if (mp->numsel <= 0)
401                 adios(EX_DATAERR, NULL, "no messages match specification");
402
403         seqs[seqp] = NULL;
404
405         /*
406         ** Add the matching messages to sequences
407         */
408         for (seqp = 0; seqs[seqp]; seqp++)
409                 if (!seq_addsel(mp, seqs[seqp], publicsw, zerosw))
410                         exit(EX_USAGE);
411
412         /*
413         ** Print total matched if not printing each matched message number.
414         */
415         if (!listsw) {
416                 printf("%d hit%s\n", mp->numsel, mp->numsel == 1 ? "" : "s");
417         }
418
419         context_replace(curfolder, folder);  /* update current folder */
420         seq_save(mp);  /* synchronize message sequences */
421         context_save();  /* save the context file */
422         folder_free(mp);  /* free folder/message structure */
423         listsw = 0; /* HACK */
424         return 0;
425 }
426
427 static void
428 scan_mbox(char *file, char *fmtstr, int width)
429 {
430         FILE *in;
431         int msgnum;
432         int state;
433
434         if (strcmp(file, "-") == 0) {
435                 in = stdin;
436                 file = "stdin";
437         } else if (!(in = fopen(file, "r"))) {
438                 adios(EX_IOERR, file, "unable to open");
439         }
440
441         for (msgnum = 1; ;msgnum++) {
442                 state = scan(in, msgnum, SCN_MBOX, fmtstr, width, 0, 0);
443                 if (state != SCNMSG) {
444                         break;
445                 }
446         }
447         fclose(in);
448 }
449
450 void
451 putzero_done()
452 {
453         if (listsw && !isatty(fileno(stdout)))
454                 printf("0\n");
455 }
456
457 static void
458 printmsg(FILE *f, struct msgs *mp, int msgnum, char *fmtstr, int width)
459 {
460         int seqnum;
461         int state;
462         boolean unseen = FALSE;
463
464         fseek(f, 0L, SEEK_SET);
465
466         seqnum = seq_getnum(mp, seq_unseen);
467         unseen = in_sequence(mp, seqnum, msgnum);
468
469         switch (state = scan(f, msgnum, SCN_FOLD, fmtstr,
470                         width, msgnum==mp->curmsg, unseen)) {
471         case SCNMSG:
472         case SCNERR:
473                 break;
474         case SCNEOF:
475                 advise(NULL, "message %d: empty", msgnum);
476                 break;
477         default:
478                 adios(EX_SOFTWARE, NULL, "scan() botch(%d)", state);
479         }
480 }
481
482 static struct swit parswit[] = {
483 #define PRAND   0
484         { "and", 0 },
485 #define PROR    1
486         { "or", 0 },
487 #define PRNOT   2
488         { "not", 0 },
489 #define PRLBR   3
490         { "lbrace", 0 },
491 #define PRRBR   4
492         { "rbrace", 0 },
493 #define PRCC    5
494         { "cc  pattern", 0 },
495 #define PRDATE  6
496         { "date  pattern", 0 },
497 #define PRFROM  7
498         { "from  pattern", 0 },
499 #define PRSRCH  8
500         { "search  pattern", 0 },
501 #define PRSUBJ  9
502         { "subject  pattern", 0 },
503 #define PRTO   10
504         { "to  pattern", 0 },
505 #define PROTHR 11
506         { "-othercomponent  pattern", 15 },
507 #define PRAFTR 12
508         { "after date", 0 },
509 #define PRBEFR 13
510         { "before date", 0 },
511 #define PRDATF 14
512         { "datefield field", 5 },
513 #define PRTHREAD 15
514         { "thread msg", 0 },
515         { NULL, 0 }
516 };
517
518 /* DEFINITIONS FOR PATTERN MATCHING */
519
520 /*
521 ** We really should be using re_comp() and re_exec() here.  Unfortunately,
522 ** pick advertises that lowercase characters matches characters of both
523 ** cases.  Since re_exec() doesn't exhibit this behavior, we are stuck
524 ** with this version.  Furthermore, we need to be able to save and restore
525 ** the state of the pattern matcher in order to do things "efficiently".
526 **
527 ** The matching power of this algorithm isn't as powerful as the re_xxx()
528 ** routines (no \(xxx\) and \n constructs).  Such is life.
529 */
530
531 #define CCHR       2
532 #define CDOT       4
533 #define CCL        6
534 #define NCCL       8
535 #define CDOL      10
536 #define CEOF      11
537
538 #define STAR      01
539
540 #define LBSIZE  1024
541 #define ESIZE   1024
542
543 /*
544 ** DEFINITIONS FOR NEXUS
545 */
546
547 #define nxtarg() (*argp ? *argp++ : NULL)
548 #define prvarg() argp--
549
550 #define padvise if (!talked++) advise
551
552 static int talked;
553 static int pdebug = 0;
554
555 static char *datesw;
556 static char **argp;
557
558 /*
559 ** prototypes for date routines
560 */
561 static struct tws *tws_parse(char *, int);
562 static struct tws *tws_special(char *);
563
564 /*
565 ** static prototypes
566 */
567 static int gcompile(struct grep_data *, const char *);
568 static int tcompile(char *, struct tws *, int);
569
570 static struct nexus *parse(void);
571 static struct nexus *nexp1(void);
572 static struct nexus *nexp2(void);
573 static struct nexus *nexp3(void);
574 static struct nexus *newnexus(enum nexus_type);
575
576 static int
577 pcompile(char **vec, char *date)
578 {
579         char *cp;
580
581         if ((cp = getenv("MHPDEBUG")) && *cp)
582                 pdebug++;
583
584         argp = vec;
585         if ((datesw = date) == NULL)
586                 datesw = "date";
587         talked = 0;
588
589         if ((head = parse()) == NULL)
590                 return (talked ? 0 : 1);
591
592         if (*argp) {
593                 padvise(NULL, "%s unexpected", *argp);
594                 return 0;
595         }
596
597         return 1;
598 }
599
600
601 static struct nexus *
602 parse(void)
603 {
604         char  *cp;
605         struct nexus *n, *o;
606         struct bin_data *bin;
607
608         if ((n = nexp1()) == NULL || (cp = nxtarg()) == NULL)
609                 return n;
610
611         if (*cp != '-') {
612                 padvise(NULL, "%s unexpected", cp);
613                 return NULL;
614         }
615
616         if (*++cp == '-')
617                 goto header;
618         switch (smatch(cp, parswit)) {
619         case AMBIGSW:
620                 ambigsw(cp, parswit);
621                 talked++;
622                 return NULL;
623         case UNKWNSW:
624                 fprintf(stderr, "-%s unknown\n", cp);
625                 talked++;
626                 return NULL;
627
628         case PROR:
629                 o = newnexus(or_t);
630                 bin = &o->data.b;
631                 bin->left = n;
632                 if ((bin->right = parse()))
633                         return o;
634                 padvise(NULL, "missing disjunctive");
635                 return NULL;
636
637 header: ;
638         default:
639                 prvarg();
640                 return n;
641         }
642 }
643
644 static struct nexus *
645 nexp1(void)
646 {
647         char *cp;
648         struct nexus *n, *o;
649         struct bin_data *bin;
650
651         if ((n = nexp2()) == NULL || (cp = nxtarg()) == NULL)
652                 return n;
653
654         if (*cp != '-') {
655                 padvise(NULL, "%s unexpected", cp);
656                 return NULL;
657         }
658
659         if (*++cp == '-')
660                 goto header;
661         switch (smatch(cp, parswit)) {
662         case AMBIGSW:
663                 ambigsw(cp, parswit);
664                 talked++;
665                 return NULL;
666         case UNKWNSW:
667                 fprintf(stderr, "-%s unknown\n", cp);
668                 talked++;
669                 return NULL;
670
671         case PRAND:
672                 o = newnexus(and_t);
673                 bin = &o->data.b;
674                 bin->left = n;
675                 if ((bin->right = nexp1()))
676                         return o;
677                 padvise(NULL, "missing conjunctive");
678                 return NULL;
679
680 header: ;
681         default:
682                 prvarg();
683                 return n;
684         }
685 }
686
687
688 static struct nexus *
689 nexp2(void)
690 {
691         char *cp;
692         struct nexus *n;
693         struct bin_data *bin;
694
695         if ((cp = nxtarg()) == NULL)
696                 return NULL;
697
698         if (*cp != '-') {
699                 prvarg();
700                 return nexp3();
701         }
702
703         if (*++cp == '-')
704                 goto header;
705         switch (smatch(cp, parswit)) {
706         case AMBIGSW:
707                 ambigsw(cp, parswit);
708                 talked++;
709                 return NULL;
710         case UNKWNSW:
711                 fprintf(stderr, "-%s unknown\n", cp);
712                 talked++;
713                 return NULL;
714
715         case PRNOT:
716                 n = newnexus(not_t);
717                 bin = &n->data.b;
718                 if ((bin->left = nexp3()))
719                         return n;
720                 padvise(NULL, "missing negation");
721                 return NULL;
722
723 header: ;
724         default:
725                 prvarg();
726                 return nexp3();
727         }
728 }
729
730 static struct nexus *
731 nexp3(void)
732 {
733         int i;
734         char *cp, *dp;
735         char buffer[BUFSIZ], temp[64];
736         struct nexus *n;
737         struct grep_data *gdata;
738         struct date_data *twsd;
739
740         if ((cp = nxtarg()) == NULL)
741                 return NULL;
742
743         if (*cp != '-') {
744                 padvise(NULL, "%s unexpected", cp);
745                 return NULL;
746         }
747
748         if (*++cp == '-') {
749                 dp = ++cp;
750                 goto header;
751         }
752         switch (i = smatch(cp, parswit)) {
753         case AMBIGSW:
754                 ambigsw(cp, parswit);
755                 talked++;
756                 return NULL;
757         case UNKWNSW:
758                 fprintf(stderr, "-%s unknown\n", cp);
759                 talked++;
760                 return NULL;
761
762         case PRLBR:
763                 if ((n = parse()) == NULL) {
764                         padvise(NULL, "missing group");
765                         return NULL;
766                 }
767                 if ((cp = nxtarg()) == NULL) {
768                         padvise(NULL, "missing -rbrace");
769                         return NULL;
770                 }
771                 if (*cp++ == '-' && smatch(cp, parswit) == PRRBR)
772                         return n;
773                 padvise(NULL, "%s unexpected", --cp);
774                 return NULL;
775
776         default:
777                 prvarg();
778                 return NULL;
779
780         case PRTHREAD:
781                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
782                         padvise(NULL, "missing argument to %s", argp[-2]);
783                 }
784                 return createpickthread(cp);
785         case PRCC:
786         case PRDATE:
787         case PRFROM:
788         case PRTO:
789         case PRSUBJ:
790                 strncpy(temp, parswit[i].sw, sizeof(temp));
791                 temp[sizeof(temp) - 1] = '\0';
792                 dp = *brkstring(temp, " ", NULL);
793 header: ;
794                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
795                         padvise(NULL, "missing argument to %s", argp[-2]);
796                         return NULL;
797                 }
798                 n = newnexus(grep_t);
799                 gdata = &n->data.g;
800                 gdata->header = mh_xstrdup(dp);
801                 snprintf(buffer, sizeof(buffer), "%s", cp);
802                 dp = buffer;
803                 goto pattern;
804
805         case PRSRCH:
806                 n = newnexus(grep_t);
807                 gdata = &n->data.g;
808                 gdata->header = NULL;
809                 body = TRUE;
810                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
811                         padvise(NULL, "missing argument to %s", argp[-2]);
812                         return NULL;
813                 }
814                 dp = cp;
815 pattern: ;
816                 if (!gcompile(gdata, dp)) {
817                         padvise("regcomp", "pattern error in %s %s", argp[-2], cp);
818                         return NULL;
819                 }
820                 return n;
821
822         case PROTHR:
823                 padvise(NULL, "internal error!");
824                 return NULL;
825
826         case PRDATF:
827                 if (!(datesw = nxtarg()) || *datesw == '-') {
828                         padvise(NULL, "missing argument to %s",
829                                         argp[-2]);
830                         return NULL;
831                 }
832                 return nexp3();
833
834         case PRAFTR:
835         case PRBEFR:
836                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
837                         padvise(NULL, "missing argument to %s", argp[-2]);
838                         return NULL;
839                 }
840                 n = newnexus(date_t);
841                 twsd = &n->data.d;
842                 twsd->datef = datesw;
843                 if (!tcompile(cp, &twsd->tws, twsd->after = i == PRAFTR)) {
844                         padvise(NULL, "unable to parse %s %s", argp[-2], cp);
845                         return NULL;
846                 }
847                 return n;
848         }
849 }
850
851
852 static struct nexus *
853 newnexus(enum nexus_type t)
854 {
855         struct nexus *p = NULL;
856         p = mh_xcalloc(1, sizeof(struct nexus));
857         p->t = t;
858         return p;
859
860 }
861
862 static void nexus_clear(struct nexus *n)
863 {
864         n->match = FALSE;
865         switch(n->t) {
866         case and_t:
867         case or_t:
868                 nexus_clear(n->data.b.right);
869                 /* FALL */
870         case not_t:
871                 nexus_clear(n->data.b.left);
872                 break;
873         default:
874                 break;
875         }
876 }
877
878 static int
879 pmatches(FILE *fp, int msgnum)
880 {
881         struct field f = {{0}};
882         enum state s = FLD2;
883
884
885         if (!head)
886                 return 1;
887
888         nexus_clear(head);
889         if (!talked++ && pdebug) {
890                 nexus_debug(head, 0);
891         }
892
893         while (s == FLD2 || s == BODY2) {
894                 switch (s = m_getfld2(s, &f, fp)) {
895                 case LENERR2:
896                         s = FLD2;
897                         /* FALL */
898                 case FLD2:
899                         nexus_match(&f, msgnum, head);
900                         break;
901                 case BODY2:
902                         if (!body) {
903                                 return head->match;
904                         }
905                         nexus_match(&f, msgnum, head);
906                         break;
907                 case IOERR2:
908                         advise(NULL, "IOERR in message %d\n", msgnum);
909                         return FALSE;
910                 case FILEEOF2:
911                         break;
912                 default:
913                         adios(EX_SOFTWARE, "m_getfld2", "returned unknown state %d at message %d", s, msgnum);
914                 }
915         }
916         return head->match;
917 }
918
919 static boolean
920 match_grep(struct field *f, struct grep_data *g)
921 {
922         int ret;
923         char buf[BUFSIZ];
924
925         if (!g->header && *f->name) {
926                 return FALSE;
927         }
928
929         if (!g->header) {
930                 ret = regexec(g->preg, f->value, 0, NULL, 0);
931                 goto out;
932         }
933
934         /* check for the right field */
935         if (!(g->header && *g->header && mh_strcasecmp(g->header, f->name)==0)) {
936                 return FALSE;
937         }
938
939         if (decode_rfc2047(f->value, buf, sizeof(buf))) {
940                 ret = regexec(g->preg, buf, 0, NULL, 0);
941         } else {
942                 ret = regexec(g->preg, f->value, 0, NULL, 0);
943         }
944 out:
945         switch (ret) {
946         case 0:
947                 return TRUE;
948         case REG_NOMATCH:
949                 return FALSE;
950         default:
951                 regerror(ret, g->preg, buf, sizeof(buf));
952                 fprintf(stderr, "%s\n", buf);
953                 return FALSE;
954         }
955 }
956
957 static boolean
958 match_date(struct field *f, int msgnum, struct date_data *dd)
959 {
960         struct tws *tw;
961         char *bp;
962         boolean ret = FALSE;
963
964         if (mh_strcasecmp(f->name, dd->datef)!=0) {
965                 return FALSE;
966         }
967         bp = mh_xstrdup(f->value);
968         if ((tw = dparsetime(bp)) == NULL) {
969                 advise(NULL, "unable to parse %s field in message %d, not matching...", dd->datef, msgnum);
970         } else if (dd->after) {
971                 ret = twsort(tw, &dd->tws) > 0;
972         } else {
973                 ret = twsort(tw, &dd->tws) < 0;
974         }
975
976         mh_free0(&bp);
977         return ret;
978 }
979
980 static boolean
981 nexus_match(struct field *f, int msgnum, struct nexus *n)
982 {
983         switch (n->t) {
984         case and_t:
985                 n->match = nexus_match(f, msgnum, n->data.b.left);
986                 n->match = nexus_match(f, msgnum, n->data.b.right) && n->match;
987                 break;
988         case or_t:
989                 n->match = nexus_match(f, msgnum, n->data.b.left);
990                 n->match = nexus_match(f, msgnum, n->data.b.right) || n->match;
991                 break;
992         case not_t:
993                 n->match = !nexus_match(f, msgnum, n->data.b.left);
994                 break;
995         case date_t:
996                 if (n->match) {
997                         return n->match;
998                 }
999                 n->match = match_date(f, msgnum, &n->data.d);
1000                 break;
1001         case grep_t:
1002                 if (n->match) {
1003                         return n->match;
1004                 }
1005                 n->match = match_grep(f, &n->data.g);
1006                 break;
1007         default:
1008                 adios(EX_SOFTWARE, NULL, "nexus tree contains a unknown nexus_type (%d)", n->t);
1009         }
1010         return n->match;
1011 }
1012
1013 static void
1014 nexus_debug(struct nexus *n, size_t level)
1015 {
1016         struct date_data *dd;
1017         print_debug_level(level);
1018         switch (n->t) {
1019         case and_t:
1020                 fputs("AND\n", stderr);
1021                 nexus_debug(n->data.b.left, level+1);
1022                 nexus_debug(n->data.b.right, level+1);
1023                 break;
1024         case or_t:
1025                 fputs("OR\n", stderr);
1026                 nexus_debug(n->data.b.left, level+1);
1027                 nexus_debug(n->data.b.right, level+1);
1028                 break;
1029         case not_t:
1030                 fputs("NOT\n", stderr);
1031                 nexus_debug(n->data.b.left, level+1);
1032                 break;
1033         case grep_t:
1034                 nexus_debug_grep(&n->data.g);
1035                 break;
1036         case date_t:
1037                 dd = &n->data.d;
1038                 fprintf(stderr, "TEMPORAL(%s) %s: %s\n",dd->after ? "after" : "before", dd->datef, dasctime(&dd->tws));
1039                 break;
1040         default:
1041                 adios(EX_SOFTWARE, NULL, "nexus tree contains a unknown nexus_type (%d)", n->t);
1042         }
1043 }
1044
1045 static void
1046 nexus_debug_grep(struct grep_data *gd)
1047 {
1048         char *buf, *buf2, *pbuf, *pbuf2;
1049
1050         pbuf = pbuf2 = mh_xstrdup(gd->pattern);
1051
1052         for (;*pbuf2; pbuf2++) {
1053                 *pbuf2 = tolower(*pbuf2);
1054         }
1055
1056         if (gd->header) {
1057                 buf = buf2 = mh_xstrdup(gd->header);
1058                 for (;*buf2; buf2++) {
1059                         *buf2 = tolower(*buf2);
1060                 }
1061                 fprintf(stderr, "PETTERN(%s) %s\n", buf, pbuf);
1062         } else {
1063                 fprintf(stderr, "PETTERN(BODY) %s\n", pbuf);
1064         }
1065         mh_free0(&buf);
1066         mh_free0(&pbuf);
1067 }
1068
1069 static void
1070 nexus_free(struct nexus **n)
1071 {
1072         if (!(*n)) {
1073                 return;
1074         }
1075         switch((*n)->t) {
1076         case and_t:
1077         case or_t:
1078                 nexus_free(&(*n)->data.b.right);
1079                 /* FALL */
1080         case not_t:
1081                 nexus_free(&(*n)->data.b.left);
1082                 break;
1083         case grep_t:
1084                 mh_free0(&(*n)->data.g.header);
1085                 mh_free0(&(*n)->data.g.pattern);
1086                 regfree((*n)->data.g.preg);
1087         case date_t:
1088                 break;
1089         default:
1090                 advise(NULL, "Unknown nexus_type (%d) to free", (*n)->t);
1091         }
1092         mh_free0(n);
1093 }
1094
1095 static void
1096 print_debug_level(size_t level)
1097 {
1098         size_t i;
1099
1100         for (i = 0; i < level; i++) {
1101                 fputs("| ", stderr);
1102         }
1103 }
1104
1105 static int
1106 gcompile(struct grep_data *g, const char *astr)
1107 {
1108         regex_t *preg = mh_xcalloc(1, sizeof(regex_t));
1109         char *buf;
1110         int ret;
1111
1112         g->preg = preg;
1113         g->pattern = mh_xstrdup(astr);
1114         ret = regcomp(preg, astr, REG_ICASE | REG_NOSUB);
1115         if (ret != 0) {
1116                 buf = mh_xcalloc(BUFSIZ, sizeof(char));
1117                 regerror(ret, g->preg, buf, BUFSIZ*sizeof(char));
1118                 fprintf(stderr, "%s\n", buf);
1119                 return FALSE;
1120         }
1121         return TRUE;
1122
1123 }
1124
1125 static int
1126 tcompile(char *ap, struct tws *tb, int isafter)
1127 {
1128         struct tws *tw;
1129
1130         if ((tw = tws_parse(ap, isafter)) == NULL)
1131                 return 0;
1132
1133         twscopy(tb, tw);
1134         return 1;
1135 }
1136
1137
1138 static struct tws *
1139 tws_parse(char *ap, int isafter)
1140 {
1141         char buffer[BUFSIZ];
1142         struct tws *tw, *ts;
1143
1144         if ((tw = tws_special(ap)) != NULL) {
1145                 tw->tw_sec = tw->tw_min = isafter ? 59 : 0;
1146                 tw->tw_hour = isafter ? 23 : 0;
1147                 return tw;
1148         }
1149         if ((tw = dparsetime(ap)) != NULL)
1150                 return tw;
1151
1152         if ((ts = dlocaltimenow()) == NULL)
1153                 return NULL;
1154
1155         snprintf(buffer, sizeof(buffer), "%s %s", ap, dtwszone(ts));
1156         if ((tw = dparsetime(buffer)) != NULL)
1157                 return tw;
1158
1159         snprintf(buffer, sizeof(buffer), "%s %02d:%02d:%02d %s", ap,
1160                         ts->tw_hour, ts->tw_min, ts->tw_sec, dtwszone(ts));
1161         if ((tw = dparsetime(buffer)) != NULL)
1162                 return tw;
1163
1164         snprintf(buffer, sizeof(buffer), "%02d %s %04d %s",
1165                         ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year, ap);
1166         if ((tw = dparsetime(buffer)) != NULL)
1167                 return tw;
1168
1169         snprintf(buffer, sizeof(buffer), "%02d %s %04d %s %s",
1170                         ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year,
1171                         ap, dtwszone(ts));
1172         if ((tw = dparsetime(buffer)) != NULL)
1173                 return tw;
1174
1175         return NULL;
1176 }
1177
1178
1179 static struct tws *
1180 tws_special(char *ap)
1181 {
1182         int i;
1183         time_t clock;
1184         struct tws *tw;
1185
1186         time(&clock);
1187         if (!mh_strcasecmp(ap, "today"))
1188                 return dlocaltime(&clock);
1189         if (!mh_strcasecmp(ap, "yesterday")) {
1190                 clock -= (long) (60 * 60 * 24);
1191                 return dlocaltime(&clock);
1192         }
1193         if (!mh_strcasecmp(ap, "tomorrow")) {
1194                 clock += (long) (60 * 60 * 24);
1195                 return dlocaltime(&clock);
1196         }
1197
1198         for (i = 0; tw_ldotw[i]; i++)
1199                 if (!mh_strcasecmp(ap, tw_ldotw[i]))
1200                         break;
1201         if (tw_ldotw[i]) {
1202                 if ((tw = dlocaltime(&clock)) == NULL)
1203                         return NULL;
1204                 if ((i -= tw->tw_wday) > 0)
1205                         i -= 7;
1206         }
1207         else
1208                 if (*ap != '-')
1209                         return NULL;
1210                 else  /* -ddd days ago */
1211                         i = atoi(ap);  /* we should error check this */
1212
1213         clock += (long) ((60 * 60 * 24) * i);
1214         return dlocaltime(&clock);
1215 }
1216
1217
1218 static struct nexus *
1219 createpickthread(char *msgs)
1220 {
1221         char *folder = NULL;
1222         struct msgs_array msgarray = {0};
1223         struct msgs_array files = {0};
1224         struct nexus *ret = NULL;
1225         struct nexus *c;
1226         struct nexus *or;
1227         struct bin_data *bd;
1228         char *buf;
1229         char **cp = brkstring(msgs, " \t", NULL);
1230         int i;
1231
1232         for (; cp && *cp; cp++) {
1233                 switch (**cp) {
1234                 case '@':
1235                 case '+':
1236                         if (folder) {
1237                                 advise("","");
1238                                 break;
1239                         }
1240                         folder = mh_xstrdup(*cp);
1241                         break;
1242                 default:
1243                         app_msgarg(&msgarray, mh_xstrdup(*cp));
1244                 }
1245         }
1246
1247         parse_msgs(&msgarray, folder, &files);
1248
1249         for (i = 0; i < files.size; i++) {
1250                 buf = getthreadid(files.msgs[i]);
1251                 if (!buf) {
1252                         adios(EX_DATAERR, NULL, "message %s is not part of a thread", basename(files.msgs[i]));
1253                         continue;
1254                 }
1255
1256                 c = createonethread(buf);
1257
1258                 if (!ret) {
1259                         ret = c;
1260                         continue;
1261                 }
1262
1263
1264                 or = newnexus(or_t);
1265                 bd = &or->data.b;
1266                 bd->right = ret;
1267                 bd->left = c;
1268                 ret = or;
1269         }
1270
1271         mh_free0(&(files.msgs));
1272         mh_free0(&(msgarray.msgs));
1273
1274         return ret;
1275 }
1276
1277 static struct nexus *
1278 createonethread(char *c)
1279 {
1280         struct nexus *ret = newnexus(or_t);
1281         struct nexus *left = newnexus(grep_t);
1282         struct nexus *right = newnexus(grep_t);
1283         char buf[BUFSIZ];
1284
1285         ret->data.b.left = left;
1286         ret->data.b.right = right;
1287         left->data.g.header = mh_xstrdup("message-id");
1288
1289
1290         snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1291         if(!gcompile(&left->data.g, buf)) {
1292                 padvise(NULL, "pattern error %s", c);
1293                 goto error;
1294         }
1295
1296         right->data.g.header = mh_xstrdup("references");
1297
1298         snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1299         if(!gcompile(&right->data.g, buf)) {
1300                 padvise(NULL, "pattern error in %s", c);
1301                 goto error;
1302         }
1303
1304         return ret;
1305
1306 error:
1307         nexus_free(&ret);
1308         return NULL;
1309         
1310 }