Update.
[mymail.git] / mymail.c
1
2 /*
3  *  Copyright (c) 2013 Francois Fleuret
4  *  Written by Francois Fleuret <francois@fleuret.org>
5  *
6  *  This file is part of mymail.
7  *
8  *  mymail is free software: you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License version 3 as
10  *  published by the Free Software Foundation.
11  *
12  *  mymail is distributed in the hope that it will be useful, but
13  *  WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *  General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with mymail.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21
22 /*
23
24   This command is a dumb mail indexer. It can either (1) scan
25   directories containing mbox files, and create a db file containing
26   for each mail a list of fields computed from the header, or (2)
27   read such a db file and get all the mails matching regexp-defined
28   conditions on the fields, 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   /*
1035   {
1036 #warning Test code added on 2013 May 02 11:17:01
1037     struct alias_node *a;
1038     for(a = global_alias_list; a; a = a->next) {
1039       printf ("ALIAS [%s] [%s]\n", a->alias, a->value);
1040     }
1041   }
1042   */
1043
1044   setlocale(LC_ALL, "");
1045
1046   nb_search_conditions = 0;
1047
1048   while ((c = getopt_long(argc, argv, "hvqip:s:d:r:l:o:a:m:",
1049                           long_options, NULL)) != -1) {
1050
1051     switch(c) {
1052
1053     case 'h':
1054       show_help = 1;
1055       break;
1056
1057     case 'v':
1058       print_version(stdout);
1059       break;
1060
1061     case 'q':
1062       global_quiet = 1;
1063       break;
1064
1065     case 't':
1066       global_use_leading_time = 1;
1067       break;
1068
1069     case 'i':
1070       action_index = 1;
1071       break;
1072
1073     case 'd':
1074       if(db_filename) {
1075         fprintf(stderr, "mymail: Can not set the db filename twice.\n");
1076         exit(EXIT_FAILURE);
1077       }
1078       db_filename = strdup(optarg);
1079       break;
1080
1081     case 'p':
1082       if(db_filename_regexp_string) {
1083         fprintf(stderr, "mymail: Can not set the db filename pattern twice.\n");
1084         exit(EXIT_FAILURE);
1085       }
1086       db_filename_regexp_string = strdup(optarg);
1087       break;
1088
1089     case 'm':
1090       if(mbox_filename_regexp_string) {
1091         fprintf(stderr, "mymail: Can not set the mbox filename pattern twice.\n");
1092         exit(EXIT_FAILURE);
1093       }
1094       mbox_filename_regexp_string = strdup(optarg);
1095       break;
1096
1097     case 'o':
1098       strncpy(output_filename, optarg, PATH_MAX);
1099       break;
1100
1101     case 'r':
1102       if(db_root_path) {
1103         fprintf(stderr, "mymail: Can not set the db root path twice.\n");
1104         exit(EXIT_FAILURE);
1105       }
1106       db_root_path = strdup(optarg);
1107       break;
1108
1109     case 'l':
1110       if(db_filename_list) {
1111         fprintf(stderr, "mymail: Can not set the db filename list twice.\n");
1112         exit(EXIT_FAILURE);
1113       }
1114       db_filename_list = strdup(optarg);
1115       break;
1116
1117     case 's':
1118       if(nb_search_conditions == MAX_NB_SEARCH_CONDITIONS) {
1119         fprintf(stderr, "mymail: Too many search patterns.\n");
1120         exit(EXIT_FAILURE);
1121       }
1122       init_condition(&search_conditions[nb_search_conditions], optarg, default_search_field);
1123       nb_search_conditions++;
1124       break;
1125
1126     case 'a':
1127       default_search_field = optarg;
1128       break;
1129
1130     default:
1131       error = 1;
1132       break;
1133     }
1134   }
1135
1136   /* Set all the values that may defined in the arguments, through
1137      environment variables, or hard-coded */
1138
1139   db_filename = default_value(db_filename,
1140                               "MYMAIL_DB_FILE",
1141                               "mymail.db");
1142
1143   db_filename_regexp_string = default_value(db_filename_regexp_string,
1144                                             "MYMAIL_DB_FILE",
1145                                             "\\.db$");
1146
1147   db_root_path = default_value(db_root_path,
1148                                "MYMAIL_DB_ROOT",
1149                                0);
1150
1151   db_filename_list = default_value(db_filename_list,
1152                                    "MYMAIL_DB_LIST",
1153                                    0);
1154
1155   mbox_filename_regexp_string = default_value(mbox_filename_regexp_string,
1156                                               "MYMAIL_MBOX_PATTERN",
1157                                               0);
1158
1159   /* Start the processing */
1160
1161   if(error) {
1162     print_usage(stderr);
1163     exit(EXIT_FAILURE);
1164   }
1165
1166   if(show_help) {
1167     print_usage(stdout);
1168     exit(EXIT_SUCCESS);
1169   }
1170
1171   /* mbox indexing */
1172
1173   if(action_index) {
1174     FILE *db_file;
1175     regex_t mbox_filename_regexp_static;
1176     regex_t *mbox_filename_regexp;
1177
1178     if(mbox_filename_regexp_string) {
1179       if(regcomp(&mbox_filename_regexp_static,
1180                  mbox_filename_regexp_string,
1181                  0)) {
1182         fprintf(stderr,
1183                 "mymail: Syntax error in regexp \"%s\".\n",
1184                 mbox_filename_regexp_string);
1185         exit(EXIT_FAILURE);
1186       }
1187       mbox_filename_regexp = &mbox_filename_regexp_static;
1188     } else {
1189       mbox_filename_regexp = 0;
1190     }
1191
1192     db_file = safe_fopen(db_filename, "w", "index file for indexing");
1193
1194     for(f = 0; f < nb_fields_to_parse; f++) {
1195       if(regcomp(&fields_to_parse[f].regexp,
1196                  fields_to_parse[f].regexp_string,
1197                  fields_to_parse[f].cflags)) {
1198         fprintf(stderr,
1199                 "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
1200                 fields_to_parse[f].regexp_string,
1201                 field_keys[fields_to_parse[f].id]);
1202         exit(EXIT_FAILURE);
1203       }
1204     }
1205
1206     fprintf(db_file,
1207             "%s version_%s format_%d raw\n",
1208             MYMAIL_DB_MAGIC_TOKEN,
1209             MYMAIL_VERSION,
1210             MYMAIL_DB_FORMAT_VERSION);
1211
1212     while(optind < argc) {
1213       recursive_index_mbox(db_file,
1214                            argv[optind], mbox_filename_regexp,
1215                            nb_fields_to_parse, fields_to_parse);
1216       optind++;
1217     }
1218
1219     fflush(db_file);
1220     fclose(db_file);
1221
1222     if(mbox_filename_regexp) {
1223       regfree(mbox_filename_regexp);
1224     }
1225
1226     for(f = 0; f < nb_fields_to_parse; f++) {
1227       regfree(&fields_to_parse[f].regexp);
1228     }
1229   }
1230
1231   /* Mail search */
1232
1233   else {
1234
1235     FILE *output_file;
1236     int nb_extracted_mails = 0;
1237
1238     if(output_filename[0]) {
1239       output_file = safe_fopen(output_filename, "w", "result mbox");
1240     } else {
1241       output_file = stdout;
1242       global_quiet = 1;
1243     }
1244
1245     if(nb_search_conditions > 0) {
1246
1247       /* Recursive search if db_root_path is set */
1248
1249       if(db_root_path) {
1250         regex_t db_filename_regexp;
1251         if(regcomp(&db_filename_regexp,
1252                    db_filename_regexp_string,
1253                    0)) {
1254           fprintf(stderr,
1255                   "mymail: Syntax error in regexp \"%s\".\n",
1256                   db_filename_regexp_string);
1257           exit(EXIT_FAILURE);
1258         }
1259
1260         nb_extracted_mails += recursive_search_in_db(db_root_path, &db_filename_regexp,
1261                                                      nb_search_conditions, search_conditions,
1262                                                      output_file);
1263
1264         regfree(&db_filename_regexp);
1265       }
1266
1267       /* Search in all db files listed in db_filename_list */
1268
1269       if(db_filename_list) {
1270         char db_filename[PATH_MAX + 1];
1271         const char *s;
1272
1273         s = db_filename_list;
1274
1275         while(*s) {
1276           s = parse_token(db_filename, PATH_MAX + 1, ';', s);
1277
1278           if(db_filename[0]) {
1279             nb_extracted_mails +=
1280               search_in_db(db_filename, nb_search_conditions, search_conditions, output_file);
1281           }
1282         }
1283       }
1284
1285       /* Search in all db files listed in the command arguments */
1286
1287       while(optind < argc) {
1288         nb_extracted_mails +=
1289           search_in_db(argv[optind], nb_search_conditions, search_conditions, output_file);
1290         optind++;
1291       }
1292     }
1293
1294     if(!global_quiet) {
1295       if(nb_extracted_mails > 0) {
1296         printf("Found %d matching mails.\n", nb_extracted_mails);
1297       } else {
1298         printf("No matching mail found.\n");
1299       }
1300     }
1301
1302     fflush(output_file);
1303
1304     if(output_file != stdout) {
1305       fclose(output_file);
1306     }
1307   }
1308
1309   for(n = 0; n < nb_search_conditions; n++) {
1310     free_condition(&search_conditions[n]);
1311   }
1312
1313   a = global_alias_list;
1314   while(a) {
1315     b = a->next;
1316     free(a->alias);
1317     free(a->value);
1318     free(a);
1319     a = b;
1320   }
1321
1322   free(db_filename);
1323   free(db_filename_regexp_string);
1324   free(db_root_path);
1325   free(db_filename_list);
1326   free(mbox_filename_regexp_string);
1327
1328   regfree(&global_leading_from_line_regexp);
1329
1330   exit(EXIT_SUCCESS);
1331 }