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