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