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