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