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