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