Fixed a bug indexing the last header line of a mail in the next one.
[mymail.git] / mymail.c
1
2 /*
3  *  Copyright (c) 2013 Francois Fleuret
4  *  Written by Francois Fleuret <francois@fleuret.org>
5  *
6  *  This file is part of mymail.
7  *
8  *  mymail is free software: you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License version 3 as
10  *  published by the Free Software Foundation.
11  *
12  *  mymail is distributed in the hope that it will be useful, but
13  *  WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *  General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with mymail.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21
22 /*
23
24   This command is a dumb mail indexer. It can either (1) scan
25   directories containing mbox files, and create a db file containing
26   for each mail a list of fields computed from the header, or (2)
27   read such a db file and get all the mails matching regexp-defined
28   conditions on the fields, to create a resulting mbox file.
29
30   It is low-tech, simple, light and fast.
31
32 */
33
34 #define _GNU_SOURCE
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <locale.h>
42 #include <getopt.h>
43 #include <limits.h>
44 #include <dirent.h>
45 #include <regex.h>
46 #include <time.h>
47
48 #define MYMAIL_DB_MAGIC_TOKEN "mymail_index_file"
49 #define VERSION "0.9.5"
50
51 #define MAX_NB_SEARCH_CONDITIONS 32
52
53 #define BUFFER_SIZE 65536
54 #define TOKEN_BUFFER_SIZE 1024
55
56 #define LEADING_FROM_LINE_REGEXP_STRING "^From [^ ]*  \\(Mon\\|Tue\\|Wed\\|Thu\\|Fri\\|Sat\\|Sun\\) \\(Jan\\|Feb\\|Mar\\|Apr\\|May\\|Jun\\|Jul\\|Aug\\|Sep\\|Oct\\|Nov\\|Dec\\) [ 123][0-9] [0-9][0-9]:[0-9][0-9]:[0-9][0-9] [0-9][0-9][0-9][0-9]\n$"
57
58 /* Global variables! */
59
60 int global_quiet;
61
62 regex_t global_leading_from_line_regexp;
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_keys[] = {
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 const char *parse_token(char *token_buffer, size_t token_buffer_size,
154                         char separator, const char *string) {
155   char *u = token_buffer;
156   while(*string == separator) { string++; }
157   while(u < token_buffer + token_buffer_size - 1 && *string &&
158         *string != separator) {
159     *(u++) = *(string++);
160   }
161   while(*string == separator) { string++; }
162   *u = '\0';
163   return string;
164 }
165
166 char *default_value(char *current_value,
167                     const char *env_variable,
168                     const char *hard_default_value) {
169   if(current_value) {
170     return current_value;
171   } else {
172     char *env_value = getenv(env_variable);
173     if(env_value) {
174       return strdup(env_value);
175     } else if(hard_default_value) {
176       return strdup(hard_default_value);
177     } else {
178       return 0;
179     }
180   }
181 }
182
183 FILE *safe_fopen(const char *path, const char *mode, const char *comment) {
184   FILE *result = fopen(path, mode);
185   if(result) {
186     return result;
187   } else {
188     fprintf(stderr,
189             "mymail: Cannot open file '%s' (%s) with mode \"%s\".\n",
190             path, comment, mode);
191     exit(EXIT_FAILURE);
192   }
193 }
194
195 /*********************************************************************/
196
197 void print_version(FILE *out) {
198   fprintf(out, "mymail version %s (%s)\n", VERSION, UNAME);
199 }
200
201 void print_usage(FILE *out) {
202   print_version(out);
203   fprintf(out, "Written by Francois Fleuret <francois@fleuret.org>.\n");
204   fprintf(out, "\n");
205   fprintf(out, "Usage: mymail [options] [<mbox dir1> [<mbox dir2> ...]|<db file1> [<db file2> ...]]\n");
206   fprintf(out, "\n");
207   fprintf(out, " -h, --help\n");
208   fprintf(out, "         show this help\n");
209   fprintf(out, " -v, --version\n");
210   fprintf(out, "         print the version number\n");
211   fprintf(out, " -q, --quiet\n");
212   fprintf(out, "         do not print information during search\n");
213   fprintf(out, " -p <db filename pattern>, --db-pattern <db filename pattern>\n");
214   fprintf(out, "         set the db filename pattern for recursive search\n");
215   fprintf(out, " -r <db root path>, --db-root <db root path>\n");
216   fprintf(out, "         set the db root path for recursive search\n");
217   fprintf(out, " -l <db filename list>, --db-list <db filename list>\n");
218   fprintf(out, "         set the semicolon-separated list of db files for search\n");
219   fprintf(out, " -m <mbox filename pattern>, --mbox-pattern <mbox filename pattern>\n");
220   fprintf(out, "         set the mbox filename pattern for recursive search\n");
221   fprintf(out, " -s <search pattern>, --search <search pattern>\n");
222   fprintf(out, "         search for matching mails in the db file\n");
223   fprintf(out, " -d <db filename>, --db-file-generate <db filename>\n");
224   fprintf(out, "         set the db filename for indexing\n");
225   fprintf(out, " -i, --index\n");
226   fprintf(out, "         index mails\n");
227   fprintf(out, " -o <output filename>, --output <output filename>\n");
228   fprintf(out, "         set the result file, use stdout if unset\n");
229   fprintf(out, " -a <search field>, --default-search <search field>\n");
230   fprintf(out, "         set the default search field\n");
231 }
232
233 /*********************************************************************/
234
235 int ignore_entry(const char *name) {
236   return
237     strcmp(name, ".") == 0 ||
238     strcmp(name, "..") == 0 ||
239     (name[0] == '.' && name[1] != '/');
240 }
241
242 int is_a_leading_from_line(char *mbox_line) {
243   return
244     strncmp(mbox_line, "From ", 5) == 0 &&
245     regexec(&global_leading_from_line_regexp, mbox_line, 0, 0, 0) == 0;
246 }
247
248 int mbox_line_match_search(struct search_condition *condition,
249                            int mbox_id, const char *mbox_value) {
250
251   if(condition->field_id == ID_INTERVAL) {
252     if(mbox_id == ID_LEADING_LINE) {
253       const char *c;
254       time_t t;
255       struct tm tm;
256
257       c = mbox_value;
258       while(*c && *c != ' ') c++; while(*c && *c == ' ') c++;
259       strptime(c, "%a %b %e %k:%M:%S %Y", &tm);
260       t = mktime(&tm);
261
262       return (t >= condition->interval_start &&
263               (condition->interval_stop == 0 ||
264                t <= condition->interval_stop));
265     } else {
266       return 0;
267     }
268   } else {
269     return
270       (
271
272        (condition->field_id == mbox_id)
273
274        ||
275
276        (condition->field_id == ID_PARTICIPANT && (mbox_id == ID_LEADING_LINE ||
277                                                   mbox_id == ID_FROM ||
278                                                   mbox_id == ID_TO))
279        ||
280
281        (condition->field_id == ID_FROM && mbox_id == ID_LEADING_LINE)
282
283        )
284
285       &&
286
287       regexec(&condition->regexp, mbox_value, 0, 0, 0) == 0;
288   }
289 }
290
291 void update_body_hits(char *mail_filename, int position_in_mail,
292                       int nb_search_conditions, struct search_condition *search_conditions,
293                       int nb_body_conditions,
294                       int *hits) {
295   FILE *mail_file;
296   int header, n;
297   char raw_mbox_line[BUFFER_SIZE];
298   int nb_body_hits;
299
300   nb_body_hits = 0;
301
302   header = 1;
303   mail_file = safe_fopen(mail_filename, "r", "mbox for body scan");
304
305   fseek(mail_file, position_in_mail, SEEK_SET);
306
307   if(fgets(raw_mbox_line, BUFFER_SIZE, mail_file)) {
308     while(nb_body_hits < nb_body_conditions) {
309       /* last_mbox_line_was_empty = (raw_mbox_line[0] == '\n'); */
310       /* if(last_mbox_line_was_empty) { header = 0; } */
311
312       if(raw_mbox_line[0] == '\n') { header = 0; }
313
314       if(!header) {
315         for(n = 0; n < nb_search_conditions; n++) {
316           if(search_conditions[n].field_id == ID_BODY && !hits[n]) {
317             hits[n] =
318               (regexec(&search_conditions[n].regexp, raw_mbox_line, 0, 0, 0) == 0);
319             if(hits[n]) {
320               nb_body_hits++;
321             }
322           }
323         }
324       }
325
326       if(!fgets(raw_mbox_line, BUFFER_SIZE, mail_file) ||
327          (is_a_leading_from_line(raw_mbox_line)))
328         break;
329     }
330   }
331
332   fclose(mail_file);
333 }
334
335 void extract_mail(const char *mail_filename, unsigned long int position_in_mail,
336                 FILE *output_file) {
337   char raw_mbox_line[BUFFER_SIZE];
338   FILE *mail_file;
339
340   mail_file = safe_fopen(mail_filename, "r", "mbox for mail extraction");
341   fseek(mail_file, position_in_mail, SEEK_SET);
342
343   if(fgets(raw_mbox_line, BUFFER_SIZE, mail_file)) {
344     fprintf(output_file, "%s", raw_mbox_line);
345     while(1) {
346       if(!fgets(raw_mbox_line, BUFFER_SIZE, mail_file) ||
347          (is_a_leading_from_line(raw_mbox_line))
348          )
349         break;
350       fprintf(output_file, "%s", raw_mbox_line);
351     }
352   }
353
354   fclose(mail_file);
355 }
356
357 int search_in_db(const char *db_filename,
358                  int nb_search_conditions,
359                  struct search_condition *search_conditions,
360                  FILE *output_file) {
361
362   int hits[MAX_NB_SEARCH_CONDITIONS];
363   char raw_db_line[BUFFER_SIZE];
364   char current_mail_filename[PATH_MAX + 1];
365   unsigned long int current_position_in_mail;
366   char mbox_key[TOKEN_BUFFER_SIZE];
367   const char *mbox_value;
368   int mbox_id;
369   int already_written, m, n;
370   int nb_body_conditions, nb_fulfilled_body_conditions;
371   FILE *db_file;
372   int nb_extracted_mails;
373
374   nb_extracted_mails = 0;
375
376   if(!global_quiet) {
377     printf("Searching in '%s' ... ", db_filename);
378     fflush(stdout);
379   }
380
381   db_file = safe_fopen(db_filename, "r", "index file for search");
382
383   /* First, check the db file leading line integrity */
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   /* Then parse the said db file */
400
401   current_position_in_mail = 0;
402   already_written = 0;
403
404   for(n = 0; n < nb_search_conditions; n++) { hits[n] = 0; }
405
406   nb_body_conditions = 0;
407   for(n = 0; n < nb_search_conditions; n++) {
408     if(search_conditions[n].field_id == ID_BODY) {
409       nb_body_conditions++;
410     }
411   }
412
413   strcpy(current_mail_filename, "");
414
415   while(fgets(raw_db_line, BUFFER_SIZE, db_file)) {
416     mbox_value = parse_token(mbox_key, TOKEN_BUFFER_SIZE, ' ', raw_db_line);
417
418     if(strcmp("mail", mbox_key) == 0) {
419       char position_in_file_string[TOKEN_BUFFER_SIZE];
420
421       if(current_mail_filename[0]) {
422
423         /* We first check all conditions but the body ones */
424
425         for(n = 0; n < nb_search_conditions &&
426               ((search_conditions[n].field_id == ID_BODY) ||
427                xor(hits[n], search_conditions[n].negation)); n++);
428
429         if(n == nb_search_conditions) {
430
431           /* Now check the body ones */
432
433           nb_fulfilled_body_conditions = 0;
434
435           if(nb_body_conditions > 0) {
436             update_body_hits(current_mail_filename, current_position_in_mail,
437                              nb_search_conditions, search_conditions,
438                              nb_body_conditions,
439                              hits);
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
449           if(nb_body_conditions == nb_fulfilled_body_conditions) {
450             nb_extracted_mails++;
451             extract_mail(current_mail_filename, current_position_in_mail, output_file);
452           }
453         }
454       }
455
456       for(n = 0; n < nb_search_conditions; n++) { hits[n] = 0; }
457
458       mbox_value = parse_token(position_in_file_string, TOKEN_BUFFER_SIZE, ' ', mbox_value);
459       mbox_value = parse_token(current_mail_filename, TOKEN_BUFFER_SIZE, '\n', mbox_value);
460       current_position_in_mail = atol(position_in_file_string);
461       already_written = 0;
462     }
463
464     else {
465       mbox_id = -1;
466       for(m = 0; (m < MAX_ID) && mbox_id == -1; m++) {
467         if(strncmp(field_keys[m], mbox_key, strlen(mbox_key)) == 0) {
468           mbox_id = m;
469         }
470       }
471       for(n = 0; n < nb_search_conditions; n++) {
472         hits[n] |= mbox_line_match_search(&search_conditions[n],
473                                           mbox_id, mbox_value);
474       }
475     }
476   }
477
478   fclose(db_file);
479
480   if(!global_quiet) {
481     printf("done.\n");
482     fflush(stdout);
483   }
484
485   return nb_extracted_mails;
486 }
487
488 int recursive_search_in_db(const char *entry_name, regex_t *db_filename_regexp,
489                            int nb_search_conditions,
490                            struct search_condition *search_conditions,
491                            FILE *output_file) {
492   DIR *dir;
493   struct dirent *dir_e;
494   struct stat sb;
495   char subname[PATH_MAX + 1];
496   int nb_extracted_mails = 0;
497
498   if(lstat(entry_name, &sb) != 0) {
499     fprintf(stderr,
500             "mymail: Cannot stat \"%s\": %s\n",
501             entry_name,
502             strerror(errno));
503     exit(EXIT_FAILURE);
504   }
505
506   /* printf("recursive_search_in_db %s\n", entry_name); */
507
508   dir = opendir(entry_name);
509
510   if(dir) {
511     while((dir_e = readdir(dir))) {
512       if(!ignore_entry(dir_e->d_name)) {
513         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
514         nb_extracted_mails += recursive_search_in_db(subname, db_filename_regexp,
515                                                      nb_search_conditions, search_conditions,
516                                                      output_file);
517       }
518     }
519     closedir(dir);
520   }
521
522   else {
523     const char *s = entry_name, *filename = entry_name;
524     while(*s) { if(*s == '/') { filename = s+1; } s++; }
525
526     if(regexec(db_filename_regexp, filename, 0, 0, 0) == 0) {
527       nb_extracted_mails +=
528         search_in_db(entry_name, nb_search_conditions, search_conditions, output_file);
529     }
530   }
531
532   return nb_extracted_mails;
533 }
534
535 /*********************************************************************/
536
537 void index_one_mbox_line(unsigned int nb_fields_to_parse,
538                          struct parsable_field *fields_to_parse,
539                          char *raw_mbox_line, FILE *db_file) {
540   regmatch_t matches;
541   unsigned int f;
542   for(f = 0; f < nb_fields_to_parse; f++) {
543     if(regexec(&fields_to_parse[f].regexp, raw_mbox_line, 1, &matches, 0) == 0) {
544       fprintf(db_file, "%s %s\n",
545               field_keys[fields_to_parse[f].id],
546               raw_mbox_line + matches.rm_eo);
547     }
548   }
549 }
550
551 void index_mbox(const char *mbox_filename,
552                 int nb_fields_to_parse, struct parsable_field *fields_to_parse,
553                 FILE *db_file) {
554   char raw_mbox_line[BUFFER_SIZE], full_line[BUFFER_SIZE];
555   char *end_of_full_line;
556   FILE *file;
557   int in_header, new_header;
558   unsigned long int position_in_file;
559
560   file = safe_fopen(mbox_filename, "r", "mbox for indexing");
561
562   in_header = 0;
563   new_header = 0;
564
565   position_in_file = 0;
566   end_of_full_line = 0;
567   full_line[0] = '\0';
568
569   while(fgets(raw_mbox_line, BUFFER_SIZE, file)) {
570     if(is_a_leading_from_line(raw_mbox_line)) {
571       /* This starts a new mail */
572       if(in_header) {
573         fprintf(stderr,
574                 "Got a ^\"From \" in the header in %s:%lu.\n",
575                 mbox_filename, position_in_file);
576         fprintf(stderr, "%s", raw_mbox_line);
577       }
578
579       /* printf("LEADING_LINE %s", raw_mbox_line); */
580
581       in_header = 1;
582       new_header = 1;
583     } else if(raw_mbox_line[0] == '\n') {
584       if(in_header) {
585         in_header = 0;
586         /* We leave the header, index the current line */
587         if(full_line[0]) {
588           /* printf("INDEX %s\n", full_line); */
589           index_one_mbox_line(nb_fields_to_parse, fields_to_parse, full_line, db_file);
590         }
591         end_of_full_line = full_line;
592         *end_of_full_line = '\0';
593       }
594     }
595
596     if(in_header) {
597       if(new_header) {
598         fprintf(db_file, "mail %lu %s\n", position_in_file, mbox_filename);
599         new_header = 0;
600       }
601
602       if(raw_mbox_line[0] == ' ' || raw_mbox_line[0] == '\t') {
603         /* Continuation of a line */
604         char *start = raw_mbox_line;
605         while(*start == ' ' || *start == '\t') start++;
606         *(end_of_full_line++) = ' ';
607         strcpy(end_of_full_line, start);
608         while(*end_of_full_line && *end_of_full_line != '\n') {
609           end_of_full_line++;
610         }
611         *end_of_full_line = '\0';
612       }
613
614       else {
615         /* Start a new header line, not a continuation */
616
617         if(full_line[0]) {
618           /* printf("INDEX %s\n", full_line); */
619           index_one_mbox_line(nb_fields_to_parse, fields_to_parse, full_line, db_file);
620         }
621
622         end_of_full_line = full_line;
623         strcpy(end_of_full_line, raw_mbox_line);
624         while(*end_of_full_line && *end_of_full_line != '\n') {
625           end_of_full_line++;
626         }
627         *end_of_full_line = '\0';
628       }
629
630     }
631
632     position_in_file += strlen(raw_mbox_line);
633   }
634
635   fclose(file);
636 }
637
638 void recursive_index_mbox(FILE *db_file,
639                           const char *entry_name, regex_t *mbox_filename_regexp,
640                           int nb_fields_to_parse, struct parsable_field *fields_to_parse) {
641   DIR *dir;
642   struct dirent *dir_e;
643   struct stat sb;
644   char subname[PATH_MAX + 1];
645
646   if(lstat(entry_name, &sb) != 0) {
647     fprintf(stderr,
648             "mymail: Cannot stat \"%s\": %s\n",
649             entry_name,
650             strerror(errno));
651     exit(EXIT_FAILURE);
652   }
653
654   dir = opendir(entry_name);
655
656   if(dir) {
657     while((dir_e = readdir(dir))) {
658       if(!ignore_entry(dir_e->d_name)) {
659         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
660         recursive_index_mbox(db_file, subname, mbox_filename_regexp,
661                              nb_fields_to_parse, fields_to_parse);
662       }
663     }
664     closedir(dir);
665   } else {
666     const char *s = entry_name, *filename = s;
667     while(*s) { if(*s == '/') { filename = s+1; }; s++; }
668     if(!mbox_filename_regexp || regexec(mbox_filename_regexp, filename, 0, 0, 0) == 0) {
669       index_mbox(entry_name, nb_fields_to_parse, fields_to_parse, db_file);
670     }
671   }
672 }
673
674 /*********************************************************************/
675
676 /* For long options that have no equivalent short option, use a
677    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
678 enum {
679   OPT_BASH_MODE = CHAR_MAX + 1
680 };
681
682 static struct option long_options[] = {
683   { "help", no_argument, 0, 'h' },
684   { "version", no_argument, 0, 'v' },
685   { "quiet", no_argument, 0, 'q' },
686   { "db-file-generate", 1, 0, 'd' },
687   { "db-pattern", 1, 0, 'p' },
688   { "db-root", 1, 0, 'r' },
689   { "db-list", 1, 0, 'l' },
690   { "mbox-pattern", 1, 0, 'm' },
691   { "search", 1, 0, 's' },
692   { "index", 0, 0, 'i' },
693   { "output", 1, 0, 'o' },
694   { "default-search", 1, 0, 'a' },
695   { 0, 0, 0, 0 }
696 };
697
698 struct time_criterion {
699   char *label;
700   int start_hour, end_hour;
701   int past_week_day;
702 };
703
704 /*********************************************************************/
705
706 static struct time_criterion time_criteria[] = {
707
708   { "8h",         8,       -1, -1 },
709   { "today",     24,       -1, -1 },
710   { "24h",       24,       -1, -1 },
711   { "48h",       48,       -1, -1 },
712   { "week",      24 *   7, -1, -1 },
713   { "month",     24 *  31, -1, -1 },
714   { "year",      24 * 365, -1, -1 },
715
716   { "yesterday", 48,       24, -1 },
717
718   { "monday",    -1,       -1,  1 },
719   { "tuesday",   -1,       -1,  2 },
720   { "wednesday", -1,       -1,  3 },
721   { "thursday",  -1,       -1,  4 },
722   { "friday",    -1,       -1,  5 },
723   { "saturday",  -1,       -1,  6 },
724   { "sunday",    -1,       -1,  7 },
725
726 };
727
728 /*********************************************************************/
729
730 time_t time_for_past_day(int day) {
731   time_t t;
732   struct tm *tm;
733   int delta_day;
734   t = time(0);
735   tm = localtime(&t);
736   delta_day = (7 + tm->tm_wday - day) % 7;
737   if(delta_day == 0) { delta_day = 7; }
738   return t - (delta_day * 3600 * 24 + tm->tm_sec + 60 * tm->tm_min + 3600 * tm->tm_hour);
739 }
740
741 void init_condition(struct search_condition *condition, const char *full_string,
742                     const char *default_search_field) {
743   char full_search_field[TOKEN_BUFFER_SIZE], *search_field;
744   unsigned int k, m;
745   const char *string;
746
747   string = parse_token(full_search_field, TOKEN_BUFFER_SIZE, ' ', full_string);
748   search_field = full_search_field;
749
750   if(search_field[0] == '!') {
751     search_field++;
752     condition->negation = 1;
753   } else {
754     condition->negation = 0;
755   }
756
757   condition->field_id = -1;
758
759   /* Recently */
760
761   for(k = 0; k < sizeof(time_criteria) / sizeof(struct time_criterion); k++) {
762     if(strcmp(time_criteria[k].label, search_field) == 0) {
763       condition->field_id = ID_INTERVAL;
764       if(time_criteria[k].past_week_day < 0) {
765         condition->interval_start = time(0) - 3600 * time_criteria[k].start_hour;
766         if(time_criteria[k].end_hour >= 0) {
767           condition->interval_stop = time(0) - 3600 * time_criteria[k].end_hour;
768         } else {
769           condition->interval_stop = 0;
770         }
771       } else {
772         condition->interval_start = time_for_past_day(time_criteria[k].past_week_day);
773         condition->interval_stop = condition->interval_start + 3600 * 24;
774       }
775       break;
776     }
777   }
778
779   if(condition->field_id == -1) {
780
781     /* No time condition matched, look for the search fields */
782
783     for(m = 0; (m < MAX_ID) && condition->field_id == -1; m++) {
784       if(strncmp(field_keys[m], search_field, strlen(search_field)) == 0) {
785         condition->field_id = m;
786       }
787     }
788
789     /* None match, if there is a default search field, re-run the search with it */
790
791     if(condition->field_id == -1) {
792       if(default_search_field) {
793         for(m = 0; (m < MAX_ID) && condition->field_id == -1; m++) {
794           if(strncmp(field_keys[m],
795                      default_search_field, strlen(default_search_field)) == 0) {
796             condition->field_id = m;
797           }
798         }
799         string = full_string;
800         if(string[0] == '!') { string++; }
801       }
802     }
803
804     if(condition->field_id == -1) {
805       fprintf(stderr,
806               "mymail: Syntax error in field key \"%s\".\n",
807               search_field);
808       exit(EXIT_FAILURE);
809     }
810
811     if(regcomp(&condition->regexp,
812                string,
813                REG_ICASE)) {
814       fprintf(stderr,
815               "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
816               string,
817               field_keys[condition->field_id]);
818       exit(EXIT_FAILURE);
819     }
820   }
821 }
822
823 void free_condition(struct search_condition *condition) {
824   if(condition->field_id != ID_INTERVAL) {
825     regfree(&condition->regexp);
826   }
827 }
828
829 /*********************************************************************/
830 /*********************************************************************/
831 /*********************************************************************/
832
833 int main(int argc, char **argv) {
834   char *db_filename = 0;
835   char *db_filename_regexp_string = 0;
836   char *db_root_path = 0;
837   char *db_filename_list = 0;
838   char *mbox_filename_regexp_string = 0;
839   char *default_search_field;
840   char output_filename[PATH_MAX + 1];
841   int action_index = 0;
842   int error = 0, show_help = 0;
843   const unsigned int nb_fields_to_parse =
844     sizeof(fields_to_parse) / sizeof(struct parsable_field);
845   char c;
846   unsigned int f, n;
847   unsigned int nb_search_conditions;
848   struct search_condition search_conditions[MAX_NB_SEARCH_CONDITIONS];
849
850   if(regcomp(&global_leading_from_line_regexp, LEADING_FROM_LINE_REGEXP_STRING, 0)) {
851     fprintf(stderr,
852             "mymail: Cannot compile leading \"from\" line regexp. That is strange.\n");
853     exit(EXIT_FAILURE);
854   }
855
856   global_quiet = 0;
857   default_search_field = 0;
858   strncpy(output_filename, "", PATH_MAX);
859
860   setlocale(LC_ALL, "");
861
862   nb_search_conditions = 0;
863
864   while ((c = getopt_long(argc, argv, "hvqip:s:d:r:l:o:a:m:",
865                           long_options, NULL)) != -1) {
866
867     switch(c) {
868
869     case 'h':
870       show_help = 1;
871       break;
872
873     case 'v':
874       print_version(stdout);
875       break;
876
877     case 'q':
878       global_quiet = 1;
879       break;
880
881     case 'i':
882       action_index = 1;
883       break;
884
885     case 'd':
886       if(db_filename) {
887         fprintf(stderr, "mymail: Can not set the db filename twice.\n");
888         exit(EXIT_FAILURE);
889       }
890       db_filename = strdup(optarg);
891       break;
892
893     case 'p':
894       if(db_filename_regexp_string) {
895         fprintf(stderr, "mymail: Can not set the db filename pattern twice.\n");
896         exit(EXIT_FAILURE);
897       }
898       db_filename_regexp_string = strdup(optarg);
899       break;
900
901     case 'm':
902       if(mbox_filename_regexp_string) {
903         fprintf(stderr, "mymail: Can not set the mbox filename pattern twice.\n");
904         exit(EXIT_FAILURE);
905       }
906       mbox_filename_regexp_string = strdup(optarg);
907       break;
908
909     case 'o':
910       strncpy(output_filename, optarg, PATH_MAX);
911       break;
912
913     case 'r':
914       if(db_root_path) {
915         fprintf(stderr, "mymail: Can not set the db root path twice.\n");
916         exit(EXIT_FAILURE);
917       }
918       db_root_path = strdup(optarg);
919       break;
920
921     case 'l':
922       if(db_filename_list) {
923         fprintf(stderr, "mymail: Can not set the db filename list twice.\n");
924         exit(EXIT_FAILURE);
925       }
926       db_filename_list = strdup(optarg);
927       break;
928
929     case 's':
930       if(nb_search_conditions == MAX_NB_SEARCH_CONDITIONS) {
931         fprintf(stderr, "mymail: Too many search patterns.\n");
932         exit(EXIT_FAILURE);
933       }
934       init_condition(&search_conditions[nb_search_conditions], optarg, default_search_field);
935       nb_search_conditions++;
936       break;
937
938     case 'a':
939       default_search_field = optarg;
940       break;
941
942     default:
943       error = 1;
944       break;
945     }
946   }
947
948   /* Set all the values that may defined in the arguments, through
949      environment variables, or hard-coded */
950
951   db_filename = default_value(db_filename,
952                               "MYMAIL_DB_FILE",
953                               "mymail.db");
954
955   db_filename_regexp_string = default_value(db_filename_regexp_string,
956                                             "MYMAIL_DB_FILE",
957                                             "\\.db$");
958
959   db_root_path = default_value(db_root_path,
960                                "MYMAIL_DB_ROOT",
961                                0);
962
963   db_filename_list = default_value(db_filename_list,
964                                    "MYMAIL_DB_LIST",
965                                    0);
966
967   mbox_filename_regexp_string = default_value(mbox_filename_regexp_string,
968                                               "MYMAIL_MBOX_PATTERN",
969                                               0);
970
971   /* Start the processing */
972
973   if(error) {
974     print_usage(stderr);
975     exit(EXIT_FAILURE);
976   }
977
978   if(show_help) {
979     print_usage(stdout);
980     exit(EXIT_SUCCESS);
981   }
982
983   /* mbox indexing */
984
985   if(action_index) {
986     FILE *db_file;
987     regex_t mbox_filename_regexp_static;
988     regex_t *mbox_filename_regexp;
989
990     if(mbox_filename_regexp_string) {
991       if(regcomp(&mbox_filename_regexp_static,
992                  mbox_filename_regexp_string,
993                  0)) {
994         fprintf(stderr,
995                 "mymail: Syntax error in regexp \"%s\".\n",
996                 mbox_filename_regexp_string);
997         exit(EXIT_FAILURE);
998       }
999       mbox_filename_regexp = &mbox_filename_regexp_static;
1000     } else {
1001       mbox_filename_regexp = 0;
1002     }
1003
1004     db_file = safe_fopen(db_filename, "w", "index file for indexing");
1005
1006     for(f = 0; f < nb_fields_to_parse; f++) {
1007       if(regcomp(&fields_to_parse[f].regexp,
1008                  fields_to_parse[f].regexp_string,
1009                  fields_to_parse[f].cflags)) {
1010         fprintf(stderr,
1011                 "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
1012                 fields_to_parse[f].regexp_string,
1013                 field_keys[fields_to_parse[f].id]);
1014         exit(EXIT_FAILURE);
1015       }
1016     }
1017
1018     fprintf(db_file, "%s version_%s raw\n", MYMAIL_DB_MAGIC_TOKEN, VERSION);
1019
1020     while(optind < argc) {
1021       recursive_index_mbox(db_file,
1022                            argv[optind], mbox_filename_regexp,
1023                            nb_fields_to_parse, fields_to_parse);
1024       optind++;
1025     }
1026
1027     fflush(db_file);
1028     fclose(db_file);
1029
1030     if(mbox_filename_regexp) {
1031       regfree(mbox_filename_regexp);
1032     }
1033
1034     for(f = 0; f < nb_fields_to_parse; f++) {
1035       regfree(&fields_to_parse[f].regexp);
1036     }
1037   }
1038
1039   /* Mail search */
1040
1041   else {
1042
1043     FILE *output_file;
1044     int nb_extracted_mails = 0;
1045
1046     if(output_filename[0]) {
1047       output_file = safe_fopen(output_filename, "w", "result mbox");
1048     } else {
1049       output_file = stdout;
1050       global_quiet = 1;
1051     }
1052
1053     if(nb_search_conditions > 0) {
1054
1055       /* Recursive search if db_root_path is set */
1056
1057       if(db_root_path) {
1058         regex_t db_filename_regexp;
1059         if(regcomp(&db_filename_regexp,
1060                    db_filename_regexp_string,
1061                    0)) {
1062           fprintf(stderr,
1063                   "mymail: Syntax error in regexp \"%s\".\n",
1064                   db_filename_regexp_string);
1065           exit(EXIT_FAILURE);
1066         }
1067
1068         nb_extracted_mails += recursive_search_in_db(db_root_path, &db_filename_regexp,
1069                                                      nb_search_conditions, search_conditions,
1070                                                      output_file);
1071
1072         regfree(&db_filename_regexp);
1073       }
1074
1075       /* Search in all db files listed in db_filename_list */
1076
1077       if(db_filename_list) {
1078         char db_filename[PATH_MAX + 1];
1079         const char *s;
1080
1081         s = db_filename_list;
1082
1083         while(*s) {
1084           s = parse_token(db_filename, PATH_MAX + 1, ';', s);
1085
1086           if(db_filename[0]) {
1087             nb_extracted_mails +=
1088               search_in_db(db_filename, nb_search_conditions, search_conditions, output_file);
1089           }
1090         }
1091       }
1092
1093       /* Search in all db files listed in the command arguments */
1094
1095       while(optind < argc) {
1096         nb_extracted_mails +=
1097           search_in_db(argv[optind], nb_search_conditions, search_conditions, output_file);
1098         optind++;
1099       }
1100     }
1101
1102     if(!global_quiet) {
1103       if(nb_extracted_mails > 0) {
1104         printf("Found %d matching mails.\n", nb_extracted_mails);
1105       } else {
1106         printf("No matching mail found.\n");
1107       }
1108     }
1109
1110     fflush(output_file);
1111
1112     if(output_file != stdout) {
1113       fclose(output_file);
1114     }
1115   }
1116
1117   for(n = 0; n < nb_search_conditions; n++) {
1118     free_condition(&search_conditions[n]);
1119   }
1120
1121   free(db_filename);
1122   free(db_filename_regexp_string);
1123   free(db_root_path);
1124   free(db_filename_list);
1125   free(mbox_filename_regexp_string);
1126
1127   regfree(&global_leading_from_line_regexp);
1128
1129   exit(EXIT_SUCCESS);
1130 }