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