Cosmetics, renamed global variables global_*.
[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       }
794     }
795
796     if(condition->field_id == -1) {
797       fprintf(stderr,
798               "mymail: Syntax error in field key \"%s\".\n",
799               search_field);
800       exit(EXIT_FAILURE);
801     }
802
803     if(regcomp(&condition->regexp,
804                string,
805                REG_ICASE)) {
806       fprintf(stderr,
807               "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
808               string,
809               field_keys[condition->field_id]);
810       exit(EXIT_FAILURE);
811     }
812   }
813 }
814
815 void free_condition(struct search_condition *condition) {
816   if(condition->field_id != ID_INTERVAL) {
817     regfree(&condition->regexp);
818   }
819 }
820
821 /*********************************************************************/
822 /*********************************************************************/
823 /*********************************************************************/
824
825 int main(int argc, char **argv) {
826   char *db_filename = 0;
827   char *db_filename_regexp_string = 0;
828   char *db_root_path = 0;
829   char *db_filename_list = 0;
830   char *mbox_filename_regexp_string = 0;
831   char *default_search_field;
832   char output_filename[PATH_MAX + 1];
833   int action_index = 0;
834   int error = 0, show_help = 0;
835   const unsigned int nb_fields_to_parse =
836     sizeof(fields_to_parse) / sizeof(struct parsable_field);
837   char c;
838   unsigned int f, n;
839   unsigned int nb_search_conditions;
840   struct search_condition search_conditions[MAX_NB_SEARCH_CONDITIONS];
841
842   if(regcomp(&global_leading_from_line_regexp, LEADING_FROM_LINE_REGEXP_STRING, 0)) {
843     fprintf(stderr,
844             "mymail: Cannot compile leading \"from\" line regexp. That is strange.\n");
845     exit(EXIT_FAILURE);
846   }
847
848   global_quiet = 0;
849   default_search_field = 0;
850   strncpy(output_filename, "", PATH_MAX);
851
852   setlocale(LC_ALL, "");
853
854   nb_search_conditions = 0;
855
856   while ((c = getopt_long(argc, argv, "hvqip:s:d:r:l:o:a:m:",
857                           long_options, NULL)) != -1) {
858
859     switch(c) {
860
861     case 'h':
862       show_help = 1;
863       break;
864
865     case 'v':
866       print_version(stdout);
867       break;
868
869     case 'q':
870       global_quiet = 1;
871       break;
872
873     case 'i':
874       action_index = 1;
875       break;
876
877     case 'd':
878       if(db_filename) {
879         fprintf(stderr, "mymail: Can not set the db filename twice.\n");
880         exit(EXIT_FAILURE);
881       }
882       db_filename = strdup(optarg);
883       break;
884
885     case 'p':
886       if(db_filename_regexp_string) {
887         fprintf(stderr, "mymail: Can not set the db filename pattern twice.\n");
888         exit(EXIT_FAILURE);
889       }
890       db_filename_regexp_string = strdup(optarg);
891       break;
892
893     case 'm':
894       if(mbox_filename_regexp_string) {
895         fprintf(stderr, "mymail: Can not set the mbox filename pattern twice.\n");
896         exit(EXIT_FAILURE);
897       }
898       mbox_filename_regexp_string = strdup(optarg);
899       break;
900
901     case 'o':
902       strncpy(output_filename, optarg, PATH_MAX);
903       break;
904
905     case 'r':
906       if(db_root_path) {
907         fprintf(stderr, "mymail: Can not set the db root path twice.\n");
908         exit(EXIT_FAILURE);
909       }
910       db_root_path = strdup(optarg);
911       break;
912
913     case 'l':
914       if(db_filename_list) {
915         fprintf(stderr, "mymail: Can not set the db filename list twice.\n");
916         exit(EXIT_FAILURE);
917       }
918       db_filename_list = strdup(optarg);
919       break;
920
921     case 's':
922       if(nb_search_conditions == MAX_NB_SEARCH_CONDITIONS) {
923         fprintf(stderr, "mymail: Too many search patterns.\n");
924         exit(EXIT_FAILURE);
925       }
926       init_condition(&search_conditions[nb_search_conditions], optarg, default_search_field);
927       nb_search_conditions++;
928       break;
929
930     case 'a':
931       default_search_field = optarg;
932       break;
933
934     default:
935       error = 1;
936       break;
937     }
938   }
939
940   /* Set all the values that may defined in the arguments, through
941      environment variables, or hard-coded */
942
943   db_filename = default_value(db_filename,
944                               "MYMAIL_DB_FILE",
945                               "mymail.db");
946
947   db_filename_regexp_string = default_value(db_filename_regexp_string,
948                                             "MYMAIL_DB_FILE",
949                                             "\\.db$");
950
951   db_root_path = default_value(db_root_path,
952                                "MYMAIL_DB_ROOT",
953                                0);
954
955   db_filename_list = default_value(db_filename_list,
956                                    "MYMAIL_DB_LIST",
957                                    0);
958
959   mbox_filename_regexp_string = default_value(mbox_filename_regexp_string,
960                                               "MYMAIL_MBOX_PATTERN",
961                                               0);
962
963   /* Start the processing */
964
965   if(error) {
966     print_usage(stderr);
967     exit(EXIT_FAILURE);
968   }
969
970   if(show_help) {
971     print_usage(stdout);
972     exit(EXIT_SUCCESS);
973   }
974
975   /* mbox indexing */
976
977   if(action_index) {
978     FILE *db_file;
979     regex_t mbox_filename_regexp_static;
980     regex_t *mbox_filename_regexp;
981
982     if(mbox_filename_regexp_string) {
983       if(regcomp(&mbox_filename_regexp_static,
984                  mbox_filename_regexp_string,
985                  0)) {
986         fprintf(stderr,
987                 "mymail: Syntax error in regexp \"%s\".\n",
988                 mbox_filename_regexp_string);
989         exit(EXIT_FAILURE);
990       }
991       mbox_filename_regexp = &mbox_filename_regexp_static;
992     } else {
993       mbox_filename_regexp = 0;
994     }
995
996     db_file = safe_fopen(db_filename, "w", "index file for indexing");
997
998     for(f = 0; f < nb_fields_to_parse; f++) {
999       if(regcomp(&fields_to_parse[f].regexp,
1000                  fields_to_parse[f].regexp_string,
1001                  fields_to_parse[f].cflags)) {
1002         fprintf(stderr,
1003                 "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
1004                 fields_to_parse[f].regexp_string,
1005                 field_keys[fields_to_parse[f].id]);
1006         exit(EXIT_FAILURE);
1007       }
1008     }
1009
1010     fprintf(db_file, "%s version_%s raw\n", MYMAIL_DB_MAGIC_TOKEN, VERSION);
1011
1012     while(optind < argc) {
1013       recursive_index_mbox(db_file,
1014                            argv[optind], mbox_filename_regexp,
1015                            nb_fields_to_parse, fields_to_parse);
1016       optind++;
1017     }
1018
1019     fflush(db_file);
1020     fclose(db_file);
1021
1022     if(mbox_filename_regexp) {
1023       regfree(mbox_filename_regexp);
1024     }
1025
1026     for(f = 0; f < nb_fields_to_parse; f++) {
1027       regfree(&fields_to_parse[f].regexp);
1028     }
1029   }
1030
1031   /* Mail search */
1032
1033   else {
1034
1035     FILE *output_file;
1036     int nb_extracted_mails = 0;
1037
1038     if(output_filename[0]) {
1039       output_file = safe_fopen(output_filename, "w", "result mbox");
1040     } else {
1041       output_file = stdout;
1042       global_quiet = 1;
1043     }
1044
1045     if(nb_search_conditions > 0) {
1046
1047       /* Recursive search if db_root_path is set */
1048
1049       if(db_root_path) {
1050         regex_t db_filename_regexp;
1051         if(regcomp(&db_filename_regexp,
1052                    db_filename_regexp_string,
1053                    0)) {
1054           fprintf(stderr,
1055                   "mymail: Syntax error in regexp \"%s\".\n",
1056                   db_filename_regexp_string);
1057           exit(EXIT_FAILURE);
1058         }
1059
1060         nb_extracted_mails += recursive_search_in_db(db_root_path, &db_filename_regexp,
1061                                                      nb_search_conditions, search_conditions,
1062                                                      output_file);
1063
1064         regfree(&db_filename_regexp);
1065       }
1066
1067       /* Search in all db files listed in db_filename_list */
1068
1069       if(db_filename_list) {
1070         char db_filename[PATH_MAX + 1];
1071         const char *s;
1072
1073         s = db_filename_list;
1074
1075         while(*s) {
1076           s = parse_token(db_filename, PATH_MAX + 1, ';', s);
1077
1078           if(db_filename[0]) {
1079             nb_extracted_mails +=
1080               search_in_db(db_filename, nb_search_conditions, search_conditions, output_file);
1081           }
1082         }
1083       }
1084
1085       /* Search in all db files listed in the command arguments */
1086
1087       while(optind < argc) {
1088         nb_extracted_mails +=
1089           search_in_db(argv[optind], nb_search_conditions, search_conditions, output_file);
1090         optind++;
1091       }
1092     }
1093
1094     if(!global_quiet) {
1095       if(nb_extracted_mails > 0) {
1096         printf("Found %d matching mails.\n", nb_extracted_mails);
1097       } else {
1098         printf("No matching mail found.\n");
1099       }
1100     }
1101
1102     fflush(output_file);
1103
1104     if(output_file != stdout) {
1105       fclose(output_file);
1106     }
1107   }
1108
1109   for(n = 0; n < nb_search_conditions; n++) {
1110     free_condition(&search_conditions[n]);
1111   }
1112
1113   free(db_filename);
1114   free(db_filename_regexp_string);
1115   free(db_root_path);
1116   free(db_filename_list);
1117   free(mbox_filename_regexp_string);
1118
1119   regfree(&global_leading_from_line_regexp);
1120
1121   exit(EXIT_SUCCESS);
1122 }