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