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