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