1 /* notmuch - Not much of an email program, (just index and search)
3 * Copyright © 2009 Carl Worth
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.
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.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see http://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "notmuch-client.h"
25 typedef struct _filename_node {
27 struct _filename_node *next;
30 typedef struct _filename_list {
31 _filename_node_t *head;
32 _filename_node_t **tail;
42 struct timeval tv_start;
44 _filename_list_t *removed_files;
45 _filename_list_t *removed_directories;
48 static volatile sig_atomic_t do_add_files_print_progress = 0;
51 handle_sigalrm (unused (int signal))
53 do_add_files_print_progress = 1;
56 static volatile sig_atomic_t interrupted;
59 handle_sigint (unused (int sig))
62 static char msg[] = "Stopping... \n";
64 ignored = write(2, msg, sizeof(msg)-1);
68 static _filename_list_t *
69 _filename_list_create (const void *ctx)
71 _filename_list_t *list;
73 list = talloc (ctx, _filename_list_t);
78 list->tail = &list->head;
84 _filename_list_add (_filename_list_t *list,
87 _filename_node_t *node = talloc (list, _filename_node_t);
89 node->filename = talloc_strdup (list, filename);
93 list->tail = &node->next;
97 tag_inbox_and_unread (notmuch_message_t *message)
99 notmuch_message_add_tag (message, "inbox");
100 notmuch_message_add_tag (message, "unread");
104 add_files_print_progress (add_files_state_t *state)
106 struct timeval tv_now;
107 double elapsed_overall, rate_overall;
109 gettimeofday (&tv_now, NULL);
111 elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
112 rate_overall = (state->processed_files) / elapsed_overall;
114 printf ("Processed %d", state->processed_files);
116 if (state->total_files) {
117 double time_remaining;
119 time_remaining = ((state->total_files - state->processed_files) /
121 printf (" of %d files (", state->total_files);
122 notmuch_time_print_formatted_seconds (time_remaining);
123 printf (" remaining). \r");
125 printf (" files (%d files/sec.) \r", (int) rate_overall);
132 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
134 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
138 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
140 return strcmp ((*a)->d_name, (*b)->d_name);
143 /* Test if the directory looks like a Maildir directory.
145 * Search through the array of directory entries to see if we can find all
146 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
148 * Return 1 if the directory looks like a Maildir and 0 otherwise.
151 _entries_resemble_maildir (struct dirent **entries, int count)
155 for (i = 0; i < count; i++) {
156 if (entries[i]->d_type != DT_DIR)
159 if (strcmp(entries[i]->d_name, "new") == 0 ||
160 strcmp(entries[i]->d_name, "cur") == 0 ||
161 strcmp(entries[i]->d_name, "tmp") == 0)
172 /* Examine 'path' recursively as follows:
174 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
175 * o Ask the database for its timestamp of 'path' (db_mtime)
177 * o Ask the filesystem for files and directories within 'path'
178 * (via scandir and stored in fs_entries)
179 * o Ask the database for files and directories within 'path'
180 * (db_files and db_subdirs)
182 * o Pass 1: For each directory in fs_entries, recursively call into
183 * this same function.
185 * o Pass 2: If 'fs_mtime' > 'db_mtime', then walk fs_entries
186 * simultaneously with db_files and db_subdirs. Look for one of
187 * three interesting cases:
189 * 1. Regular file in fs_entries and not in db_files
190 * This is a new file to add_message into the database.
192 * 2. Filename in db_files not in fs_entries.
193 * This is a file that has been removed from the mail store.
195 * 3. Directory in db_subdirs not in fs_entries
196 * This is a directory that has been removed from the mail store.
198 * Note that the addition of a directory is not interesting here,
199 * since that will have been taken care of in pass 1. Also, we
200 * don't immediately act on file/directory removal since we must
201 * ensure that in the case of a rename that the new filename is
202 * added before the old filename is removed, (so that no
203 * information is lost from the database).
205 * o Tell the database to update its time of 'path' to 'fs_mtime'
207 static notmuch_status_t
208 add_files_recursive (notmuch_database_t *notmuch,
210 add_files_state_t *state)
213 struct dirent *entry = NULL;
215 time_t fs_mtime, db_mtime;
216 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
217 notmuch_message_t *message = NULL;
218 struct dirent **fs_entries = NULL;
219 int i, num_fs_entries;
220 notmuch_directory_t *directory;
221 notmuch_filenames_t *db_files = NULL;
222 notmuch_filenames_t *db_subdirs = NULL;
224 notmuch_bool_t is_maildir, new_directory;
226 if (stat (path, &st)) {
227 fprintf (stderr, "Error reading directory %s: %s\n",
228 path, strerror (errno));
229 return NOTMUCH_STATUS_FILE_ERROR;
232 /* This is not an error since we may have recursed based on a
233 * symlink to a regular file, not a directory, and we don't know
234 * that until this stat. */
235 if (! S_ISDIR (st.st_mode))
236 return NOTMUCH_STATUS_SUCCESS;
238 fs_mtime = st.st_mtime;
240 directory = notmuch_database_get_directory (notmuch, path);
241 db_mtime = notmuch_directory_get_mtime (directory);
244 new_directory = TRUE;
248 new_directory = FALSE;
249 db_files = notmuch_directory_get_child_files (directory);
250 db_subdirs = notmuch_directory_get_child_directories (directory);
253 /* If the database knows about this directory, then we sort based
254 * on strcmp to match the database sorting. Otherwise, we can do
255 * inode-based sorting for faster filesystem operation. */
256 num_fs_entries = scandir (path, &fs_entries, 0,
258 dirent_sort_inode : dirent_sort_strcmp_name);
260 if (num_fs_entries == -1) {
261 fprintf (stderr, "Error opening directory %s: %s\n",
262 path, strerror (errno));
263 ret = NOTMUCH_STATUS_FILE_ERROR;
267 /* Pass 1: Recurse into all sub-directories. */
268 is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
270 for (i = 0; i < num_fs_entries; i++) {
274 entry = fs_entries[i];
276 if (entry->d_type != DT_DIR && entry->d_type != DT_LNK)
279 /* Ignore special directories to avoid infinite recursion.
280 * Also ignore the .notmuch directory and any "tmp" directory
281 * that appears within a maildir.
283 /* XXX: Eventually we'll want more sophistication to let the
284 * user specify files to be ignored. */
285 if (strcmp (entry->d_name, ".") == 0 ||
286 strcmp (entry->d_name, "..") == 0 ||
287 (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
288 strcmp (entry->d_name, ".notmuch") ==0)
293 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
294 status = add_files_recursive (notmuch, next, state);
295 if (status && ret == NOTMUCH_STATUS_SUCCESS)
301 /* If this directory hasn't been modified since the last
302 * "notmuch new", then we can skip the second pass entirely. */
303 if (fs_mtime <= db_mtime)
306 /* Pass 2: Scan for new files, removed files, and removed directories. */
307 for (i = 0; i < num_fs_entries; i++)
312 entry = fs_entries[i];
314 /* Check if we've walked past any names in db_files or
315 * db_subdirs. If so, these have been deleted. */
316 while (notmuch_filenames_has_more (db_files) &&
317 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
319 char *absolute = talloc_asprintf (state->removed_files,
321 notmuch_filenames_get (db_files));
323 _filename_list_add (state->removed_files, absolute);
325 notmuch_filenames_advance (db_files);
328 while (notmuch_filenames_has_more (db_subdirs) &&
329 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
331 const char *filename = notmuch_filenames_get (db_subdirs);
333 if (strcmp (filename, entry->d_name) < 0)
335 char *absolute = talloc_asprintf (state->removed_directories,
336 "%s/%s", path, filename);
338 _filename_list_add (state->removed_directories, absolute);
341 notmuch_filenames_advance (db_subdirs);
344 /* If we're looking at a symlink, we only want to add it if it
345 * links to a regular file, (and not to a directory, say). */
346 if (entry->d_type == DT_LNK) {
349 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
350 err = stat (next, &st);
354 /* Don't emit an error for a link pointing nowhere, since
355 * the directory-traversal pass will have already done
360 if (! S_ISREG (st.st_mode))
362 } else if (entry->d_type != DT_REG) {
366 /* Don't add a file that we've added before. */
367 if (notmuch_filenames_has_more (db_files) &&
368 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
370 notmuch_filenames_advance (db_files);
374 /* We're now looking at a regular file that doesn't yet exist
375 * in the database, so add it. */
376 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
378 state->processed_files++;
380 if (state->verbose) {
381 if (state->output_is_a_tty)
385 state->processed_files,
389 putchar((state->output_is_a_tty) ? '\r' : '\n');
393 status = notmuch_database_add_message (notmuch, next, &message);
396 case NOTMUCH_STATUS_SUCCESS:
397 state->added_messages++;
398 tag_inbox_and_unread (message);
400 /* Non-fatal issues (go on to next file) */
401 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
402 /* Stay silent on this one. */
404 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
405 fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
408 /* Fatal issues. Don't process anymore. */
409 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
410 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
411 case NOTMUCH_STATUS_OUT_OF_MEMORY:
412 fprintf (stderr, "Error: %s. Halting processing.\n",
413 notmuch_status_to_string (status));
417 case NOTMUCH_STATUS_FILE_ERROR:
418 case NOTMUCH_STATUS_NULL_POINTER:
419 case NOTMUCH_STATUS_TAG_TOO_LONG:
420 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
421 case NOTMUCH_STATUS_LAST_STATUS:
422 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
427 notmuch_message_destroy (message);
431 if (do_add_files_print_progress) {
432 do_add_files_print_progress = 0;
433 add_files_print_progress (state);
440 /* Now that we've walked the whole filesystem list, anything left
441 * over in the database lists has been deleted. */
442 while (notmuch_filenames_has_more (db_files))
444 char *absolute = talloc_asprintf (state->removed_files,
446 notmuch_filenames_get (db_files));
448 _filename_list_add (state->removed_files, absolute);
450 notmuch_filenames_advance (db_files);
453 while (notmuch_filenames_has_more (db_subdirs))
455 char *absolute = talloc_asprintf (state->removed_directories,
457 notmuch_filenames_get (db_subdirs));
459 _filename_list_add (state->removed_directories, absolute);
461 notmuch_filenames_advance (db_subdirs);
465 status = notmuch_directory_set_mtime (directory, fs_mtime);
466 if (status && ret == NOTMUCH_STATUS_SUCCESS)
480 notmuch_filenames_destroy (db_subdirs);
482 notmuch_filenames_destroy (db_files);
484 notmuch_directory_destroy (directory);
489 /* This is the top-level entry point for add_files. It does a couple
490 * of error checks, sets up the progress-printing timer and then calls
491 * into the recursive function. */
492 static notmuch_status_t
493 add_files (notmuch_database_t *notmuch,
495 add_files_state_t *state)
497 notmuch_status_t status;
498 struct sigaction action;
499 struct itimerval timerval;
500 notmuch_bool_t timer_is_active = FALSE;
503 if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
504 /* Setup our handler for SIGALRM */
505 memset (&action, 0, sizeof (struct sigaction));
506 action.sa_handler = handle_sigalrm;
507 sigemptyset (&action.sa_mask);
508 action.sa_flags = SA_RESTART;
509 sigaction (SIGALRM, &action, NULL);
511 /* Then start a timer to send SIGALRM once per second. */
512 timerval.it_interval.tv_sec = 1;
513 timerval.it_interval.tv_usec = 0;
514 timerval.it_value.tv_sec = 1;
515 timerval.it_value.tv_usec = 0;
516 setitimer (ITIMER_REAL, &timerval, NULL);
518 timer_is_active = TRUE;
521 if (stat (path, &st)) {
522 fprintf (stderr, "Error reading directory %s: %s\n",
523 path, strerror (errno));
524 return NOTMUCH_STATUS_FILE_ERROR;
527 if (! S_ISDIR (st.st_mode)) {
528 fprintf (stderr, "Error: %s is not a directory.\n", path);
529 return NOTMUCH_STATUS_FILE_ERROR;
532 status = add_files_recursive (notmuch, path, state);
534 if (timer_is_active) {
535 /* Now stop the timer. */
536 timerval.it_interval.tv_sec = 0;
537 timerval.it_interval.tv_usec = 0;
538 timerval.it_value.tv_sec = 0;
539 timerval.it_value.tv_usec = 0;
540 setitimer (ITIMER_REAL, &timerval, NULL);
542 /* And disable the signal handler. */
543 action.sa_handler = SIG_IGN;
544 sigaction (SIGALRM, &action, NULL);
550 /* XXX: This should be merged with the add_files function since it
551 * shares a lot of logic with it. */
552 /* Recursively count all regular files in path and all sub-directories
553 * of path. The result is added to *count (which should be
554 * initialized to zero by the top-level caller before calling
557 count_files (const char *path, int *count)
559 struct dirent *entry = NULL;
562 struct dirent **fs_entries = NULL;
563 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
566 if (num_fs_entries == -1) {
567 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
568 path, strerror (errno));
572 while (!interrupted) {
573 if (i == num_fs_entries)
576 entry = fs_entries[i++];
578 /* Ignore special directories to avoid infinite recursion.
579 * Also ignore the .notmuch directory.
581 /* XXX: Eventually we'll want more sophistication to let the
582 * user specify files to be ignored. */
583 if (strcmp (entry->d_name, ".") == 0 ||
584 strcmp (entry->d_name, "..") == 0 ||
585 strcmp (entry->d_name, ".notmuch") == 0)
590 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
592 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
593 path, entry->d_name);
599 if (S_ISREG (st.st_mode)) {
601 if (*count % 1000 == 0) {
602 printf ("Found %d files so far.\r", *count);
605 } else if (S_ISDIR (st.st_mode)) {
606 count_files (next, count);
620 upgrade_print_progress (void *closure,
623 add_files_state_t *state = closure;
625 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
628 struct timeval tv_now;
629 double elapsed, time_remaining;
631 gettimeofday (&tv_now, NULL);
633 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
634 time_remaining = (elapsed / progress) * (1.0 - progress);
636 notmuch_time_print_formatted_seconds (time_remaining);
637 printf (" remaining)");
645 /* Recursively remove all filenames from the database referring to
646 * 'path' (or to any of its children). */
648 _remove_directory (void *ctx,
649 notmuch_database_t *notmuch,
654 notmuch_directory_t *directory;
655 notmuch_filenames_t *files, *subdirs;
656 notmuch_status_t status;
659 directory = notmuch_database_get_directory (notmuch, path);
661 for (files = notmuch_directory_get_child_files (directory);
662 notmuch_filenames_has_more (files);
663 notmuch_filenames_advance (files))
665 absolute = talloc_asprintf (ctx, "%s/%s", path,
666 notmuch_filenames_get (files));
667 status = notmuch_database_remove_message (notmuch, absolute);
668 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
669 *renamed_files = *renamed_files + 1;
671 *removed_files = *removed_files + 1;
672 talloc_free (absolute);
675 for (subdirs = notmuch_directory_get_child_directories (directory);
676 notmuch_filenames_has_more (subdirs);
677 notmuch_filenames_advance (subdirs))
679 absolute = talloc_asprintf (ctx, "%s/%s", path,
680 notmuch_filenames_get (subdirs));
681 _remove_directory (ctx, notmuch, absolute, renamed_files, removed_files);
682 talloc_free (absolute);
685 notmuch_directory_destroy (directory);
689 notmuch_new_command (void *ctx, int argc, char *argv[])
691 notmuch_config_t *config;
692 notmuch_database_t *notmuch;
693 add_files_state_t add_files_state;
695 struct timeval tv_now;
699 char *dot_notmuch_path;
700 struct sigaction action;
702 int renamed_files, removed_files;
703 notmuch_status_t status;
706 add_files_state.verbose = 0;
707 add_files_state.output_is_a_tty = isatty (fileno (stdout));
709 for (i = 0; i < argc && argv[i][0] == '-'; i++) {
710 if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
711 add_files_state.verbose = 1;
713 fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
718 config = notmuch_config_open (ctx, NULL, NULL);
722 db_path = notmuch_config_get_database_path (config);
724 dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
726 if (stat (dot_notmuch_path, &st)) {
730 count_files (db_path, &count);
734 printf ("Found %d total files (that's not much mail).\n", count);
735 notmuch = notmuch_database_create (db_path);
736 add_files_state.total_files = count;
738 notmuch = notmuch_database_open (db_path,
739 NOTMUCH_DATABASE_MODE_READ_WRITE);
743 if (notmuch_database_needs_upgrade (notmuch)) {
744 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
745 gettimeofday (&add_files_state.tv_start, NULL);
746 notmuch_database_upgrade (notmuch, upgrade_print_progress,
748 printf ("Your notmuch database has now been upgraded to database format version %u.\n",
749 notmuch_database_get_version (notmuch));
752 add_files_state.total_files = 0;
758 /* Setup our handler for SIGINT. We do this after having
759 * potentially done a database upgrade we this interrupt handler
761 memset (&action, 0, sizeof (struct sigaction));
762 action.sa_handler = handle_sigint;
763 sigemptyset (&action.sa_mask);
764 action.sa_flags = SA_RESTART;
765 sigaction (SIGINT, &action, NULL);
767 talloc_free (dot_notmuch_path);
768 dot_notmuch_path = NULL;
770 add_files_state.processed_files = 0;
771 add_files_state.added_messages = 0;
772 gettimeofday (&add_files_state.tv_start, NULL);
774 add_files_state.removed_files = _filename_list_create (ctx);
775 add_files_state.removed_directories = _filename_list_create (ctx);
777 ret = add_files (notmuch, db_path, &add_files_state);
781 for (f = add_files_state.removed_files->head; f; f = f->next) {
782 status = notmuch_database_remove_message (notmuch, f->filename);
783 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
789 for (f = add_files_state.removed_directories->head; f; f = f->next) {
790 _remove_directory (ctx, notmuch, f->filename,
791 &renamed_files, &removed_files);
794 talloc_free (add_files_state.removed_files);
795 talloc_free (add_files_state.removed_directories);
797 gettimeofday (&tv_now, NULL);
798 elapsed = notmuch_time_elapsed (add_files_state.tv_start,
801 if (add_files_state.processed_files) {
802 printf ("Processed %d %s in ", add_files_state.processed_files,
803 add_files_state.processed_files == 1 ?
804 "file" : "total files");
805 notmuch_time_print_formatted_seconds (elapsed);
807 printf (" (%d files/sec.). \n",
808 (int) (add_files_state.processed_files / elapsed));
814 if (add_files_state.added_messages) {
815 printf ("Added %d new %s to the database.",
816 add_files_state.added_messages,
817 add_files_state.added_messages == 1 ?
818 "message" : "messages");
820 printf ("No new mail.");
824 printf (" Removed %d %s.",
826 removed_files == 1 ? "message" : "messages");
830 printf (" Detected %d file %s.",
832 renamed_files == 1 ? "rename" : "renames");
838 printf ("\nNote: At least one error was encountered: %s\n",
839 notmuch_status_to_string (ret));
842 notmuch_database_close (notmuch);
844 return ret || interrupted;