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