]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
Merge branch 'release'
[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 %d ", action, processed);
135
136     if (total) {
137         printf ("of %d %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_add_message (notmuch, filename, &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         fprintf (stderr, "Error: %s. Halting processing.\n",
295                  notmuch_status_to_string (status));
296         goto DONE;
297     default:
298         INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
299         goto DONE;
300     }
301
302     status = notmuch_database_end_atomic (notmuch);
303
304   DONE:
305     if (message)
306         notmuch_message_destroy (message);
307
308     return status;
309 }
310
311 /* Examine 'path' recursively as follows:
312  *
313  *   o Ask the filesystem for the mtime of 'path' (fs_mtime)
314  *   o Ask the database for its timestamp of 'path' (db_mtime)
315  *
316  *   o Ask the filesystem for files and directories within 'path'
317  *     (via scandir and stored in fs_entries)
318  *
319  *   o Pass 1: For each directory in fs_entries, recursively call into
320  *     this same function.
321  *
322  *   o Compare fs_mtime to db_mtime. If they are equivalent, terminate
323  *     the algorithm at this point, (this directory has not been
324  *     updated in the filesystem since the last database scan of PASS
325  *     2).
326  *
327  *   o Ask the database for files and directories within 'path'
328  *     (db_files and db_subdirs)
329  *
330  *   o Pass 2: Walk fs_entries simultaneously with db_files and
331  *     db_subdirs. Look for one of three interesting cases:
332  *
333  *         1. Regular file in fs_entries and not in db_files
334  *            This is a new file to add_message into the database.
335  *
336  *         2. Filename in db_files not in fs_entries.
337  *            This is a file that has been removed from the mail store.
338  *
339  *         3. Directory in db_subdirs not in fs_entries
340  *            This is a directory that has been removed from the mail store.
341  *
342  *     Note that the addition of a directory is not interesting here,
343  *     since that will have been taken care of in pass 1. Also, we
344  *     don't immediately act on file/directory removal since we must
345  *     ensure that in the case of a rename that the new filename is
346  *     added before the old filename is removed, (so that no
347  *     information is lost from the database).
348  *
349  *   o Tell the database to update its time of 'path' to 'fs_mtime'
350  *     if fs_mtime isn't the current wall-clock time.
351  */
352 static notmuch_status_t
353 add_files (notmuch_database_t *notmuch,
354            const char *path,
355            add_files_state_t *state)
356 {
357     struct dirent *entry = NULL;
358     char *next = NULL;
359     time_t fs_mtime, db_mtime;
360     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
361     struct dirent **fs_entries = NULL;
362     int i, num_fs_entries = 0, entry_type;
363     notmuch_directory_t *directory;
364     notmuch_filenames_t *db_files = NULL;
365     notmuch_filenames_t *db_subdirs = NULL;
366     time_t stat_time;
367     struct stat st;
368     notmuch_bool_t is_maildir;
369
370     if (stat (path, &st)) {
371         fprintf (stderr, "Error reading directory %s: %s\n",
372                  path, strerror (errno));
373         return NOTMUCH_STATUS_FILE_ERROR;
374     }
375     stat_time = time (NULL);
376
377     if (! S_ISDIR (st.st_mode)) {
378         fprintf (stderr, "Error: %s is not a directory.\n", path);
379         return NOTMUCH_STATUS_FILE_ERROR;
380     }
381
382     fs_mtime = st.st_mtime;
383
384     status = notmuch_database_get_directory (notmuch, path, &directory);
385     if (status) {
386         ret = status;
387         goto DONE;
388     }
389     db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
390
391     /* If the directory is unchanged from our last scan and has no
392      * sub-directories, then return without scanning it at all.  In
393      * some situations, skipping the scan can substantially reduce the
394      * cost of notmuch new, especially since the huge numbers of files
395      * in Maildirs make scans expensive, but all files live in leaf
396      * directories.
397      *
398      * To check for sub-directories, we borrow a trick from find,
399      * kpathsea, and many other UNIX tools: since a directory's link
400      * count is the number of sub-directories (specifically, their
401      * '..' entries) plus 2 (the link from the parent and the link for
402      * '.').  This check is safe even on weird file systems, since
403      * file systems that can't compute this will return 0 or 1.  This
404      * is safe even on *really* weird file systems like HFS+ that
405      * mistakenly return the total number of directory entries, since
406      * that only inflates the count beyond 2.
407      */
408     if (directory && fs_mtime == db_mtime && st.st_nlink == 2) {
409         /* There's one catch: pass 1 below considers symlinks to
410          * directories to be directories, but these don't increase the
411          * file system link count.  So, only bail early if the
412          * database agrees that there are no sub-directories. */
413         db_subdirs = notmuch_directory_get_child_directories (directory);
414         if (!notmuch_filenames_valid (db_subdirs))
415             goto DONE;
416         notmuch_filenames_destroy (db_subdirs);
417         db_subdirs = NULL;
418     }
419
420     /* If the database knows about this directory, then we sort based
421      * on strcmp to match the database sorting. Otherwise, we can do
422      * inode-based sorting for faster filesystem operation. */
423     num_fs_entries = scandir (path, &fs_entries, 0,
424                               directory ?
425                               dirent_sort_strcmp_name : dirent_sort_inode);
426
427     if (num_fs_entries == -1) {
428         fprintf (stderr, "Error opening directory %s: %s\n",
429                  path, strerror (errno));
430         /* We consider this a fatal error because, if a user moved a
431          * message from another directory that we were able to scan
432          * into this directory, skipping this directory will cause
433          * that message to be lost. */
434         ret = NOTMUCH_STATUS_FILE_ERROR;
435         goto DONE;
436     }
437
438     /* Pass 1: Recurse into all sub-directories. */
439     is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
440
441     for (i = 0; i < num_fs_entries; i++) {
442         if (interrupted)
443             break;
444
445         entry = fs_entries[i];
446
447         /* Ignore any files/directories the user has configured to
448          * ignore.  We do this before dirent_type both for performance
449          * and because we don't care if dirent_type fails on entries
450          * that are explicitly ignored.
451          */
452         if (_entry_in_ignore_list (entry->d_name, state)) {
453             if (state->debug)
454                 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
455                         path, entry->d_name);
456             continue;
457         }
458
459         /* We only want to descend into directories (and symlinks to
460          * directories). */
461         entry_type = dirent_type (path, entry);
462         if (entry_type == -1) {
463             /* Be pessimistic, e.g. so we don't lose lots of mail just
464              * because a user broke a symlink. */
465             fprintf (stderr, "Error reading file %s/%s: %s\n",
466                      path, entry->d_name, strerror (errno));
467             return NOTMUCH_STATUS_FILE_ERROR;
468         } else if (entry_type != S_IFDIR) {
469             continue;
470         }
471
472         /* Ignore special directories to avoid infinite recursion.
473          * Also ignore the .notmuch directory and any "tmp" directory
474          * that appears within a maildir.
475          */
476         if (strcmp (entry->d_name, ".") == 0 ||
477             strcmp (entry->d_name, "..") == 0 ||
478             (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
479             strcmp (entry->d_name, ".notmuch") == 0)
480             continue;
481
482         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
483         status = add_files (notmuch, next, state);
484         if (status) {
485             ret = status;
486             goto DONE;
487         }
488         talloc_free (next);
489         next = NULL;
490     }
491
492     /* If the directory's modification time in the filesystem is the
493      * same as what we recorded in the database the last time we
494      * scanned it, then we can skip the second pass entirely.
495      *
496      * We test for strict equality here to avoid a bug that can happen
497      * if the system clock jumps backward, (preventing new mail from
498      * being discovered until the clock catches up and the directory
499      * is modified again).
500      */
501     if (directory && fs_mtime == db_mtime)
502         goto DONE;
503
504     /* If the database has never seen this directory before, we can
505      * simply leave db_files and db_subdirs NULL. */
506     if (directory) {
507         db_files = notmuch_directory_get_child_files (directory);
508         db_subdirs = notmuch_directory_get_child_directories (directory);
509     }
510
511     /* Pass 2: Scan for new files, removed files, and removed directories. */
512     for (i = 0; i < num_fs_entries; i++)
513     {
514         if (interrupted)
515             break;
516
517         entry = fs_entries[i];
518
519         /* Ignore files & directories user has configured to be ignored */
520         if (_entry_in_ignore_list (entry->d_name, state)) {
521             if (state->debug)
522                 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
523                         path, entry->d_name);
524             continue;
525         }
526
527         /* Check if we've walked past any names in db_files or
528          * db_subdirs. If so, these have been deleted. */
529         while (notmuch_filenames_valid (db_files) &&
530                strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
531         {
532             char *absolute = talloc_asprintf (state->removed_files,
533                                               "%s/%s", path,
534                                               notmuch_filenames_get (db_files));
535
536             if (state->debug)
537                 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
538                         absolute);
539
540             _filename_list_add (state->removed_files, absolute);
541
542             notmuch_filenames_move_to_next (db_files);
543         }
544
545         while (notmuch_filenames_valid (db_subdirs) &&
546                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
547         {
548             const char *filename = notmuch_filenames_get (db_subdirs);
549
550             if (strcmp (filename, entry->d_name) < 0)
551             {
552                 char *absolute = talloc_asprintf (state->removed_directories,
553                                                   "%s/%s", path, filename);
554                 if (state->debug)
555                     printf ("(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
556                         absolute);
557
558                 _filename_list_add (state->removed_directories, absolute);
559             }
560
561             notmuch_filenames_move_to_next (db_subdirs);
562         }
563
564         /* Only add regular files (and symlinks to regular files). */
565         entry_type = dirent_type (path, entry);
566         if (entry_type == -1) {
567             fprintf (stderr, "Error reading file %s/%s: %s\n",
568                      path, entry->d_name, strerror (errno));
569             return NOTMUCH_STATUS_FILE_ERROR;
570         } else if (entry_type != S_IFREG) {
571             continue;
572         }
573
574         /* Don't add a file that we've added before. */
575         if (notmuch_filenames_valid (db_files) &&
576             strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
577         {
578             notmuch_filenames_move_to_next (db_files);
579             continue;
580         }
581
582         /* We're now looking at a regular file that doesn't yet exist
583          * in the database, so add it. */
584         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
585
586         state->processed_files++;
587
588         if (state->verbosity >= VERBOSITY_VERBOSE) {
589             if (state->output_is_a_tty)
590                 printf("\r\033[K");
591
592             printf ("%i/%i: %s", state->processed_files, state->total_files,
593                     next);
594
595             putchar((state->output_is_a_tty) ? '\r' : '\n');
596             fflush (stdout);
597         }
598
599         status = add_file (notmuch, next, state);
600         if (status) {
601             ret = status;
602             goto DONE;
603         }
604
605         if (do_print_progress) {
606             do_print_progress = 0;
607             generic_print_progress ("Processed", "files", state->tv_start,
608                                     state->processed_files, state->total_files);
609         }
610
611         talloc_free (next);
612         next = NULL;
613     }
614
615     if (interrupted)
616         goto DONE;
617
618     /* Now that we've walked the whole filesystem list, anything left
619      * over in the database lists has been deleted. */
620     while (notmuch_filenames_valid (db_files))
621     {
622         char *absolute = talloc_asprintf (state->removed_files,
623                                           "%s/%s", path,
624                                           notmuch_filenames_get (db_files));
625         if (state->debug)
626             printf ("(D) add_files, pass 3: queuing leftover file %s for deletion from database\n",
627                     absolute);
628
629         _filename_list_add (state->removed_files, absolute);
630
631         notmuch_filenames_move_to_next (db_files);
632     }
633
634     while (notmuch_filenames_valid (db_subdirs))
635     {
636         char *absolute = talloc_asprintf (state->removed_directories,
637                                           "%s/%s", path,
638                                           notmuch_filenames_get (db_subdirs));
639
640         if (state->debug)
641             printf ("(D) add_files, pass 3: queuing leftover directory %s for deletion from database\n",
642                     absolute);
643
644         _filename_list_add (state->removed_directories, absolute);
645
646         notmuch_filenames_move_to_next (db_subdirs);
647     }
648
649     /* If the directory's mtime is the same as the wall-clock time
650      * when we stat'ed the directory, we skip updating the mtime in
651      * the database because a message could be delivered later in this
652      * same second.  This may lead to unnecessary re-scans, but it
653      * avoids overlooking messages. */
654     if (fs_mtime != stat_time)
655         _filename_list_add (state->directory_mtimes, path)->mtime = fs_mtime;
656
657   DONE:
658     if (next)
659         talloc_free (next);
660     if (fs_entries) {
661         for (i = 0; i < num_fs_entries; i++)
662             free (fs_entries[i]);
663
664         free (fs_entries);
665     }
666     if (db_subdirs)
667         notmuch_filenames_destroy (db_subdirs);
668     if (db_files)
669         notmuch_filenames_destroy (db_files);
670     if (directory)
671         notmuch_directory_destroy (directory);
672
673     return ret;
674 }
675
676 static void
677 setup_progress_printing_timer (void)
678 {
679     struct sigaction action;
680     struct itimerval timerval;
681
682     /* Set up our handler for SIGALRM */
683     memset (&action, 0, sizeof (struct sigaction));
684     action.sa_handler = handle_sigalrm;
685     sigemptyset (&action.sa_mask);
686     action.sa_flags = SA_RESTART;
687     sigaction (SIGALRM, &action, NULL);
688
689     /* Then start a timer to send SIGALRM once per second. */
690     timerval.it_interval.tv_sec = 1;
691     timerval.it_interval.tv_usec = 0;
692     timerval.it_value.tv_sec = 1;
693     timerval.it_value.tv_usec = 0;
694     setitimer (ITIMER_REAL, &timerval, NULL);
695 }
696
697 static void
698 stop_progress_printing_timer (void)
699 {
700     struct sigaction action;
701     struct itimerval timerval;
702
703     /* Now stop the timer. */
704     timerval.it_interval.tv_sec = 0;
705     timerval.it_interval.tv_usec = 0;
706     timerval.it_value.tv_sec = 0;
707     timerval.it_value.tv_usec = 0;
708     setitimer (ITIMER_REAL, &timerval, NULL);
709
710     /* And disable the signal handler. */
711     action.sa_handler = SIG_IGN;
712     sigaction (SIGALRM, &action, NULL);
713 }
714
715
716 /* XXX: This should be merged with the add_files function since it
717  * shares a lot of logic with it. */
718 /* Recursively count all regular files in path and all sub-directories
719  * of path.  The result is added to *count (which should be
720  * initialized to zero by the top-level caller before calling
721  * count_files). */
722 static void
723 count_files (const char *path, int *count, add_files_state_t *state)
724 {
725     struct dirent *entry = NULL;
726     char *next;
727     struct dirent **fs_entries = NULL;
728     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
729     int entry_type, i;
730
731     if (num_fs_entries == -1) {
732         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
733                  path, strerror (errno));
734         goto DONE;
735     }
736
737     for (i = 0; i < num_fs_entries && ! interrupted; i++) {
738         entry = fs_entries[i];
739
740         /* Ignore special directories to avoid infinite recursion.
741          * Also ignore the .notmuch directory.
742          */
743         if (strcmp (entry->d_name, ".") == 0 ||
744             strcmp (entry->d_name, "..") == 0 ||
745             strcmp (entry->d_name, ".notmuch") == 0)
746             continue;
747
748         /* Ignore any files/directories the user has configured to be
749          * ignored
750          */
751         if (_entry_in_ignore_list (entry->d_name, state)) {
752             if (state->debug)
753                 printf ("(D) count_files: explicitly ignoring %s/%s\n",
754                         path, entry->d_name);
755             continue;
756         }
757
758         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
759             next = NULL;
760             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
761                      path, entry->d_name);
762             continue;
763         }
764
765         entry_type = dirent_type (path, entry);
766         if (entry_type == S_IFREG) {
767             *count = *count + 1;
768             if (*count % 1000 == 0 && state->verbosity >= VERBOSITY_NORMAL) {
769                 printf ("Found %d files so far.\r", *count);
770                 fflush (stdout);
771             }
772         } else if (entry_type == S_IFDIR) {
773             count_files (next, count, state);
774         }
775
776         free (next);
777     }
778
779   DONE:
780     if (fs_entries) {
781         for (i = 0; i < num_fs_entries; i++)
782             free (fs_entries[i]);
783
784         free (fs_entries);
785     }
786 }
787
788 static void
789 upgrade_print_progress (void *closure,
790                         double progress)
791 {
792     add_files_state_t *state = closure;
793
794     printf ("Upgrading database: %.2f%% complete", progress * 100.0);
795
796     if (progress > 0) {
797         struct timeval tv_now;
798         double elapsed, time_remaining;
799
800         gettimeofday (&tv_now, NULL);
801
802         elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
803         time_remaining = (elapsed / progress) * (1.0 - progress);
804         printf (" (");
805         notmuch_time_print_formatted_seconds (time_remaining);
806         printf (" remaining)");
807     }
808
809     printf (".      \r");
810
811     fflush (stdout);
812 }
813
814 /* Remove one message filename from the database. */
815 static notmuch_status_t
816 remove_filename (notmuch_database_t *notmuch,
817                  const char *path,
818                  add_files_state_t *add_files_state)
819 {
820     notmuch_status_t status;
821     notmuch_message_t *message;
822     status = notmuch_database_begin_atomic (notmuch);
823     if (status)
824         return status;
825     status = notmuch_database_find_message_by_filename (notmuch, path, &message);
826     if (status || message == NULL)
827         goto DONE;
828
829     status = notmuch_database_remove_message (notmuch, path);
830     if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
831         add_files_state->renamed_messages++;
832         if (add_files_state->synchronize_flags == TRUE)
833             notmuch_message_maildir_flags_to_tags (message);
834         status = NOTMUCH_STATUS_SUCCESS;
835     } else if (status == NOTMUCH_STATUS_SUCCESS) {
836         add_files_state->removed_messages++;
837     }
838     notmuch_message_destroy (message);
839
840   DONE:
841     notmuch_database_end_atomic (notmuch);
842     return status;
843 }
844
845 /* Recursively remove all filenames from the database referring to
846  * 'path' (or to any of its children). */
847 static notmuch_status_t
848 _remove_directory (void *ctx,
849                    notmuch_database_t *notmuch,
850                    const char *path,
851                    add_files_state_t *add_files_state)
852 {
853     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
854     notmuch_directory_t *directory;
855     notmuch_filenames_t *files, *subdirs;
856     char *absolute;
857
858     status = notmuch_database_get_directory (notmuch, path, &directory);
859     if (status || !directory)
860         return status;
861
862     for (files = notmuch_directory_get_child_files (directory);
863          notmuch_filenames_valid (files);
864          notmuch_filenames_move_to_next (files))
865     {
866         absolute = talloc_asprintf (ctx, "%s/%s", path,
867                                     notmuch_filenames_get (files));
868         status = remove_filename (notmuch, absolute, add_files_state);
869         talloc_free (absolute);
870         if (status)
871             goto DONE;
872     }
873
874     for (subdirs = notmuch_directory_get_child_directories (directory);
875          notmuch_filenames_valid (subdirs);
876          notmuch_filenames_move_to_next (subdirs))
877     {
878         absolute = talloc_asprintf (ctx, "%s/%s", path,
879                                     notmuch_filenames_get (subdirs));
880         status = _remove_directory (ctx, notmuch, absolute, add_files_state);
881         talloc_free (absolute);
882         if (status)
883             goto DONE;
884     }
885
886     status = notmuch_directory_delete (directory);
887
888   DONE:
889     if (status)
890         notmuch_directory_destroy (directory);
891     return status;
892 }
893
894 static void
895 print_results (const add_files_state_t *state)
896 {
897     double elapsed;
898     struct timeval tv_now;
899
900     gettimeofday (&tv_now, NULL);
901     elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
902
903     if (state->processed_files) {
904         printf ("Processed %d %s in ", state->processed_files,
905                 state->processed_files == 1 ? "file" : "total files");
906         notmuch_time_print_formatted_seconds (elapsed);
907         if (elapsed > 1)
908             printf (" (%d files/sec.)",
909                     (int) (state->processed_files / elapsed));
910         printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
911     }
912
913     if (state->added_messages)
914         printf ("Added %d new %s to the database.", state->added_messages,
915                 state->added_messages == 1 ? "message" : "messages");
916     else
917         printf ("No new mail.");
918
919     if (state->removed_messages)
920         printf (" Removed %d %s.", state->removed_messages,
921                 state->removed_messages == 1 ? "message" : "messages");
922
923     if (state->renamed_messages)
924         printf (" Detected %d file %s.", state->renamed_messages,
925                 state->renamed_messages == 1 ? "rename" : "renames");
926
927     printf ("\n");
928 }
929
930 int
931 notmuch_new_command (notmuch_config_t *config, int argc, char *argv[])
932 {
933     notmuch_database_t *notmuch;
934     add_files_state_t add_files_state = {
935         .verbosity = VERBOSITY_NORMAL,
936         .debug = FALSE,
937         .output_is_a_tty = isatty (fileno (stdout)),
938     };
939     struct timeval tv_start;
940     int ret = 0;
941     struct stat st;
942     const char *db_path;
943     char *dot_notmuch_path;
944     struct sigaction action;
945     _filename_node_t *f;
946     int opt_index;
947     unsigned int i;
948     notmuch_bool_t timer_is_active = FALSE;
949     notmuch_bool_t no_hooks = FALSE;
950     notmuch_bool_t quiet = FALSE, verbose = FALSE;
951     notmuch_status_t status;
952
953     notmuch_opt_desc_t options[] = {
954         { NOTMUCH_OPT_BOOLEAN,  &quiet, "quiet", 'q', 0 },
955         { NOTMUCH_OPT_BOOLEAN,  &verbose, "verbose", 'v', 0 },
956         { NOTMUCH_OPT_BOOLEAN,  &add_files_state.debug, "debug", 'd', 0 },
957         { NOTMUCH_OPT_BOOLEAN,  &no_hooks, "no-hooks", 'n', 0 },
958         { NOTMUCH_OPT_INHERIT, (void *) &notmuch_shared_options, NULL, 0, 0 },
959         { 0, 0, 0, 0, 0 }
960     };
961
962     opt_index = parse_arguments (argc, argv, options, 1);
963     if (opt_index < 0)
964         return EXIT_FAILURE;
965
966     notmuch_process_shared_options (argv[0]);
967
968     /* quiet trumps verbose */
969     if (quiet)
970         add_files_state.verbosity = VERBOSITY_QUIET;
971     else if (verbose)
972         add_files_state.verbosity = VERBOSITY_VERBOSE;
973
974     add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
975     add_files_state.new_ignore = notmuch_config_get_new_ignore (config, &add_files_state.new_ignore_length);
976     add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
977     db_path = notmuch_config_get_database_path (config);
978
979     for (i = 0; i < add_files_state.new_tags_length; i++) {
980         const char *error_msg;
981
982         error_msg = illegal_tag (add_files_state.new_tags[i], FALSE);
983         if (error_msg) {
984             fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
985                      add_files_state.new_tags[i], error_msg);
986             return EXIT_FAILURE;
987         }
988     }
989
990     if (!no_hooks) {
991         ret = notmuch_run_hook (db_path, "pre-new");
992         if (ret)
993             return EXIT_FAILURE;
994     }
995
996     dot_notmuch_path = talloc_asprintf (config, "%s/%s", db_path, ".notmuch");
997
998     if (stat (dot_notmuch_path, &st)) {
999         int count;
1000
1001         count = 0;
1002         count_files (db_path, &count, &add_files_state);
1003         if (interrupted)
1004             return EXIT_FAILURE;
1005
1006         if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1007             printf ("Found %d total files (that's not much mail).\n", count);
1008         if (notmuch_database_create (db_path, &notmuch))
1009             return EXIT_FAILURE;
1010         add_files_state.total_files = count;
1011     } else {
1012         char *status_string = NULL;
1013         if (notmuch_database_open_verbose (db_path, NOTMUCH_DATABASE_MODE_READ_WRITE,
1014                                            &notmuch, &status_string)) {
1015             if (status_string) {
1016                 fputs (status_string, stderr);
1017                 free (status_string);
1018             }
1019             return EXIT_FAILURE;
1020         }
1021
1022         notmuch_exit_if_unmatched_db_uuid (notmuch);
1023
1024         if (notmuch_database_needs_upgrade (notmuch)) {
1025             time_t now = time (NULL);
1026             struct tm *gm_time = gmtime (&now);
1027
1028             /* since dump files are written atomically, the amount of
1029              * harm from overwriting one within a second seems
1030              * relatively small. */
1031
1032             const char *backup_name =
1033                 talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1034                                  dot_notmuch_path,
1035                                  gm_time->tm_year + 1900,
1036                                  gm_time->tm_mon + 1,
1037                                  gm_time->tm_mday,
1038                                  gm_time->tm_hour,
1039                                  gm_time->tm_min,
1040                                  gm_time->tm_sec);
1041
1042             if (add_files_state.verbosity >= VERBOSITY_NORMAL) {
1043                 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1044                 printf ("This process is safe to interrupt.\n");
1045                 printf ("Backing up tags to %s...\n", backup_name);
1046             }
1047
1048             if (notmuch_database_dump (notmuch, backup_name, "",
1049                                        DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, TRUE)) {
1050                 fprintf (stderr, "Backup failed. Aborting upgrade.");
1051                 return EXIT_FAILURE;
1052             }
1053
1054             gettimeofday (&add_files_state.tv_start, NULL);
1055             status = notmuch_database_upgrade (
1056                 notmuch,
1057                 add_files_state.verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1058                 &add_files_state);
1059             if (status) {
1060                 printf ("Upgrade failed: %s\n",
1061                         notmuch_status_to_string (status));
1062                 notmuch_database_destroy (notmuch);
1063                 return EXIT_FAILURE;
1064             }
1065             if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1066                 printf ("Your notmuch database has now been upgraded.\n");
1067         }
1068
1069         add_files_state.total_files = 0;
1070     }
1071
1072     if (notmuch == NULL)
1073         return EXIT_FAILURE;
1074
1075     /* Set up our handler for SIGINT. We do this after having
1076      * potentially done a database upgrade we this interrupt handler
1077      * won't support. */
1078     memset (&action, 0, sizeof (struct sigaction));
1079     action.sa_handler = handle_sigint;
1080     sigemptyset (&action.sa_mask);
1081     action.sa_flags = SA_RESTART;
1082     sigaction (SIGINT, &action, NULL);
1083
1084     talloc_free (dot_notmuch_path);
1085     dot_notmuch_path = NULL;
1086
1087     gettimeofday (&add_files_state.tv_start, NULL);
1088
1089     add_files_state.removed_files = _filename_list_create (config);
1090     add_files_state.removed_directories = _filename_list_create (config);
1091     add_files_state.directory_mtimes = _filename_list_create (config);
1092
1093     if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1094         add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1095         setup_progress_printing_timer ();
1096         timer_is_active = TRUE;
1097     }
1098
1099     ret = add_files (notmuch, db_path, &add_files_state);
1100     if (ret)
1101         goto DONE;
1102
1103     gettimeofday (&tv_start, NULL);
1104     for (f = add_files_state.removed_files->head; f && !interrupted; f = f->next) {
1105         ret = remove_filename (notmuch, f->filename, &add_files_state);
1106         if (ret)
1107             goto DONE;
1108         if (do_print_progress) {
1109             do_print_progress = 0;
1110             generic_print_progress ("Cleaned up", "messages",
1111                 tv_start, add_files_state.removed_messages + add_files_state.renamed_messages,
1112                 add_files_state.removed_files->count);
1113         }
1114     }
1115
1116     gettimeofday (&tv_start, NULL);
1117     for (f = add_files_state.removed_directories->head, i = 0; f && !interrupted; f = f->next, i++) {
1118         ret = _remove_directory (config, notmuch, f->filename, &add_files_state);
1119         if (ret)
1120             goto DONE;
1121         if (do_print_progress) {
1122             do_print_progress = 0;
1123             generic_print_progress ("Cleaned up", "directories",
1124                 tv_start, i,
1125                 add_files_state.removed_directories->count);
1126         }
1127     }
1128
1129     for (f = add_files_state.directory_mtimes->head; f && !interrupted; f = f->next) {
1130         notmuch_directory_t *directory;
1131         status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1132         if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1133             notmuch_directory_set_mtime (directory, f->mtime);
1134             notmuch_directory_destroy (directory);
1135         }
1136     }
1137
1138   DONE:
1139     talloc_free (add_files_state.removed_files);
1140     talloc_free (add_files_state.removed_directories);
1141     talloc_free (add_files_state.directory_mtimes);
1142
1143     if (timer_is_active)
1144         stop_progress_printing_timer ();
1145
1146     if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1147         print_results (&add_files_state);
1148
1149     if (ret)
1150         fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1151                  notmuch_status_to_string (ret));
1152
1153     notmuch_database_destroy (notmuch);
1154
1155     if (!no_hooks && !ret && !interrupted)
1156         ret = notmuch_run_hook (db_path, "post-new");
1157
1158     if (ret || interrupted)
1159         return EXIT_FAILURE;
1160
1161     if (add_files_state.vanished_files)
1162         return NOTMUCH_EXIT_TEMPFAIL;
1163
1164     return EXIT_SUCCESS;
1165 }