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