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