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