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