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