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