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