]> 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     int output_is_a_tty;
49     enum verbosity verbosity;
50     bool debug;
51     bool full_scan;
52     notmuch_config_values_t *new_tags;
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     notmuch_bool_t 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             found++;
233             if (found == 3)
234                 return 1;
235         }
236     }
237
238     return 0;
239 }
240
241 static bool
242 _special_directory (const char *entry)
243 {
244     return strcmp (entry, ".") == 0 || strcmp (entry, "..") == 0;
245 }
246
247 static bool
248 _setup_ignore (notmuch_database_t *notmuch, add_files_state_t *state)
249 {
250     notmuch_config_values_t *ignore_list;
251     int nregex = 0, nverbatim = 0;
252     const char **verbatim = NULL;
253     regex_t *regex = NULL;
254
255     for (ignore_list = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_IGNORE);
256          notmuch_config_values_valid (ignore_list);
257          notmuch_config_values_move_to_next (ignore_list)) {
258         const char *s = notmuch_config_values_get (ignore_list);
259         size_t len = strlen (s);
260
261         if (len == 0) {
262             fprintf (stderr, "Error: Empty string in new.ignore list\n");
263             return false;
264         }
265
266         if (s[0] == '/') {
267             regex_t *preg;
268             char *r;
269             int rerr;
270
271             if (len < 3 || s[len - 1] != '/') {
272                 fprintf (stderr, "Error: Malformed pattern '%s' in new.ignore\n",
273                          s);
274                 return false;
275             }
276
277             r = talloc_strndup (notmuch, s + 1, len - 2);
278             regex = talloc_realloc (notmuch, regex, regex_t, nregex + 1);
279             preg = &regex[nregex];
280
281             rerr = regcomp (preg, r, REG_EXTENDED | REG_NOSUB);
282             if (rerr) {
283                 size_t error_size = regerror (rerr, preg, NULL, 0);
284                 char *error = talloc_size (r, error_size);
285
286                 regerror (rerr, preg, error, error_size);
287
288                 fprintf (stderr, "Error: Invalid regex '%s' in new.ignore: %s\n",
289                          r, error);
290                 return false;
291             }
292             nregex++;
293
294             talloc_free (r);
295         } else {
296             verbatim = talloc_realloc (notmuch, verbatim, const char *,
297                                        nverbatim + 1);
298             verbatim[nverbatim++] = s;
299         }
300     }
301
302     state->ignore_regex = regex;
303     state->ignore_regex_length = nregex;
304     state->ignore_verbatim = verbatim;
305     state->ignore_verbatim_length = nverbatim;
306
307     return true;
308 }
309
310 static char *
311 _get_relative_path (const char *mail_root, const char *dirpath, const char *entry)
312 {
313     size_t mail_root_len = strlen (mail_root);
314
315     /* paranoia? */
316     if (strncmp (dirpath, mail_root, mail_root_len) != 0) {
317         fprintf (stderr, "Warning: '%s' is not a subdirectory of '%s'\n",
318                  dirpath, mail_root);
319         return NULL;
320     }
321
322     dirpath += mail_root_len;
323     while (*dirpath == '/')
324         dirpath++;
325
326     if (*dirpath)
327         return talloc_asprintf (NULL, "%s/%s", dirpath, entry);
328     else
329         return talloc_strdup (NULL, entry);
330 }
331
332 /* Test if the file/directory is to be ignored.
333  */
334 static bool
335 _entry_in_ignore_list (add_files_state_t *state, const char *dirpath,
336                        const char *entry)
337 {
338     bool ret = false;
339     size_t i;
340     char *path;
341
342     for (i = 0; i < state->ignore_verbatim_length; i++) {
343         if (strcmp (entry, state->ignore_verbatim[i]) == 0)
344             return true;
345     }
346
347     if (state->ignore_regex_length == 0)
348         return false;
349
350     path = _get_relative_path (state->mail_root, dirpath, entry);
351     if (! path)
352         return false;
353
354     for (i = 0; i < state->ignore_regex_length; i++) {
355         if (regexec (&state->ignore_regex[i], path, 0, NULL, 0) == 0) {
356             ret = true;
357             break;
358         }
359     }
360
361     talloc_free (path);
362
363     return ret;
364 }
365
366 /* Add a single file to the database. */
367 static notmuch_status_t
368 add_file (notmuch_database_t *notmuch, const char *filename,
369           add_files_state_t *state)
370 {
371     notmuch_message_t *message = NULL;
372     const char *tag;
373     notmuch_status_t status;
374
375     status = notmuch_database_begin_atomic (notmuch);
376     if (status)
377         goto DONE;
378
379     status = notmuch_database_index_file (notmuch, filename, indexing_cli_choices.opts, &message);
380     switch (status) {
381     /* Success. */
382     case NOTMUCH_STATUS_SUCCESS:
383         state->added_messages++;
384         notmuch_message_freeze (message);
385         if (state->synchronize_flags)
386             notmuch_message_maildir_flags_to_tags (message);
387
388         for (notmuch_config_values_start (state->new_tags);
389              notmuch_config_values_valid (state->new_tags);
390              notmuch_config_values_move_to_next (state->new_tags)) {
391             notmuch_bool_t is_set;
392
393             tag = notmuch_config_values_get (state->new_tags);
394             /* Currently all errors from has_maildir_flag are fatal */
395             if ((status = notmuch_message_has_maildir_flag_st (message, 'S', &is_set)))
396                 goto DONE;
397             if (strcmp ("unread", tag) != 0 || ! is_set) {
398                 notmuch_message_add_tag (message, tag);
399             }
400         }
401
402         notmuch_message_thaw (message);
403         break;
404     /* Non-fatal issues (go on to next file). */
405     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
406         if (state->synchronize_flags)
407             notmuch_message_maildir_flags_to_tags (message);
408         break;
409     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
410         fprintf (stderr, "Note: Ignoring non-mail file: %s\n", filename);
411         break;
412     case NOTMUCH_STATUS_FILE_ERROR:
413         /* Someone renamed/removed the file between scandir and now. */
414         state->vanished_files++;
415         fprintf (stderr, "Unexpected error with file %s\n", filename);
416         (void) print_status_database ("add_file", notmuch, status);
417         break;
418     /* Fatal issues. Don't process anymore. */
419     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
420     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
421     case NOTMUCH_STATUS_OUT_OF_MEMORY:
422         (void) print_status_database ("add_file", notmuch, status);
423         goto DONE;
424     default:
425         INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
426         goto DONE;
427     }
428
429     status = notmuch_database_end_atomic (notmuch);
430
431   DONE:
432     if (message)
433         notmuch_message_destroy (message);
434
435     return status;
436 }
437
438 /* Examine 'path' recursively as follows:
439  *
440  *   o Ask the filesystem for the mtime of 'path' (fs_mtime)
441  *   o Ask the database for its timestamp of 'path' (db_mtime)
442  *
443  *   o Ask the filesystem for files and directories within 'path'
444  *     (via scandir and stored in fs_entries)
445  *
446  *   o Pass 1: For each directory in fs_entries, recursively call into
447  *     this same function.
448  *
449  *   o Compare fs_mtime to db_mtime. If they are equivalent, terminate
450  *     the algorithm at this point, (this directory has not been
451  *     updated in the filesystem since the last database scan of PASS
452  *     2).
453  *
454  *   o Ask the database for files and directories within 'path'
455  *     (db_files and db_subdirs)
456  *
457  *   o Pass 2: Walk fs_entries simultaneously with db_files and
458  *     db_subdirs. Look for one of three interesting cases:
459  *
460  *         1. Regular file in fs_entries and not in db_files
461  *            This is a new file to add_message into the database.
462  *
463  *         2. Filename in db_files not in fs_entries.
464  *            This is a file that has been removed from the mail store.
465  *
466  *         3. Directory in db_subdirs not in fs_entries
467  *            This is a directory that has been removed from the mail store.
468  *
469  *     Note that the addition of a directory is not interesting here,
470  *     since that will have been taken care of in pass 1. Also, we
471  *     don't immediately act on file/directory removal since we must
472  *     ensure that in the case of a rename that the new filename is
473  *     added before the old filename is removed, (so that no
474  *     information is lost from the database).
475  *
476  *   o Tell the database to update its time of 'path' to 'fs_mtime'
477  *     if fs_mtime isn't the current wall-clock time.
478  */
479 static notmuch_status_t
480 add_files (notmuch_database_t *notmuch,
481            const char *path,
482            add_files_state_t *state)
483 {
484     struct dirent *entry = NULL;
485     char *next = NULL;
486     time_t fs_mtime, db_mtime;
487     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
488     struct dirent **fs_entries = NULL;
489     int i, num_fs_entries = 0, entry_type;
490     notmuch_directory_t *directory;
491     notmuch_filenames_t *db_files = NULL;
492     notmuch_filenames_t *db_subdirs = NULL;
493     time_t stat_time;
494     struct stat st;
495     bool is_maildir;
496
497     if (stat (path, &st)) {
498         fprintf (stderr, "Error reading directory %s: %s\n",
499                  path, strerror (errno));
500         return NOTMUCH_STATUS_FILE_ERROR;
501     }
502     stat_time = time (NULL);
503
504     if (! S_ISDIR (st.st_mode)) {
505         fprintf (stderr, "Error: %s is not a directory.\n", path);
506         return NOTMUCH_STATUS_FILE_ERROR;
507     }
508
509     fs_mtime = st.st_mtime;
510
511     status = notmuch_database_get_directory (notmuch, path, &directory);
512     if (status) {
513         ret = status;
514         goto DONE;
515     }
516     db_mtime = directory ? notmuch_directory_get_mtime (directory) : 0;
517
518     /* If the directory is unchanged from our last scan and has no
519      * sub-directories, then return without scanning it at all.  In
520      * some situations, skipping the scan can substantially reduce the
521      * cost of notmuch new, especially since the huge numbers of files
522      * in Maildirs make scans expensive, but all files live in leaf
523      * directories.
524      *
525      * To check for sub-directories, we borrow a trick from find,
526      * kpathsea, and many other UNIX tools: since a directory's link
527      * count is the number of sub-directories (specifically, their
528      * '..' entries) plus 2 (the link from the parent and the link for
529      * '.').  This check is safe even on weird file systems, since
530      * file systems that can't compute this will return 0 or 1.  This
531      * is safe even on *really* weird file systems like HFS+ that
532      * mistakenly return the total number of directory entries, since
533      * that only inflates the count beyond 2.
534      */
535     if (directory && (! state->full_scan) && fs_mtime == db_mtime && st.st_nlink == 2) {
536         /* There's one catch: pass 1 below considers symlinks to
537          * directories to be directories, but these don't increase the
538          * file system link count.  So, only bail early if the
539          * database agrees that there are no sub-directories. */
540         db_subdirs = notmuch_directory_get_child_directories (directory);
541         if (! notmuch_filenames_valid (db_subdirs))
542             goto DONE;
543         notmuch_filenames_destroy (db_subdirs);
544         db_subdirs = NULL;
545     }
546
547     /* If the database knows about this directory, then we sort based
548      * on strcmp to match the database sorting. Otherwise, we can do
549      * inode-based sorting for faster filesystem operation. */
550     num_fs_entries = scandir (path, &fs_entries, 0,
551                               directory ?
552                               dirent_sort_strcmp_name : dirent_sort_inode);
553
554     if (num_fs_entries == -1) {
555         fprintf (stderr, "Error opening directory %s: %s\n",
556                  path, strerror (errno));
557         /* We consider this a fatal error because, if a user moved a
558          * message from another directory that we were able to scan
559          * into this directory, skipping this directory will cause
560          * that message to be lost. */
561         ret = NOTMUCH_STATUS_FILE_ERROR;
562         goto DONE;
563     }
564
565     /* Pass 1: Recurse into all sub-directories. */
566     is_maildir = _entries_resemble_maildir (path, fs_entries, num_fs_entries);
567
568     for (i = 0; i < num_fs_entries && ! interrupted; i++) {
569         entry = fs_entries[i];
570
571         /* Ignore special directories to avoid infinite recursion. */
572         if (_special_directory (entry->d_name))
573             continue;
574
575         /* Ignore any files/directories the user has configured to
576          * ignore.  We do this before dirent_type both for performance
577          * and because we don't care if dirent_type fails on entries
578          * that are explicitly ignored.
579          */
580         if (_entry_in_ignore_list (state, path, entry->d_name)) {
581             if (state->debug)
582                 printf ("(D) add_files, pass 1: explicitly ignoring %s/%s\n",
583                         path, entry->d_name);
584             continue;
585         }
586
587         /* We only want to descend into directories (and symlinks to
588          * directories). */
589         entry_type = dirent_type (path, entry);
590         if (entry_type == -1) {
591             /* Be pessimistic, e.g. so we don't lose lots of mail just
592              * because a user broke a symlink. */
593             fprintf (stderr, "Error reading file %s/%s: %s\n",
594                      path, entry->d_name, strerror (errno));
595             return NOTMUCH_STATUS_FILE_ERROR;
596         } else if (entry_type != S_IFDIR) {
597             continue;
598         }
599
600         /* Ignore the .notmuch directory and any "tmp" directory
601          * that appears within a maildir.
602          */
603         if ((is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
604             strcmp (entry->d_name, ".notmuch") == 0)
605             continue;
606
607         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
608         status = add_files (notmuch, next, state);
609         if (status) {
610             ret = status;
611             goto DONE;
612         }
613         talloc_free (next);
614         next = NULL;
615     }
616
617     /* If the directory's modification time in the filesystem is the
618      * same as what we recorded in the database the last time we
619      * scanned it, then we can skip the second pass entirely.
620      *
621      * We test for strict equality here to avoid a bug that can happen
622      * if the system clock jumps backward, (preventing new mail from
623      * being discovered until the clock catches up and the directory
624      * is modified again).
625      */
626     if (directory && (! state->full_scan) && fs_mtime == db_mtime)
627         goto DONE;
628
629     /* If the database has never seen this directory before, we can
630      * simply leave db_files and db_subdirs NULL. */
631     if (directory) {
632         db_files = notmuch_directory_get_child_files (directory);
633         db_subdirs = notmuch_directory_get_child_directories (directory);
634     }
635
636     /* Pass 2: Scan for new files, removed files, and removed directories. */
637     for (i = 0; i < num_fs_entries && ! interrupted; i++) {
638         entry = fs_entries[i];
639
640         /* Ignore special directories early. */
641         if (_special_directory (entry->d_name))
642             continue;
643
644         /* Ignore files & directories user has configured to be ignored */
645         if (_entry_in_ignore_list (state, path, entry->d_name)) {
646             if (state->debug)
647                 printf ("(D) add_files, pass 2: explicitly ignoring %s/%s\n",
648                         path, entry->d_name);
649             continue;
650         }
651
652         /* Check if we've walked past any names in db_files or
653          * db_subdirs. If so, these have been deleted. */
654         while (notmuch_filenames_valid (db_files) &&
655                strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0) {
656             char *absolute = talloc_asprintf (state->removed_files,
657                                               "%s/%s", path,
658                                               notmuch_filenames_get (db_files));
659
660             if (state->debug)
661                 printf ("(D) add_files, pass 2: queuing passed file %s for deletion from database\n",
662                         absolute);
663
664             _filename_list_add (state->removed_files, absolute);
665
666             notmuch_filenames_move_to_next (db_files);
667         }
668
669         while (notmuch_filenames_valid (db_subdirs) &&
670                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0) {
671             const char *filename = notmuch_filenames_get (db_subdirs);
672
673             if (strcmp (filename, entry->d_name) < 0) {
674                 char *absolute = talloc_asprintf (state->removed_directories,
675                                                   "%s/%s", path, filename);
676                 if (state->debug)
677                     printf (
678                         "(D) add_files, pass 2: queuing passed directory %s for deletion from database\n",
679                         absolute);
680
681                 _filename_list_add (state->removed_directories, absolute);
682             }
683
684             notmuch_filenames_move_to_next (db_subdirs);
685         }
686
687         /* Only add regular files (and symlinks to regular files). */
688         entry_type = dirent_type (path, entry);
689         if (entry_type == -1) {
690             fprintf (stderr, "Error reading file %s/%s: %s\n",
691                      path, entry->d_name, strerror (errno));
692             return NOTMUCH_STATUS_FILE_ERROR;
693         } else if (entry_type != S_IFREG) {
694             continue;
695         }
696
697         /* Don't add a file that we've added before. */
698         if (notmuch_filenames_valid (db_files) &&
699             strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0) {
700             notmuch_filenames_move_to_next (db_files);
701             continue;
702         }
703
704         /* We're now looking at a regular file that doesn't yet exist
705          * in the database, so add it. */
706         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
707
708         state->processed_files++;
709
710         if (state->verbosity >= VERBOSITY_VERBOSE) {
711             if (state->output_is_a_tty)
712                 printf ("\r\033[K");
713
714             printf ("%i/%i: %s", state->processed_files, state->total_files,
715                     next);
716
717             putchar ((state->output_is_a_tty) ? '\r' : '\n');
718             fflush (stdout);
719         }
720
721         status = add_file (notmuch, next, state);
722         if (status) {
723             ret = status;
724             goto DONE;
725         }
726
727         if (do_print_progress) {
728             do_print_progress = 0;
729             generic_print_progress ("Processed", "files", state->tv_start,
730                                     state->processed_files, state->total_files);
731         }
732
733         talloc_free (next);
734         next = NULL;
735     }
736
737     if (interrupted)
738         goto DONE;
739
740     /* Now that we've walked the whole filesystem list, anything left
741      * over in the database lists has been deleted. */
742     while (notmuch_filenames_valid (db_files)) {
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         char *absolute = talloc_asprintf (state->removed_directories,
757                                           "%s/%s", path,
758                                           notmuch_filenames_get (db_subdirs));
759
760         if (state->debug)
761             printf (
762                 "(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
943     status = notmuch_database_begin_atomic (notmuch);
944     if (status)
945         return status;
946     status = notmuch_database_find_message_by_filename (notmuch, path, &message);
947     if (status || message == NULL)
948         goto DONE;
949
950     status = notmuch_database_remove_message (notmuch, path);
951     if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
952         add_files_state->renamed_messages++;
953         if (add_files_state->synchronize_flags == true)
954             notmuch_message_maildir_flags_to_tags (message);
955         status = NOTMUCH_STATUS_SUCCESS;
956     } else if (status == NOTMUCH_STATUS_SUCCESS) {
957         add_files_state->removed_messages++;
958     }
959     notmuch_message_destroy (message);
960
961   DONE:
962     notmuch_database_end_atomic (notmuch);
963     return status;
964 }
965
966 /* Recursively remove all filenames from the database referring to
967  * 'path' (or to any of its children). */
968 static notmuch_status_t
969 _remove_directory (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         absolute = talloc_asprintf (notmuch, "%s/%s", path,
986                                     notmuch_filenames_get (files));
987         status = remove_filename (notmuch, absolute, add_files_state);
988         talloc_free (absolute);
989         if (status)
990             goto DONE;
991     }
992
993     for (subdirs = notmuch_directory_get_child_directories (directory);
994          notmuch_filenames_valid (subdirs);
995          notmuch_filenames_move_to_next (subdirs)) {
996         absolute = talloc_asprintf (notmuch, "%s/%s", path,
997                                     notmuch_filenames_get (subdirs));
998         status = _remove_directory (notmuch, absolute, add_files_state);
999         talloc_free (absolute);
1000         if (status)
1001             goto DONE;
1002     }
1003
1004     status = notmuch_directory_delete (directory);
1005
1006   DONE:
1007     if (status)
1008         notmuch_directory_destroy (directory);
1009     return status;
1010 }
1011
1012 static void
1013 print_results (const add_files_state_t *state)
1014 {
1015     double elapsed;
1016     struct timeval tv_now;
1017
1018     gettimeofday (&tv_now, NULL);
1019     elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
1020
1021     if (state->processed_files) {
1022         printf ("Processed %d %s in ", state->processed_files,
1023                 state->processed_files == 1 ? "file" : "total files");
1024         notmuch_time_print_formatted_seconds (elapsed);
1025         if (elapsed > 1)
1026             printf (" (%d files/sec.)",
1027                     (int) (state->processed_files / elapsed));
1028         printf (".%s\n", (state->output_is_a_tty) ? "\033[K" : "");
1029     }
1030
1031     if (state->added_messages)
1032         printf ("Added %d new %s to the database.", state->added_messages,
1033                 state->added_messages == 1 ? "message" : "messages");
1034     else
1035         printf ("No new mail.");
1036
1037     if (state->removed_messages)
1038         printf (" Removed %d %s.", state->removed_messages,
1039                 state->removed_messages == 1 ? "message" : "messages");
1040
1041     if (state->renamed_messages)
1042         printf (" Detected %d file %s.", state->renamed_messages,
1043                 state->renamed_messages == 1 ? "rename" : "renames");
1044
1045     printf ("\n");
1046 }
1047
1048 static int
1049 _maybe_upgrade (notmuch_database_t *notmuch, add_files_state_t *state)
1050 {
1051     if (notmuch_database_needs_upgrade (notmuch)) {
1052         time_t now = time (NULL);
1053         struct tm *gm_time = gmtime (&now);
1054         int err;
1055         notmuch_status_t status;
1056         const char *backup_dir = notmuch_config_get (notmuch, NOTMUCH_CONFIG_BACKUP_DIR);
1057         const char *backup_name;
1058
1059         err = mkdir (backup_dir, 0755);
1060         if (err && errno != EEXIST) {
1061             fprintf (stderr, "Failed to create %s: %s\n", backup_dir, strerror (errno));
1062             return EXIT_FAILURE;
1063         }
1064
1065         /* since dump files are written atomically, the amount of
1066          * harm from overwriting one within a second seems
1067          * relatively small. */
1068         backup_name = talloc_asprintf (notmuch, "%s/dump-%04d%02d%02dT%02d%02d%02d.gz",
1069                                        backup_dir,
1070                                        gm_time->tm_year + 1900,
1071                                        gm_time->tm_mon + 1,
1072                                        gm_time->tm_mday,
1073                                        gm_time->tm_hour,
1074                                        gm_time->tm_min,
1075                                        gm_time->tm_sec);
1076
1077         if (state->verbosity >= VERBOSITY_NORMAL) {
1078             printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
1079             printf ("This process is safe to interrupt.\n");
1080             printf ("Backing up tags to %s...\n", backup_name);
1081         }
1082
1083         if (notmuch_database_dump (notmuch, backup_name, "",
1084                                    DUMP_FORMAT_BATCH_TAG, DUMP_INCLUDE_DEFAULT, true)) {
1085             fprintf (stderr, "Backup failed. Aborting upgrade.");
1086             return EXIT_FAILURE;
1087         }
1088
1089         gettimeofday (&state->tv_start, NULL);
1090         status = notmuch_database_upgrade (
1091             notmuch,
1092             state->verbosity >= VERBOSITY_NORMAL ? upgrade_print_progress : NULL,
1093             state);
1094         if (status) {
1095             printf ("Upgrade failed: %s\n",
1096                     notmuch_status_to_string (status));
1097             notmuch_database_destroy (notmuch);
1098             return EXIT_FAILURE;
1099         }
1100         if (state->verbosity >= VERBOSITY_NORMAL)
1101             printf ("Your notmuch database has now been upgraded.\n");
1102     }
1103     return EXIT_SUCCESS;
1104 }
1105
1106 int
1107 notmuch_new_command (notmuch_database_t *notmuch, int argc, char *argv[])
1108 {
1109     add_files_state_t add_files_state = {
1110         .verbosity = VERBOSITY_NORMAL,
1111         .debug = false,
1112         .full_scan = false,
1113         .output_is_a_tty = isatty (fileno (stdout)),
1114     };
1115     struct timeval tv_start;
1116     int ret = 0;
1117     const char *db_path, *mail_root;
1118     struct sigaction action;
1119     _filename_node_t *f;
1120     int opt_index;
1121     unsigned int i;
1122     bool timer_is_active = false;
1123     bool hooks = true;
1124     bool quiet = false, verbose = false;
1125     notmuch_status_t status;
1126
1127     notmuch_opt_desc_t options[] = {
1128         { .opt_bool = &quiet, .name = "quiet" },
1129         { .opt_bool = &verbose, .name = "verbose" },
1130         { .opt_bool = &add_files_state.debug, .name = "debug" },
1131         { .opt_bool = &add_files_state.full_scan, .name = "full-scan" },
1132         { .opt_bool = &hooks, .name = "hooks" },
1133         { .opt_inherit = notmuch_shared_indexing_options },
1134         { .opt_inherit = notmuch_shared_options },
1135         { }
1136     };
1137
1138     opt_index = parse_arguments (argc, argv, options, 1);
1139     if (opt_index < 0)
1140         return EXIT_FAILURE;
1141
1142     notmuch_process_shared_options (argv[0]);
1143
1144     /* quiet trumps verbose */
1145     if (quiet)
1146         add_files_state.verbosity = VERBOSITY_QUIET;
1147     else if (verbose)
1148         add_files_state.verbosity = VERBOSITY_VERBOSE;
1149
1150     add_files_state.new_tags = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_TAGS);
1151
1152     if (print_status_database (
1153             "notmuch new",
1154             notmuch,
1155             notmuch_config_get_bool (notmuch, NOTMUCH_CONFIG_SYNC_MAILDIR_FLAGS,
1156                                      &add_files_state.synchronize_flags)))
1157         return EXIT_FAILURE;
1158
1159     db_path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
1160     add_files_state.db_path = db_path;
1161
1162     mail_root = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
1163     add_files_state.mail_root = mail_root;
1164
1165     if (! _setup_ignore (notmuch, &add_files_state))
1166         return EXIT_FAILURE;
1167
1168     for (notmuch_config_values_start (add_files_state.new_tags);
1169          notmuch_config_values_valid (add_files_state.new_tags);
1170          notmuch_config_values_move_to_next (add_files_state.new_tags)) {
1171         const char *tag, *error_msg;
1172
1173         tag = notmuch_config_values_get (add_files_state.new_tags);
1174         error_msg = illegal_tag (tag, false);
1175         if (error_msg) {
1176             fprintf (stderr, "Error: tag '%s' in new.tags: %s\n", tag, error_msg);
1177             return EXIT_FAILURE;
1178         }
1179     }
1180
1181     if (hooks) {
1182         /* Drop write lock to run hook */
1183         status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_ONLY);
1184         if (print_status_database ("notmuch new", notmuch, status))
1185             return EXIT_FAILURE;
1186
1187         ret = notmuch_run_hook (notmuch, "pre-new");
1188         if (ret)
1189             return EXIT_FAILURE;
1190
1191         /* acquire write lock again */
1192         status = notmuch_database_reopen (notmuch, NOTMUCH_DATABASE_MODE_READ_WRITE);
1193         if (print_status_database ("notmuch new", notmuch, status))
1194             return EXIT_FAILURE;
1195     }
1196
1197     notmuch_exit_if_unmatched_db_uuid (notmuch);
1198
1199     if (notmuch_database_get_revision (notmuch, NULL) == 0) {
1200         int count = 0;
1201         count_files (mail_root, &count, &add_files_state);
1202         if (interrupted)
1203             return EXIT_FAILURE;
1204
1205         if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1206             printf ("Found %d total files (that's not much mail).\n", count);
1207
1208         add_files_state.total_files = count;
1209     } else {
1210         if (_maybe_upgrade (notmuch, &add_files_state))
1211             return EXIT_FAILURE;
1212
1213         add_files_state.total_files = 0;
1214     }
1215
1216     if (notmuch == NULL)
1217         return EXIT_FAILURE;
1218
1219     status = notmuch_process_shared_indexing_options (notmuch);
1220     if (status != NOTMUCH_STATUS_SUCCESS) {
1221         fprintf (stderr, "Error: Failed to process index options. (%s)\n",
1222                  notmuch_status_to_string (status));
1223         return EXIT_FAILURE;
1224     }
1225
1226     /* Set up our handler for SIGINT. We do this after having
1227      * potentially done a database upgrade we this interrupt handler
1228      * won't support. */
1229     memset (&action, 0, sizeof (struct sigaction));
1230     action.sa_handler = handle_sigint;
1231     sigemptyset (&action.sa_mask);
1232     action.sa_flags = SA_RESTART;
1233     sigaction (SIGINT, &action, NULL);
1234
1235     gettimeofday (&add_files_state.tv_start, NULL);
1236
1237     add_files_state.removed_files = _filename_list_create (notmuch);
1238     add_files_state.removed_directories = _filename_list_create (notmuch);
1239     add_files_state.directory_mtimes = _filename_list_create (notmuch);
1240
1241     if (add_files_state.verbosity == VERBOSITY_NORMAL &&
1242         add_files_state.output_is_a_tty && ! debugger_is_active ()) {
1243         setup_progress_printing_timer ();
1244         timer_is_active = true;
1245     }
1246
1247     ret = add_files (notmuch, mail_root, &add_files_state);
1248     if (ret)
1249         goto DONE;
1250
1251     gettimeofday (&tv_start, NULL);
1252     for (f = add_files_state.removed_files->head; f && ! interrupted; f = f->next) {
1253         ret = remove_filename (notmuch, f->filename, &add_files_state);
1254         if (ret)
1255             goto DONE;
1256         if (do_print_progress) {
1257             do_print_progress = 0;
1258             generic_print_progress ("Cleaned up", "messages",
1259                                     tv_start, add_files_state.removed_messages +
1260                                     add_files_state.renamed_messages,
1261                                     add_files_state.removed_files->count);
1262         }
1263     }
1264
1265     gettimeofday (&tv_start, NULL);
1266     for (f = add_files_state.removed_directories->head, i = 0; f && ! interrupted; f = f->next, i++) {
1267         ret = _remove_directory (notmuch, f->filename, &add_files_state);
1268         if (ret)
1269             goto DONE;
1270         if (do_print_progress) {
1271             do_print_progress = 0;
1272             generic_print_progress ("Cleaned up", "directories",
1273                                     tv_start, i,
1274                                     add_files_state.removed_directories->count);
1275         }
1276     }
1277
1278     for (f = add_files_state.directory_mtimes->head; f && ! interrupted; f = f->next) {
1279         notmuch_directory_t *directory;
1280         status = notmuch_database_get_directory (notmuch, f->filename, &directory);
1281         if (status == NOTMUCH_STATUS_SUCCESS && directory) {
1282             notmuch_directory_set_mtime (directory, f->mtime);
1283             notmuch_directory_destroy (directory);
1284         }
1285     }
1286
1287   DONE:
1288     talloc_free (add_files_state.removed_files);
1289     talloc_free (add_files_state.removed_directories);
1290     talloc_free (add_files_state.directory_mtimes);
1291
1292     if (timer_is_active)
1293         stop_progress_printing_timer ();
1294
1295     if (add_files_state.verbosity >= VERBOSITY_NORMAL)
1296         print_results (&add_files_state);
1297
1298     if (ret)
1299         fprintf (stderr, "Note: A fatal error was encountered: %s\n",
1300                  notmuch_status_to_string (ret));
1301
1302     notmuch_database_close (notmuch);
1303
1304     if (hooks && ! ret && ! interrupted)
1305         ret = notmuch_run_hook (notmuch, "post-new");
1306
1307     notmuch_database_destroy (notmuch);
1308
1309     if (ret || interrupted)
1310         return EXIT_FAILURE;
1311
1312     if (add_files_state.vanished_files)
1313         return NOTMUCH_EXIT_TEMPFAIL;
1314
1315     return EXIT_SUCCESS;
1316 }