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