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