Fixed a bug when we use '!' with the default search field.
[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       if(in_header) {
572         fprintf(stderr,
573                 "Got a ^\"From \" in the header in %s:%lu.\n",
574                 mbox_filename, position_in_file);
575         fprintf(stderr, "%s", raw_mbox_line);
576       }
577       in_header = 1;
578       new_header = 1;
579     } else if(raw_mbox_line[0] == '\n') {
580       if(in_header) { in_header = 0; }
581     }
582
583     if(in_header) {
584       if(new_header) {
585         fprintf(db_file, "mail %lu %s\n", position_in_file, mbox_filename);
586         new_header = 0;
587       }
588
589       if(raw_mbox_line[0] == ' ' || raw_mbox_line[0] == '\t') {
590         char *start = raw_mbox_line;
591         while(*start == ' ' || *start == '\t') start++;
592         *(end_of_full_line++) = ' ';
593         strcpy(end_of_full_line, start);
594         while(*end_of_full_line && *end_of_full_line != '\n') {
595           end_of_full_line++;
596         }
597         *end_of_full_line = '\0';
598       }
599
600       else {
601         /*
602           if(!((raw_mbox_line[0] >= 'a' && raw_mbox_line[0] <= 'z') ||
603           (raw_mbox_line[0] >= 'A' && raw_mbox_line[0] <= 'Z'))) {
604           fprintf(stderr,
605           "Header line syntax error %s:%lu.\n",
606           mbox_filename, position_in_file);
607           fprintf(stderr, "%s", raw_mbox_line);
608           }
609         */
610
611         if(full_line[0]) {
612           index_one_mbox_line(nb_fields_to_parse, fields_to_parse, full_line, db_file);
613         }
614
615         end_of_full_line = full_line;
616         strcpy(end_of_full_line, raw_mbox_line);
617         while(*end_of_full_line && *end_of_full_line != '\n') {
618           end_of_full_line++;
619         }
620         *end_of_full_line = '\0';
621       }
622
623     }
624
625     position_in_file += strlen(raw_mbox_line);
626   }
627
628   fclose(file);
629 }
630
631 void recursive_index_mbox(FILE *db_file,
632                           const char *entry_name, regex_t *mbox_filename_regexp,
633                           int nb_fields_to_parse, struct parsable_field *fields_to_parse) {
634   DIR *dir;
635   struct dirent *dir_e;
636   struct stat sb;
637   char subname[PATH_MAX + 1];
638
639   if(lstat(entry_name, &sb) != 0) {
640     fprintf(stderr,
641             "mymail: Cannot stat \"%s\": %s\n",
642             entry_name,
643             strerror(errno));
644     exit(EXIT_FAILURE);
645   }
646
647   dir = opendir(entry_name);
648
649   if(dir) {
650     while((dir_e = readdir(dir))) {
651       if(!ignore_entry(dir_e->d_name)) {
652         snprintf(subname, PATH_MAX, "%s/%s", entry_name, dir_e->d_name);
653         recursive_index_mbox(db_file, subname, mbox_filename_regexp,
654                              nb_fields_to_parse, fields_to_parse);
655       }
656     }
657     closedir(dir);
658   } else {
659     const char *s = entry_name, *filename = s;
660     while(*s) { if(*s == '/') { filename = s+1; }; s++; }
661     if(!mbox_filename_regexp || regexec(mbox_filename_regexp, filename, 0, 0, 0) == 0) {
662       index_mbox(entry_name, nb_fields_to_parse, fields_to_parse, db_file);
663     }
664   }
665 }
666
667 /*********************************************************************/
668
669 /* For long options that have no equivalent short option, use a
670    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
671 enum {
672   OPT_BASH_MODE = CHAR_MAX + 1
673 };
674
675 static struct option long_options[] = {
676   { "help", no_argument, 0, 'h' },
677   { "version", no_argument, 0, 'v' },
678   { "quiet", no_argument, 0, 'q' },
679   { "db-file-generate", 1, 0, 'd' },
680   { "db-pattern", 1, 0, 'p' },
681   { "db-root", 1, 0, 'r' },
682   { "db-list", 1, 0, 'l' },
683   { "mbox-pattern", 1, 0, 'm' },
684   { "search", 1, 0, 's' },
685   { "index", 0, 0, 'i' },
686   { "output", 1, 0, 'o' },
687   { "default-search", 1, 0, 'a' },
688   { 0, 0, 0, 0 }
689 };
690
691 struct time_criterion {
692   char *label;
693   int start_hour, end_hour;
694   int past_week_day;
695 };
696
697 /*********************************************************************/
698
699 static struct time_criterion time_criteria[] = {
700
701   { "8h",         8,       -1, -1 },
702   { "today",     24,       -1, -1 },
703   { "24h",       24,       -1, -1 },
704   { "48h",       48,       -1, -1 },
705   { "week",      24 *   7, -1, -1 },
706   { "month",     24 *  31, -1, -1 },
707   { "year",      24 * 365, -1, -1 },
708
709   { "yesterday", 48,       24, -1 },
710
711   { "monday",    -1,       -1,  1 },
712   { "tuesday",   -1,       -1,  2 },
713   { "wednesday", -1,       -1,  3 },
714   { "thursday",  -1,       -1,  4 },
715   { "friday",    -1,       -1,  5 },
716   { "saturday",  -1,       -1,  6 },
717   { "sunday",    -1,       -1,  7 },
718
719 };
720
721 /*********************************************************************/
722
723 time_t time_for_past_day(int day) {
724   time_t t;
725   struct tm *tm;
726   int delta_day;
727   t = time(0);
728   tm = localtime(&t);
729   delta_day = (7 + tm->tm_wday - day) % 7;
730   if(delta_day == 0) { delta_day = 7; }
731   return t - (delta_day * 3600 * 24 + tm->tm_sec + 60 * tm->tm_min + 3600 * tm->tm_hour);
732 }
733
734 void init_condition(struct search_condition *condition, const char *full_string,
735                     const char *default_search_field) {
736   char full_search_field[TOKEN_BUFFER_SIZE], *search_field;
737   unsigned int k, m;
738   const char *string;
739
740   string = parse_token(full_search_field, TOKEN_BUFFER_SIZE, ' ', full_string);
741   search_field = full_search_field;
742
743   if(search_field[0] == '!') {
744     search_field++;
745     condition->negation = 1;
746   } else {
747     condition->negation = 0;
748   }
749
750   condition->field_id = -1;
751
752   /* Recently */
753
754   for(k = 0; k < sizeof(time_criteria) / sizeof(struct time_criterion); k++) {
755     if(strcmp(time_criteria[k].label, search_field) == 0) {
756       condition->field_id = ID_INTERVAL;
757       if(time_criteria[k].past_week_day < 0) {
758         condition->interval_start = time(0) - 3600 * time_criteria[k].start_hour;
759         if(time_criteria[k].end_hour >= 0) {
760           condition->interval_stop = time(0) - 3600 * time_criteria[k].end_hour;
761         } else {
762           condition->interval_stop = 0;
763         }
764       } else {
765         condition->interval_start = time_for_past_day(time_criteria[k].past_week_day);
766         condition->interval_stop = condition->interval_start + 3600 * 24;
767       }
768       break;
769     }
770   }
771
772   if(condition->field_id == -1) {
773
774     /* No time condition matched, look for the search fields */
775
776     for(m = 0; (m < MAX_ID) && condition->field_id == -1; m++) {
777       if(strncmp(field_keys[m], search_field, strlen(search_field)) == 0) {
778         condition->field_id = m;
779       }
780     }
781
782     /* None match, if there is a default search field, re-run the search with it */
783
784     if(condition->field_id == -1) {
785       if(default_search_field) {
786         for(m = 0; (m < MAX_ID) && condition->field_id == -1; m++) {
787           if(strncmp(field_keys[m],
788                      default_search_field, strlen(default_search_field)) == 0) {
789             condition->field_id = m;
790           }
791         }
792         string = full_string;
793         if(string[0] == '!') { string++; }
794       }
795     }
796
797     if(condition->field_id == -1) {
798       fprintf(stderr,
799               "mymail: Syntax error in field key \"%s\".\n",
800               search_field);
801       exit(EXIT_FAILURE);
802     }
803
804     if(regcomp(&condition->regexp,
805                string,
806                REG_ICASE)) {
807       fprintf(stderr,
808               "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
809               string,
810               field_keys[condition->field_id]);
811       exit(EXIT_FAILURE);
812     }
813   }
814 }
815
816 void free_condition(struct search_condition *condition) {
817   if(condition->field_id != ID_INTERVAL) {
818     regfree(&condition->regexp);
819   }
820 }
821
822 /*********************************************************************/
823 /*********************************************************************/
824 /*********************************************************************/
825
826 int main(int argc, char **argv) {
827   char *db_filename = 0;
828   char *db_filename_regexp_string = 0;
829   char *db_root_path = 0;
830   char *db_filename_list = 0;
831   char *mbox_filename_regexp_string = 0;
832   char *default_search_field;
833   char output_filename[PATH_MAX + 1];
834   int action_index = 0;
835   int error = 0, show_help = 0;
836   const unsigned int nb_fields_to_parse =
837     sizeof(fields_to_parse) / sizeof(struct parsable_field);
838   char c;
839   unsigned int f, n;
840   unsigned int nb_search_conditions;
841   struct search_condition search_conditions[MAX_NB_SEARCH_CONDITIONS];
842
843   if(regcomp(&global_leading_from_line_regexp, LEADING_FROM_LINE_REGEXP_STRING, 0)) {
844     fprintf(stderr,
845             "mymail: Cannot compile leading \"from\" line regexp. That is strange.\n");
846     exit(EXIT_FAILURE);
847   }
848
849   global_quiet = 0;
850   default_search_field = 0;
851   strncpy(output_filename, "", PATH_MAX);
852
853   setlocale(LC_ALL, "");
854
855   nb_search_conditions = 0;
856
857   while ((c = getopt_long(argc, argv, "hvqip:s:d:r:l:o:a:m:",
858                           long_options, NULL)) != -1) {
859
860     switch(c) {
861
862     case 'h':
863       show_help = 1;
864       break;
865
866     case 'v':
867       print_version(stdout);
868       break;
869
870     case 'q':
871       global_quiet = 1;
872       break;
873
874     case 'i':
875       action_index = 1;
876       break;
877
878     case 'd':
879       if(db_filename) {
880         fprintf(stderr, "mymail: Can not set the db filename twice.\n");
881         exit(EXIT_FAILURE);
882       }
883       db_filename = strdup(optarg);
884       break;
885
886     case 'p':
887       if(db_filename_regexp_string) {
888         fprintf(stderr, "mymail: Can not set the db filename pattern twice.\n");
889         exit(EXIT_FAILURE);
890       }
891       db_filename_regexp_string = strdup(optarg);
892       break;
893
894     case 'm':
895       if(mbox_filename_regexp_string) {
896         fprintf(stderr, "mymail: Can not set the mbox filename pattern twice.\n");
897         exit(EXIT_FAILURE);
898       }
899       mbox_filename_regexp_string = strdup(optarg);
900       break;
901
902     case 'o':
903       strncpy(output_filename, optarg, PATH_MAX);
904       break;
905
906     case 'r':
907       if(db_root_path) {
908         fprintf(stderr, "mymail: Can not set the db root path twice.\n");
909         exit(EXIT_FAILURE);
910       }
911       db_root_path = strdup(optarg);
912       break;
913
914     case 'l':
915       if(db_filename_list) {
916         fprintf(stderr, "mymail: Can not set the db filename list twice.\n");
917         exit(EXIT_FAILURE);
918       }
919       db_filename_list = strdup(optarg);
920       break;
921
922     case 's':
923       if(nb_search_conditions == MAX_NB_SEARCH_CONDITIONS) {
924         fprintf(stderr, "mymail: Too many search patterns.\n");
925         exit(EXIT_FAILURE);
926       }
927       init_condition(&search_conditions[nb_search_conditions], optarg, default_search_field);
928       nb_search_conditions++;
929       break;
930
931     case 'a':
932       default_search_field = optarg;
933       break;
934
935     default:
936       error = 1;
937       break;
938     }
939   }
940
941   /* Set all the values that may defined in the arguments, through
942      environment variables, or hard-coded */
943
944   db_filename = default_value(db_filename,
945                               "MYMAIL_DB_FILE",
946                               "mymail.db");
947
948   db_filename_regexp_string = default_value(db_filename_regexp_string,
949                                             "MYMAIL_DB_FILE",
950                                             "\\.db$");
951
952   db_root_path = default_value(db_root_path,
953                                "MYMAIL_DB_ROOT",
954                                0);
955
956   db_filename_list = default_value(db_filename_list,
957                                    "MYMAIL_DB_LIST",
958                                    0);
959
960   mbox_filename_regexp_string = default_value(mbox_filename_regexp_string,
961                                               "MYMAIL_MBOX_PATTERN",
962                                               0);
963
964   /* Start the processing */
965
966   if(error) {
967     print_usage(stderr);
968     exit(EXIT_FAILURE);
969   }
970
971   if(show_help) {
972     print_usage(stdout);
973     exit(EXIT_SUCCESS);
974   }
975
976   /* mbox indexing */
977
978   if(action_index) {
979     FILE *db_file;
980     regex_t mbox_filename_regexp_static;
981     regex_t *mbox_filename_regexp;
982
983     if(mbox_filename_regexp_string) {
984       if(regcomp(&mbox_filename_regexp_static,
985                  mbox_filename_regexp_string,
986                  0)) {
987         fprintf(stderr,
988                 "mymail: Syntax error in regexp \"%s\".\n",
989                 mbox_filename_regexp_string);
990         exit(EXIT_FAILURE);
991       }
992       mbox_filename_regexp = &mbox_filename_regexp_static;
993     } else {
994       mbox_filename_regexp = 0;
995     }
996
997     db_file = safe_fopen(db_filename, "w", "index file for indexing");
998
999     for(f = 0; f < nb_fields_to_parse; f++) {
1000       if(regcomp(&fields_to_parse[f].regexp,
1001                  fields_to_parse[f].regexp_string,
1002                  fields_to_parse[f].cflags)) {
1003         fprintf(stderr,
1004                 "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
1005                 fields_to_parse[f].regexp_string,
1006                 field_keys[fields_to_parse[f].id]);
1007         exit(EXIT_FAILURE);
1008       }
1009     }
1010
1011     fprintf(db_file, "%s version_%s raw\n", MYMAIL_DB_MAGIC_TOKEN, VERSION);
1012
1013     while(optind < argc) {
1014       recursive_index_mbox(db_file,
1015                            argv[optind], mbox_filename_regexp,
1016                            nb_fields_to_parse, fields_to_parse);
1017       optind++;
1018     }
1019
1020     fflush(db_file);
1021     fclose(db_file);
1022
1023     if(mbox_filename_regexp) {
1024       regfree(mbox_filename_regexp);
1025     }
1026
1027     for(f = 0; f < nb_fields_to_parse; f++) {
1028       regfree(&fields_to_parse[f].regexp);
1029     }
1030   }
1031
1032   /* Mail search */
1033
1034   else {
1035
1036     FILE *output_file;
1037     int nb_extracted_mails = 0;
1038
1039     if(output_filename[0]) {
1040       output_file = safe_fopen(output_filename, "w", "result mbox");
1041     } else {
1042       output_file = stdout;
1043       global_quiet = 1;
1044     }
1045
1046     if(nb_search_conditions > 0) {
1047
1048       /* Recursive search if db_root_path is set */
1049
1050       if(db_root_path) {
1051         regex_t db_filename_regexp;
1052         if(regcomp(&db_filename_regexp,
1053                    db_filename_regexp_string,
1054                    0)) {
1055           fprintf(stderr,
1056                   "mymail: Syntax error in regexp \"%s\".\n",
1057                   db_filename_regexp_string);
1058           exit(EXIT_FAILURE);
1059         }
1060
1061         nb_extracted_mails += recursive_search_in_db(db_root_path, &db_filename_regexp,
1062                                                      nb_search_conditions, search_conditions,
1063                                                      output_file);
1064
1065         regfree(&db_filename_regexp);
1066       }
1067
1068       /* Search in all db files listed in db_filename_list */
1069
1070       if(db_filename_list) {
1071         char db_filename[PATH_MAX + 1];
1072         const char *s;
1073
1074         s = db_filename_list;
1075
1076         while(*s) {
1077           s = parse_token(db_filename, PATH_MAX + 1, ';', s);
1078
1079           if(db_filename[0]) {
1080             nb_extracted_mails +=
1081               search_in_db(db_filename, nb_search_conditions, search_conditions, output_file);
1082           }
1083         }
1084       }
1085
1086       /* Search in all db files listed in the command arguments */
1087
1088       while(optind < argc) {
1089         nb_extracted_mails +=
1090           search_in_db(argv[optind], nb_search_conditions, search_conditions, output_file);
1091         optind++;
1092       }
1093     }
1094
1095     if(!global_quiet) {
1096       if(nb_extracted_mails > 0) {
1097         printf("Found %d matching mails.\n", nb_extracted_mails);
1098       } else {
1099         printf("No matching mail found.\n");
1100       }
1101     }
1102
1103     fflush(output_file);
1104
1105     if(output_file != stdout) {
1106       fclose(output_file);
1107     }
1108   }
1109
1110   for(n = 0; n < nb_search_conditions; n++) {
1111     free_condition(&search_conditions[n]);
1112   }
1113
1114   free(db_filename);
1115   free(db_filename_regexp_string);
1116   free(db_root_path);
1117   free(db_filename_list);
1118   free(mbox_filename_regexp_string);
1119
1120   regfree(&global_leading_from_line_regexp);
1121
1122   exit(EXIT_SUCCESS);
1123 }