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