]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
ee6f196ecb9b79346c586a44265403f5ddcb3b71
[notmuch] / notmuch-new.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22
23 #include <unistd.h>
24
25 static volatile sig_atomic_t do_add_files_print_progress = 0;
26
27 static void
28 handle_sigalrm (unused (int signal))
29 {
30     do_add_files_print_progress = 1;
31 }
32
33 static volatile sig_atomic_t interrupted;
34
35 static void
36 handle_sigint (unused (int sig))
37 {
38     ssize_t ignored;
39     static char msg[] = "Stopping...         \n";
40
41     ignored = write(2, msg, sizeof(msg)-1);
42     interrupted = 1;
43 }
44
45 static void
46 tag_inbox_and_unread (notmuch_message_t *message)
47 {
48     notmuch_message_add_tag (message, "inbox");
49     notmuch_message_add_tag (message, "unread");
50 }
51
52 static void
53 add_files_print_progress (add_files_state_t *state)
54 {
55     struct timeval tv_now;
56     double elapsed_overall, rate_overall;
57
58     gettimeofday (&tv_now, NULL);
59
60     elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
61     rate_overall = (state->processed_files) / elapsed_overall;
62
63     printf ("Processed %d", state->processed_files);
64
65     if (state->total_files) {
66         double time_remaining;
67
68         time_remaining = ((state->total_files - state->processed_files) /
69                           rate_overall);
70         printf (" of %d files (", state->total_files);
71         notmuch_time_print_formatted_seconds (time_remaining);
72         printf (" remaining).      \r");
73     } else {
74         printf (" files (%d files/sec.)    \r", (int) rate_overall);
75     }
76
77     fflush (stdout);
78 }
79
80 static int ino_cmp(const struct dirent **a, const struct dirent **b)
81 {
82     return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
83 }
84
85 /* Test if the directory looks like a Maildir directory.
86  *
87  * Search through the array of directory entries to see if we can find all
88  * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
89  *
90  * Return 1 if the directory looks like a Maildir and 0 otherwise.
91  */
92 static int
93 is_maildir (struct dirent **entries, int count)
94 {
95     int i, found = 0;
96
97     for (i = 0; i < count; i++) {
98         if (entries[i]->d_type != DT_DIR) continue;
99         if (strcmp(entries[i]->d_name, "new") == 0 ||
100             strcmp(entries[i]->d_name, "cur") == 0 ||
101             strcmp(entries[i]->d_name, "tmp") == 0)
102         {
103             found++;
104             if (found == 3)
105                 return 1;
106         }
107     }
108
109     return 0;
110 }
111
112 /* Examine 'path' recursively as follows:
113  *
114  *   o Ask the filesystem for the mtime of 'path' (path_mtime)
115  *
116  *   o Ask the database for its timestamp of 'path' (path_dbtime)
117  *
118  *   o If 'path_mtime' > 'path_dbtime'
119  *
120  *       o For each regular file in 'path' with mtime newer than the
121  *         'path_dbtime' call add_message to add the file to the
122  *         database.
123  *
124  *       o For each sub-directory of path, recursively call into this
125  *         same function.
126  *
127  *   o Tell the database to update its time of 'path' to 'path_mtime'
128  *
129  * The 'struct stat *st' must point to a structure that has already
130  * been initialized for 'path' by calling stat().
131  */
132 static notmuch_status_t
133 add_files_recursive (notmuch_database_t *notmuch,
134                      const char *path,
135                      struct stat *st,
136                      add_files_state_t *state)
137 {
138     DIR *dir = NULL;
139     struct dirent *entry = NULL;
140     char *next = NULL;
141     time_t path_mtime, path_dbtime;
142     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
143     notmuch_message_t *message = NULL;
144     struct dirent **namelist = NULL;
145     int num_entries;
146     notmuch_directory_t *directory;
147
148     path_mtime = st->st_mtime;
149
150     directory = notmuch_database_get_directory (notmuch, path);
151     path_dbtime = notmuch_directory_get_mtime (directory);
152
153     num_entries = scandir (path, &namelist, 0, ino_cmp);
154
155     if (num_entries == -1) {
156         fprintf (stderr, "Error opening directory %s: %s\n",
157                  path, strerror (errno));
158         ret = NOTMUCH_STATUS_FILE_ERROR;
159         goto DONE;
160     }
161
162     int i=0;
163
164     while (!interrupted) {
165         if (i == num_entries)
166             break;
167
168         entry= namelist[i++];
169
170         /* If this directory hasn't been modified since the last
171          * add_files, then we only need to look further for
172          * sub-directories. */
173         if (path_mtime <= path_dbtime && entry->d_type == DT_REG)
174             continue;
175
176         /* Ignore special directories to avoid infinite recursion.
177          * Also ignore the .notmuch directory.
178          */
179         /* XXX: Eventually we'll want more sophistication to let the
180          * user specify files to be ignored. */
181         if (strcmp (entry->d_name, ".") == 0 ||
182             strcmp (entry->d_name, "..") == 0 ||
183             (entry->d_type == DT_DIR &&
184              (strcmp (entry->d_name, "tmp") == 0) &&
185              is_maildir (namelist, num_entries)) ||
186             strcmp (entry->d_name, ".notmuch") ==0)
187         {
188             continue;
189         }
190
191         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
192
193         if (stat (next, st)) {
194             int err = errno;
195
196             switch (err) {
197             case ENOENT:
198                 /* The file was removed between scandir and now... */
199             case EPERM:
200             case EACCES:
201                 /* We can't read this file so don't add it to the cache. */
202                 continue;
203             }
204
205             fprintf (stderr, "Error reading %s: %s\n",
206                      next, strerror (errno));
207             ret = NOTMUCH_STATUS_FILE_ERROR;
208             goto DONE;
209         }
210
211         if (S_ISREG (st->st_mode)) {
212             /* If the file hasn't been modified since the last
213              * add_files, then we need not look at it. */
214             if (path_dbtime == 0 || st->st_mtime > path_dbtime) {
215                 state->processed_files++;
216
217                 if (state->verbose) {
218                     if (state->output_is_a_tty)
219                         printf("\r\033[K");
220
221                     printf ("%i/%i: %s",
222                             state->processed_files,
223                             state->total_files,
224                             next);
225
226                     putchar((state->output_is_a_tty) ? '\r' : '\n');
227                     fflush (stdout);
228                 }
229
230                 status = notmuch_database_add_message (notmuch, next, &message);
231                 switch (status) {
232                     /* success */
233                     case NOTMUCH_STATUS_SUCCESS:
234                         state->added_messages++;
235                         tag_inbox_and_unread (message);
236                         break;
237                     /* Non-fatal issues (go on to next file) */
238                     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
239                         /* Stay silent on this one. */
240                         break;
241                     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
242                         fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
243                                  next);
244                         break;
245                     /* Fatal issues. Don't process anymore. */
246                     case NOTMUCH_STATUS_READONLY_DATABASE:
247                     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
248                     case NOTMUCH_STATUS_OUT_OF_MEMORY:
249                         fprintf (stderr, "Error: %s. Halting processing.\n",
250                                  notmuch_status_to_string (status));
251                         ret = status;
252                         goto DONE;
253                     default:
254                     case NOTMUCH_STATUS_FILE_ERROR:
255                     case NOTMUCH_STATUS_NULL_POINTER:
256                     case NOTMUCH_STATUS_TAG_TOO_LONG:
257                     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
258                     case NOTMUCH_STATUS_LAST_STATUS:
259                         INTERNAL_ERROR ("add_message returned unexpected value: %d",  status);
260                         goto DONE;
261                 }
262
263                 if (message) {
264                     notmuch_message_destroy (message);
265                     message = NULL;
266                 }
267
268                 if (do_add_files_print_progress) {
269                     do_add_files_print_progress = 0;
270                     add_files_print_progress (state);
271                 }
272             }
273         } else if (S_ISDIR (st->st_mode)) {
274             status = add_files_recursive (notmuch, next, st, state);
275             if (status && ret == NOTMUCH_STATUS_SUCCESS)
276                 ret = status;
277         }
278
279         talloc_free (next);
280         next = NULL;
281     }
282
283     status = notmuch_directory_set_mtime (directory, path_mtime);
284     if (status && ret == NOTMUCH_STATUS_SUCCESS)
285         ret = status;
286
287   DONE:
288     if (next)
289         talloc_free (next);
290     if (entry)
291         free (entry);
292     if (dir)
293         closedir (dir);
294     if (namelist)
295         free (namelist);
296
297     return ret;
298 }
299
300 /* This is the top-level entry point for add_files. It does a couple
301  * of error checks, sets up the progress-printing timer and then calls
302  * into the recursive function. */
303 notmuch_status_t
304 add_files (notmuch_database_t *notmuch,
305            const char *path,
306            add_files_state_t *state)
307 {
308     struct stat st;
309     notmuch_status_t status;
310     struct sigaction action;
311     struct itimerval timerval;
312     notmuch_bool_t timer_is_active = FALSE;
313
314     if (stat (path, &st)) {
315         fprintf (stderr, "Error reading directory %s: %s\n",
316                  path, strerror (errno));
317         return NOTMUCH_STATUS_FILE_ERROR;
318     }
319
320     if (! S_ISDIR (st.st_mode)) {
321         fprintf (stderr, "Error: %s is not a directory.\n", path);
322         return NOTMUCH_STATUS_FILE_ERROR;
323     }
324
325     if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
326         /* Setup our handler for SIGALRM */
327         memset (&action, 0, sizeof (struct sigaction));
328         action.sa_handler = handle_sigalrm;
329         sigemptyset (&action.sa_mask);
330         action.sa_flags = SA_RESTART;
331         sigaction (SIGALRM, &action, NULL);
332
333         /* Then start a timer to send SIGALRM once per second. */
334         timerval.it_interval.tv_sec = 1;
335         timerval.it_interval.tv_usec = 0;
336         timerval.it_value.tv_sec = 1;
337         timerval.it_value.tv_usec = 0;
338         setitimer (ITIMER_REAL, &timerval, NULL);
339
340         timer_is_active = TRUE;
341     }
342
343     status = add_files_recursive (notmuch, path, &st, state);
344
345     if (timer_is_active) {
346         /* Now stop the timer. */
347         timerval.it_interval.tv_sec = 0;
348         timerval.it_interval.tv_usec = 0;
349         timerval.it_value.tv_sec = 0;
350         timerval.it_value.tv_usec = 0;
351         setitimer (ITIMER_REAL, &timerval, NULL);
352
353         /* And disable the signal handler. */
354         action.sa_handler = SIG_IGN;
355         sigaction (SIGALRM, &action, NULL);
356     }
357
358     return status;
359 }
360
361 /* XXX: This should be merged with the add_files function since it
362  * shares a lot of logic with it. */
363 /* Recursively count all regular files in path and all sub-directories
364  * of path.  The result is added to *count (which should be
365  * initialized to zero by the top-level caller before calling
366  * count_files). */
367 static void
368 count_files (const char *path, int *count)
369 {
370     struct dirent *entry = NULL;
371     char *next;
372     struct stat st;
373     struct dirent **namelist = NULL;
374     int n_entries = scandir (path, &namelist, 0, ino_cmp);
375     int i = 0;
376
377     if (n_entries == -1) {
378         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
379                  path, strerror (errno));
380         goto DONE;
381     }
382
383     while (!interrupted) {
384         if (i == n_entries)
385             break;
386
387         entry= namelist[i++];
388
389         /* Ignore special directories to avoid infinite recursion.
390          * Also ignore the .notmuch directory.
391          */
392         /* XXX: Eventually we'll want more sophistication to let the
393          * user specify files to be ignored. */
394         if (strcmp (entry->d_name, ".") == 0 ||
395             strcmp (entry->d_name, "..") == 0 ||
396             strcmp (entry->d_name, ".notmuch") == 0)
397         {
398             continue;
399         }
400
401         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
402             next = NULL;
403             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
404                      path, entry->d_name);
405             continue;
406         }
407
408         stat (next, &st);
409
410         if (S_ISREG (st.st_mode)) {
411             *count = *count + 1;
412             if (*count % 1000 == 0) {
413                 printf ("Found %d files so far.\r", *count);
414                 fflush (stdout);
415             }
416         } else if (S_ISDIR (st.st_mode)) {
417             count_files (next, count);
418         }
419
420         free (next);
421     }
422
423   DONE:
424     if (entry)
425         free (entry);
426     if (namelist)
427         free (namelist);
428 }
429
430 int
431 notmuch_new_command (void *ctx, int argc, char *argv[])
432 {
433     notmuch_config_t *config;
434     notmuch_database_t *notmuch;
435     add_files_state_t add_files_state;
436     double elapsed;
437     struct timeval tv_now;
438     int ret = 0;
439     struct stat st;
440     const char *db_path;
441     char *dot_notmuch_path;
442     struct sigaction action;
443     int i;
444
445     add_files_state.verbose = 0;
446     add_files_state.output_is_a_tty = isatty (fileno (stdout));
447
448     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
449         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
450             add_files_state.verbose = 1;
451         } else {
452             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
453             return 1;
454         }
455     }
456
457     /* Setup our handler for SIGINT */
458     memset (&action, 0, sizeof (struct sigaction));
459     action.sa_handler = handle_sigint;
460     sigemptyset (&action.sa_mask);
461     action.sa_flags = SA_RESTART;
462     sigaction (SIGINT, &action, NULL);
463
464     config = notmuch_config_open (ctx, NULL, NULL);
465     if (config == NULL)
466         return 1;
467
468     db_path = notmuch_config_get_database_path (config);
469
470     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
471
472     if (stat (dot_notmuch_path, &st)) {
473         int count;
474
475         count = 0;
476         count_files (db_path, &count);
477         if (interrupted)
478             return 1;
479
480         printf ("Found %d total files (that's not much mail).\n", count);
481         notmuch = notmuch_database_create (db_path);
482         add_files_state.total_files = count;
483     } else {
484         notmuch = notmuch_database_open (db_path,
485                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
486         add_files_state.total_files = 0;
487     }
488
489     if (notmuch == NULL)
490         return 1;
491
492     talloc_free (dot_notmuch_path);
493     dot_notmuch_path = NULL;
494
495     add_files_state.processed_files = 0;
496     add_files_state.added_messages = 0;
497     gettimeofday (&add_files_state.tv_start, NULL);
498
499     ret = add_files (notmuch, db_path, &add_files_state);
500
501     gettimeofday (&tv_now, NULL);
502     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
503                                     tv_now);
504     if (add_files_state.processed_files) {
505         printf ("Processed %d %s in ", add_files_state.processed_files,
506                 add_files_state.processed_files == 1 ?
507                 "file" : "total files");
508         notmuch_time_print_formatted_seconds (elapsed);
509         if (elapsed > 1) {
510             printf (" (%d files/sec.).                 \n",
511                     (int) (add_files_state.processed_files / elapsed));
512         } else {
513             printf (".                    \n");
514         }
515     }
516     if (add_files_state.added_messages) {
517         printf ("Added %d new %s to the database.\n",
518                 add_files_state.added_messages,
519                 add_files_state.added_messages == 1 ?
520                 "message" : "messages");
521     } else {
522         printf ("No new mail.\n");
523     }
524
525     if (ret) {
526         printf ("\nNote: At least one error was encountered: %s\n",
527                 notmuch_status_to_string (ret));
528     }
529
530     notmuch_database_close (notmuch);
531
532     return ret || interrupted;
533 }