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