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