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