remove unused defines in uip/pick.c
[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 /*
519 ** DEFINITIONS FOR NEXUS
520 */
521
522 #define nxtarg() (*argp ? *argp++ : NULL)
523 #define prvarg() argp--
524
525 #define padvise if (!talked++) advise
526
527 static int talked;
528 static int pdebug = 0;
529
530 static char *datesw;
531 static char **argp;
532
533 /*
534 ** prototypes for date routines
535 */
536 static struct tws *tws_parse(char *, int);
537 static struct tws *tws_special(char *);
538
539 /*
540 ** static prototypes
541 */
542 static int gcompile(struct grep_data *, const char *);
543 static int tcompile(char *, struct tws *, int);
544
545 static struct nexus *parse(void);
546 static struct nexus *nexp1(void);
547 static struct nexus *nexp2(void);
548 static struct nexus *nexp3(void);
549 static struct nexus *newnexus(enum nexus_type);
550
551 static int
552 pcompile(char **vec, char *date)
553 {
554         char *cp;
555
556         if ((cp = getenv("MHPDEBUG")) && *cp)
557                 pdebug++;
558
559         argp = vec;
560         if ((datesw = date) == NULL)
561                 datesw = "date";
562         talked = 0;
563
564         if ((head = parse()) == NULL)
565                 return (talked ? 0 : 1);
566
567         if (*argp) {
568                 padvise(NULL, "%s unexpected", *argp);
569                 return 0;
570         }
571
572         return 1;
573 }
574
575
576 static struct nexus *
577 parse(void)
578 {
579         char  *cp;
580         struct nexus *n, *o;
581         struct bin_data *bin;
582
583         if ((n = nexp1()) == NULL || (cp = nxtarg()) == NULL)
584                 return n;
585
586         if (*cp != '-') {
587                 padvise(NULL, "%s unexpected", cp);
588                 return NULL;
589         }
590
591         if (*++cp == '-')
592                 goto header;
593         switch (smatch(cp, parswit)) {
594         case AMBIGSW:
595                 ambigsw(cp, parswit);
596                 talked++;
597                 return NULL;
598         case UNKWNSW:
599                 fprintf(stderr, "-%s unknown\n", cp);
600                 talked++;
601                 return NULL;
602
603         case PROR:
604                 o = newnexus(or_t);
605                 bin = &o->data.b;
606                 bin->left = n;
607                 if ((bin->right = parse()))
608                         return o;
609                 padvise(NULL, "missing disjunctive");
610                 return NULL;
611
612 header: ;
613         default:
614                 prvarg();
615                 return n;
616         }
617 }
618
619 static struct nexus *
620 nexp1(void)
621 {
622         char *cp;
623         struct nexus *n, *o;
624         struct bin_data *bin;
625
626         if ((n = nexp2()) == NULL || (cp = nxtarg()) == NULL)
627                 return n;
628
629         if (*cp != '-') {
630                 padvise(NULL, "%s unexpected", cp);
631                 return NULL;
632         }
633
634         if (*++cp == '-')
635                 goto header;
636         switch (smatch(cp, parswit)) {
637         case AMBIGSW:
638                 ambigsw(cp, parswit);
639                 talked++;
640                 return NULL;
641         case UNKWNSW:
642                 fprintf(stderr, "-%s unknown\n", cp);
643                 talked++;
644                 return NULL;
645
646         case PRAND:
647                 o = newnexus(and_t);
648                 bin = &o->data.b;
649                 bin->left = n;
650                 if ((bin->right = nexp1()))
651                         return o;
652                 padvise(NULL, "missing conjunctive");
653                 return NULL;
654
655 header: ;
656         default:
657                 prvarg();
658                 return n;
659         }
660 }
661
662
663 static struct nexus *
664 nexp2(void)
665 {
666         char *cp;
667         struct nexus *n;
668         struct bin_data *bin;
669
670         if ((cp = nxtarg()) == NULL)
671                 return NULL;
672
673         if (*cp != '-') {
674                 prvarg();
675                 return nexp3();
676         }
677
678         if (*++cp == '-')
679                 goto header;
680         switch (smatch(cp, parswit)) {
681         case AMBIGSW:
682                 ambigsw(cp, parswit);
683                 talked++;
684                 return NULL;
685         case UNKWNSW:
686                 fprintf(stderr, "-%s unknown\n", cp);
687                 talked++;
688                 return NULL;
689
690         case PRNOT:
691                 n = newnexus(not_t);
692                 bin = &n->data.b;
693                 if ((bin->left = nexp3()))
694                         return n;
695                 padvise(NULL, "missing negation");
696                 return NULL;
697
698 header: ;
699         default:
700                 prvarg();
701                 return nexp3();
702         }
703 }
704
705 static struct nexus *
706 nexp3(void)
707 {
708         int i;
709         char *cp, *dp;
710         char buffer[BUFSIZ], temp[64];
711         struct nexus *n;
712         struct grep_data *gdata;
713         struct date_data *twsd;
714
715         if ((cp = nxtarg()) == NULL)
716                 return NULL;
717
718         if (*cp != '-') {
719                 padvise(NULL, "%s unexpected", cp);
720                 return NULL;
721         }
722
723         if (*++cp == '-') {
724                 dp = ++cp;
725                 goto header;
726         }
727         switch (i = smatch(cp, parswit)) {
728         case AMBIGSW:
729                 ambigsw(cp, parswit);
730                 talked++;
731                 return NULL;
732         case UNKWNSW:
733                 fprintf(stderr, "-%s unknown\n", cp);
734                 talked++;
735                 return NULL;
736
737         case PRLBR:
738                 if ((n = parse()) == NULL) {
739                         padvise(NULL, "missing group");
740                         return NULL;
741                 }
742                 if ((cp = nxtarg()) == NULL) {
743                         padvise(NULL, "missing -rbrace");
744                         return NULL;
745                 }
746                 if (*cp++ == '-' && smatch(cp, parswit) == PRRBR)
747                         return n;
748                 padvise(NULL, "%s unexpected", --cp);
749                 return NULL;
750
751         default:
752                 prvarg();
753                 return NULL;
754
755         case PRTHREAD:
756                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
757                         padvise(NULL, "missing argument to %s", argp[-2]);
758                 }
759                 return createpickthread(cp);
760         case PRCC:
761         case PRDATE:
762         case PRFROM:
763         case PRTO:
764         case PRSUBJ:
765                 strncpy(temp, parswit[i].sw, sizeof(temp));
766                 temp[sizeof(temp) - 1] = '\0';
767                 dp = *brkstring(temp, " ", NULL);
768 header: ;
769                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
770                         padvise(NULL, "missing argument to %s", argp[-2]);
771                         return NULL;
772                 }
773                 n = newnexus(grep_t);
774                 gdata = &n->data.g;
775                 gdata->header = mh_xstrdup(dp);
776                 snprintf(buffer, sizeof(buffer), "%s", cp);
777                 dp = buffer;
778                 goto pattern;
779
780         case PRSRCH:
781                 n = newnexus(grep_t);
782                 gdata = &n->data.g;
783                 gdata->header = NULL;
784                 body = TRUE;
785                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
786                         padvise(NULL, "missing argument to %s", argp[-2]);
787                         return NULL;
788                 }
789                 dp = cp;
790 pattern: ;
791                 if (!gcompile(gdata, dp)) {
792                         padvise("regcomp", "pattern error in %s %s", argp[-2], cp);
793                         return NULL;
794                 }
795                 return n;
796
797         case PROTHR:
798                 padvise(NULL, "internal error!");
799                 return NULL;
800
801         case PRDATF:
802                 if (!(datesw = nxtarg()) || *datesw == '-') {
803                         padvise(NULL, "missing argument to %s",
804                                         argp[-2]);
805                         return NULL;
806                 }
807                 return nexp3();
808
809         case PRAFTR:
810         case PRBEFR:
811                 if (!(cp = nxtarg())) {  /* allow -xyz arguments */
812                         padvise(NULL, "missing argument to %s", argp[-2]);
813                         return NULL;
814                 }
815                 n = newnexus(date_t);
816                 twsd = &n->data.d;
817                 twsd->datef = datesw;
818                 if (!tcompile(cp, &twsd->tws, twsd->after = i == PRAFTR)) {
819                         padvise(NULL, "unable to parse %s %s", argp[-2], cp);
820                         return NULL;
821                 }
822                 return n;
823         }
824 }
825
826
827 static struct nexus *
828 newnexus(enum nexus_type t)
829 {
830         struct nexus *p = NULL;
831         p = mh_xcalloc(1, sizeof(struct nexus));
832         p->t = t;
833         return p;
834
835 }
836
837 static void nexus_clear(struct nexus *n)
838 {
839         n->match = FALSE;
840         switch(n->t) {
841         case and_t:
842         case or_t:
843                 nexus_clear(n->data.b.right);
844                 /* FALL */
845         case not_t:
846                 nexus_clear(n->data.b.left);
847                 break;
848         default:
849                 break;
850         }
851 }
852
853 static int
854 pmatches(FILE *fp, int msgnum)
855 {
856         struct field f = {{0}};
857         enum state s = FLD2;
858
859
860         if (!head)
861                 return 1;
862
863         nexus_clear(head);
864         if (!talked++ && pdebug) {
865                 nexus_debug(head, 0);
866         }
867
868         while (s == FLD2 || s == BODY2) {
869                 switch (s = m_getfld2(s, &f, fp)) {
870                 case LENERR2:
871                         s = FLD2;
872                         /* FALL */
873                 case FLD2:
874                         nexus_match(&f, msgnum, head);
875                         break;
876                 case BODY2:
877                         if (!body) {
878                                 return head->match;
879                         }
880                         nexus_match(&f, msgnum, head);
881                         break;
882                 case IOERR2:
883                         advise(NULL, "IOERR in message %d\n", msgnum);
884                         return FALSE;
885                 case FILEEOF2:
886                         break;
887                 default:
888                         adios(EX_SOFTWARE, "m_getfld2", "returned unknown state %d at message %d", s, msgnum);
889                 }
890         }
891         return head->match;
892 }
893
894 static boolean
895 match_grep(struct field *f, struct grep_data *g)
896 {
897         int ret;
898         char buf[BUFSIZ];
899
900         if (!g->header && *f->name) {
901                 return FALSE;
902         }
903
904         if (!g->header) {
905                 ret = regexec(g->preg, f->value, 0, NULL, 0);
906                 goto out;
907         }
908
909         /* check for the right field */
910         if (!(g->header && *g->header && mh_strcasecmp(g->header, f->name)==0)) {
911                 return FALSE;
912         }
913
914         if (decode_rfc2047(f->value, buf, sizeof(buf))) {
915                 ret = regexec(g->preg, buf, 0, NULL, 0);
916         } else {
917                 ret = regexec(g->preg, f->value, 0, NULL, 0);
918         }
919 out:
920         switch (ret) {
921         case 0:
922                 return TRUE;
923         case REG_NOMATCH:
924                 return FALSE;
925         default:
926                 regerror(ret, g->preg, buf, sizeof(buf));
927                 fprintf(stderr, "%s\n", buf);
928                 return FALSE;
929         }
930 }
931
932 static boolean
933 match_date(struct field *f, int msgnum, struct date_data *dd)
934 {
935         struct tws *tw;
936         char *bp;
937         boolean ret = FALSE;
938
939         if (mh_strcasecmp(f->name, dd->datef)!=0) {
940                 return FALSE;
941         }
942         bp = mh_xstrdup(f->value);
943         if ((tw = dparsetime(bp)) == NULL) {
944                 advise(NULL, "unable to parse %s field in message %d, not matching...", dd->datef, msgnum);
945         } else if (dd->after) {
946                 ret = twsort(tw, &dd->tws) > 0;
947         } else {
948                 ret = twsort(tw, &dd->tws) < 0;
949         }
950
951         mh_free0(&bp);
952         return ret;
953 }
954
955 static boolean
956 nexus_match(struct field *f, int msgnum, struct nexus *n)
957 {
958         switch (n->t) {
959         case and_t:
960                 n->match = nexus_match(f, msgnum, n->data.b.left);
961                 n->match = nexus_match(f, msgnum, n->data.b.right) && n->match;
962                 break;
963         case or_t:
964                 n->match = nexus_match(f, msgnum, n->data.b.left);
965                 n->match = nexus_match(f, msgnum, n->data.b.right) || n->match;
966                 break;
967         case not_t:
968                 n->match = !nexus_match(f, msgnum, n->data.b.left);
969                 break;
970         case date_t:
971                 if (n->match) {
972                         return n->match;
973                 }
974                 n->match = match_date(f, msgnum, &n->data.d);
975                 break;
976         case grep_t:
977                 if (n->match) {
978                         return n->match;
979                 }
980                 n->match = match_grep(f, &n->data.g);
981                 break;
982         default:
983                 adios(EX_SOFTWARE, NULL, "nexus tree contains a unknown nexus_type (%d)", n->t);
984         }
985         return n->match;
986 }
987
988 static void
989 nexus_debug(struct nexus *n, size_t level)
990 {
991         struct date_data *dd;
992         print_debug_level(level);
993         switch (n->t) {
994         case and_t:
995                 fputs("AND\n", stderr);
996                 nexus_debug(n->data.b.left, level+1);
997                 nexus_debug(n->data.b.right, level+1);
998                 break;
999         case or_t:
1000                 fputs("OR\n", stderr);
1001                 nexus_debug(n->data.b.left, level+1);
1002                 nexus_debug(n->data.b.right, level+1);
1003                 break;
1004         case not_t:
1005                 fputs("NOT\n", stderr);
1006                 nexus_debug(n->data.b.left, level+1);
1007                 break;
1008         case grep_t:
1009                 nexus_debug_grep(&n->data.g);
1010                 break;
1011         case date_t:
1012                 dd = &n->data.d;
1013                 fprintf(stderr, "TEMPORAL(%s) %s: %s\n",dd->after ? "after" : "before", dd->datef, dasctime(&dd->tws));
1014                 break;
1015         default:
1016                 adios(EX_SOFTWARE, NULL, "nexus tree contains a unknown nexus_type (%d)", n->t);
1017         }
1018 }
1019
1020 static void
1021 nexus_debug_grep(struct grep_data *gd)
1022 {
1023         char *buf, *buf2, *pbuf, *pbuf2;
1024
1025         pbuf = pbuf2 = mh_xstrdup(gd->pattern);
1026
1027         for (;*pbuf2; pbuf2++) {
1028                 *pbuf2 = tolower(*pbuf2);
1029         }
1030
1031         if (gd->header) {
1032                 buf = buf2 = mh_xstrdup(gd->header);
1033                 for (;*buf2; buf2++) {
1034                         *buf2 = tolower(*buf2);
1035                 }
1036                 fprintf(stderr, "PETTERN(%s) %s\n", buf, pbuf);
1037         } else {
1038                 fprintf(stderr, "PETTERN(BODY) %s\n", pbuf);
1039         }
1040         mh_free0(&buf);
1041         mh_free0(&pbuf);
1042 }
1043
1044 static void
1045 nexus_free(struct nexus **n)
1046 {
1047         if (!(*n)) {
1048                 return;
1049         }
1050         switch((*n)->t) {
1051         case and_t:
1052         case or_t:
1053                 nexus_free(&(*n)->data.b.right);
1054                 /* FALL */
1055         case not_t:
1056                 nexus_free(&(*n)->data.b.left);
1057                 break;
1058         case grep_t:
1059                 mh_free0(&(*n)->data.g.header);
1060                 mh_free0(&(*n)->data.g.pattern);
1061                 regfree((*n)->data.g.preg);
1062         case date_t:
1063                 break;
1064         default:
1065                 advise(NULL, "Unknown nexus_type (%d) to free", (*n)->t);
1066         }
1067         mh_free0(n);
1068 }
1069
1070 static void
1071 print_debug_level(size_t level)
1072 {
1073         size_t i;
1074
1075         for (i = 0; i < level; i++) {
1076                 fputs("| ", stderr);
1077         }
1078 }
1079
1080 static int
1081 gcompile(struct grep_data *g, const char *astr)
1082 {
1083         regex_t *preg = mh_xcalloc(1, sizeof(regex_t));
1084         char *buf;
1085         int ret;
1086
1087         g->preg = preg;
1088         g->pattern = mh_xstrdup(astr);
1089         ret = regcomp(preg, astr, REG_ICASE | REG_NOSUB);
1090         if (ret != 0) {
1091                 buf = mh_xcalloc(BUFSIZ, sizeof(char));
1092                 regerror(ret, g->preg, buf, BUFSIZ*sizeof(char));
1093                 fprintf(stderr, "%s\n", buf);
1094                 return FALSE;
1095         }
1096         return TRUE;
1097
1098 }
1099
1100 static int
1101 tcompile(char *ap, struct tws *tb, int isafter)
1102 {
1103         struct tws *tw;
1104
1105         if ((tw = tws_parse(ap, isafter)) == NULL)
1106                 return 0;
1107
1108         twscopy(tb, tw);
1109         return 1;
1110 }
1111
1112
1113 static struct tws *
1114 tws_parse(char *ap, int isafter)
1115 {
1116         char buffer[BUFSIZ];
1117         struct tws *tw, *ts;
1118
1119         if ((tw = tws_special(ap)) != NULL) {
1120                 tw->tw_sec = tw->tw_min = isafter ? 59 : 0;
1121                 tw->tw_hour = isafter ? 23 : 0;
1122                 return tw;
1123         }
1124         if ((tw = dparsetime(ap)) != NULL)
1125                 return tw;
1126
1127         if ((ts = dlocaltimenow()) == NULL)
1128                 return NULL;
1129
1130         snprintf(buffer, sizeof(buffer), "%s %s", ap, dtwszone(ts));
1131         if ((tw = dparsetime(buffer)) != NULL)
1132                 return tw;
1133
1134         snprintf(buffer, sizeof(buffer), "%s %02d:%02d:%02d %s", ap,
1135                         ts->tw_hour, ts->tw_min, ts->tw_sec, dtwszone(ts));
1136         if ((tw = dparsetime(buffer)) != NULL)
1137                 return tw;
1138
1139         snprintf(buffer, sizeof(buffer), "%02d %s %04d %s",
1140                         ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year, ap);
1141         if ((tw = dparsetime(buffer)) != NULL)
1142                 return tw;
1143
1144         snprintf(buffer, sizeof(buffer), "%02d %s %04d %s %s",
1145                         ts->tw_mday, tw_moty[ts->tw_mon], ts->tw_year,
1146                         ap, dtwszone(ts));
1147         if ((tw = dparsetime(buffer)) != NULL)
1148                 return tw;
1149
1150         return NULL;
1151 }
1152
1153
1154 static struct tws *
1155 tws_special(char *ap)
1156 {
1157         int i;
1158         time_t clock;
1159         struct tws *tw;
1160
1161         time(&clock);
1162         if (!mh_strcasecmp(ap, "today"))
1163                 return dlocaltime(&clock);
1164         if (!mh_strcasecmp(ap, "yesterday")) {
1165                 clock -= (long) (60 * 60 * 24);
1166                 return dlocaltime(&clock);
1167         }
1168         if (!mh_strcasecmp(ap, "tomorrow")) {
1169                 clock += (long) (60 * 60 * 24);
1170                 return dlocaltime(&clock);
1171         }
1172
1173         for (i = 0; tw_ldotw[i]; i++)
1174                 if (!mh_strcasecmp(ap, tw_ldotw[i]))
1175                         break;
1176         if (tw_ldotw[i]) {
1177                 if ((tw = dlocaltime(&clock)) == NULL)
1178                         return NULL;
1179                 if ((i -= tw->tw_wday) > 0)
1180                         i -= 7;
1181         }
1182         else
1183                 if (*ap != '-')
1184                         return NULL;
1185                 else  /* -ddd days ago */
1186                         i = atoi(ap);  /* we should error check this */
1187
1188         clock += (long) ((60 * 60 * 24) * i);
1189         return dlocaltime(&clock);
1190 }
1191
1192
1193 static struct nexus *
1194 createpickthread(char *msgs)
1195 {
1196         char *folder = NULL;
1197         struct msgs_array msgarray = {0};
1198         struct msgs_array files = {0};
1199         struct nexus *ret = NULL;
1200         struct nexus *c;
1201         struct nexus *or;
1202         struct bin_data *bd;
1203         char *buf;
1204         char **cp = brkstring(msgs, " \t", NULL);
1205         int i;
1206
1207         for (; cp && *cp; cp++) {
1208                 switch (**cp) {
1209                 case '@':
1210                 case '+':
1211                         if (folder) {
1212                                 advise("","");
1213                                 break;
1214                         }
1215                         folder = mh_xstrdup(*cp);
1216                         break;
1217                 default:
1218                         app_msgarg(&msgarray, mh_xstrdup(*cp));
1219                 }
1220         }
1221
1222         parse_msgs(&msgarray, folder, &files);
1223
1224         for (i = 0; i < files.size; i++) {
1225                 buf = getthreadid(files.msgs[i]);
1226                 if (!buf) {
1227                         adios(EX_DATAERR, NULL, "message %s is not part of a thread", basename(files.msgs[i]));
1228                         continue;
1229                 }
1230
1231                 c = createonethread(buf);
1232
1233                 if (!ret) {
1234                         ret = c;
1235                         continue;
1236                 }
1237
1238
1239                 or = newnexus(or_t);
1240                 bd = &or->data.b;
1241                 bd->right = ret;
1242                 bd->left = c;
1243                 ret = or;
1244         }
1245
1246         mh_free0(&(files.msgs));
1247         mh_free0(&(msgarray.msgs));
1248
1249         return ret;
1250 }
1251
1252 static struct nexus *
1253 createonethread(char *c)
1254 {
1255         struct nexus *ret = newnexus(or_t);
1256         struct nexus *left = newnexus(grep_t);
1257         struct nexus *right = newnexus(grep_t);
1258         char buf[BUFSIZ];
1259
1260         ret->data.b.left = left;
1261         ret->data.b.right = right;
1262         left->data.g.header = mh_xstrdup("message-id");
1263
1264
1265         snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1266         if(!gcompile(&left->data.g, buf)) {
1267                 padvise(NULL, "pattern error %s", c);
1268                 goto error;
1269         }
1270
1271         right->data.g.header = mh_xstrdup("references");
1272
1273         snprintf(buf, sizeof(buf), "^[ \t]*<%s>", c);
1274         if(!gcompile(&right->data.g, buf)) {
1275                 padvise(NULL, "pattern error in %s", c);
1276                 goto error;
1277         }
1278
1279         return ret;
1280
1281 error:
1282         nexus_free(&ret);
1283         return NULL;
1284         
1285 }