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