mhl and mhbuild ignore to long lines
[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
344         /*
345         ** If we aren't saving the results to a sequence,
346         ** we default to list the results.
347         */
348         if (listsw == -1)
349                 listsw = !seqp;
350
351         if (publicsw == 1 && is_readonly(mp))
352                 adios(EX_NOPERM, NULL, "folder %s is read-only, so -public not allowed",
353                                 folder);
354
355         if (!pcompile(vec, NULL))
356                 exit(EX_SOFTWARE);
357
358         lo = mp->lowsel;
359         hi = mp->hghsel;
360
361         /*
362         ** If printing message numbers to standard out,
363         ** force line buffering on.
364         */
365         if (listsw)
366                 setvbuf(stdout, NULL, _IOLBF, 0);
367
368         /*
369         ** Scan through all the SELECTED messages and check for a
370         ** match.  If the message does not match, then unselect it.
371         */
372         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
373                 if (is_selected(mp, msgnum)) {
374                         if ((fp = fopen(cp = m_name(msgnum), "r")) == NULL)
375                                 admonish(cp, "unable to read message");
376                         if (fp && pmatches(fp, msgnum)) {
377                                 if (msgnum < lo)
378                                         lo = msgnum;
379                                 if (msgnum > hi)
380                                         hi = msgnum;
381
382                                 if (listsw) {
383                                         printmsg(fp, mp, msgnum, fmtstr, width);
384                                 }
385                         } else {
386                                 /* if it doesn't match, then unselect it */
387                                 unset_selected(mp, msgnum);
388                         }
389                         if (fp)
390                                 fclose(fp);
391                 }
392         }
393
394         nexus_free(&head);
395
396         mp->lowsel = lo;
397         mp->hghsel = hi;
398
399         if (mp->numsel <= 0)
400                 adios(EX_DATAERR, NULL, "no messages match specification");
401
402         seqs[seqp] = NULL;
403
404         /*
405         ** Add the matching messages to sequences
406         */
407         for (seqp = 0; seqs[seqp]; seqp++)
408                 if (!seq_addsel(mp, seqs[seqp], publicsw, zerosw))
409                         exit(EX_USAGE);
410
411         /*
412         ** Print total matched if not printing each matched message number.
413         */
414         if (!listsw) {
415                 printf("%d hit%s\n", mp->numsel, mp->numsel == 1 ? "" : "s");
416         }
417
418         context_replace(curfolder, folder);  /* update current folder */
419         seq_save(mp);  /* synchronize message sequences */
420         context_save();  /* save the context file */
421         folder_free(mp);  /* free folder/message structure */
422         listsw = 0; /* HACK */
423         return 0;
424 }
425
426 static void
427 scan_mbox(char *file, char *fmtstr, int width)
428 {
429         FILE *in;
430         int msgnum;
431         int state;
432
433         if (strcmp(file, "-") == 0) {
434                 in = stdin;
435                 file = "stdin";
436         } else if (!(in = fopen(file, "r"))) {
437                 adios(EX_IOERR, file, "unable to open");
438         }
439
440         for (msgnum = 1; ;msgnum++) {
441                 state = scan(in, msgnum, SCN_MBOX, fmtstr, width, 0, 0);
442                 if (state != SCNMSG) {
443                         break;
444                 }
445         }
446         fclose(in);
447 }
448
449 void
450 putzero_done()
451 {
452         if (listsw && !isatty(fileno(stdout)))
453                 printf("0\n");
454 }
455
456 static void
457 printmsg(FILE *f, struct msgs *mp, int msgnum, char *fmtstr, int width)
458 {
459         int seqnum;
460         int state;
461         boolean unseen = FALSE;
462
463         fseek(f, 0L, SEEK_SET);
464
465         seqnum = seq_getnum(mp, seq_unseen);
466         unseen = in_sequence(mp, seqnum, msgnum);
467
468         switch (state = scan(f, msgnum, SCN_FOLD, fmtstr,
469                         width, msgnum==mp->curmsg, unseen)) {
470         case SCNMSG:
471         case SCNERR:
472                 break;
473         case SCNEOF:
474                 advise(NULL, "message %d: empty", msgnum);
475                 break;
476         default:
477                 adios(EX_SOFTWARE, NULL, "scan() botch(%d)", state);
478         }
479 }
480
481 static struct swit parswit[] = {
482 #define PRAND   0
483         { "and", 0 },
484 #define PROR    1
485         { "or", 0 },
486 #define PRNOT   2
487         { "not", 0 },
488 #define PRLBR   3
489         { "lbrace", 0 },
490 #define PRRBR   4
491         { "rbrace", 0 },
492 #define PRCC    5
493         { "cc  pattern", 0 },
494 #define PRDATE  6
495         { "date  pattern", 0 },
496 #define PRFROM  7
497         { "from  pattern", 0 },
498 #define PRSRCH  8
499         { "search  pattern", 0 },
500 #define PRSUBJ  9
501         { "subject  pattern", 0 },
502 #define PRTO   10
503         { "to  pattern", 0 },
504 #define PROTHR 11
505         { "-othercomponent  pattern", 15 },
506 #define PRAFTR 12
507         { "after date", 0 },
508 #define PRBEFR 13
509         { "before date", 0 },
510 #define PRDATF 14
511         { "datefield field", 5 },
512 #define PRTHREAD 15
513         { "thread msg", 0 },
514         { NULL, 0 }
515 };
516
517 /*
518 ** DEFINITIONS FOR NEXUS
519 */
520
521 #define nxtarg() (*argp ? *argp++ : NULL)
522 #define prvarg() argp--
523
524 #define padvise if (!talked++) advise
525
526 static int talked;
527 static int pdebug = 0;
528
529 static char *datesw;
530 static char **argp;
531
532 /*
533 ** prototypes for date routines
534 */
535 static struct tws *tws_parse(char *, int);
536 static struct tws *tws_special(char *);
537
538 /*
539 ** static prototypes
540 */
541 static int gcompile(struct grep_data *, const char *);
542 static int tcompile(char *, struct tws *, int);
543
544 static struct nexus *parse(void);
545 static struct nexus *nexp1(void);
546 static struct nexus *nexp2(void);
547 static struct nexus *nexp3(void);
548 static struct nexus *newnexus(enum nexus_type);
549
550 static int
551 pcompile(char **vec, char *date)
552 {
553         char *cp;
554
555         if ((cp = getenv("MHPDEBUG")) && *cp)
556                 pdebug++;
557
558         argp = vec;
559         if ((datesw = date) == NULL)
560                 datesw = "date";
561         talked = 0;
562
563         if ((head = parse()) == NULL)
564                 return (talked ? 0 : 1);
565
566         if (*argp) {
567                 padvise(NULL, "%s unexpected", *argp);
568                 return 0;
569         }
570
571         return 1;
572 }
573
574
575 static struct nexus *
576 parse(void)
577 {
578         char  *cp;
579         struct nexus *n, *o;
580         struct bin_data *bin;
581
582         if ((n = nexp1()) == NULL || (cp = nxtarg()) == NULL)
583                 return n;
584
585         if (*cp != '-') {
586                 padvise(NULL, "%s unexpected", cp);
587                 return NULL;
588         }
589
590         if (*++cp == '-')
591                 goto header;
592         switch (smatch(cp, parswit)) {
593         case AMBIGSW:
594                 ambigsw(cp, parswit);
595                 talked++;
596                 return NULL;
597         case UNKWNSW:
598                 fprintf(stderr, "-%s unknown\n", cp);
599                 talked++;
600                 return NULL;
601
602         case PROR:
603                 o = newnexus(or_t);
604                 bin = &o->data.b;
605                 bin->left = n;
606                 if ((bin->right = parse()))
607                         return o;
608                 padvise(NULL, "missing disjunctive");
609                 return NULL;
610
611 header: ;
612         default:
613                 prvarg();
614                 return n;
615         }
616 }
617
618 static struct nexus *
619 nexp1(void)
620 {
621         char *cp;
622         struct nexus *n, *o;
623         struct bin_data *bin;
624
625         if ((n = nexp2()) == NULL || (cp = nxtarg()) == NULL)
626                 return n;
627
628         if (*cp != '-') {
629                 padvise(NULL, "%s unexpected", cp);
630                 return NULL;
631         }
632
633         if (*++cp == '-')
634                 goto header;
635         switch (smatch(cp, parswit)) {
636         case AMBIGSW:
637                 ambigsw(cp, parswit);
638                 talked++;
639                 return NULL;
640         case UNKWNSW:
641                 fprintf(stderr, "-%s unknown\n", cp);
642                 talked++;
643                 return NULL;
644
645         case PRAND:
646                 o = newnexus(and_t);
647                 bin = &o->data.b;
648                 bin->left = n;
649                 if ((bin->right = nexp1()))
650                         return o;
651                 padvise(NULL, "missing conjunctive");
652                 return NULL;
653
654 header: ;
655         default:
656                 prvarg();
657                 return n;
658         }
659 }
660
661
662 static struct nexus *
663 nexp2(void)
664 {
665         char *cp;
666         struct nexus *n;
667         struct bin_data *bin;
668
669         if ((cp = nxtarg()) == NULL)
670                 return NULL;
671
672         if (*cp != '-') {
673                 prvarg();
674                 return nexp3();
675         }
676
677         if (*++cp == '-')
678                 goto header;
679         switch (smatch(cp, parswit)) {
680         case AMBIGSW:
681                 ambigsw(cp, parswit);
682                 talked++;
683                 return NULL;
684         case UNKWNSW:
685                 fprintf(stderr, "-%s unknown\n", cp);
686                 talked++;
687                 return NULL;
688
689         case PRNOT:
690                 n = newnexus(not_t);
691                 bin = &n->data.b;
692                 if ((bin->left = nexp3()))
693                         return n;
694                 padvise(NULL, "missing negation");
695                 return NULL;
696
697 header: ;
698         default:
699                 prvarg();
700                 return nexp3();
701         }
702 }
703
704 static struct nexus *
705 nexp3(void)
706 {
707         int i;
708         char *cp, *dp;
709         char buffer[BUFSIZ], temp[64];
710         struct nexus *n;
711         struct grep_data *gdata;
712         struct date_data *twsd;
713
714         if ((cp = nxtarg()) == NULL)
715                 return NULL;
716
717         if (*cp != '-') {
718                 padvise(NULL, "%s unexpected", cp);
719                 return NULL;
720         }
721
722         if (*++cp == '-') {
723                 dp = ++cp;
724                 goto header;
725         }
726         switch (i = smatch(cp, parswit)) {
727         case AMBIGSW:
728                 ambigsw(cp, parswit);
729                 talked++;
730                 return NULL;
731         case UNKWNSW:
732                 fprintf(stderr, "-%s unknown\n", cp);
733                 talked++;
734                 return NULL;
735
736         case PRLBR:
737                 if ((n = parse()) == NULL) {
738                         padvise(NULL, "missing group");
739                         return NULL;
740                 }
741                 if ((cp = nxtarg()) == NULL) {
742                         padvise(NULL, "missing -rbrace");
743                         return NULL;
744                 }
745                 if (*cp++ == '-' && smatch(cp, parswit) == PRRBR)
746                         return n;
747                 padvise(NULL, "%s unexpected", --cp);
748                 return NULL;
749
750         default:
751                 prvarg();
752                 return NULL;
753
754         case PRTHREAD:
755                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
756                         padvise(NULL, "missing argument to %s", argp[-2]);
757                 }
758                 return createpickthread(cp);
759         case PRCC:
760         case PRDATE:
761         case PRFROM:
762         case PRTO:
763         case PRSUBJ:
764                 strncpy(temp, parswit[i].sw, sizeof(temp));
765                 temp[sizeof(temp) - 1] = '\0';
766                 dp = *brkstring(temp, " ", NULL);
767 header: ;
768                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
769                         padvise(NULL, "missing argument to %s", argp[-2]);
770                         return NULL;
771                 }
772                 n = newnexus(grep_t);
773                 gdata = &n->data.g;
774                 gdata->header = mh_xstrdup(dp);
775                 snprintf(buffer, sizeof(buffer), "%s", cp);
776                 dp = buffer;
777                 goto pattern;
778
779         case PRSRCH:
780                 n = newnexus(grep_t);
781                 gdata = &n->data.g;
782                 gdata->header = NULL;
783                 body = TRUE;
784                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
785                         padvise(NULL, "missing argument to %s", argp[-2]);
786                         return NULL;
787                 }
788                 dp = cp;
789 pattern: ;
790                 if (!gcompile(gdata, dp)) {
791                         padvise("regcomp", "pattern error in %s %s", argp[-2], cp);
792                         return NULL;
793                 }
794                 return n;
795
796         case PROTHR:
797                 padvise(NULL, "internal error!");
798                 return NULL;
799
800         case PRDATF:
801                 if (!(datesw = nxtarg()) || *datesw == '-') {
802                         padvise(NULL, "missing argument to %s",
803                                         argp[-2]);
804                         return NULL;
805                 }
806                 return nexp3();
807
808         case PRAFTR:
809         case PRBEFR:
810                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
811                         padvise(NULL, "missing argument to %s", argp[-2]);
812                         return NULL;
813                 }
814                 n = newnexus(date_t);
815                 twsd = &n->data.d;
816                 twsd->datef = datesw;
817                 if (!tcompile(cp, &twsd->tws, twsd->after = i == PRAFTR)) {
818                         padvise(NULL, "unable to parse %s %s", argp[-2], cp);
819                         return NULL;
820                 }
821                 return n;
822         }
823 }
824
825
826 static struct nexus *
827 newnexus(enum nexus_type t)
828 {
829         struct nexus *p = NULL;
830         p = mh_xcalloc(1, sizeof(struct nexus));
831         p->t = t;
832         return p;
833
834 }
835
836 static void nexus_clear(struct nexus *n)
837 {
838         n->match = FALSE;
839         switch(n->t) {
840         case and_t:
841         case or_t:
842                 nexus_clear(n->data.b.right);
843                 /* FALL */
844         case not_t:
845                 nexus_clear(n->data.b.left);
846                 break;
847         default:
848                 break;
849         }
850 }
851
852 static int
853 pmatches(FILE *fp, int msgnum)
854 {
855         struct field f = {{0}};
856         enum state s = FLD2;
857
858
859         if (!head)
860                 return 1;
861
862         nexus_clear(head);
863         if (!talked++ && pdebug) {
864                 nexus_debug(head, 0);
865         }
866
867         while (s == FLD2 || s == BODY2) {
868                 switch (s = m_getfld2(s, &f, fp)) {
869                 case LENERR2:
870                         s = FLD2;
871                         /* FALL */
872                 case FLD2:
873                         nexus_match(&f, msgnum, head);
874                         break;
875                 case BODY2:
876                         if (!body) {
877                                 return head->match;
878                         }
879                         nexus_match(&f, msgnum, head);
880                         break;
881                 case IOERR2:
882                         advise(NULL, "IOERR in message %d\n", msgnum);
883                         return FALSE;
884                 case FILEEOF2:
885                         break;
886                 default:
887                         adios(EX_SOFTWARE, "m_getfld2", "returned unknown state %d at message %d", s, msgnum);
888                 }
889         }
890         return head->match;
891 }
892
893 static boolean
894 match_grep(struct field *f, struct grep_data *g)
895 {
896         int ret;
897         char buf[BUFSIZ];
898
899         if (!g->header && *f->name) {
900                 return FALSE;
901         }
902
903         if (!g->header) {
904                 ret = regexec(g->preg, f->value, 0, NULL, 0);
905                 goto out;
906         }
907
908         /* check for the right field */
909         if (!(g->header && *g->header && mh_strcasecmp(g->header, f->name)==0)) {
910                 return FALSE;
911         }
912
913         if (decode_rfc2047(f->value, buf, sizeof(buf))) {
914                 ret = regexec(g->preg, buf, 0, NULL, 0);
915         } else {
916                 ret = regexec(g->preg, f->value, 0, NULL, 0);
917         }
918 out:
919         switch (ret) {
920         case 0:
921                 return TRUE;
922         case REG_NOMATCH:
923                 return FALSE;
924         default:
925                 regerror(ret, g->preg, buf, sizeof(buf));
926                 fprintf(stderr, "%s\n", buf);
927                 return FALSE;
928         }
929 }
930
931 static boolean
932 match_date(struct field *f, int msgnum, struct date_data *dd)
933 {
934         struct tws *tw;
935         char *bp;
936         boolean ret = FALSE;
937
938         if (mh_strcasecmp(f->name, dd->datef)!=0) {
939                 return FALSE;
940         }
941         bp = mh_xstrdup(f->value);
942         if ((tw = dparsetime(bp)) == NULL) {
943                 advise(NULL, "unable to parse %s field in message %d, not matching...", dd->datef, msgnum);
944         } else if (dd->after) {
945                 ret = twsort(tw, &dd->tws) > 0;
946         } else {
947                 ret = twsort(tw, &dd->tws) < 0;
948         }
949
950         mh_free0(&bp);
951         return ret;
952 }
953
954 static boolean
955 nexus_match(struct field *f, int msgnum, struct nexus *n)
956 {
957         switch (n->t) {
958         case and_t:
959                 n->match = nexus_match(f, msgnum, n->data.b.left);
960                 n->match = nexus_match(f, msgnum, n->data.b.right) && n->match;
961                 break;
962         case or_t:
963                 n->match = nexus_match(f, msgnum, n->data.b.left);
964                 n->match = nexus_match(f, msgnum, n->data.b.right) || n->match;
965                 break;
966         case not_t:
967                 n->match = !nexus_match(f, msgnum, n->data.b.left);
968                 break;
969         case date_t:
970                 if (n->match) {
971                         return n->match;
972                 }
973                 n->match = match_date(f, msgnum, &n->data.d);
974                 break;
975         case grep_t:
976                 if (n->match) {
977                         return n->match;
978                 }
979                 n->match = match_grep(f, &n->data.g);
980                 break;
981         default:
982                 adios(EX_SOFTWARE, NULL, "nexus tree contains a unknown nexus_type (%d)", n->t);
983         }
984         return n->match;
985 }
986
987 static void
988 nexus_debug(struct nexus *n, size_t level)
989 {
990         struct date_data *dd;
991         print_debug_level(level);
992         switch (n->t) {
993         case and_t:
994                 fputs("AND\n", stderr);
995                 nexus_debug(n->data.b.left, level+1);
996                 nexus_debug(n->data.b.right, level+1);
997                 break;
998         case or_t:
999                 fputs("OR\n", stderr);
1000                 nexus_debug(n->data.b.left, level+1);
1001                 nexus_debug(n->data.b.right, level+1);
1002                 break;
1003         case not_t:
1004                 fputs("NOT\n", stderr);
1005                 nexus_debug(n->data.b.left, level+1);
1006                 break;
1007         case grep_t:
1008                 nexus_debug_grep(&n->data.g);
1009                 break;
1010         case date_t:
1011                 dd = &n->data.d;
1012                 fprintf(stderr, "TEMPORAL(%s) %s: %s\n",dd->after ? "after" : "before", dd->datef, dasctime(&dd->tws));
1013                 break;
1014         default:
1015                 adios(EX_SOFTWARE, NULL, "nexus tree contains a unknown nexus_type (%d)", n->t);
1016         }
1017 }
1018
1019 static void
1020 nexus_debug_grep(struct grep_data *gd)
1021 {
1022         char *buf, *buf2, *pbuf, *pbuf2;
1023
1024         pbuf = pbuf2 = mh_xstrdup(gd->pattern);
1025
1026         for (;*pbuf2; pbuf2++) {
1027                 *pbuf2 = tolower(*pbuf2);
1028         }
1029
1030         if (gd->header) {
1031                 buf = buf2 = mh_xstrdup(gd->header);
1032                 for (;*buf2; buf2++) {
1033                         *buf2 = tolower(*buf2);
1034                 }
1035                 fprintf(stderr, "PETTERN(%s) %s\n", buf, pbuf);
1036         } else {
1037                 fprintf(stderr, "PETTERN(BODY) %s\n", pbuf);
1038         }
1039         mh_free0(&buf);
1040         mh_free0(&pbuf);
1041 }
1042
1043 static void
1044 nexus_free(struct nexus **n)
1045 {
1046         if (!(*n)) {
1047                 return;
1048         }
1049         switch((*n)->t) {
1050         case and_t:
1051         case or_t:
1052                 nexus_free(&(*n)->data.b.right);
1053                 /* FALL */
1054         case not_t:
1055                 nexus_free(&(*n)->data.b.left);
1056                 break;
1057         case grep_t:
1058                 mh_free0(&(*n)->data.g.header);
1059                 mh_free0(&(*n)->data.g.pattern);
1060                 regfree((*n)->data.g.preg);
1061         case date_t:
1062                 break;
1063         default:
1064                 advise(NULL, "Unknown nexus_type (%d) to free", (*n)->t);
1065         }
1066         mh_free0(n);
1067 }
1068
1069 static void
1070 print_debug_level(size_t level)
1071 {
1072         size_t i;
1073
1074         for (i = 0; i < level; i++) {
1075                 fputs("| ", stderr);
1076         }
1077 }
1078
1079 static int
1080 gcompile(struct grep_data *g, const char *astr)
1081 {
1082         regex_t *preg = mh_xcalloc(1, sizeof(regex_t));
1083         char *buf;
1084         int ret;
1085
1086         g->preg = preg;
1087         g->pattern = mh_xstrdup(astr);
1088         ret = regcomp(preg, astr, REG_ICASE | REG_NOSUB);
1089         if (ret != 0) {
1090                 buf = mh_xcalloc(BUFSIZ, sizeof(char));
1091                 regerror(ret, g->preg, buf, BUFSIZ*sizeof(char));
1092                 fprintf(stderr, "%s\n", buf);
1093                 return FALSE;
1094         }
1095         return TRUE;
1096
1097 }
1098
1099 static int
1100 tcompile(char *ap, struct tws *tb, int isafter)
1101 {
1102         struct tws *tw;
1103
1104         if ((tw = tws_parse(ap, isafter)) == NULL)
1105                 return 0;
1106
1107         twscopy(tb, tw);
1108         return 1;
1109 }
1110
1111
1112 static struct tws *
1113 tws_parse(char *ap, int isafter)
1114 {
1115         char buffer[BUFSIZ];
1116         struct tws *tw, *ts;
1117
1118         if ((tw = tws_special(ap)) != NULL) {
1119                 tw->tw_sec = tw->tw_min = isafter ? 59 : 0;
1120                 tw->tw_hour = isafter ? 23 : 0;
1121                 return tw;
1122         }
1123         if ((tw = dparsetime(ap)) != NULL)
1124                 return tw;
1125
1126         if ((ts = dlocaltimenow()) == NULL)
1127                 return NULL;
1128
1129         snprintf(buffer, sizeof(buffer), "%s %s", ap, dtwszone(ts));
1130         if ((tw = dparsetime(buffer)) != NULL)
1131                 return tw;
1132
1133         snprintf(buffer, sizeof(buffer), "%s %02d:%02d:%02d %s", ap,
1134                         ts->tw_hour, ts->tw_min, ts->tw_sec, dtwszone(ts));
1135         if ((tw = dparsetime(buffer)) != NULL)
1136                 return tw;
1137
1138         snprintf(buffer, sizeof(buffer), "%02d %s %04d %s",
1139                         ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year, ap);
1140         if ((tw = dparsetime(buffer)) != NULL)
1141                 return tw;
1142
1143         snprintf(buffer, sizeof(buffer), "%02d %s %04d %s %s",
1144                         ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year,
1145                         ap, dtwszone(ts));
1146         if ((tw = dparsetime(buffer)) != NULL)
1147                 return tw;
1148
1149         return NULL;
1150 }
1151
1152
1153 static struct tws *
1154 tws_special(char *ap)
1155 {
1156         int i;
1157         time_t clock;
1158         struct tws *tw;
1159
1160         time(&clock);
1161         if (!mh_strcasecmp(ap, "today"))
1162                 return dlocaltime(&clock);
1163         if (!mh_strcasecmp(ap, "yesterday")) {
1164                 clock -= (long) (60 * 60 * 24);
1165                 return dlocaltime(&clock);
1166         }
1167         if (!mh_strcasecmp(ap, "tomorrow")) {
1168                 clock += (long) (60 * 60 * 24);
1169                 return dlocaltime(&clock);
1170         }
1171
1172         for (i = 0; tw_ldotw[i]; i++)
1173                 if (!mh_strcasecmp(ap, tw_ldotw[i]))
1174                         break;
1175         if (tw_ldotw[i]) {
1176                 if ((tw = dlocaltime(&clock)) == NULL)
1177                         return NULL;
1178                 if ((i -= tw->tw_wday) > 0)
1179                         i -= 7;
1180         }
1181         else
1182                 if (*ap != '-')
1183                         return NULL;
1184                 else  /* -ddd days ago */
1185                         i = atoi(ap);  /* we should error check this */
1186
1187         clock += (long) ((60 * 60 * 24) * i);
1188         return dlocaltime(&clock);
1189 }
1190
1191
1192 static struct nexus *
1193 createpickthread(char *msgs)
1194 {
1195         char *folder = NULL;
1196         struct msgs_array msgarray = {0};
1197         struct msgs_array files = {0};
1198         struct nexus *ret = NULL;
1199         struct nexus *c;
1200         struct nexus *or;
1201         struct bin_data *bd;
1202         char *buf;
1203         char **cp = brkstring(msgs, " \t", NULL);
1204         int i;
1205
1206         for (; cp && *cp; cp++) {
1207                 switch (**cp) {
1208                 case '@':
1209                 case '+':
1210                         if (folder) {
1211                                 advise("","");
1212                                 break;
1213                         }
1214                         folder = mh_xstrdup(*cp);
1215                         break;
1216                 default:
1217                         app_msgarg(&msgarray, mh_xstrdup(*cp));
1218                 }
1219         }
1220
1221         parse_msgs(&msgarray, folder, &files);
1222
1223         for (i = 0; i < files.size; i++) {
1224                 buf = getthreadid(files.msgs[i]);
1225                 if (!buf) {
1226                         adios(EX_DATAERR, NULL, "message %s is not part of a thread", basename(files.msgs[i]));
1227                         continue;
1228                 }
1229
1230                 c = createonethread(buf);
1231
1232                 if (!ret) {
1233                         ret = c;
1234                         continue;
1235                 }
1236
1237
1238                 or = newnexus(or_t);
1239                 bd = &or->data.b;
1240                 bd->right = ret;
1241                 bd->left = c;
1242                 ret = or;
1243         }
1244
1245         mh_free0(&(files.msgs));
1246         mh_free0(&(msgarray.msgs));
1247
1248         return ret;
1249 }
1250
1251 static struct nexus *
1252 createonethread(char *c)
1253 {
1254         struct nexus *ret = newnexus(or_t);
1255         struct nexus *left = newnexus(grep_t);
1256         struct nexus *right = newnexus(grep_t);
1257         char buf[BUFSIZ];
1258
1259         ret->data.b.left = left;
1260         ret->data.b.right = right;
1261         left->data.g.header = mh_xstrdup("message-id");
1262
1263
1264         snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1265         if(!gcompile(&left->data.g, buf)) {
1266                 padvise(NULL, "pattern error %s", c);
1267                 goto error;
1268         }
1269
1270         right->data.g.header = mh_xstrdup("references");
1271
1272         snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1273         if(!gcompile(&right->data.g, buf)) {
1274                 padvise(NULL, "pattern error in %s", c);
1275                 goto error;
1276         }
1277
1278         return ret;
1279
1280 error:
1281         nexus_free(&ret);
1282         return NULL;
1283         
1284 }