Added a regexp-based check for the "leading From lines". This sucks horribly.
[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.1"
50
51 #define MAX_NB_SEARCH_CONDITIONS 10
52
53 #define BUFFER_SIZE 65536
54
55 regex_t leading_from_line_regexp;
56
57 char *db_filename;
58 char *db_filename_regexp_string;
59 char *db_root_path;
60 char *db_filename_list;
61 char output_filename[PATH_MAX + 1];
62
63 int paranoid;
64 int action_index;
65 int quiet;
66
67 time_t being_today;
68
69 /********************************************************************/
70
71 enum {
72   ID_MAIL = 0,
73   ID_LEADING_LINE,
74   ID_FROM,
75   ID_TO,
76   ID_SUBJECT,
77   ID_DATE,
78   ID_PARTICIPANT,
79   ID_BODY,
80   ID_INTERVAL,
81   MAX_ID
82 };
83
84 static char *field_names[] = {
85   "mail",
86   "lead",
87   "from",
88   "to",
89   "subject",
90   "date",
91   "part",
92   "body",
93   "interval"
94 };
95
96 /********************************************************************/
97
98 struct search_condition {
99   int field_id;
100   int negation;
101   regex_t regexp;
102   time_t interval_start, interval_stop;
103 };
104
105 /********************************************************************/
106
107 struct parsable_field {
108   int id;
109   char *regexp_string;
110   regex_t regexp;
111 };
112
113 static struct parsable_field fields_to_parse[] = {
114   {
115     ID_LEADING_LINE,
116     "^From ",
117     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
118   },
119
120   {
121     ID_FROM,
122     "^\\([Ff][Rr][Oo][Mm]:\\|[Rr][Ee][Pp][Ll][Yy]-[Tt][Oo]:\\|[Ss][Ee][Nn][Dd][Ee][Rr]:\\)",
123     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
124   },
125
126   {
127     ID_TO,
128     "^\\([Tt][Oo]\\|[Cc][Cc]\\|[Bb][Cc][Cc]\\): ",
129     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
130   },
131
132   {
133     ID_SUBJECT,
134     "^[Ss][Uu][Bb][Jj][Ee][Cc][Tt]: ",
135     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
136   },
137
138   {
139     ID_DATE,
140     "^[Dd][Aa][Tt][Ee]: ",
141     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
142   },
143
144 };
145
146 /********************************************************************/
147
148 int xor(int a, int b) {
149   return (a && !b) || (!a && b);
150 }
151
152 char *segment_next_field(char *current) {
153   while(*current && *current != ' ') current++;
154   *current = '\0'; current++;
155   while(*current && *current == ' ') current++;
156   return current;
157 }
158
159 void remove_eof(char *c) {
160   while(*c && *c != '\n' && *c != '\r') c++;
161   *c = '\0';
162 }
163
164 /********************************************************************/
165
166 /* malloc with error checking.  */
167
168 void *safe_malloc(size_t n) {
169   void *p = malloc(n);
170   if(!p && n != 0) {
171     fprintf(stderr,
172             "mymail: cannot allocate memory: %s\n", strerror(errno));
173     exit(EXIT_FAILURE);
174   }
175   return p;
176 }
177
178 /*********************************************************************/
179
180 void print_version(FILE *out) {
181   fprintf(out, "mymail version %s (%s)\n", VERSION, UNAME);
182 }
183
184 void print_usage(FILE *out) {
185   print_version(out);
186   fprintf(out, "Written by Francois Fleuret <francois@fleuret.org>.\n");
187   fprintf(out, "\n");
188   fprintf(out, "Usage: mymail [options] [<mbox dir1> [<mbox dir2> ...]|<db file1> [<db file2> ...]]\n");
189   fprintf(out, "\n");
190   fprintf(out, " -h, --help\n");
191   fprintf(out, "         show this help\n");
192   fprintf(out, " -v, --version\n");
193   fprintf(out, "         print the version number\n");
194   fprintf(out, " -q, --quiet\n");
195   fprintf(out, "         do not print information during search\n");
196   fprintf(out, " -p <db filename pattern>, --db-pattern <db filename pattern>\n");
197   fprintf(out, "         set the db filename pattern for recursive search\n");
198   fprintf(out, " -r <db root path>, --db-root <db root path>\n");
199   fprintf(out, "         set the db root path for recursive search\n");
200   fprintf(out, " -l <db filename list>, --db-list <db filename list>\n");
201   fprintf(out, "         set the semicolon-separated list of db files for search\n");
202   fprintf(out, " -s <search pattern>, --search <search pattern>\n");
203   fprintf(out, "         search for matching mails in the db file\n");
204   fprintf(out, " -d <db filename>, --db-file <db filename>\n");
205   fprintf(out, "         set the db filename for indexing\n");
206   fprintf(out, " -i, --index\n");
207   fprintf(out, "         index mails\n");
208   fprintf(out, " -o <output filename>, --output <output filename>\n");
209   fprintf(out, "         set the result file, use stdout if unset\n");
210 }
211
212 /*********************************************************************/
213
214 int ignore_entry(const char *name) {
215   return
216     /* strcmp(name, ".") == 0 || */
217     /* strcmp(name, "..") == 0 || */
218     (name[0] == '.' && name[1] != '/');
219 }
220
221 int is_a_leading_from_line(char *s) {
222   return strncmp(s, "From ", 5) == 0 &&
223     regexec(&leading_from_line_regexp, s, 0, 0, 0) == 0;
224 }
225
226 int mbox_line_match_search(struct search_condition *condition,
227                            int mbox_id, char *mbox_value) {
228
229   if(condition->field_id == ID_INTERVAL) {
230     if(mbox_id == ID_LEADING_LINE) {
231       char *c;
232       time_t t;
233       struct tm tm;
234
235       c = mbox_value;
236       while(*c && *c != ' ') c++; while(*c && *c == ' ') c++;
237       strptime(c, "%a %b %e %k:%M:%S %Y", &tm);
238       t = mktime(&tm);
239
240       return (t >= condition->interval_start &&
241               (condition->interval_stop == 0 ||
242                t <= condition->interval_stop));
243     } else {
244       return 0;
245     }
246   } else {
247     return
248       (
249
250        (condition->field_id == mbox_id)
251
252        ||
253
254        (condition->field_id == ID_PARTICIPANT && (mbox_id == ID_LEADING_LINE ||
255                                                   mbox_id == ID_FROM ||
256                                                   mbox_id == ID_TO))
257        ||
258
259        (condition->field_id == ID_FROM && mbox_id == ID_LEADING_LINE)
260
261        )
262       &&
263       regexec(&condition->regexp, mbox_value, 0, 0, 0) == 0;
264   }
265 }
266
267 void search_in_db(FILE *db_file,
268                   int nb_search_conditions,
269                   struct search_condition *search_conditions,
270                   FILE *output_file) {
271
272   int hits[MAX_NB_SEARCH_CONDITIONS];
273   char raw_db_line[BUFFER_SIZE];
274   char raw_mbox_line[BUFFER_SIZE];
275   char current_mail_filename[PATH_MAX + 1];
276   unsigned long int current_position_in_mail;
277   char *mbox_name, *mbox_value;
278   int mbox_id;
279   int already_written, m, n;
280   int last_mbox_line_was_empty;
281   int nb_body_conditions, nb_fulfilled_body_conditions;
282
283   current_position_in_mail = 0;
284   already_written = 0;
285
286   for(n = 0; n < nb_search_conditions; n++) { hits[n] = 0; }
287
288   nb_body_conditions = 0;
289   for(n = 0; n < nb_search_conditions; n++) {
290     if(search_conditions[n].field_id == ID_BODY) {
291       nb_body_conditions++;
292     }
293   }
294
295   strcpy(current_mail_filename, "");
296
297   while(fgets(raw_db_line, BUFFER_SIZE, db_file)) {
298     mbox_name = raw_db_line;
299     mbox_value = segment_next_field(raw_db_line);
300
301     if(strcmp("mail", mbox_name) == 0) {
302       char *position_in_file_string;
303       char *mail_filename;
304
305       if(current_mail_filename[0]) {
306
307         /* We first check all conditions but the body ones */
308
309         for(n = 0; n < nb_search_conditions &&
310               ((search_conditions[n].field_id == ID_BODY) ||
311                xor(hits[n], search_conditions[n].negation)); n++);
312
313         if(n == nb_search_conditions) {
314
315           /* all conditions but the body ones are fine, check the body
316              ones */
317
318           nb_fulfilled_body_conditions = 0;
319
320           if(nb_body_conditions > 0) {
321             FILE *mail_file;
322             int header;
323
324             header = 1;
325             mail_file = fopen(current_mail_filename, "r");
326
327             if(!mail_file) {
328               fprintf(stderr,
329                       "mymail: Cannot open mbox '%s' for body scan.\n",
330                       current_mail_filename);
331               exit(EXIT_FAILURE);
332             }
333
334             fseek(mail_file, current_position_in_mail, SEEK_SET);
335
336             if(fgets(raw_mbox_line, BUFFER_SIZE, mail_file)) {
337               while(nb_fulfilled_body_conditions < nb_body_conditions) {
338                 last_mbox_line_was_empty = (raw_mbox_line[0] == '\n');
339
340                 if(last_mbox_line_was_empty) { header = 0; }
341
342                 if(!header) {
343                   for(n = 0; n < nb_search_conditions; n++) {
344                     if(search_conditions[n].field_id == ID_BODY && !hits[n]) {
345                       hits[n] =
346                         (regexec(&search_conditions[n].regexp, raw_mbox_line, 0, 0, 0) == 0);
347                       if(hits[n]) {
348                         nb_fulfilled_body_conditions++;
349                       }
350                     }
351                   }
352                 }
353
354                 if(!fgets(raw_mbox_line, BUFFER_SIZE, mail_file) ||
355                    (last_mbox_line_was_empty &&
356                     is_a_leading_from_line(raw_mbox_line)))
357                   break;
358               }
359             }
360
361             fclose(mail_file);
362           }
363
364           if(nb_body_conditions == nb_fulfilled_body_conditions) {
365             FILE *mail_file;
366
367             mail_file = fopen(current_mail_filename, "r");
368
369             if(!mail_file) {
370               fprintf(stderr,
371                       "mymail: Cannot open mbox '%s' for mail extraction.\n",
372                       current_mail_filename);
373               exit(EXIT_FAILURE);
374             }
375
376             fseek(mail_file, current_position_in_mail, SEEK_SET);
377
378             if(fgets(raw_mbox_line, BUFFER_SIZE, mail_file)) {
379               last_mbox_line_was_empty = 1;
380               fprintf(output_file, "%s", raw_mbox_line);
381               while(1) {
382                 if(!fgets(raw_mbox_line, BUFFER_SIZE, mail_file) ||
383                    (last_mbox_line_was_empty &&
384                     is_a_leading_from_line(raw_mbox_line))
385                    )
386                   break;
387                 last_mbox_line_was_empty = (raw_mbox_line[0] == '\n');
388                 fprintf(output_file, "%s", raw_mbox_line);
389               }
390             }
391
392             fclose(mail_file);
393           }
394         }
395       }
396
397       for(n = 0; n < nb_search_conditions; n++) { hits[n] = 0; }
398
399       position_in_file_string = mbox_value;
400       mail_filename = segment_next_field(mbox_value);
401       current_position_in_mail = atol(position_in_file_string);
402       strcpy(current_mail_filename, mail_filename);
403
404       remove_eof(current_mail_filename);
405       already_written = 0;
406     }
407
408     else {
409       mbox_id = -1;
410       for(m = 0; (m < MAX_ID) && mbox_id == -1; m++) {
411         if(strncmp(field_names[m], mbox_name, strlen(mbox_name)) == 0) {
412           mbox_id = m;
413         }
414       }
415       for(n = 0; n < nb_search_conditions; n++) {
416         hits[n] |= mbox_line_match_search(&search_conditions[n],
417                                           mbox_id, mbox_value);
418       }
419     }
420   }
421 }
422
423 void recursive_search_in_db(const char *entry_name, regex_t *db_filename_regexp,
424                             int nb_search_conditions,
425                             struct search_condition *search_conditions,
426                             FILE *output_file) {
427   DIR *dir;
428   struct dirent *dir_e;
429   struct stat sb;
430   char raw_db_line[BUFFER_SIZE];
431   char subname[PATH_MAX + 1];
432
433   if(lstat(entry_name, &sb) != 0) {
434     fprintf(stderr,
435             "mymail: Cannot stat \"%s\": %s\n",
436             entry_name,
437             strerror(errno));
438     exit(EXIT_FAILURE);
439   }
440
441   dir = opendir(entry_name);
442
443   if(dir) {
444     while((dir_e = readdir(dir))) {
445       if(!ignore_entry(dir_e->d_name)) {
446         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
447         recursive_search_in_db(subname, db_filename_regexp,
448                                nb_search_conditions, search_conditions,
449                                output_file);
450       }
451     }
452     closedir(dir);
453   }
454
455   else {
456     const char *s = entry_name, *filename = entry_name;
457     while(*s) { if(*s == '/') { filename = s+1; } s++; }
458
459     if(regexec(db_filename_regexp, filename, 0, 0, 0) == 0) {
460       FILE *db_file = fopen(entry_name, "r");
461
462       if(!quiet) {
463         printf("Searching in '%s' ... ", entry_name);
464         fflush(stdout);
465       }
466
467       if(!db_file) {
468         fprintf(stderr,
469                 "mymail: Cannot open \"%s\" for reading: %s\n",
470                 db_filename,
471                 strerror(errno));
472         exit(EXIT_FAILURE);
473       }
474
475       if(fgets(raw_db_line, BUFFER_SIZE, db_file)) {
476         if(strncmp(raw_db_line, MYMAIL_DB_MAGIC_TOKEN, strlen(MYMAIL_DB_MAGIC_TOKEN))) {
477           fprintf(stderr,
478                   "mymail: Header line in '%s' does not match the mymail db format.\n",
479                   entry_name);
480           exit(EXIT_FAILURE);
481         }
482       } else {
483         fprintf(stderr,
484                 "mymail: Cannot read the header line in '%s'.\n",
485                 entry_name);
486         exit(EXIT_FAILURE);
487       }
488
489       search_in_db(db_file, nb_search_conditions, search_conditions, output_file);
490
491       fclose(db_file);
492
493       if(!quiet) {
494         printf("done.\n");
495         fflush(stdout);
496       }
497     }
498   }
499 }
500
501 /*********************************************************************/
502
503 void index_one_mbox_line(int nb_fields_to_parse, struct parsable_field *fields_to_parse,
504                          char *raw_mbox_line, FILE *db_file) {
505   regmatch_t matches;
506   int f;
507   for(f = 0; f < nb_fields_to_parse; f++) {
508     if(regexec(&fields_to_parse[f].regexp, raw_mbox_line, 1, &matches, 0) == 0) {
509       fprintf(db_file, "%s %s\n",
510               field_names[fields_to_parse[f].id],
511               raw_mbox_line + matches.rm_eo);
512     }
513   }
514 }
515
516 void index_mbox(const char *mbox_filename,
517                 int nb_fields_to_parse, struct parsable_field *fields_to_parse,
518                 FILE *db_file) {
519   char raw_mbox_line[BUFFER_SIZE], full_line[BUFFER_SIZE];
520   char *end_of_full_line;
521   FILE *file;
522   int in_header, new_header, last_mbox_line_was_empty;
523   unsigned long int position_in_file;
524
525   file = fopen(mbox_filename, "r");
526
527   if(!file) {
528     fprintf(stderr, "mymail: Cannot open '%s'.\n", mbox_filename);
529     if(paranoid) { exit(EXIT_FAILURE); }
530     return;
531   }
532
533   in_header = 0;
534   new_header = 0;
535
536   position_in_file = 0;
537   end_of_full_line = 0;
538   full_line[0] = '\0';
539   last_mbox_line_was_empty = 1;
540
541   while(fgets(raw_mbox_line, BUFFER_SIZE, file)) {
542     if(last_mbox_line_was_empty &&
543        is_a_leading_from_line(raw_mbox_line)) {
544       if(in_header) {
545         fprintf(stderr,
546                 "Got a ^\"From \" in the header in %s:%lu.\n",
547                 mbox_filename, position_in_file);
548         fprintf(stderr, "%s", raw_mbox_line);
549         if(paranoid) { exit(EXIT_FAILURE); }
550       }
551       in_header = 1;
552       new_header = 1;
553     } else if(raw_mbox_line[0] == '\n') {
554       if(in_header) { in_header = 0; }
555     }
556
557     last_mbox_line_was_empty = (raw_mbox_line[0] == '\n');
558
559     if(in_header) {
560       if(new_header) {
561         fprintf(db_file, "mail %lu %s\n", position_in_file, mbox_filename);
562         new_header = 0;
563       }
564
565       if(raw_mbox_line[0] == ' ' || raw_mbox_line[0] == '\t') {
566         char *start = raw_mbox_line;
567         while(*start == ' ' || *start == '\t') start++;
568         *(end_of_full_line++) = ' ';
569         strcpy(end_of_full_line, start);
570         while(*end_of_full_line && *end_of_full_line != '\n') {
571           end_of_full_line++;
572         }
573         *end_of_full_line = '\0';
574       }
575
576       else {
577         /*
578           if(!((raw_mbox_line[0] >= 'a' && raw_mbox_line[0] <= 'z') ||
579           (raw_mbox_line[0] >= 'A' && raw_mbox_line[0] <= 'Z'))) {
580           fprintf(stderr,
581           "Header line syntax error %s:%lu.\n",
582           mbox_filename, position_in_file);
583           fprintf(stderr, "%s", raw_mbox_line);
584           }
585         */
586
587         if(full_line[0]) {
588           index_one_mbox_line(nb_fields_to_parse, fields_to_parse, full_line, db_file);
589         }
590
591         end_of_full_line = full_line;
592         strcpy(end_of_full_line, raw_mbox_line);
593         while(*end_of_full_line && *end_of_full_line != '\n') {
594           end_of_full_line++;
595         }
596         *end_of_full_line = '\0';
597       }
598
599     }
600
601     position_in_file += strlen(raw_mbox_line);
602   }
603
604   fclose(file);
605 }
606
607 void recursive_index_mbox(FILE *db_file,
608                           const char *entry_name,
609                           int nb_fields_to_parse, struct parsable_field *fields_to_parse) {
610   DIR *dir;
611   struct dirent *dir_e;
612   struct stat sb;
613   char subname[PATH_MAX + 1];
614
615   if(lstat(entry_name, &sb) != 0) {
616     fprintf(stderr,
617             "mymail: Cannot stat \"%s\": %s\n",
618             entry_name,
619             strerror(errno));
620     exit(EXIT_FAILURE);
621   }
622
623   dir = opendir(entry_name);
624
625   if(dir) {
626     while((dir_e = readdir(dir))) {
627       if(!ignore_entry(dir_e->d_name)) {
628         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
629         recursive_index_mbox(db_file, subname, nb_fields_to_parse, fields_to_parse);
630       }
631     }
632     closedir(dir);
633   } else {
634     index_mbox(entry_name, nb_fields_to_parse, fields_to_parse, db_file);
635   }
636 }
637
638 /*********************************************************************/
639
640 /* For long options that have no equivalent short option, use a
641    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
642 enum {
643   OPT_BASH_MODE = CHAR_MAX + 1
644 };
645
646 static struct option long_options[] = {
647   { "help", no_argument, 0, 'h' },
648   { "version", no_argument, 0, 'v' },
649   { "quiet", no_argument, 0, 'q' },
650   { "db-file", 1, 0, 'd' },
651   { "db-pattern", 1, 0, 'p' },
652   { "db-root", 1, 0, 'r' },
653   { "db-list", 1, 0, 'l' },
654   { "search", 1, 0, 's' },
655   { "index", 0, 0, 'i' },
656   { "output", 1, 0, 'o' },
657   { 0, 0, 0, 0 }
658 };
659
660 /*********************************************************************/
661
662 int main(int argc, char **argv) {
663   int error = 0, show_help = 0;
664   const int nb_fields_to_parse = sizeof(fields_to_parse) / sizeof(struct parsable_field);
665   char c;
666   int f;
667   int nb_search_conditions;
668   char *search_condition_strings[MAX_NB_SEARCH_CONDITIONS];
669   FILE *output_file;
670
671   if(regcomp(&leading_from_line_regexp,
672              "^From [^ ]*@[^ ]*  \\(Mon\\|Tue\\|Wed\\|Thu\\|Fri\\|Sat\\|Sun\\) \\(Jan\\|Feb\\|Mar\\|Apr\\|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$",
673              0)) {
674     fprintf(stderr,
675             "mymail: Cannot compile leading from line regexp. That is strange.\n");
676     exit(EXIT_FAILURE);
677   }
678
679   /* printf("%d\n", regexec(&leading_from_line_regexp, "From root@idiap.ch  Mon Apr 18 08:25:06 2011\n", 0, 0, 0)); */
680   /* exit(EXIT_SUCCESS); */
681
682   paranoid = 0;
683   action_index = 0;
684   db_filename = 0;
685   db_root_path = 0;
686   db_filename_list = 0;
687   quiet = 0;
688
689   setlocale(LC_ALL, "");
690
691   nb_search_conditions = 0;
692
693   while ((c = getopt_long(argc, argv, "hvqip:s:d:r:l:o:",
694                           long_options, NULL)) != -1) {
695
696     switch(c) {
697
698     case 'h':
699       show_help = 1;
700       break;
701
702     case 'v':
703       print_version(stdout);
704       break;
705
706     case 'q':
707       quiet = 1;
708       break;
709
710     case 'i':
711       action_index = 1;
712       break;
713
714     case 'd':
715       db_filename = strdup(optarg);
716       break;
717
718     case 'p':
719       db_filename_regexp_string = strdup(optarg);
720       break;
721
722     case 'o':
723       strncpy(output_filename, optarg, PATH_MAX);
724       break;
725
726     case 'r':
727       db_root_path = strdup(optarg);
728       break;
729
730     case 'l':
731       db_filename_list = strdup(optarg);
732       break;
733
734     case 's':
735       if(nb_search_conditions == MAX_NB_SEARCH_CONDITIONS) {
736         fprintf(stderr, "mymail: Too many search patterns.\n");
737         exit(EXIT_FAILURE);
738       }
739       search_condition_strings[nb_search_conditions++] = strdup(optarg);
740       break;
741
742     default:
743       error = 1;
744       break;
745     }
746   }
747
748   if(!db_filename) {
749     char *default_db_filename = getenv("MYMAIL_DB_FILE");
750
751     if(!default_db_filename) {
752       default_db_filename = "mymail.db";
753     }
754
755     db_filename = strdup(default_db_filename);
756   }
757
758   if(!db_filename_regexp_string) {
759     char *default_db_filename_regexp_string = getenv("MYMAIL_DB_PATTERN");
760
761     if(!default_db_filename_regexp_string) {
762       default_db_filename_regexp_string = "^mymail.db$";
763     }
764
765     db_filename_regexp_string = strdup(default_db_filename_regexp_string);
766   }
767
768   if(!db_root_path) {
769     char *default_db_root_path = getenv("MYMAIL_DB_ROOT");
770
771     if(default_db_root_path) {
772       db_root_path = strdup(default_db_root_path);
773     }
774   }
775
776   if(!db_filename_list) {
777     char *default_db_filename_list = getenv("MYMAIL_DB_LIST");
778
779     if(default_db_filename_list) {
780       db_filename_list = strdup(default_db_filename_list);
781     }
782   }
783
784   if(output_filename[0]) {
785     output_file = fopen(output_filename, "w");
786
787     if(!output_file) {
788       fprintf(stderr,
789               "mymail: Cannot open result file \"%s\" for writing: %s\n",
790               output_filename,
791               strerror(errno));
792       exit(EXIT_FAILURE);
793     }
794   } else {
795     output_file = stdout;
796     quiet = 1;
797   }
798
799   if(error) {
800     print_usage(stderr);
801     exit(EXIT_FAILURE);
802   }
803
804   if(show_help) {
805     print_usage(stdout);
806     exit(EXIT_SUCCESS);
807   }
808
809   if(action_index) {
810     FILE *db_file;
811
812     db_file = fopen(db_filename, "w");
813
814     if(!db_file) {
815       fprintf(stderr,
816               "mymail: Cannot open \"%s\" for writing: %s\n",
817               db_filename,
818               strerror(errno));
819       exit(EXIT_FAILURE);
820     }
821
822     for(f = 0; f < nb_fields_to_parse; f++) {
823       if(regcomp(&fields_to_parse[f].regexp,
824                  fields_to_parse[f].regexp_string,
825                  REG_ICASE)) {
826         fprintf(stderr,
827                 "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
828                 fields_to_parse[f].regexp_string,
829                 field_names[fields_to_parse[f].id]);
830         exit(EXIT_FAILURE);
831       }
832     }
833
834     fprintf(db_file, "%s version_%s raw\n", MYMAIL_DB_MAGIC_TOKEN, VERSION);
835
836     while(optind < argc) {
837       recursive_index_mbox(db_file,
838                            argv[optind],
839                            nb_fields_to_parse, fields_to_parse);
840       optind++;
841     }
842
843     fflush(db_file);
844     fclose(db_file);
845
846     for(f = 0; f < nb_fields_to_parse; f++) {
847       regfree(&fields_to_parse[f].regexp);
848     }
849   }
850
851   else {
852
853     if(nb_search_conditions > 0) {
854       struct search_condition search_conditions[MAX_NB_SEARCH_CONDITIONS];
855       char *search_field, *search_regexp_string;
856       int m, n;
857
858       for(n = 0; n < nb_search_conditions; n++) {
859         search_field = search_condition_strings[n];
860
861         if(search_field[0] == '!') {
862           search_field++;
863           search_conditions[n].negation = 1;
864         } else {
865           search_conditions[n].negation = 0;
866         }
867
868         if(strcmp(search_field, "today") == 0) {
869           search_conditions[n].field_id = ID_INTERVAL;
870           search_conditions[n].interval_start = time(0) - 3600 * 24;
871           search_conditions[n].interval_stop = 0;
872         }
873
874         else if(strcmp(search_field, "yesterday") == 0) {
875           search_conditions[n].field_id = ID_INTERVAL;
876           search_conditions[n].interval_start = time(0) - 2 * 3600 * 24;
877           search_conditions[n].interval_stop = time(0) - 3600 * 24;
878         }
879
880         else {
881           search_regexp_string = segment_next_field(search_condition_strings[n]);
882
883           search_conditions[n].field_id = -1;
884
885           for(m = 0; (m < MAX_ID) && search_conditions[n].field_id == -1; m++) {
886             if(strncmp(field_names[m], search_field, strlen(search_field)) == 0) {
887               search_conditions[n].field_id = m;
888             }
889           }
890
891           if(search_conditions[n].field_id == -1) {
892             fprintf(stderr,
893                     "mymail: Syntax error in field name \"%s\".\n",
894                     search_field);
895             exit(EXIT_FAILURE);
896           }
897
898           if(regcomp(&search_conditions[n].regexp,
899                      search_regexp_string,
900                      REG_ICASE)) {
901             fprintf(stderr,
902                     "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
903                     search_regexp_string,
904                     field_names[search_conditions[n].field_id]);
905             exit(EXIT_FAILURE);
906           }
907         }
908       }
909
910       /* Recursive search if db_root_path is set */
911
912       if(db_root_path) {
913         regex_t db_filename_regexp;
914         if(regcomp(&db_filename_regexp,
915                    db_filename_regexp_string,
916                    0)) {
917           fprintf(stderr,
918                   "mymail: Syntax error in regexp \"%s\".\n",
919                   db_filename_regexp_string);
920           exit(EXIT_FAILURE);
921         }
922
923         recursive_search_in_db(db_root_path, &db_filename_regexp,
924                                nb_search_conditions, search_conditions,
925                                output_file);
926
927         regfree(&db_filename_regexp);
928       }
929
930       /* Search in all db files listed in db_filename_list */
931
932       if(db_filename_list) {
933         char db_filename[PATH_MAX + 1];
934         char *s, *t;
935         FILE *db_file;
936
937         s = db_filename_list;
938
939         while(*s) {
940           t = db_filename;
941           while(*s == ';') { s++; }
942           while(*s && *s != ';') { *t++ = *s++; }
943           *t++ = '\0';
944
945           if(db_filename[0]) {
946             db_file = fopen(db_filename, "r");
947
948             if(!db_file) {
949               fprintf(stderr,
950                       "mymail: Cannot open \"%s\" for reading: %s\n",
951                       argv[optind],
952                       strerror(errno));
953               exit(EXIT_FAILURE);
954             }
955
956             search_in_db(db_file, nb_search_conditions, search_conditions, output_file);
957
958             fclose(db_file);
959           }
960         }
961       }
962
963       /* Search in all db files listed in the command arguments */
964
965       while(optind < argc) {
966         FILE *db_file = fopen(argv[optind], "r");
967
968         if(!db_file) {
969           fprintf(stderr,
970                   "mymail: Cannot open \"%s\" for reading: %s\n",
971                   argv[optind],
972                   strerror(errno));
973           exit(EXIT_FAILURE);
974         }
975
976         search_in_db(db_file, nb_search_conditions, search_conditions, output_file);
977
978         fclose(db_file);
979         optind++;
980       }
981
982       for(n = 0; n < nb_search_conditions; n++) {
983         regfree(&search_conditions[n].regexp);
984         free(search_condition_strings[n]);
985       }
986     }
987   }
988
989   if(output_file != stdout) {
990     fflush(output_file);
991     fclose(output_file);
992   }
993
994   free(db_filename);
995   free(db_filename_regexp_string);
996   free(db_root_path);
997   free(db_filename_list);
998
999   regfree(&leading_from_line_regexp);
1000
1001   exit(EXIT_SUCCESS);
1002 }