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