Cosmetics.
[mymail.git] / mymail.c
1
2 /*
3  *  Copyright (c) 2013 Francois Fleuret
4  *  Written by Francois Fleuret <francois@fleuret.org>
5  *
6  *  This file is part of mymail.
7  *
8  *  mymail is free software: you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License version 3 as
10  *  published by the Free Software Foundation.
11  *
12  *  mymail is distributed in the hope that it will be useful, but
13  *  WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *  General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with mymail.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21
22 /*
23
24   This command is a dumb mail indexer. It can either (1) scan
25   directories containing mbox files, and create a db file containing
26   for each mail a list of fields computed from the header, or (2)
27   read such a db file and get all the mails matching regexp-defined
28   conditions on the fields.
29
30   It is low-tech, simple, light and fast.
31
32 */
33
34 #define _GNU_SOURCE
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <locale.h>
42 #include <getopt.h>
43 #include <limits.h>
44 #include <dirent.h>
45 #include <regex.h>
46 #include <time.h>
47
48 #define MYMAIL_DB_MAGIC_TOKEN "mymail_index_file"
49 #define VERSION "0.9.2"
50
51 #define MAX_NB_SEARCH_CONDITIONS 32
52
53 #define BUFFER_SIZE 65536
54 #define TOKEN_BUFFER_SIZE 1024
55
56 #define LEADING_FROM_LINE_REGEXP "^From [^ ]*  \\(Mon\\|Tue\\|Wed\\|Thu\\|Fri\\|Sat\\|Sun\\) \\(Jan\\|Feb\\|Mar\\|Apr\\|May\\|Jun\\|Jul\\|Aug\\|Sep\\|Oct\\|Nov\\|Dec\\) [ 123][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9][0-9][0-9][0-9]\n$"
57
58 regex_t leading_from_line_regexp;
59
60 /* Global variables! */
61
62 int paranoid;
63 int quiet;
64 char *default_search_field;
65 int ignore_dot_files;
66
67 /********************************************************************/
68
69 enum {
70   ID_MAIL = 0,
71   ID_LEADING_LINE,
72   ID_FROM,
73   ID_TO,
74   ID_SUBJECT,
75   ID_DATE,
76   ID_PARTICIPANT,
77   ID_BODY,
78   ID_INTERVAL,
79   MAX_ID
80 };
81
82 static char *field_names[] = {
83   "mail",
84   "lead",
85   "from",
86   "to",
87   "subject",
88   "date",
89   "part",
90   "body",
91   "interval"
92 };
93
94 /********************************************************************/
95
96 struct search_condition {
97   int field_id;
98   int negation;
99   regex_t regexp;
100   time_t interval_start, interval_stop;
101 };
102
103 /********************************************************************/
104
105 struct parsable_field {
106   int id;
107   int cflags;
108   char *regexp_string;
109   regex_t regexp;
110 };
111
112 static struct parsable_field fields_to_parse[] = {
113   {
114     ID_LEADING_LINE,
115     0,
116     "^From ",
117     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
118   },
119
120   {
121     ID_FROM,
122     REG_ICASE,
123     "^\\(from\\|reply-to\\|sender\\|return-path\\): ",
124     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
125   },
126
127   {
128     ID_TO,
129     REG_ICASE,
130     "^\\(to\\|cc\\|bcc\\): ",
131     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
132   },
133
134   {
135     ID_SUBJECT,
136     REG_ICASE,
137     "^subject: ",
138     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
139   },
140
141   {
142     ID_DATE,
143     REG_ICASE,
144     "^date: ",
145     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
146   },
147
148 };
149
150 /********************************************************************/
151
152 int xor(int a, int b) {
153   return (a && !b) || (!a && b);
154 }
155
156 char *parse_token(char *token_buffer, size_t token_buffer_size,
157                   char separator, char *string) {
158   char *u = token_buffer;
159   while(u < token_buffer + token_buffer_size - 1 && *string &&
160         *string != separator) {
161     *(u++) = *(string++);
162   }
163   while(*string == separator) string++;
164   *u = '\0';
165   return string;
166 }
167
168 /********************************************************************/
169
170 /* malloc with error checking.  */
171
172 void *safe_malloc(size_t n) {
173   void *p = malloc(n);
174   if(!p && n != 0) {
175     fprintf(stderr,
176             "mymail: cannot allocate memory: %s\n", strerror(errno));
177     exit(EXIT_FAILURE);
178   }
179   return p;
180 }
181
182 /*********************************************************************/
183
184 void print_version(FILE *out) {
185   fprintf(out, "mymail version %s (%s)\n", VERSION, UNAME);
186 }
187
188 void print_usage(FILE *out) {
189   print_version(out);
190   fprintf(out, "Written by Francois Fleuret <francois@fleuret.org>.\n");
191   fprintf(out, "\n");
192   fprintf(out, "Usage: mymail [options] [<mbox dir1> [<mbox dir2> ...]|<db file1> [<db file2> ...]]\n");
193   fprintf(out, "\n");
194   fprintf(out, " -h, --help\n");
195   fprintf(out, "         show this help\n");
196   fprintf(out, " -v, --version\n");
197   fprintf(out, "         print the version number\n");
198   fprintf(out, " -q, --quiet\n");
199   fprintf(out, "         do not print information during search\n");
200   fprintf(out, " -p <db filename pattern>, --db-pattern <db filename pattern>\n");
201   fprintf(out, "         set the db filename pattern for recursive search\n");
202   fprintf(out, " -r <db root path>, --db-root <db root path>\n");
203   fprintf(out, "         set the db root path for recursive search\n");
204   fprintf(out, " -l <db filename list>, --db-list <db filename list>\n");
205   fprintf(out, "         set the semicolon-separated list of db files for search\n");
206   fprintf(out, " -s <search pattern>, --search <search pattern>\n");
207   fprintf(out, "         search for matching mails in the db file\n");
208   fprintf(out, " -d <db filename>, --db-file <db filename>\n");
209   fprintf(out, "         set the db filename for indexing\n");
210   fprintf(out, " -i, --index\n");
211   fprintf(out, "         index mails\n");
212   fprintf(out, " -o <output filename>, --output <output filename>\n");
213   fprintf(out, "         set the result file, use stdout if unset\n");
214   fprintf(out, " -a <search field>, --default-search <search field>\n");
215   fprintf(out, "         set the default search field\n");
216 }
217
218 /*********************************************************************/
219
220 time_t time_for_past_day(int day) {
221   time_t t;
222   struct tm *tm;
223   int delta_day;
224   t = time(0);
225   tm = localtime(&t);
226   delta_day = (7 + tm->tm_wday - day) % 7 + 1;
227   return t - delta_day * 3600 * 24 + tm->tm_sec + 60 * tm->tm_min + 3600 * tm->tm_hour;
228 }
229
230 /*********************************************************************/
231
232 int ignore_entry(const char *name) {
233   return
234     strcmp(name, ".") == 0 ||
235     strcmp(name, "..") == 0 ||
236     (ignore_dot_files && name[0] == '.' && name[1] != '/');
237 }
238
239 int is_a_leading_from_line(char *mbox_line) {
240   return
241
242     /*
243
244       The mbox man page in qmail documentation states:
245
246        > The reader should not attempt to take advantage of the fact
247        > that every From_ line (past the beginning of the file) is
248        > preceded by a blank line.
249
250     */
251
252     strncmp(mbox_line, "From ", 5) == 0 &&
253     regexec(&leading_from_line_regexp, mbox_line, 0, 0, 0) == 0;
254 }
255
256 int mbox_line_match_search(struct search_condition *condition,
257                            int mbox_id, char *mbox_value) {
258
259   if(condition->field_id == ID_INTERVAL) {
260     if(mbox_id == ID_LEADING_LINE) {
261       char *c;
262       time_t t;
263       struct tm tm;
264
265       c = mbox_value;
266       while(*c && *c != ' ') c++; while(*c && *c == ' ') c++;
267       strptime(c, "%a %b %e %k:%M:%S %Y", &tm);
268       t = mktime(&tm);
269
270       return (t >= condition->interval_start &&
271               (condition->interval_stop == 0 ||
272                t <= condition->interval_stop));
273     } else {
274       return 0;
275     }
276   } else {
277     return
278       (
279
280        (condition->field_id == mbox_id)
281
282        ||
283
284        (condition->field_id == ID_PARTICIPANT && (mbox_id == ID_LEADING_LINE ||
285                                                   mbox_id == ID_FROM ||
286                                                   mbox_id == ID_TO))
287        ||
288
289        (condition->field_id == ID_FROM && mbox_id == ID_LEADING_LINE)
290
291        )
292
293       &&
294
295       regexec(&condition->regexp, mbox_value, 0, 0, 0) == 0;
296   }
297 }
298
299 void update_body_hits(char *mail_filename, int position_in_mail,
300                       int nb_search_conditions, struct search_condition *search_conditions,
301                       int nb_body_conditions,
302                       int *hits) {
303   FILE *mail_file;
304   int header, n;
305   char raw_mbox_line[BUFFER_SIZE];
306   int nb_body_hits;
307
308   nb_body_hits = 0;
309
310   header = 1;
311   mail_file = fopen(mail_filename, "r");
312
313   if(!mail_file) {
314     fprintf(stderr,
315             "mymail: Cannot open mbox '%s' for body scan.\n",
316             mail_filename);
317     exit(EXIT_FAILURE);
318   }
319
320   fseek(mail_file, position_in_mail, SEEK_SET);
321
322   if(fgets(raw_mbox_line, BUFFER_SIZE, mail_file)) {
323     while(nb_body_hits < nb_body_conditions) {
324       /* last_mbox_line_was_empty = (raw_mbox_line[0] == '\n'); */
325       /* if(last_mbox_line_was_empty) { header = 0; } */
326
327       if(raw_mbox_line[0] == '\n') { header = 0; }
328
329       if(!header) {
330         for(n = 0; n < nb_search_conditions; n++) {
331           if(search_conditions[n].field_id == ID_BODY && !hits[n]) {
332             hits[n] =
333               (regexec(&search_conditions[n].regexp, raw_mbox_line, 0, 0, 0) == 0);
334             if(hits[n]) {
335               nb_body_hits++;
336             }
337           }
338         }
339       }
340
341       if(!fgets(raw_mbox_line, BUFFER_SIZE, mail_file) ||
342          (is_a_leading_from_line(raw_mbox_line)))
343         break;
344     }
345   }
346
347   fclose(mail_file);
348 }
349
350 void extract_mail(const char *mail_filename, unsigned long int position_in_mail,
351                 FILE *output_file) {
352   char raw_mbox_line[BUFFER_SIZE];
353   FILE *mail_file;
354
355   mail_file = fopen(mail_filename, "r");
356
357   if(!mail_file) {
358     fprintf(stderr,
359             "mymail: Cannot open mbox '%s' for mail extraction.\n",
360             mail_filename);
361     exit(EXIT_FAILURE);
362   }
363
364   fseek(mail_file, position_in_mail, SEEK_SET);
365
366   if(fgets(raw_mbox_line, BUFFER_SIZE, mail_file)) {
367     fprintf(output_file, "%s", raw_mbox_line);
368     while(1) {
369       if(!fgets(raw_mbox_line, BUFFER_SIZE, mail_file) ||
370          (is_a_leading_from_line(raw_mbox_line))
371          )
372         break;
373       fprintf(output_file, "%s", raw_mbox_line);
374     }
375   }
376
377   fclose(mail_file);
378 }
379
380 void search_in_db(const char *db_filename,
381                   int nb_search_conditions,
382                   struct search_condition *search_conditions,
383                   FILE *output_file) {
384
385   int hits[MAX_NB_SEARCH_CONDITIONS];
386   char raw_db_line[BUFFER_SIZE];
387   char current_mail_filename[PATH_MAX + 1];
388   unsigned long int current_position_in_mail;
389   char mbox_name[TOKEN_BUFFER_SIZE], *mbox_value;
390   int mbox_id;
391   int already_written, m, n;
392   int nb_body_conditions, nb_fulfilled_body_conditions;
393   FILE *db_file;
394
395   if(!quiet) {
396     printf("Searching in '%s' ... ", db_filename);
397     fflush(stdout);
398   }
399
400   db_file = fopen(db_filename, "r");
401
402   if(!db_file) {
403     fprintf(stderr,
404             "mymail: Cannot open \"%s\" for reading: %s\n",
405             db_filename,
406             strerror(errno));
407     exit(EXIT_FAILURE);
408   }
409
410   /* First, check the db file leading line integrity */
411
412   if(fgets(raw_db_line, BUFFER_SIZE, db_file)) {
413     if(strncmp(raw_db_line, MYMAIL_DB_MAGIC_TOKEN, strlen(MYMAIL_DB_MAGIC_TOKEN))) {
414       fprintf(stderr,
415               "mymail: Header line in '%s' does not match the mymail db format.\n",
416               db_filename);
417       exit(EXIT_FAILURE);
418     }
419   } else {
420     fprintf(stderr,
421             "mymail: Cannot read the header line in '%s'.\n",
422             db_filename);
423     exit(EXIT_FAILURE);
424   }
425
426   /* Then parse the said db file */
427
428   current_position_in_mail = 0;
429   already_written = 0;
430
431   for(n = 0; n < nb_search_conditions; n++) { hits[n] = 0; }
432
433   nb_body_conditions = 0;
434   for(n = 0; n < nb_search_conditions; n++) {
435     if(search_conditions[n].field_id == ID_BODY) {
436       nb_body_conditions++;
437     }
438   }
439
440   strcpy(current_mail_filename, "");
441
442   while(fgets(raw_db_line, BUFFER_SIZE, db_file)) {
443     mbox_value = parse_token(mbox_name, TOKEN_BUFFER_SIZE, ' ', raw_db_line);
444
445     if(strcmp("mail", mbox_name) == 0) {
446       char position_in_file_string[TOKEN_BUFFER_SIZE];
447
448       if(current_mail_filename[0]) {
449
450         /* We first check all conditions but the body ones */
451
452         for(n = 0; n < nb_search_conditions &&
453               ((search_conditions[n].field_id == ID_BODY) ||
454                xor(hits[n], search_conditions[n].negation)); n++);
455
456         if(n == nb_search_conditions) {
457
458           /* Now check the body ones */
459
460           if(nb_body_conditions > 0) {
461             update_body_hits(current_mail_filename, current_position_in_mail,
462                              nb_search_conditions, search_conditions,
463                              nb_body_conditions,
464                              hits);
465           }
466
467           nb_fulfilled_body_conditions = 0;
468
469           for(n = 0; n < nb_search_conditions; n++) {
470             if(search_conditions[n].field_id == ID_BODY &&
471                xor(hits[n], search_conditions[n].negation)) {
472               nb_fulfilled_body_conditions++;
473             }
474           }
475
476           if(nb_body_conditions == nb_fulfilled_body_conditions) {
477             extract_mail(current_mail_filename, current_position_in_mail, output_file);
478           }
479         }
480       }
481
482       for(n = 0; n < nb_search_conditions; n++) { hits[n] = 0; }
483
484       mbox_value = parse_token(position_in_file_string, TOKEN_BUFFER_SIZE, ' ', mbox_value);
485       mbox_value = parse_token(current_mail_filename, TOKEN_BUFFER_SIZE, '\n', mbox_value);
486       current_position_in_mail = atol(position_in_file_string);
487       already_written = 0;
488     }
489
490     else {
491       mbox_id = -1;
492       for(m = 0; (m < MAX_ID) && mbox_id == -1; m++) {
493         if(strncmp(field_names[m], mbox_name, strlen(mbox_name)) == 0) {
494           mbox_id = m;
495         }
496       }
497       for(n = 0; n < nb_search_conditions; n++) {
498         hits[n] |= mbox_line_match_search(&search_conditions[n],
499                                           mbox_id, mbox_value);
500       }
501     }
502   }
503
504   fclose(db_file);
505
506   if(!quiet) {
507     printf("done.\n");
508     fflush(stdout);
509   }
510 }
511
512 void recursive_search_in_db(const char *entry_name, regex_t *db_filename_regexp,
513                             int nb_search_conditions,
514                             struct search_condition *search_conditions,
515                             FILE *output_file) {
516   DIR *dir;
517   struct dirent *dir_e;
518   struct stat sb;
519   char subname[PATH_MAX + 1];
520
521   if(lstat(entry_name, &sb) != 0) {
522     fprintf(stderr,
523             "mymail: Cannot stat \"%s\": %s\n",
524             entry_name,
525             strerror(errno));
526     exit(EXIT_FAILURE);
527   }
528
529   dir = opendir(entry_name);
530
531   if(dir) {
532     while((dir_e = readdir(dir))) {
533       if(!ignore_entry(dir_e->d_name)) {
534         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
535         recursive_search_in_db(subname, db_filename_regexp,
536                                nb_search_conditions, search_conditions,
537                                output_file);
538       }
539     }
540     closedir(dir);
541   }
542
543   else {
544     const char *s = entry_name, *filename = entry_name;
545     while(*s) { if(*s == '/') { filename = s+1; } s++; }
546
547     if(regexec(db_filename_regexp, filename, 0, 0, 0) == 0) {
548       search_in_db(entry_name, nb_search_conditions, search_conditions, output_file);
549     }
550   }
551 }
552
553 /*********************************************************************/
554
555 void index_one_mbox_line(int nb_fields_to_parse, struct parsable_field *fields_to_parse,
556                          char *raw_mbox_line, FILE *db_file) {
557   regmatch_t matches;
558   int f;
559   for(f = 0; f < nb_fields_to_parse; f++) {
560     if(regexec(&fields_to_parse[f].regexp, raw_mbox_line, 1, &matches, 0) == 0) {
561       fprintf(db_file, "%s %s\n",
562               field_names[fields_to_parse[f].id],
563               raw_mbox_line + matches.rm_eo);
564     }
565   }
566 }
567
568 void index_mbox(const char *mbox_filename,
569                 int nb_fields_to_parse, struct parsable_field *fields_to_parse,
570                 FILE *db_file) {
571   char raw_mbox_line[BUFFER_SIZE], full_line[BUFFER_SIZE];
572   char *end_of_full_line;
573   FILE *file;
574   int in_header, new_header;
575   unsigned long int position_in_file;
576
577   file = fopen(mbox_filename, "r");
578
579   if(!file) {
580     fprintf(stderr, "mymail: Cannot open '%s'.\n", mbox_filename);
581     if(paranoid) { exit(EXIT_FAILURE); }
582     return;
583   }
584
585   in_header = 0;
586   new_header = 0;
587
588   position_in_file = 0;
589   end_of_full_line = 0;
590   full_line[0] = '\0';
591
592   while(fgets(raw_mbox_line, BUFFER_SIZE, file)) {
593     if(is_a_leading_from_line(raw_mbox_line)) {
594       if(in_header) {
595         fprintf(stderr,
596                 "Got a ^\"From \" in the header in %s:%lu.\n",
597                 mbox_filename, position_in_file);
598         fprintf(stderr, "%s", raw_mbox_line);
599         if(paranoid) { exit(EXIT_FAILURE); }
600       }
601       in_header = 1;
602       new_header = 1;
603     } else if(raw_mbox_line[0] == '\n') {
604       if(in_header) { in_header = 0; }
605     }
606
607     if(in_header) {
608       if(new_header) {
609         fprintf(db_file, "mail %lu %s\n", position_in_file, mbox_filename);
610         new_header = 0;
611       }
612
613       if(raw_mbox_line[0] == ' ' || raw_mbox_line[0] == '\t') {
614         char *start = raw_mbox_line;
615         while(*start == ' ' || *start == '\t') start++;
616         *(end_of_full_line++) = ' ';
617         strcpy(end_of_full_line, start);
618         while(*end_of_full_line && *end_of_full_line != '\n') {
619           end_of_full_line++;
620         }
621         *end_of_full_line = '\0';
622       }
623
624       else {
625         /*
626           if(!((raw_mbox_line[0] >= 'a' && raw_mbox_line[0] <= 'z') ||
627           (raw_mbox_line[0] >= 'A' && raw_mbox_line[0] <= 'Z'))) {
628           fprintf(stderr,
629           "Header line syntax error %s:%lu.\n",
630           mbox_filename, position_in_file);
631           fprintf(stderr, "%s", raw_mbox_line);
632           }
633         */
634
635         if(full_line[0]) {
636           index_one_mbox_line(nb_fields_to_parse, fields_to_parse, full_line, db_file);
637         }
638
639         end_of_full_line = full_line;
640         strcpy(end_of_full_line, raw_mbox_line);
641         while(*end_of_full_line && *end_of_full_line != '\n') {
642           end_of_full_line++;
643         }
644         *end_of_full_line = '\0';
645       }
646
647     }
648
649     position_in_file += strlen(raw_mbox_line);
650   }
651
652   fclose(file);
653 }
654
655 void recursive_index_mbox(FILE *db_file,
656                           const char *entry_name,
657                           int nb_fields_to_parse, struct parsable_field *fields_to_parse) {
658   DIR *dir;
659   struct dirent *dir_e;
660   struct stat sb;
661   char subname[PATH_MAX + 1];
662
663   if(lstat(entry_name, &sb) != 0) {
664     fprintf(stderr,
665             "mymail: Cannot stat \"%s\": %s\n",
666             entry_name,
667             strerror(errno));
668     exit(EXIT_FAILURE);
669   }
670
671   dir = opendir(entry_name);
672
673   if(dir) {
674     while((dir_e = readdir(dir))) {
675       if(!ignore_entry(dir_e->d_name)) {
676         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
677         recursive_index_mbox(db_file, subname, nb_fields_to_parse, fields_to_parse);
678       }
679     }
680     closedir(dir);
681   } else {
682     index_mbox(entry_name, nb_fields_to_parse, fields_to_parse, db_file);
683   }
684 }
685
686 /*********************************************************************/
687
688 /* For long options that have no equivalent short option, use a
689    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
690 enum {
691   OPT_BASH_MODE = CHAR_MAX + 1
692 };
693
694 static struct option long_options[] = {
695   { "help", no_argument, 0, 'h' },
696   { "version", no_argument, 0, 'v' },
697   { "quiet", no_argument, 0, 'q' },
698   { "db-file", 1, 0, 'd' },
699   { "db-pattern", 1, 0, 'p' },
700   { "db-root", 1, 0, 'r' },
701   { "db-list", 1, 0, 'l' },
702   { "search", 1, 0, 's' },
703   { "index", 0, 0, 'i' },
704   { "output", 1, 0, 'o' },
705   { "default-search", 1, 0, 'a' },
706   { 0, 0, 0, 0 }
707 };
708
709 /*********************************************************************/
710
711 void init_condition(struct search_condition *condition, char *full_string) {
712   char full_search_field[TOKEN_BUFFER_SIZE], *search_field;
713   int m;
714   char *string;
715
716   string = parse_token(full_search_field, TOKEN_BUFFER_SIZE, ' ', full_string);
717   search_field = full_search_field;
718
719   if(search_field[0] == '!') {
720     search_field++;
721     condition->negation = 1;
722   } else {
723     condition->negation = 0;
724   }
725
726   /* Recently */
727
728   if(strcmp(search_field, "8h") == 0) {
729     condition->field_id = ID_INTERVAL;
730     condition->interval_start = time(0) - 3600 * 8;
731     condition->interval_stop = 0;
732   }
733
734   else if(strcmp(search_field, "24h") == 0 ||
735           strcmp(search_field, "today") == 0) {
736     condition->field_id = ID_INTERVAL;
737     condition->interval_start = time(0) - 3600 * 24;
738     condition->interval_stop = 0;
739   }
740
741   else if(strcmp(search_field, "week") == 0) {
742     condition->field_id = ID_INTERVAL;
743     condition->interval_start = time(0) - 3600 * 24 * 7;
744     condition->interval_stop = 0;
745   }
746
747   else if(strcmp(search_field, "month") == 0) {
748     condition->field_id = ID_INTERVAL;
749     condition->interval_start = time(0) - 3600 * 24 * 31;
750     condition->interval_stop = 0;
751   }
752
753   else if(strcmp(search_field, "year") == 0) {
754     condition->field_id = ID_INTERVAL;
755     condition->interval_start = time(0) - 3600 * 24 * 365;
756     condition->interval_stop = 0;
757   }
758
759   /* Yesterday */
760
761   else if(strcmp(search_field, "yesterday") == 0) {
762     condition->field_id = ID_INTERVAL;
763     condition->interval_start = time(0) - 2 * 3600 * 24;
764     condition->interval_stop = condition->interval_start + 3600 * 24;
765   }
766
767   /* Week days */
768
769   else if(strcmp(search_field, "monday") == 0) {
770     condition->field_id = ID_INTERVAL;
771     condition->interval_start = time_for_past_day(1);
772     condition->interval_stop = condition->interval_start + 3600 * 24;
773   }
774
775   else if(strcmp(search_field, "tuesday") == 0) {
776     condition->field_id = ID_INTERVAL;
777     condition->interval_start = time_for_past_day(2);
778     condition->interval_stop = condition->interval_start + 3600 * 24;
779   }
780
781   else if(strcmp(search_field, "wednesday") == 0) {
782     condition->field_id = ID_INTERVAL;
783     condition->interval_start = time_for_past_day(3);
784     condition->interval_stop = condition->interval_start + 3600 * 24;
785   }
786
787   else if(strcmp(search_field, "thursday") == 0) {
788     condition->field_id = ID_INTERVAL;
789     condition->interval_start = time_for_past_day(4);
790     condition->interval_stop = condition->interval_start + 3600 * 24;
791   }
792
793   else if(strcmp(search_field, "friday") == 0) {
794     condition->field_id = ID_INTERVAL;
795     condition->interval_start = time_for_past_day(5);
796     condition->interval_stop = condition->interval_start + 3600 * 24;
797   }
798
799   else if(strcmp(search_field, "saturday") == 0) {
800     condition->field_id = ID_INTERVAL;
801     condition->interval_start = time_for_past_day(6);
802     condition->interval_stop = condition->interval_start + 3600 * 24;
803   }
804
805   else if(strcmp(search_field, "sunday") == 0) {
806     condition->field_id = ID_INTERVAL;
807     condition->interval_start = time_for_past_day(7);
808     condition->interval_stop = condition->interval_start + 3600 * 24;
809   }
810
811   else {
812
813     /* header-related conditions */
814
815     condition->field_id = -1;
816
817     for(m = 0; (m < MAX_ID) && condition->field_id == -1; m++) {
818       if(strncmp(field_names[m], search_field, strlen(search_field)) == 0) {
819         condition->field_id = m;
820       }
821     }
822
823     if(condition->field_id == -1) {
824       if(default_search_field) {
825         for(m = 0; (m < MAX_ID) && condition->field_id == -1; m++) {
826           if(strncmp(field_names[m],
827                      default_search_field, strlen(default_search_field)) == 0) {
828             condition->field_id = m;
829           }
830         }
831         string = full_string;
832       }
833     }
834
835     if(condition->field_id == -1) {
836       fprintf(stderr,
837               "mymail: Syntax error in field name \"%s\".\n",
838               search_field);
839       exit(EXIT_FAILURE);
840     }
841
842     if(regcomp(&condition->regexp,
843                string,
844                REG_ICASE)) {
845       fprintf(stderr,
846               "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
847               string,
848               field_names[condition->field_id]);
849       exit(EXIT_FAILURE);
850     }
851   }
852 }
853
854 void free_condition(struct search_condition *condition) {
855   if(condition->field_id != ID_INTERVAL) {
856     regfree(&condition->regexp);
857   }
858 }
859
860 /*********************************************************************/
861 /*********************************************************************/
862 /*********************************************************************/
863
864 int main(int argc, char **argv) {
865   char *db_filename;
866   char *db_filename_regexp_string;
867   char *db_root_path;
868   char *db_filename_list;
869   char output_filename[PATH_MAX + 1];
870   int action_index;
871   int error = 0, show_help = 0;
872   const int nb_fields_to_parse = sizeof(fields_to_parse) / sizeof(struct parsable_field);
873   char c;
874   int f, n;
875   int nb_search_conditions;
876   FILE *output_file;
877   struct search_condition search_conditions[MAX_NB_SEARCH_CONDITIONS];
878
879   if(regcomp(&leading_from_line_regexp, LEADING_FROM_LINE_REGEXP, 0)) {
880     fprintf(stderr,
881             "mymail: Cannot compile leading \"from\" line regexp. That is strange.\n");
882     exit(EXIT_FAILURE);
883   }
884
885   paranoid = 0;
886   action_index = 0;
887   db_filename = 0;
888   db_filename_regexp_string = 0;
889   db_root_path = 0;
890   db_filename_list = 0;
891   quiet = 0;
892   default_search_field = 0;
893   ignore_dot_files = 1;
894
895   setlocale(LC_ALL, "");
896
897   nb_search_conditions = 0;
898
899   while ((c = getopt_long(argc, argv, "hvqip:s:d:r:l:o:a:",
900                           long_options, NULL)) != -1) {
901
902     switch(c) {
903
904     case 'h':
905       show_help = 1;
906       break;
907
908     case 'v':
909       print_version(stdout);
910       break;
911
912     case 'q':
913       quiet = 1;
914       break;
915
916     case 'i':
917       action_index = 1;
918       break;
919
920     case 'd':
921       db_filename = strdup(optarg);
922       break;
923
924     case 'p':
925       db_filename_regexp_string = strdup(optarg);
926       break;
927
928     case 'o':
929       strncpy(output_filename, optarg, PATH_MAX);
930       break;
931
932     case 'r':
933       db_root_path = strdup(optarg);
934       break;
935
936     case 'l':
937       db_filename_list = strdup(optarg);
938       break;
939
940     case 's':
941       if(nb_search_conditions == MAX_NB_SEARCH_CONDITIONS) {
942         fprintf(stderr, "mymail: Too many search patterns.\n");
943         exit(EXIT_FAILURE);
944       }
945       init_condition(&search_conditions[nb_search_conditions], optarg);
946       nb_search_conditions++;
947       break;
948
949     case 'a':
950       default_search_field = optarg;
951       break;
952
953     default:
954       error = 1;
955       break;
956     }
957   }
958
959   if(!db_filename) {
960     char *default_db_filename = getenv("MYMAIL_DB_FILE");
961
962     if(!default_db_filename) {
963       default_db_filename = "mymail.db";
964     }
965
966     db_filename = strdup(default_db_filename);
967   }
968
969   if(!db_filename_regexp_string) {
970     char *default_db_filename_regexp_string = getenv("MYMAIL_DB_PATTERN");
971
972     if(!default_db_filename_regexp_string) {
973       default_db_filename_regexp_string = "^mymail.db$";
974     }
975
976     db_filename_regexp_string = strdup(default_db_filename_regexp_string);
977   }
978
979   if(!db_root_path) {
980     char *default_db_root_path = getenv("MYMAIL_DB_ROOT");
981
982     if(default_db_root_path) {
983       db_root_path = strdup(default_db_root_path);
984     }
985   }
986
987   if(!db_filename_list) {
988     char *default_db_filename_list = getenv("MYMAIL_DB_LIST");
989
990     if(default_db_filename_list) {
991       db_filename_list = strdup(default_db_filename_list);
992     }
993   }
994
995   if(output_filename[0]) {
996     output_file = fopen(output_filename, "w");
997
998     if(!output_file) {
999       fprintf(stderr,
1000               "mymail: Cannot open result file \"%s\" for writing: %s\n",
1001               output_filename,
1002               strerror(errno));
1003       exit(EXIT_FAILURE);
1004     }
1005   } else {
1006     output_file = stdout;
1007     quiet = 1;
1008   }
1009
1010   if(error) {
1011     print_usage(stderr);
1012     exit(EXIT_FAILURE);
1013   }
1014
1015   if(show_help) {
1016     print_usage(stdout);
1017     exit(EXIT_SUCCESS);
1018   }
1019
1020   if(action_index) {
1021     FILE *db_file;
1022
1023     db_file = fopen(db_filename, "w");
1024
1025     if(!db_file) {
1026       fprintf(stderr,
1027               "mymail: Cannot open \"%s\" for writing: %s\n",
1028               db_filename,
1029               strerror(errno));
1030       exit(EXIT_FAILURE);
1031     }
1032
1033     for(f = 0; f < nb_fields_to_parse; f++) {
1034       if(regcomp(&fields_to_parse[f].regexp,
1035                  fields_to_parse[f].regexp_string,
1036                  fields_to_parse[f].cflags)) {
1037         fprintf(stderr,
1038                 "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
1039                 fields_to_parse[f].regexp_string,
1040                 field_names[fields_to_parse[f].id]);
1041         exit(EXIT_FAILURE);
1042       }
1043     }
1044
1045     fprintf(db_file, "%s version_%s raw\n", MYMAIL_DB_MAGIC_TOKEN, VERSION);
1046
1047     while(optind < argc) {
1048       recursive_index_mbox(db_file,
1049                            argv[optind],
1050                            nb_fields_to_parse, fields_to_parse);
1051       optind++;
1052     }
1053
1054     fflush(db_file);
1055     fclose(db_file);
1056
1057     for(f = 0; f < nb_fields_to_parse; f++) {
1058       regfree(&fields_to_parse[f].regexp);
1059     }
1060   }
1061
1062   else {
1063
1064     if(nb_search_conditions > 0) {
1065
1066       /* Recursive search if db_root_path is set */
1067
1068       if(db_root_path) {
1069         regex_t db_filename_regexp;
1070         if(regcomp(&db_filename_regexp,
1071                    db_filename_regexp_string,
1072                    0)) {
1073           fprintf(stderr,
1074                   "mymail: Syntax error in regexp \"%s\".\n",
1075                   db_filename_regexp_string);
1076           exit(EXIT_FAILURE);
1077         }
1078
1079         recursive_search_in_db(db_root_path, &db_filename_regexp,
1080                                nb_search_conditions, search_conditions,
1081                                output_file);
1082
1083         regfree(&db_filename_regexp);
1084       }
1085
1086       /* Search in all db files listed in db_filename_list */
1087
1088       if(db_filename_list) {
1089         char db_filename[PATH_MAX + 1];
1090         char *s;
1091
1092         s = db_filename_list;
1093
1094         while(*s) {
1095           s = parse_token(db_filename, PATH_MAX + 1, ';', s);
1096
1097           if(db_filename[0]) {
1098             search_in_db(db_filename, nb_search_conditions, search_conditions, output_file);
1099           }
1100         }
1101       }
1102
1103       /* Search in all db files listed in the command arguments */
1104
1105       while(optind < argc) {
1106         search_in_db(argv[optind], nb_search_conditions, search_conditions, output_file);
1107         optind++;
1108       }
1109     }
1110   }
1111
1112   for(n = 0; n < nb_search_conditions; n++) {
1113     free_condition(&search_conditions[n]);
1114   }
1115
1116   if(output_file != stdout) {
1117     fflush(output_file);
1118     fclose(output_file);
1119   }
1120
1121   free(db_filename);
1122   free(db_filename_regexp_string);
1123   free(db_root_path);
1124   free(db_filename_list);
1125
1126   regfree(&leading_from_line_regexp);
1127
1128   exit(EXIT_SUCCESS);
1129 }