Fixed two memory leaks.
[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 #define _GNU_SOURCE
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <locale.h>
30 #include <getopt.h>
31 #include <limits.h>
32 #include <dirent.h>
33 #include <regex.h>
34
35 #define VERSION "0.1"
36
37 #define BUFFER_SIZE 16384
38
39 struct parsable_field {
40   char *name;
41   char *regexp_string;
42   regex_t regexp;
43 };
44
45 char *db_filename;
46 char *search_pattern;
47
48 int action_index;
49
50 char *segment_next_field(char *current) {
51   while(*current && *current != ' ') current++;
52   *current = '\0'; current++;
53   while(*current && *current == ' ') current++;
54   return current;
55 }
56
57 void remove_eof(char *c) {
58   while(*c && *c != '\n' && *c != '\r') c++;
59   *c = '\0';
60 }
61
62 /********************************************************************/
63
64 /* malloc with error checking.  */
65
66 void *safe_malloc(size_t n) {
67   void *p = malloc(n);
68   if(!p && n != 0) {
69     fprintf(stderr,
70             "mymail: can not allocate memory: %s\n", strerror(errno));
71     exit(EXIT_FAILURE);
72   }
73   return p;
74 }
75
76 /*********************************************************************/
77
78 void usage(FILE *out) {
79   fprintf(out, "mymail version %s (%s)\n", VERSION, UNAME);
80   fprintf(out, "Written by Francois Fleuret <francois@fleuret.org>.\n");
81   fprintf(out, "\n");
82   fprintf(out, "Usage: mymail [options] [<filename1> [<filename2> ...]]\n");
83   fprintf(out, "\n");
84 }
85
86 /*********************************************************************/
87
88 void search_in_db(const char *search_name, const char *search_regexp_string,
89                   FILE *db_file) {
90   char raw_line[BUFFER_SIZE];
91   char current_mail_filename[BUFFER_SIZE];
92   unsigned long int current_position_in_mail;
93   char *name, *value;
94   regex_t regexp;
95   int already_written;
96
97   if(regcomp(&regexp,
98              search_regexp_string,
99              REG_ICASE)) {
100     fprintf(stderr,
101             "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
102             search_regexp_string,
103             search_name);
104     exit(EXIT_FAILURE);
105   }
106
107   current_position_in_mail = 0;
108   already_written = 0;
109
110   while(fgets(raw_line, BUFFER_SIZE, db_file)) {
111     name = raw_line;
112     value = segment_next_field(raw_line);
113
114     if(strcmp("mail", name) == 0) {
115       char *position_in_file_string = value;
116       char *mail_filename = segment_next_field(value);
117       current_position_in_mail = atol(position_in_file_string);
118       strcpy(current_mail_filename, mail_filename);
119       remove_eof(current_mail_filename);
120       already_written = 0;
121     }
122
123     else if(!already_written) {
124      if(strcmp(search_name, name) == 0 && regexec(&regexp, value, 0, 0, 0) == 0) {
125         FILE *mail_file;
126         mail_file = fopen(current_mail_filename, "r");
127         if(!mail_file) {
128           fprintf(stderr, "mymail: Can not open `%s'.\n", current_mail_filename);
129           exit(EXIT_FAILURE);
130         }
131         fseek(mail_file, current_position_in_mail, SEEK_SET);
132         if(fgets(raw_line, BUFFER_SIZE, mail_file)) {
133           printf("%s", raw_line);
134           while(fgets(raw_line, BUFFER_SIZE, mail_file) &&
135                 strncmp(raw_line, "From ", 5)) {
136             printf("%s", raw_line);
137           }
138         }
139         fclose(mail_file);
140         already_written = 1;
141       }
142     }
143   }
144
145   regfree(&regexp);
146 }
147
148
149 /*********************************************************************/
150
151 void read_file(const char *input_filename,
152                int nb_fields_to_parse, struct parsable_field *fields_to_parse,
153                FILE *db_file) {
154   char raw_line[BUFFER_SIZE];
155   FILE *file;
156   int in_header, new_header;
157   unsigned long int position_in_file;
158
159   file = fopen(input_filename, "r");
160
161   if(!file) {
162     fprintf(stderr, "mymail: Can not open `%s'.\n", input_filename);
163     exit(EXIT_FAILURE);
164   }
165
166   in_header = 0;
167   new_header = 0;
168
169   position_in_file = 0;
170
171   while(fgets(raw_line, BUFFER_SIZE, file)) {
172     if(strncmp(raw_line, "From ", 5) == 0) {
173       if(in_header) {
174         fprintf(stderr,
175                 "Got a 'From ' in the header in %s:%lu.\n",
176                 input_filename, position_in_file);
177         fprintf(stderr, "%s", raw_line);
178         exit(EXIT_FAILURE);
179       }
180       in_header = 1;
181       new_header = 1;
182     } else if(strncmp(raw_line, "\n", 1) == 0) {
183       if(in_header) { in_header = 0; }
184     }
185
186     /* if(in_header) { */
187     /* printf("LINE.H %s", raw_line); */
188     /* } else { */
189     /* printf("LINE.B %s", raw_line); */
190     /* } */
191
192     if(in_header) {
193       int f;
194       regmatch_t matches;
195       if(new_header) {
196         fprintf(db_file, "mail %lu %s\n", position_in_file, input_filename);
197         new_header = 0;
198       }
199       for(f = 0; f < nb_fields_to_parse; f++) {
200         if(regexec(&fields_to_parse[f].regexp, raw_line, 1, &matches, 0) == 0) {
201           fprintf(db_file, "%s %s",
202                   fields_to_parse[f].name,
203                   raw_line + matches.rm_eo);
204         }
205       }
206     }
207
208     position_in_file += strlen(raw_line);
209   }
210
211   fclose(file);
212 }
213
214 int ignore_entry(const char *name) {
215   return
216     /* strcmp(name, ".") == 0 || */
217     /* strcmp(name, "..") == 0 || */
218     (name[0] == '.' && name[1] != '/');
219 }
220
221 void process_entry(const char *dir_name,
222                    int nb_fields_to_parse, struct parsable_field *fields_to_parse,
223                    FILE *db_file) {
224   DIR *dir;
225   struct dirent *dir_e;
226   struct stat sb;
227   char subname[PATH_MAX + 1];
228
229   if(lstat(dir_name, &sb) != 0) {
230     fprintf(stderr,
231             "mymail: Can not stat \"%s\": %s\n",
232             dir_name,
233             strerror(errno));
234     exit(EXIT_FAILURE);
235   }
236
237   /* if(S_ISLNK(sb.st_mode)) { */
238     /* return; */
239   /* } */
240
241   dir = opendir(dir_name);
242
243   if(dir) {
244     printf("Processing directory '%s'.\n", dir_name);
245     while((dir_e = readdir(dir))) {
246       if(!ignore_entry(dir_e->d_name)) {
247         snprintf(subname, PATH_MAX, "%s/%s", dir_name, dir_e->d_name);
248         process_entry(subname, nb_fields_to_parse, fields_to_parse, db_file);
249       }
250     }
251     closedir(dir);
252   } else {
253     /* if(S_ISREG(sb.st_mode)) { */
254       read_file(dir_name, nb_fields_to_parse, fields_to_parse, db_file);
255     /* } */
256   }
257 }
258
259 /*********************************************************************/
260
261 /* For long options that have no equivalent short option, use a
262    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
263 enum
264 {
265   OPT_BASH_MODE = CHAR_MAX + 1
266 };
267
268 static struct option long_options[] = {
269   { "help", no_argument, 0, 'h' },
270   { "db-prefix", 1, 0, 'p' },
271   { "search-pattern", 1, 0, 's' },
272   { "index", 0, 0, 'i' },
273   { 0, 0, 0, 0 }
274 };
275
276 static struct parsable_field fields_to_parse[] = {
277   {
278     "from",
279     "^\\([Ff][Rr][Oo][Mm]:\\|From\\) *",
280     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
281   },
282
283   {
284     "dest",
285     "^\\([Tt][Oo]\\|[Cc][Cc]\\|[Bb][Cc][Cc]\\): *",
286     { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
287   },
288 };
289
290 int main(int argc, char **argv) {
291   int error = 0, show_help = 0;
292   const int nb_fields_to_parse = sizeof(fields_to_parse) / sizeof(struct parsable_field);
293   char c;
294   int f;
295
296   action_index = 0;
297   search_pattern = 0;
298
299   setlocale(LC_ALL, "");
300
301   while ((c = getopt_long(argc, argv, "hip:s:",
302                           long_options, NULL)) != -1) {
303
304     switch(c) {
305
306     case 'h':
307       show_help = 1;
308       break;
309
310     case 'i':
311       action_index = 1;
312       break;
313
314     case 'p':
315       db_filename = strdup(optarg);
316       break;
317
318     case 's':
319       if(search_pattern) {
320         fprintf(stderr,
321                 "mymail: Search pattern already defined.\n");
322         exit(EXIT_FAILURE);
323       }
324       search_pattern = strdup(optarg);
325       break;
326
327     default:
328       error = 1;
329       break;
330     }
331   }
332
333   if(!db_filename) {
334     db_filename = strdup("/tmp/mymail");
335   }
336
337   if(error) {
338     usage(stderr);
339     exit(EXIT_FAILURE);
340   }
341
342   if(show_help) {
343     usage(stdout);
344     exit(EXIT_SUCCESS);
345   }
346
347   if(action_index) {
348     FILE *db_file = fopen(db_filename, "w");
349     if(!db_file) {
350       fprintf(stderr,
351               "mymail: Can not open \"%s\" for writing: %s\n",
352               db_filename,
353               strerror(errno));
354       exit(EXIT_FAILURE);
355     }
356
357     for(f = 0; f < nb_fields_to_parse; f++) {
358       if(regcomp(&fields_to_parse[f].regexp,
359                  fields_to_parse[f].regexp_string,
360                  REG_ICASE)) {
361         fprintf(stderr,
362                 "mymail: Syntax error in regexp \"%s\" for field \"%s\".\n",
363                 fields_to_parse[f].regexp_string,
364                 fields_to_parse[f].name);
365         exit(EXIT_FAILURE);
366       }
367     }
368
369     while(optind < argc) {
370       process_entry(argv[optind],
371                     nb_fields_to_parse, fields_to_parse, db_file);
372       optind++;
373     }
374
375     fclose(db_file);
376
377     for(f = 0; f < nb_fields_to_parse; f++) {
378       regfree(&fields_to_parse[f].regexp);
379     }
380   }
381
382   else {
383     if(search_pattern) {
384       FILE *db_file;
385       char *search_name;
386       char *search_regexp_string;
387       search_name = search_pattern;
388       search_regexp_string = segment_next_field(search_pattern);
389       if(!*search_regexp_string) {
390         fprintf(stderr,
391                 "Syntax error in the search pattern.\n");
392         exit(EXIT_FAILURE);
393       }
394
395       /* printf("Starting search in %s for field \"%s\" matching \"%s\".\n", */
396              /* db_filename, */
397              /* search_name, */
398              /* search_regexp_string); */
399
400       db_file = fopen(db_filename, "r");
401
402       if(!db_file) {
403         fprintf(stderr,
404                 "mymail: Can not open \"%s\" for reading: %s\n",
405                 db_filename,
406                 strerror(errno));
407         exit(EXIT_FAILURE);
408       }
409
410       search_in_db(search_name, search_regexp_string, db_file);
411
412       fclose(db_file);
413       free(search_pattern);
414     }
415   }
416
417   free(db_filename);
418
419   exit(EXIT_SUCCESS);
420 }