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