]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
database: add n_d_index_file (deprecates n_d_add_message)
[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 https://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22 #include "tag-util.h"
23
24 #include <unistd.h>
25
26 typedef struct _filename_node {
27     char *filename;
28     time_t mtime;
29     struct _filename_node *next;
30 } _filename_node_t;
31
32 typedef struct _filename_list {
33     unsigned count;
34     _filename_node_t *head;
35     _filename_node_t **tail;
36 } _filename_list_t;
37
38 enum verbosity {
39     VERBOSITY_QUIET,
40     VERBOSITY_NORMAL,
41     VERBOSITY_VERBOSE,
42 };
43
44 typedef struct {
45     int output_is_a_tty;
46     enum verbosity verbosity;
47     notmuch_bool_t debug;
48     const char **new_tags;
49     size_t new_tags_length;
50     const char **new_ignore;
51     size_t new_ignore_length;
52
53     int total_files;
54     int processed_files;
55     int added_messages, removed_messages, renamed_messages;
56     int vanished_files;
57     struct timeval tv_start;
58
59     _filename_list_t *removed_files;
60     _filename_list_t *removed_directories;
61     _filename_list_t *directory_mtimes;
62
63     notmuch_bool_t synchronize_flags;
64 } add_files_state_t;
65
66 static volatile sig_atomic_t do_print_progress = 0;
67
68 static void
69 handle_sigalrm (unused (int signal))
70 {
71     do_print_progress = 1;
72 }
73
74 static volatile sig_atomic_t interrupted;
75
76 static void
77 handle_sigint (unused (int sig))
78 {
79     static char msg[] = "Stopping...         \n";
80
81     /* This write is "opportunistic", so it's okay to ignore the
82      * result.  It is not required for correctness, and if it does
83      * fail or produce a short write, we want to get out of the signal
84      * handler as quickly as possible, not retry it. */
85     IGNORE_RESULT (write (2, msg, sizeof(msg)-1));
86     interrupted = 1;
87 }
88
89 static _filename_list_t *
90 _filename_list_create (const void *ctx)
91 {
92     _filename_list_t *list;
93
94     list = talloc (ctx, _filename_list_t);
95     if (list == NULL)
96         return NULL;
97
98     list->head = NULL;
99     list->tail = &list->head;
100     list->count = 0;
101
102     return list;
103 }
104
105 static _filename_node_t *
106 _filename_list_add (_filename_list_t *list,
107                     const char *filename)
108 {
109     _filename_node_t *node = talloc (list, _filename_node_t);
110
111     list->count++;
112
113     node->filename = talloc_strdup (list, filename);
114     node->next = NULL;
115
116     *(list->tail) = node;
117     list->tail = &node->next;
118
119     return node;
120 }
121
122 static void
123 generic_print_progress (const char *action, const char *object,
124                         struct timeval tv_start, unsigned processed, unsigned total)
125 {
126     struct timeval tv_now;
127     double elapsed_overall, rate_overall;
128
129     gettimeofday (&tv_now, NULL);
130
131     elapsed_overall = notmuch_time_elapsed (tv_start, tv_now);
132     rate_overall = processed / elapsed_overall;
133
134     printf ("%s %u ", action, processed);
135
136     if (total) {
137         printf ("of %u %s", total, object);
138         if (processed > 0 && elapsed_overall > 0.5) {
139             double time_remaining = ((total - processed) / rate_overall);
140             printf (" (");
141             notmuch_time_print_formatted_seconds (time_remaining);
142             printf (" remaining)");
143         }
144     } else {
145         printf ("%s", object);
146         if (elapsed_overall > 0.5)
147             printf (" (%d %s/sec.)", (int) rate_overall, object);
148     }
149     printf (".\033[K\r");
150
151     fflush (stdout);
152 }
153
154 static int
155 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
156 {
157     return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
158 }
159
160 static int
161 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
162 {
163     return strcmp ((*a)->d_name, (*b)->d_name);
164 }
165
166 /* Return the type of a directory entry relative to path as a stat(2)
167  * mode.  Like stat, this follows symlinks.  Returns -1 and sets errno
168  * if the file's type cannot be determined (which includes dangling
169  * symlinks).
170  */
171 static int
172 dirent_type (const char *path, const struct dirent *entry)
173 {
174     struct stat statbuf;
175     char *abspath;
176     int err, saved_errno;
177
178 #if HAVE_D_TYPE
179     /* Mapping from d_type to stat mode_t.  We omit DT_LNK so that
180      * we'll fall through to stat and get the real file type. */
181     static const mode_t modes[] = {
182         [DT_BLK]  = S_IFBLK,
183         [DT_CHR]  = S_IFCHR,
184         [DT_DIR]  = S_IFDIR,
185         [DT_FIFO] = S_IFIFO,
186         [DT_REG]  = S_IFREG,
187         [DT_SOCK] = S_IFSOCK
188     };
189     if (entry->d_type < ARRAY_SIZE(modes) && modes[entry->d_type])
190         return modes[entry->d_type];
191 #endif
192
193     abspath = talloc_asprintf (NULL, "%s/%s", path, entry->d_name);
194     if (!abspath) {
195         errno = ENOMEM;
196         return -1;
197     }
198     err = stat(abspath, &statbuf);
199     saved_errno = errno;
200     talloc_free (abspath);
201     if (err < 0) {
202         errno = saved_errno;
203         return -1;
204     }
205     return statbuf.st_mode & S_IFMT;
206 }
207
208 /* Test if the directory looks like a Maildir directory.
209  *
210  * Search through the array of directory entries to see if we can find all
211  * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
212  *
213  * Return 1 if the directory looks like a Maildir and 0 otherwise.
214  */
215 static int
216 _entries_resemble_maildir (const char *path, struct dirent **entries, int count)
217 {
218     int i, found = 0;
219
220     for (i = 0; i < count; i++) {
221         if (dirent_type (path, entries[i]) != S_IFDIR)
222             continue;
223
224         if (strcmp(entries[i]->d_name, "new") == 0 ||
225             strcmp(entries[i]->d_name, "cur") == 0 ||
226             strcmp(entries[i]->d_name, "tmp") == 0)
227         {
228             found++;
229             if (found == 3)
230                 return 1;
231         }
232     }
233
234     return 0;
235 }
236
237 /* Test if the file/directory is to be ignored.
238  */
239 static notmuch_bool_t
240 _entry_in_ignore_list (const char *entry, add_files_state_t *state)
241 {
242     size_t i;
243
244     for (i = 0; i < state->new_ignore_length; i++)
245         if (strcmp (entry, state->new_ignore[i]) == 0)
246             return TRUE;
247
248     return FALSE;
249 }
250
251 /* Add a single file to the database. */
252 static notmuch_status_t
253 add_file (notmuch_database_t *notmuch, const char *filename,
254           add_files_state_t *state)
255 {
256     notmuch_message_t *message = NULL;
257     const char **tag;
258     notmuch_status_t status;
259
260     status = notmuch_database_begin_atomic (notmuch);
261     if (status)
262         goto DONE;
263
264     status = notmuch_database_index_file (notmuch, filename, NULL, &message);
265     switch (status) {
266     /* Success. */
267     case NOTMUCH_STATUS_SUCCESS:
268         state->added_messages++;
269         notmuch_message_freeze (message);
270         for (tag = state->new_tags; *tag != NULL; tag++)
271             notmuch_message_add_tag (message, *tag);
272         if (state->synchronize_flags)
273             notmuch_message_maildir_flags_to_tags (message);
274         notmuch_message_thaw (message);
275         break;
276     /* Non-fatal issues (go on to next file). */
277     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
278         if (state->synchronize_flags)
279             notmuch_message_maildir_flags_to_tags (message);
280         break;
281     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
282         fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
283         break;
284     case NOTMUCH_STATUS_FILE_ERROR:
285         /* Someone renamed/removed the file between scandir and now. */
286         state->vanished_files++;
287         fprintf (stderr, "Unexpected error with file %s\n", filename);
288         (void) print_status_database ("add_file", notmuch, status);
289         break;
290     /* Fatal issues. Don't process anymore. */
291     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
292     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
293     case NOTMUCH_STATUS_OUT_OF_MEMORY:
294         (void) print_status_database("add_file", notmuch, status);
295         goto DONE;
296     default:
297         INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
298         goto DONE;
299     }
300
301     status = notmuch_database_end_atomic (notmuch);
302
303   DONE:
304     if (message)
305         notmuch_message_destroy (message);
306
307     return status;
308 }
309
310 /* Examine 'path' recursively as follows:
311  *
312  *   o Ask the filesystem for the mtime of 'path' (fs_mtime)
313  *   o Ask the database for its timestamp of 'path' (db_mtime)
314  *
315  *   o Ask the filesystem for files and directories within 'path'
316  *     (via scandir and stored in fs_entries)
317  *
318  *   o Pass 1: For each directory in fs_entries, recursively call into
319  *     this same function.
320  *
321  *   o Compare fs_mtime to db_mtime. If they are equivalent, terminate
322  *     the algorithm at this point, (this directory has not been
323  *     updated in the filesystem since the last database scan of PASS
324  *     2).
325  *
326  *   o Ask the database for files and directories within 'path'
327  *     (db_files and db_subdirs)
328  *
329  *   o Pass 2: Walk fs_entries simultaneously with db_files and
330  *     db_subdirs. Look for one of three interesting cases:
331  *
332  *         1. Regular file in fs_entries and not in db_files
333  *            This is a new file to add_message into the database.
334  *
335  *         2. Filename in db_files not in fs_entries.
336  *            This is a file that has been removed from the mail store.
337  *
338  *         3. Directory in db_subdirs not in fs_entries
339  *            This is a directory that has been removed from the mail store.
340  *
341  *     Note that the addition of a directory is not interesting here,
342  *     since that will have been taken care of in pass 1. Also, we
343  *     don't immediately act on file/directory removal since we must
344  *     ensure that in the case of a rename that the new filename is
345  *     added before the old filename is removed, (so that no
346  *     information is lost from the database).
347  *
348  *   o Tell the database to update its time of 'path' to 'fs_mtime'
349  *     if fs_mtime isn't the current wall-clock time.
350  */
351 static notmuch_status_t
352 add_files (notmuch_database_t *notmuch,
353            const char *path,
354            add_files_state_t *state)
355 {
356     struct dirent *entry = NULL;
357     char *next = NULL;
358     time_t fs_mtime, db_mtime;
359     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
360     struct dirent **fs_entries = NULL;
361     int i, num_fs_entries = 0, entry_type;
362     notmuch_directory_t *directory;
363     notmuch_filenames_t *db_files = NULL;
364     notmuch_filenames_t *db_subdirs = NULL;
365     time_t stat_time;
366     struct stat st;
367     notmuch_bool_t is_maildir;
368
369     if (stat (path, &st)) {
370         fprintf (stderr, "Error reading directory %s: %s\n",
371                  path, strerror (errno));
372         return NOTMUCH_STATUS_FILE_ERROR;
373     }
374     stat_time = time (NULL);
375
376     if (! S_ISDIR (st.st_mode)) {
377         fprintf (stderr, "Error: %s is not a directory.\n", path);
378         return NOTMUCH_STATUS_FILE_ERROR;
379     }
380
381     fs_mtime = st.st_mtime;
382
383     status = notmuch_database_get_directory (notmuch, path, &directory);
384     if (status) {
385         ret = status;
386         goto DONE;
387     }
388     db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
389
390     /* If the directory is unchanged from our last scan and has no
391      * sub-directories, then return without scanning it at all.  In
392      * some situations, skipping the scan can substantially reduce the
393      * cost of notmuch new, especially since the huge numbers of files
394      * in Maildirs make scans expensive, but all files live in leaf
395      * directories.
396      *
397      * To check for sub-directories, we borrow a trick from find,
398      * kpathsea, and many other UNIX tools: since a directory's link
399      * count is the number of sub-directories (specifically, their
400      * '..' entries) plus 2 (the link from the parent and the link for
401      * '.').  This check is safe even on weird file systems, since
402      * file systems that can't compute this will return 0 or 1.  This
403      * is safe even on *really* weird file systems like HFS+ that
404      * mistakenly return the total number of directory entries, since
405      * that only inflates the count beyond 2.
406      */
407     if (directory && fs_mtime == db_mtime && st.st_nlink == 2) {
408         /* There's one catch: pass 1 below considers symlinks to
409          * directories to be directories, but these don't increase the
410          * file system link count.  So, only bail early if the
411          * database agrees that there are no sub-directories. */
412         db_subdirs = notmuch_directory_get_child_directories (directory);
413         if (!notmuch_filenames_valid (db_subdirs))
414             goto DONE;
415         notmuch_filenames_destroy (db_subdirs);
416         db_subdirs = NULL;
417     }
418
419     /* If the database knows about this directory, then we sort based
420      * on strcmp to match the database sorting. Otherwise, we can do
421      * inode-based sorting for faster filesystem operation. */
422     num_fs_entries = scandir (path, &fs_entries, 0,
423                               directory ?
424                               dirent_sort_strcmp_name : dirent_sort_inode);
425
426     if (num_fs_entries == -1) {
427         fprintf (stderr, "Error opening directory %s: %s\n",
428                  path, strerror (errno));
429         /* We consider this a fatal error because, if a user moved a
430          * message from another directory that we were able to scan
431          * into this directory, skipping this directory will cause
432          * that message to be lost. */
433         ret = NOTMUCH_STATUS_FILE_ERROR;
434         goto DONE;
435     }
436
437     /* Pass 1: Recurse into all sub-directories. */
438     is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
439
440     for (i = 0; i < num_fs_entries; i++) {
441         if (interrupted)
442             break;
443
444         entry = fs_entries[i];
445
446         /* Ignore any files/directories the user has configured to
447          * ignore.  We do this before dirent_type both for performance
448          * and because we don't care if dirent_type fails on entries
449          * that are explicitly ignored.
450          */
451         if (_entry_in_ignore_list (entry->d_name, state)) {
452             if (state->debug)
453                 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
454                         path, entry->d_name);
455             continue;
456         }
457
458         /* We only want to descend into directories (and symlinks to
459          * directories). */
460         entry_type = dirent_type (path, entry);
461         if (entry_type == -1) {
462             /* Be pessimistic, e.g. so we don't lose lots of mail just
463              * because a user broke a symlink. */
464             fprintf (stderr, "Error reading file %s/%s: %s\n",
465                      path, entry->d_name, strerror (errno));
466             return NOTMUCH_STATUS_FILE_ERROR;
467         } else if (entry_type != S_IFDIR) {
468             continue;
469         }
470
471         /* Ignore special directories to avoid infinite recursion.
472          * Also ignore the .notmuch directory and any "tmp" directory
473          * that appears within a maildir.
474          */
475         if (strcmp (entry->d_name, ".") == 0 ||
476             strcmp (entry->d_name, "..") == 0 ||
477             (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
478             strcmp (entry->d_name, ".notmuch") == 0)
479             continue;
480
481         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
482         status = add_files (notmuch, next, state);
483         if (status) {
484             ret = status;
485             goto DONE;
486         }
487         talloc_free (next);
488         next = NULL;
489     }
490
491     /* If the directory's modification time in the filesystem is the
492      * same as what we recorded in the database the last time we
493      * scanned it, then we can skip the second pass entirely.
494      *
495      * We test for strict equality here to avoid a bug that can happen
496      * if the system clock jumps backward, (preventing new mail from
497      * being discovered until the clock catches up and the directory
498      * is modified again).
499      */
500     if (directory && fs_mtime == db_mtime)
501         goto DONE;
502
503     /* If the database has never seen this directory before, we can
504      * simply leave db_files and db_subdirs NULL. */
505     if (directory) {
506         db_files = notmuch_directory_get_child_files (directory);
507         db_subdirs = notmuch_directory_get_child_directories (directory);
508     }
509
510     /* Pass 2: Scan for new files, removed files, and removed directories. */
511     for (i = 0; i < num_fs_entries; i++)
512     {
513         if (interrupted)
514             break;
515
516         entry = fs_entries[i];
517
518         /* Ignore files & directories user has configured to be ignored */
519         if (_entry_in_ignore_list (entry->d_name, state)) {
520             if (state->debug)
521                 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
522                         path, entry->d_name);
523             continue;
524         }
525
526         /* Check if we've walked past any names in db_files or
527          * db_subdirs. If so, these have been deleted. */
528         while (notmuch_filenames_valid (db_files) &&
529                strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
530         {
531             char *absolute = talloc_asprintf (state->removed_files,
532                                               "%s/%s", path,
533                                               notmuch_filenames_get (db_files));
534
535             if (state->debug)
536                 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
537                         absolute);
538
539             _filename_list_add (state->removed_files, absolute);
540
541             notmuch_filenames_move_to_next (db_files);
542         }
543
544         while (notmuch_filenames_valid (db_subdirs) &&
545                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
546         {
547             const char *filename = notmuch_filenames_get (db_subdirs);
548
549             if (strcmp (filename, entry->d_name) < 0)
550             {
551                 char *absolute = talloc_asprintf (state->removed_directories,
552                                                   "%s/%s", path, filename);
553                 if (state->debug)
554                     printf ("(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
555                         absolute);
556
557                 _filename_list_add (state->removed_directories, absolute);
558             }
559
560             notmuch_filenames_move_to_next (db_subdirs);
561         }
562
563         /* Only add regular files (and symlinks to regular files). */
564         entry_type = dirent_type (path, entry);
565         if (entry_type == -1) {
566             fprintf (stderr, "Error reading file %s/%s: %s\n",
567                      path, entry->d_name, strerror (errno));
568             return NOTMUCH_STATUS_FILE_ERROR;
569         } else if (entry_type != S_IFREG) {
570             continue;
571         }
572
573         /* Don't add a file that we've added before. */
574         if (notmuch_filenames_valid (db_files) &&
575             strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
576         {
577             notmuch_filenames_move_to_next (db_files);
578             continue;
579         }
580
581         /* We're now looking at a regular file that doesn't yet exist
582          * in the database, so add it. */
583         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
584
585         state->processed_files++;
586
587         if (state->verbosity >= VERBOSITY_VERBOSE) {
588             if (state->output_is_a_tty)
589                 printf("\r\033[K");
590
591             printf ("%i/%i: %s", state->processed_files, state->total_files,
592                     next);
593
594             putchar((state->output_is_a_tty) ? '\r' : '\n');
595             fflush (stdout);
596         }
597
598         status = add_file (notmuch, next, state);
599         if (status) {
600             ret = status;
601             goto DONE;
602         }
603
604         if (do_print_progress) {
605             do_print_progress = 0;
606             generic_print_progress ("Processed", "files", state->tv_start,
607                                     state->processed_files, state->total_files);
608         }
609
610         talloc_free (next);
611         next = NULL;
612     }
613
614     if (interrupted)
615         goto DONE;
616
617     /* Now that we've walked the whole filesystem list, anything left
618      * over in the database lists has been deleted. */
619     while (notmuch_filenames_valid (db_files))
620     {
621         char *absolute = talloc_asprintf (state->removed_files,
622                                           "%s/%s", path,
623                                           notmuch_filenames_get (db_files));
624         if (state->debug)
625             printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
626                     absolute);
627
628         _filename_list_add (state->removed_files, absolute);
629
630         notmuch_filenames_move_to_next (db_files);
631     }
632
633     while (notmuch_filenames_valid (db_subdirs))
634     {
635         char *absolute = talloc_asprintf (state->removed_directories,
636                                           "%s/%s", path,
637                                           notmuch_filenames_get (db_subdirs));
638
639         if (state->debug)
640             printf ("(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
641                     absolute);
642
643         _filename_list_add (state->removed_directories, absolute);
644
645         notmuch_filenames_move_to_next (db_subdirs);
646     }
647
648     /* If the directory's mtime is the same as the wall-clock time
649      * when we stat'ed the directory, we skip updating the mtime in
650      * the database because a message could be delivered later in this
651      * same second.  This may lead to unnecessary re-scans, but it
652      * avoids overlooking messages. */
653     if (fs_mtime != stat_time)
654         _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
655
656   DONE:
657     if (next)
658         talloc_free (next);
659     if (fs_entries) {
660         for (i = 0; i < num_fs_entries; i++)
661             free (fs_entries[i]);
662
663         free (fs_entries);
664     }
665     if (db_subdirs)
666         notmuch_filenames_destroy (db_subdirs);
667     if (db_files)
668         notmuch_filenames_destroy (db_files);
669     if (directory)
670         notmuch_directory_destroy (directory);
671
672     return ret;
673 }
674
675 static void
676 setup_progress_printing_timer (void)
677 {
678     struct sigaction action;
679     struct itimerval timerval;
680
681     /* Set up our handler for SIGALRM */
682     memset (&action, 0, sizeof (struct sigaction));
683     action.sa_handler = handle_sigalrm;
684     sigemptyset (&action.sa_mask);
685     action.sa_flags = SA_RESTART;
686     sigaction (SIGALRM, &action, NULL);
687
688     /* Then start a timer to send SIGALRM once per second. */
689     timerval.it_interval.tv_sec = 1;
690     timerval.it_interval.tv_usec = 0;
691     timerval.it_value.tv_sec = 1;
692     timerval.it_value.tv_usec = 0;
693     setitimer (ITIMER_REAL, &timerval, NULL);
694 }
695
696 static void
697 stop_progress_printing_timer (void)
698 {
699     struct sigaction action;
700     struct itimerval timerval;
701
702     /* Now stop the timer. */
703     timerval.it_interval.tv_sec = 0;
704     timerval.it_interval.tv_usec = 0;
705     timerval.it_value.tv_sec = 0;
706     timerval.it_value.tv_usec = 0;
707     setitimer (ITIMER_REAL, &timerval, NULL);
708
709     /* And disable the signal handler. */
710     action.sa_handler = SIG_IGN;
711     sigaction (SIGALRM, &action, NULL);
712 }
713
714
715 /* XXX: This should be merged with the add_files function since it
716  * shares a lot of logic with it. */
717 /* Recursively count all regular files in path and all sub-directories
718  * of path.  The result is added to *count (which should be
719  * initialized to zero by the top-level caller before calling
720  * count_files). */
721 static void
722 count_files (const char *path, int *count, add_files_state_t *state)
723 {
724     struct dirent *entry = NULL;
725     char *next;
726     struct dirent **fs_entries = NULL;
727     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
728     int entry_type, i;
729
730     if (num_fs_entries == -1) {
731         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
732                  path, strerror (errno));
733         goto DONE;
734     }
735
736     for (i = 0; i < num_fs_entries && ! interrupted; i++) {
737         entry = fs_entries[i];
738
739         /* Ignore special directories to avoid infinite recursion.
740          * Also ignore the .notmuch directory.
741          */
742         if (strcmp (entry->d_name, ".") == 0 ||
743             strcmp (entry->d_name, "..") == 0 ||
744             strcmp (entry->d_name, ".notmuch") == 0)
745             continue;
746
747         /* Ignore any files/directories the user has configured to be
748          * ignored
749          */
750         if (_entry_in_ignore_list (entry->d_name, state)) {
751             if (state->debug)
752                 printf ("(D) count_files: explicitly ignoring %s/%s\n",
753                         path, entry->d_name);
754             continue;
755         }
756
757         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
758             next = NULL;
759             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
760                      path, entry->d_name);
761             continue;
762         }
763
764         entry_type = dirent_type (path, entry);
765         if (entry_type == S_IFREG) {
766             *count = *count + 1;
767             if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
768                 printf ("Found %d files so far.\r", *count);
769                 fflush (stdout);
770             }
771         } else if (entry_type == S_IFDIR) {
772             count_files (next, count, state);
773         }
774
775         free (next);
776     }
777
778   DONE:
779     if (fs_entries) {
780         for (i = 0; i < num_fs_entries; i++)
781             free (fs_entries[i]);
782
783         free (fs_entries);
784     }
785 }
786
787 static void
788 upgrade_print_progress (void *closure,
789                         double progress)
790 {
791     add_files_state_t *state = closure;
792
793     printf ("Upgrading database: %.2f%% complete", progress * 100.0);
794
795     if (progress > 0) {
796         struct timeval tv_now;
797         double elapsed, time_remaining;
798
799         gettimeofday (&tv_now, NULL);
800
801         elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
802         time_remaining = (elapsed / progress) * (1.0 - progress);
803         printf (" (");
804         notmuch_time_print_formatted_seconds (time_remaining);
805         printf (" remaining)");
806     }
807
808     printf (".      \r");
809
810     fflush (stdout);
811 }
812
813 /* Remove one message filename from the database. */
814 static notmuch_status_t
815 remove_filename (notmuch_database_t *notmuch,
816                  const char *path,
817                  add_files_state_t *add_files_state)
818 {
819     notmuch_status_t status;
820     notmuch_message_t *message;
821     status = notmuch_database_begin_atomic (notmuch);
822     if (status)
823         return status;
824     status = notmuch_database_find_message_by_filename (notmuch, path, &message);
825     if (status || message == NULL)
826         goto DONE;
827
828     status = notmuch_database_remove_message (notmuch, path);
829     if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
830         add_files_state->renamed_messages++;
831         if (add_files_state->synchronize_flags == TRUE)
832             notmuch_message_maildir_flags_to_tags (message);
833         status = NOTMUCH_STATUS_SUCCESS;
834     } else if (status == NOTMUCH_STATUS_SUCCESS) {
835         add_files_state->removed_messages++;
836     }
837     notmuch_message_destroy (message);
838
839   DONE:
840     notmuch_database_end_atomic (notmuch);
841     return status;
842 }
843
844 /* Recursively remove all filenames from the database referring to
845  * 'path' (or to any of its children). */
846 static notmuch_status_t
847 _remove_directory (void *ctx,
848                    notmuch_database_t *notmuch,
849                    const char *path,
850                    add_files_state_t *add_files_state)
851 {
852     notmuch_status_t status;
853     notmuch_directory_t *directory;
854     notmuch_filenames_t *files, *subdirs;
855     char *absolute;
856
857     status = notmuch_database_get_directory (notmuch, path, &directory);
858     if (status || !directory)
859         return status;
860
861     for (files = notmuch_directory_get_child_files (directory);
862          notmuch_filenames_valid (files);
863          notmuch_filenames_move_to_next (files))
864     {
865         absolute = talloc_asprintf (ctx, "%s/%s", path,
866                                     notmuch_filenames_get (files));
867         status = remove_filename (notmuch, absolute, add_files_state);
868         talloc_free (absolute);
869         if (status)
870             goto DONE;
871     }
872
873     for (subdirs = notmuch_directory_get_child_directories (directory);
874          notmuch_filenames_valid (subdirs);
875          notmuch_filenames_move_to_next (subdirs))
876     {
877         absolute = talloc_asprintf (ctx, "%s/%s", path,
878                                     notmuch_filenames_get (subdirs));
879         status = _remove_directory (ctx, notmuch, absolute, add_files_state);
880         talloc_free (absolute);
881         if (status)
882             goto DONE;
883     }
884
885     status = notmuch_directory_delete (directory);
886
887   DONE:
888     if (status)
889         notmuch_directory_destroy (directory);
890     return status;
891 }
892
893 static void
894 print_results (const add_files_state_t *state)
895 {
896     double elapsed;
897     struct timeval tv_now;
898
899     gettimeofday (&tv_now, NULL);
900     elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
901
902     if (state->processed_files) {
903         printf ("Processed %d %s in ", state->processed_files,
904                 state->processed_files == 1 ? "file" : "total files");
905         notmuch_time_print_formatted_seconds (elapsed);
906         if (elapsed > 1)
907             printf (" (%d files/sec.)",
908                     (int) (state->processed_files / elapsed));
909         printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
910     }
911
912     if (state->added_messages)
913         printf ("Added %d new %s to the database.", state->added_messages,
914                 state->added_messages == 1 ? "message" : "messages");
915     else
916         printf ("No new mail.");
917
918     if (state->removed_messages)
919         printf (" Removed %d %s.", state->removed_messages,
920                 state->removed_messages == 1 ? "message" : "messages");
921
922     if (state->renamed_messages)
923         printf (" Detected %d file %s.", state->renamed_messages,
924                 state->renamed_messages == 1 ? "rename" : "renames");
925
926     printf ("\n");
927 }
928
929 int
930 notmuch_new_command (notmuch_config_t *config, int argc, char *argv[])
931 {
932     notmuch_database_t *notmuch;
933     add_files_state_t add_files_state = {
934         .verbosity = VERBOSITY_NORMAL,
935         .debug = FALSE,
936         .output_is_a_tty = isatty (fileno (stdout)),
937     };
938     struct timeval tv_start;
939     int ret = 0;
940     struct stat st;
941     const char *db_path;
942     char *dot_notmuch_path;
943     struct sigaction action;
944     _filename_node_t *f;
945     int opt_index;
946     unsigned int i;
947     notmuch_bool_t timer_is_active = FALSE;
948     notmuch_bool_t no_hooks = FALSE;
949     notmuch_bool_t quiet = FALSE, verbose = FALSE;
950     notmuch_status_t status;
951
952     notmuch_opt_desc_t options[] = {
953         { NOTMUCH_OPT_BOOLEAN,  &quiet, "quiet", 'q', 0 },
954         { NOTMUCH_OPT_BOOLEAN,  &verbose, "verbose", 'v', 0 },
955         { NOTMUCH_OPT_BOOLEAN,  &add_files_state.debug, "debug", 'd', 0 },
956         { NOTMUCH_OPT_BOOLEAN,  &no_hooks, "no-hooks", 'n', 0 },
957         { NOTMUCH_OPT_INHERIT, (void *) &notmuch_shared_options, NULL, 0, 0 },
958         { 0, 0, 0, 0, 0 }
959     };
960
961     opt_index = parse_arguments (argc, argv, options, 1);
962     if (opt_index < 0)
963         return EXIT_FAILURE;
964
965     notmuch_process_shared_options (argv[0]);
966
967     /* quiet trumps verbose */
968     if (quiet)
969         add_files_state.verbosity = VERBOSITY_QUIET;
970     else if (verbose)
971         add_files_state.verbosity = VERBOSITY_VERBOSE;
972
973     add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
974     add_files_state.new_ignore = notmuch_config_get_new_ignore (config, &add_files_state.new_ignore_length);
975     add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
976     db_path = notmuch_config_get_database_path (config);
977
978     for (i = 0; i < add_files_state.new_tags_length; i++) {
979         const char *error_msg;
980
981         error_msg = illegal_tag (add_files_state.new_tags[i], FALSE);
982         if (error_msg) {
983             fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
984                      add_files_state.new_tags[i], error_msg);
985             return EXIT_FAILURE;
986         }
987     }
988
989     if (!no_hooks) {
990         ret = notmuch_run_hook (db_path, "pre-new");
991         if (ret)
992             return EXIT_FAILURE;
993     }
994
995     dot_notmuch_path = talloc_asprintf (config, "%s/%s", db_path, ".notmuch");
996
997     if (stat (dot_notmuch_path, &st)) {
998         int count;
999
1000         count = 0;
1001         count_files (db_path, &count, &add_files_state);
1002         if (interrupted)
1003             return EXIT_FAILURE;
1004
1005         if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1006             printf ("Found %d total files (that's not much mail).\n", count);
1007         if (notmuch_database_create (db_path, &notmuch))
1008             return EXIT_FAILURE;
1009         add_files_state.total_files = count;
1010     } else {
1011         char *status_string = NULL;
1012         if (notmuch_database_open_verbose (db_path, NOTMUCH_DATABASE_MODE_READ_WRITE,
1013                                            &notmuch, &status_string)) {
1014             if (status_string) {
1015                 fputs (status_string, stderr);
1016                 free (status_string);
1017             }
1018             return EXIT_FAILURE;
1019         }
1020
1021         notmuch_exit_if_unmatched_db_uuid (notmuch);
1022
1023         if (notmuch_database_needs_upgrade (notmuch)) {
1024             time_t now = time (NULL);
1025             struct tm *gm_time = gmtime (&now);
1026
1027             /* since dump files are written atomically, the amount of
1028              * harm from overwriting one within a second seems
1029              * relatively small. */
1030
1031             const char *backup_name =
1032                 talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1033                                  dot_notmuch_path,
1034                                  gm_time->tm_year + 1900,
1035                                  gm_time->tm_mon + 1,
1036                                  gm_time->tm_mday,
1037                                  gm_time->tm_hour,
1038                                  gm_time->tm_min,
1039                                  gm_time->tm_sec);
1040
1041             if (add_files_state.verbosity >= VERBOSITY_NORMAL) {
1042                 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1043                 printf ("This process is safe to interrupt.\n");
1044                 printf ("Backing up tags to %s...\n", backup_name);
1045             }
1046
1047             if (notmuch_database_dump (notmuch, backup_name, "",
1048                                        DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, TRUE)) {
1049                 fprintf (stderr, "Backup failed. Aborting upgrade.");
1050                 return EXIT_FAILURE;
1051             }
1052
1053             gettimeofday (&add_files_state.tv_start, NULL);
1054             status = notmuch_database_upgrade (
1055                 notmuch,
1056                 add_files_state.verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1057                 &add_files_state);
1058             if (status) {
1059                 printf ("Upgrade failed: %s\n",
1060                         notmuch_status_to_string (status));
1061                 notmuch_database_destroy (notmuch);
1062                 return EXIT_FAILURE;
1063             }
1064             if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1065                 printf ("Your notmuch database has now been upgraded.\n");
1066         }
1067
1068         add_files_state.total_files = 0;
1069     }
1070
1071     if (notmuch == NULL)
1072         return EXIT_FAILURE;
1073
1074     /* Set up our handler for SIGINT. We do this after having
1075      * potentially done a database upgrade we this interrupt handler
1076      * won't support. */
1077     memset (&action, 0, sizeof (struct sigaction));
1078     action.sa_handler = handle_sigint;
1079     sigemptyset (&action.sa_mask);
1080     action.sa_flags = SA_RESTART;
1081     sigaction (SIGINT, &action, NULL);
1082
1083     talloc_free (dot_notmuch_path);
1084     dot_notmuch_path = NULL;
1085
1086     gettimeofday (&add_files_state.tv_start, NULL);
1087
1088     add_files_state.removed_files = _filename_list_create (config);
1089     add_files_state.removed_directories = _filename_list_create (config);
1090     add_files_state.directory_mtimes = _filename_list_create (config);
1091
1092     if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1093         add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1094         setup_progress_printing_timer ();
1095         timer_is_active = TRUE;
1096     }
1097
1098     ret = add_files (notmuch, db_path, &add_files_state);
1099     if (ret)
1100         goto DONE;
1101
1102     gettimeofday (&tv_start, NULL);
1103     for (f = add_files_state.removed_files->head; f && !interrupted; f = f->next) {
1104         ret = remove_filename (notmuch, f->filename, &add_files_state);
1105         if (ret)
1106             goto DONE;
1107         if (do_print_progress) {
1108             do_print_progress = 0;
1109             generic_print_progress ("Cleaned up", "messages",
1110                 tv_start, add_files_state.removed_messages + add_files_state.renamed_messages,
1111                 add_files_state.removed_files->count);
1112         }
1113     }
1114
1115     gettimeofday (&tv_start, NULL);
1116     for (f = add_files_state.removed_directories->head, i = 0; f && !interrupted; f = f->next, i++) {
1117         ret = _remove_directory (config, notmuch, f->filename, &add_files_state);
1118         if (ret)
1119             goto DONE;
1120         if (do_print_progress) {
1121             do_print_progress = 0;
1122             generic_print_progress ("Cleaned up", "directories",
1123                 tv_start, i,
1124                 add_files_state.removed_directories->count);
1125         }
1126     }
1127
1128     for (f = add_files_state.directory_mtimes->head; f && !interrupted; f = f->next) {
1129         notmuch_directory_t *directory;
1130         status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1131         if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1132             notmuch_directory_set_mtime (directory, f->mtime);
1133             notmuch_directory_destroy (directory);
1134         }
1135     }
1136
1137   DONE:
1138     talloc_free (add_files_state.removed_files);
1139     talloc_free (add_files_state.removed_directories);
1140     talloc_free (add_files_state.directory_mtimes);
1141
1142     if (timer_is_active)
1143         stop_progress_printing_timer ();
1144
1145     if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1146         print_results (&add_files_state);
1147
1148     if (ret)
1149         fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1150                  notmuch_status_to_string (ret));
1151
1152     notmuch_database_destroy (notmuch);
1153
1154     if (!no_hooks && !ret && !interrupted)
1155         ret = notmuch_run_hook (db_path, "post-new");
1156
1157     if (ret || interrupted)
1158         return EXIT_FAILURE;
1159
1160     if (add_files_state.vanished_files)
1161         return NOTMUCH_EXIT_TEMPFAIL;
1162
1163     return EXIT_SUCCESS;
1164 }