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