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