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