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