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