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