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