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