Major cosmetic changes.
[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 search_in_db(const char *db_filename,
274                   int nb_search_conditions,
275                   struct search_condition *search_conditions,
276                   FILE *output_file) {
277
278   int hits[MAX_NB_SEARCH_CONDITIONS];
279   char raw_db_line[BUFFER_SIZE];
280   char raw_mbox_line[BUFFER_SIZE];
281   char current_mail_filename[PATH_MAX + 1];
282   unsigned long int current_position_in_mail;
283   char mbox_name[TOKEN_BUFFER_SIZE], *mbox_value;
284   int mbox_id;
285   int already_written, m, n;
286   int last_mbox_line_was_empty;
287   int nb_body_conditions, nb_fulfilled_body_conditions;
288   FILE *db_file;
289
290   db_file = fopen(db_filename, "r");
291
292   if(!db_file) {
293     fprintf(stderr,
294             "mymail: Cannot open \"%s\" for reading: %s\n",
295             db_filename,
296             strerror(errno));
297     exit(EXIT_FAILURE);
298   }
299
300   if(fgets(raw_db_line, BUFFER_SIZE, db_file)) {
301     if(strncmp(raw_db_line, MYMAIL_DB_MAGIC_TOKEN, strlen(MYMAIL_DB_MAGIC_TOKEN))) {
302       fprintf(stderr,
303               "mymail: Header line in '%s' does not match the mymail db format.\n",
304               db_filename);
305       exit(EXIT_FAILURE);
306     }
307   } else {
308     fprintf(stderr,
309             "mymail: Cannot read the header line in '%s'.\n",
310             db_filename);
311     exit(EXIT_FAILURE);
312   }
313
314   current_position_in_mail = 0;
315   already_written = 0;
316
317   for(n = 0; n < nb_search_conditions; n++) { hits[n] = 0; }
318
319   nb_body_conditions = 0;
320   for(n = 0; n < nb_search_conditions; n++) {
321     if(search_conditions[n].field_id == ID_BODY) {
322       nb_body_conditions++;
323     }
324   }
325
326   strcpy(current_mail_filename, "");
327
328   while(fgets(raw_db_line, BUFFER_SIZE, db_file)) {
329     mbox_value = parse_token(mbox_name, TOKEN_BUFFER_SIZE, ' ', raw_db_line);
330
331     if(strcmp("mail", mbox_name) == 0) {
332       char position_in_file_string[TOKEN_BUFFER_SIZE];
333
334       if(current_mail_filename[0]) {
335
336         /* We first check all conditions but the body ones */
337
338         for(n = 0; n < nb_search_conditions &&
339               ((search_conditions[n].field_id == ID_BODY) ||
340                xor(hits[n], search_conditions[n].negation)); n++);
341
342         if(n == nb_search_conditions) {
343
344           /* all conditions but the body ones are fine, check the body
345              ones */
346
347           nb_fulfilled_body_conditions = 0;
348
349           if(nb_body_conditions > 0) {
350             FILE *mail_file;
351             int header;
352
353             header = 1;
354             mail_file = fopen(current_mail_filename, "r");
355
356             if(!mail_file) {
357               fprintf(stderr,
358                       "mymail: Cannot open mbox '%s' for body scan.\n",
359                       current_mail_filename);
360               exit(EXIT_FAILURE);
361             }
362
363             fseek(mail_file, current_position_in_mail, SEEK_SET);
364
365             if(fgets(raw_mbox_line, BUFFER_SIZE, mail_file)) {
366               while(nb_fulfilled_body_conditions < nb_body_conditions) {
367                 last_mbox_line_was_empty = (raw_mbox_line[0] == '\n');
368
369                 if(last_mbox_line_was_empty) { header = 0; }
370
371                 if(!header) {
372                   for(n = 0; n < nb_search_conditions; n++) {
373                     if(search_conditions[n].field_id == ID_BODY && !hits[n]) {
374                       hits[n] =
375                         (regexec(&search_conditions[n].regexp, raw_mbox_line, 0, 0, 0) == 0);
376                       if(hits[n]) {
377                         nb_fulfilled_body_conditions++;
378                       }
379                     }
380                   }
381                 }
382
383                 if(!fgets(raw_mbox_line, BUFFER_SIZE, mail_file) ||
384                    (last_mbox_line_was_empty &&
385                     is_a_leading_from_line(raw_mbox_line)))
386                   break;
387               }
388             }
389
390             fclose(mail_file);
391           }
392
393           if(nb_body_conditions == nb_fulfilled_body_conditions) {
394             FILE *mail_file;
395
396             mail_file = fopen(current_mail_filename, "r");
397
398             if(!mail_file) {
399               fprintf(stderr,
400                       "mymail: Cannot open mbox '%s' for mail extraction.\n",
401                       current_mail_filename);
402               exit(EXIT_FAILURE);
403             }
404
405             fseek(mail_file, current_position_in_mail, SEEK_SET);
406
407             if(fgets(raw_mbox_line, BUFFER_SIZE, mail_file)) {
408               last_mbox_line_was_empty = 0;
409               fprintf(output_file, "%s", raw_mbox_line);
410               while(1) {
411                 if(!fgets(raw_mbox_line, BUFFER_SIZE, mail_file) ||
412                    (last_mbox_line_was_empty &&
413                     is_a_leading_from_line(raw_mbox_line))
414                    )
415                   break;
416                 last_mbox_line_was_empty = (raw_mbox_line[0] == '\n');
417                 fprintf(output_file, "%s", raw_mbox_line);
418               }
419             }
420
421             fclose(mail_file);
422           }
423         }
424       }
425
426       for(n = 0; n < nb_search_conditions; n++) { hits[n] = 0; }
427
428       mbox_value = parse_token(position_in_file_string, TOKEN_BUFFER_SIZE, ' ', mbox_value);
429       mbox_value = parse_token(current_mail_filename, TOKEN_BUFFER_SIZE, ' ', mbox_value);
430       current_position_in_mail = atol(position_in_file_string);
431       remove_eof(current_mail_filename);
432       already_written = 0;
433     }
434
435     else {
436       mbox_id = -1;
437       for(m = 0; (m < MAX_ID) && mbox_id == -1; m++) {
438         if(strncmp(field_names[m], mbox_name, strlen(mbox_name)) == 0) {
439           mbox_id = m;
440         }
441       }
442       for(n = 0; n < nb_search_conditions; n++) {
443         hits[n] |= mbox_line_match_search(&search_conditions[n],
444                                           mbox_id, mbox_value);
445       }
446     }
447   }
448
449   fclose(db_file);
450 }
451
452 void recursive_search_in_db(const char *entry_name, regex_t *db_filename_regexp,
453                             int nb_search_conditions,
454                             struct search_condition *search_conditions,
455                             FILE *output_file) {
456   DIR *dir;
457   struct dirent *dir_e;
458   struct stat sb;
459   char subname[PATH_MAX + 1];
460
461   if(lstat(entry_name, &sb) != 0) {
462     fprintf(stderr,
463             "mymail: Cannot stat \"%s\": %s\n",
464             entry_name,
465             strerror(errno));
466     exit(EXIT_FAILURE);
467   }
468
469   dir = opendir(entry_name);
470
471   if(dir) {
472     while((dir_e = readdir(dir))) {
473       if(!ignore_entry(dir_e->d_name)) {
474         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
475         recursive_search_in_db(subname, db_filename_regexp,
476                                nb_search_conditions, search_conditions,
477                                output_file);
478       }
479     }
480     closedir(dir);
481   }
482
483   else {
484     const char *s = entry_name, *filename = entry_name;
485     while(*s) { if(*s == '/') { filename = s+1; } s++; }
486
487     if(regexec(db_filename_regexp, filename, 0, 0, 0) == 0) {
488
489       if(!quiet) {
490         printf("Searching in '%s' ... ", entry_name);
491         fflush(stdout);
492       }
493
494       search_in_db(entry_name, nb_search_conditions, search_conditions, output_file);
495
496       if(!quiet) {
497         printf("done.\n");
498         fflush(stdout);
499       }
500     }
501   }
502 }
503
504 /*********************************************************************/
505
506 void index_one_mbox_line(int nb_fields_to_parse, struct parsable_field *fields_to_parse,
507                          char *raw_mbox_line, FILE *db_file) {
508   regmatch_t matches;
509   int f;
510   for(f = 0; f < nb_fields_to_parse; f++) {
511     if(regexec(&fields_to_parse[f].regexp, raw_mbox_line, 1, &matches, 0) == 0) {
512       fprintf(db_file, "%s %s\n",
513               field_names[fields_to_parse[f].id],
514               raw_mbox_line + matches.rm_eo);
515     }
516   }
517 }
518
519 void index_mbox(const char *mbox_filename,
520                 int nb_fields_to_parse, struct parsable_field *fields_to_parse,
521                 FILE *db_file) {
522   char raw_mbox_line[BUFFER_SIZE], full_line[BUFFER_SIZE];
523   char *end_of_full_line;
524   FILE *file;
525   int in_header, new_header, last_mbox_line_was_empty;
526   unsigned long int position_in_file;
527
528   file = fopen(mbox_filename, "r");
529
530   if(!file) {
531     fprintf(stderr, "mymail: Cannot open '%s'.\n", mbox_filename);
532     if(paranoid) { exit(EXIT_FAILURE); }
533     return;
534   }
535
536   in_header = 0;
537   new_header = 0;
538
539   position_in_file = 0;
540   end_of_full_line = 0;
541   full_line[0] = '\0';
542   last_mbox_line_was_empty = 1;
543
544   while(fgets(raw_mbox_line, BUFFER_SIZE, file)) {
545     if(last_mbox_line_was_empty &&
546        is_a_leading_from_line(raw_mbox_line)) {
547       if(in_header) {
548         fprintf(stderr,
549                 "Got a ^\"From \" in the header in %s:%lu.\n",
550                 mbox_filename, position_in_file);
551         fprintf(stderr, "%s", raw_mbox_line);
552         if(paranoid) { exit(EXIT_FAILURE); }
553       }
554       in_header = 1;
555       new_header = 1;
556     } else if(raw_mbox_line[0] == '\n') {
557       if(in_header) { in_header = 0; }
558     }
559
560     last_mbox_line_was_empty = (raw_mbox_line[0] == '\n');
561
562     if(in_header) {
563       if(new_header) {
564         fprintf(db_file, "mail %lu %s\n", position_in_file, mbox_filename);
565         new_header = 0;
566       }
567
568       if(raw_mbox_line[0] == ' ' || raw_mbox_line[0] == '\t') {
569         char *start = raw_mbox_line;
570         while(*start == ' ' || *start == '\t') start++;
571         *(end_of_full_line++) = ' ';
572         strcpy(end_of_full_line, start);
573         while(*end_of_full_line && *end_of_full_line != '\n') {
574           end_of_full_line++;
575         }
576         *end_of_full_line = '\0';
577       }
578
579       else {
580         /*
581           if(!((raw_mbox_line[0] >= 'a' && raw_mbox_line[0] <= 'z') ||
582           (raw_mbox_line[0] >= 'A' && raw_mbox_line[0] <= 'Z'))) {
583           fprintf(stderr,
584           "Header line syntax error %s:%lu.\n",
585           mbox_filename, position_in_file);
586           fprintf(stderr, "%s", raw_mbox_line);
587           }
588         */
589
590         if(full_line[0]) {
591           index_one_mbox_line(nb_fields_to_parse, fields_to_parse, full_line, db_file);
592         }
593
594         end_of_full_line = full_line;
595         strcpy(end_of_full_line, raw_mbox_line);
596         while(*end_of_full_line && *end_of_full_line != '\n') {
597           end_of_full_line++;
598         }
599         *end_of_full_line = '\0';
600       }
601
602     }
603
604     position_in_file += strlen(raw_mbox_line);
605   }
606
607   fclose(file);
608 }
609
610 void recursive_index_mbox(FILE *db_file,
611                           const char *entry_name,
612                           int nb_fields_to_parse, struct parsable_field *fields_to_parse) {
613   DIR *dir;
614   struct dirent *dir_e;
615   struct stat sb;
616   char subname[PATH_MAX + 1];
617
618   if(lstat(entry_name, &sb) != 0) {
619     fprintf(stderr,
620             "mymail: Cannot stat \"%s\": %s\n",
621             entry_name,
622             strerror(errno));
623     exit(EXIT_FAILURE);
624   }
625
626   dir = opendir(entry_name);
627
628   if(dir) {
629     while((dir_e = readdir(dir))) {
630       if(!ignore_entry(dir_e->d_name)) {
631         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
632         recursive_index_mbox(db_file, subname, nb_fields_to_parse, fields_to_parse);
633       }
634     }
635     closedir(dir);
636   } else {
637     index_mbox(entry_name, nb_fields_to_parse, fields_to_parse, db_file);
638   }
639 }
640
641 /*********************************************************************/
642
643 /* For long options that have no equivalent short option, use a
644    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
645 enum {
646   OPT_BASH_MODE = CHAR_MAX + 1
647 };
648
649 static struct option long_options[] = {
650   { "help", no_argument, 0, 'h' },
651   { "version", no_argument, 0, 'v' },
652   { "quiet", no_argument, 0, 'q' },
653   { "db-file", 1, 0, 'd' },
654   { "db-pattern", 1, 0, 'p' },
655   { "db-root", 1, 0, 'r' },
656   { "db-list", 1, 0, 'l' },
657   { "search", 1, 0, 's' },
658   { "index", 0, 0, 'i' },
659   { "output", 1, 0, 'o' },
660   { 0, 0, 0, 0 }
661 };
662
663 /*********************************************************************/
664
665 void init_condition(struct search_condition *condition, char *string) {
666   char full_search_field[TOKEN_BUFFER_SIZE], *search_field;
667   int m;
668
669   string = parse_token(full_search_field, TOKEN_BUFFER_SIZE, ' ', string);
670   search_field = full_search_field;
671
672   if(search_field[0] == '!') {
673     search_field++;
674     condition->negation = 1;
675   } else {
676     condition->negation = 0;
677   }
678
679   if(strcmp(search_field, "6h") == 0) {
680     condition->field_id = ID_INTERVAL;
681     condition->interval_start = time(0) - 3600 * 6;
682     condition->interval_stop = 0;
683   }
684
685   else if(strcmp(search_field, "24h") == 0 ||
686           strcmp(search_field, "today") == 0) {
687     condition->field_id = ID_INTERVAL;
688     condition->interval_start = time(0) - 3600 * 24;
689     condition->interval_stop = 0;
690   }
691
692   else if(strcmp(search_field, "yesterday") == 0) {
693     condition->field_id = ID_INTERVAL;
694     condition->interval_start = time(0) - 2 * 3600 * 24;
695     condition->interval_stop = time(0) - 3600 * 24;
696   }
697
698   else {
699     condition->field_id = -1;
700
701     for(m = 0; (m < MAX_ID) && condition->field_id == -1; m++) {
702       if(strncmp(field_names[m], search_field, strlen(search_field)) == 0) {
703         condition->field_id = m;
704       }
705     }
706
707     if(condition->field_id == -1) {
708       fprintf(stderr,
709               "mymail: Syntax error in field name \"%s\".\n",
710               search_field);
711       exit(EXIT_FAILURE);
712     }
713
714     if(regcomp(&condition->regexp,
715                string,
716                REG_ICASE)) {
717       fprintf(stderr,
718               "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
719               string,
720               field_names[condition->field_id]);
721       exit(EXIT_FAILURE);
722     }
723   }
724 }
725
726 void free_condition(struct search_condition *condition) {
727   if(condition->field_id != ID_INTERVAL) {
728     regfree(&condition->regexp);
729   }
730 }
731
732 /*********************************************************************/
733 /*********************************************************************/
734 /*********************************************************************/
735
736 int main(int argc, char **argv) {
737   int error = 0, show_help = 0;
738   const int nb_fields_to_parse = sizeof(fields_to_parse) / sizeof(struct parsable_field);
739   char c;
740   int f, n;
741   int nb_search_conditions;
742   FILE *output_file;
743   struct search_condition search_conditions[MAX_NB_SEARCH_CONDITIONS];
744
745   if(regcomp(&leading_from_line_regexp,
746              "^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$",
747              0)) {
748     fprintf(stderr,
749             "mymail: Cannot compile leading \"from\" line regexp. That is strange.\n");
750     exit(EXIT_FAILURE);
751   }
752
753   paranoid = 0;
754   action_index = 0;
755   db_filename = 0;
756   db_root_path = 0;
757   db_filename_list = 0;
758   quiet = 0;
759
760   setlocale(LC_ALL, "");
761
762   nb_search_conditions = 0;
763
764   while ((c = getopt_long(argc, argv, "hvqip:s:d:r:l:o:",
765                           long_options, NULL)) != -1) {
766
767     switch(c) {
768
769     case 'h':
770       show_help = 1;
771       break;
772
773     case 'v':
774       print_version(stdout);
775       break;
776
777     case 'q':
778       quiet = 1;
779       break;
780
781     case 'i':
782       action_index = 1;
783       break;
784
785     case 'd':
786       db_filename = strdup(optarg);
787       break;
788
789     case 'p':
790       db_filename_regexp_string = strdup(optarg);
791       break;
792
793     case 'o':
794       strncpy(output_filename, optarg, PATH_MAX);
795       break;
796
797     case 'r':
798       db_root_path = strdup(optarg);
799       break;
800
801     case 'l':
802       db_filename_list = strdup(optarg);
803       break;
804
805     case 's':
806       if(nb_search_conditions == MAX_NB_SEARCH_CONDITIONS) {
807         fprintf(stderr, "mymail: Too many search patterns.\n");
808         exit(EXIT_FAILURE);
809       }
810       init_condition(&search_conditions[nb_search_conditions], optarg);
811       nb_search_conditions++;
812       break;
813
814     default:
815       error = 1;
816       break;
817     }
818   }
819
820   if(!db_filename) {
821     char *default_db_filename = getenv("MYMAIL_DB_FILE");
822
823     if(!default_db_filename) {
824       default_db_filename = "mymail.db";
825     }
826
827     db_filename = strdup(default_db_filename);
828   }
829
830   if(!db_filename_regexp_string) {
831     char *default_db_filename_regexp_string = getenv("MYMAIL_DB_PATTERN");
832
833     if(!default_db_filename_regexp_string) {
834       default_db_filename_regexp_string = "^mymail.db$";
835     }
836
837     db_filename_regexp_string = strdup(default_db_filename_regexp_string);
838   }
839
840   if(!db_root_path) {
841     char *default_db_root_path = getenv("MYMAIL_DB_ROOT");
842
843     if(default_db_root_path) {
844       db_root_path = strdup(default_db_root_path);
845     }
846   }
847
848   if(!db_filename_list) {
849     char *default_db_filename_list = getenv("MYMAIL_DB_LIST");
850
851     if(default_db_filename_list) {
852       db_filename_list = strdup(default_db_filename_list);
853     }
854   }
855
856   if(output_filename[0]) {
857     output_file = fopen(output_filename, "w");
858
859     if(!output_file) {
860       fprintf(stderr,
861               "mymail: Cannot open result file \"%s\" for writing: %s\n",
862               output_filename,
863               strerror(errno));
864       exit(EXIT_FAILURE);
865     }
866   } else {
867     output_file = stdout;
868     quiet = 1;
869   }
870
871   if(error) {
872     print_usage(stderr);
873     exit(EXIT_FAILURE);
874   }
875
876   if(show_help) {
877     print_usage(stdout);
878     exit(EXIT_SUCCESS);
879   }
880
881   if(action_index) {
882     FILE *db_file;
883
884     db_file = fopen(db_filename, "w");
885
886     if(!db_file) {
887       fprintf(stderr,
888               "mymail: Cannot open \"%s\" for writing: %s\n",
889               db_filename,
890               strerror(errno));
891       exit(EXIT_FAILURE);
892     }
893
894     for(f = 0; f < nb_fields_to_parse; f++) {
895       if(regcomp(&fields_to_parse[f].regexp,
896                  fields_to_parse[f].regexp_string,
897                  REG_ICASE)) {
898         fprintf(stderr,
899                 "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
900                 fields_to_parse[f].regexp_string,
901                 field_names[fields_to_parse[f].id]);
902         exit(EXIT_FAILURE);
903       }
904     }
905
906     fprintf(db_file, "%s version_%s raw\n", MYMAIL_DB_MAGIC_TOKEN, VERSION);
907
908     while(optind < argc) {
909       recursive_index_mbox(db_file,
910                            argv[optind],
911                            nb_fields_to_parse, fields_to_parse);
912       optind++;
913     }
914
915     fflush(db_file);
916     fclose(db_file);
917
918     for(f = 0; f < nb_fields_to_parse; f++) {
919       regfree(&fields_to_parse[f].regexp);
920     }
921   }
922
923   else {
924
925     if(nb_search_conditions > 0) {
926
927       /* Recursive search if db_root_path is set */
928
929       if(db_root_path) {
930         regex_t db_filename_regexp;
931         if(regcomp(&db_filename_regexp,
932                    db_filename_regexp_string,
933                    0)) {
934           fprintf(stderr,
935                   "mymail: Syntax error in regexp \"%s\".\n",
936                   db_filename_regexp_string);
937           exit(EXIT_FAILURE);
938         }
939
940         recursive_search_in_db(db_root_path, &db_filename_regexp,
941                                nb_search_conditions, search_conditions,
942                                output_file);
943
944         regfree(&db_filename_regexp);
945       }
946
947       /* Search in all db files listed in db_filename_list */
948
949       if(db_filename_list) {
950         char db_filename[PATH_MAX + 1];
951         char *s;
952
953         s = db_filename_list;
954
955         while(*s) {
956           s = parse_token(db_filename, PATH_MAX + 1, ';', s);
957
958           if(db_filename[0]) {
959             search_in_db(db_filename, nb_search_conditions, search_conditions, output_file);
960           }
961         }
962       }
963
964       /* Search in all db files listed in the command arguments */
965
966       while(optind < argc) {
967         search_in_db(argv[optind], nb_search_conditions, search_conditions, output_file);
968         optind++;
969       }
970     }
971   }
972
973   for(n = 0; n < nb_search_conditions; n++) {
974     free_condition(&search_conditions[n]);
975   }
976
977   if(output_file != stdout) {
978     fflush(output_file);
979     fclose(output_file);
980   }
981
982   free(db_filename);
983   free(db_filename_regexp_string);
984   free(db_root_path);
985   free(db_filename_list);
986
987   regfree(&leading_from_line_regexp);
988
989   exit(EXIT_SUCCESS);
990 }