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