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;
38 const char **new_tags;
39 size_t new_tags_length;
44 struct timeval tv_start;
46 _filename_list_t *removed_files;
47 _filename_list_t *removed_directories;
49 notmuch_bool_t synchronize_flags;
50 _filename_list_t *message_ids_to_sync;
53 static volatile sig_atomic_t do_add_files_print_progress = 0;
56 handle_sigalrm (unused (int signal))
58 do_add_files_print_progress = 1;
61 static volatile sig_atomic_t interrupted;
64 handle_sigint (unused (int sig))
67 static char msg[] = "Stopping... \n";
69 ignored = write(2, msg, sizeof(msg)-1);
73 static _filename_list_t *
74 _filename_list_create (const void *ctx)
76 _filename_list_t *list;
78 list = talloc (ctx, _filename_list_t);
83 list->tail = &list->head;
89 _filename_list_add (_filename_list_t *list,
92 _filename_node_t *node = talloc (list, _filename_node_t);
94 node->filename = talloc_strdup (list, filename);
98 list->tail = &node->next;
102 add_files_print_progress (add_files_state_t *state)
104 struct timeval tv_now;
105 double elapsed_overall, rate_overall;
107 gettimeofday (&tv_now, NULL);
109 elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
110 rate_overall = (state->processed_files) / elapsed_overall;
112 printf ("Processed %d", state->processed_files);
114 if (state->total_files) {
115 double time_remaining;
117 time_remaining = ((state->total_files - state->processed_files) /
119 printf (" of %d files (", state->total_files);
120 notmuch_time_print_formatted_seconds (time_remaining);
121 printf (" remaining). \r");
123 printf (" files (%d files/sec.) \r", (int) rate_overall);
130 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
132 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
136 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
138 return strcmp ((*a)->d_name, (*b)->d_name);
141 /* Test if the directory looks like a Maildir directory.
143 * Search through the array of directory entries to see if we can find all
144 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
146 * Return 1 if the directory looks like a Maildir and 0 otherwise.
149 _entries_resemble_maildir (struct dirent **entries, int count)
153 for (i = 0; i < count; i++) {
154 if (entries[i]->d_type != DT_DIR && entries[i]->d_type != DT_UNKNOWN)
157 if (strcmp(entries[i]->d_name, "new") == 0 ||
158 strcmp(entries[i]->d_name, "cur") == 0 ||
159 strcmp(entries[i]->d_name, "tmp") == 0)
170 /* Examine 'path' recursively as follows:
172 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
173 * o Ask the database for its timestamp of 'path' (db_mtime)
175 * o Ask the filesystem for files and directories within 'path'
176 * (via scandir and stored in fs_entries)
177 * o Ask the database for files and directories within 'path'
178 * (db_files and db_subdirs)
180 * o Pass 1: For each directory in fs_entries, recursively call into
181 * this same function.
183 * o Pass 2: If 'fs_mtime' > 'db_mtime', then walk fs_entries
184 * simultaneously with db_files and db_subdirs. Look for one of
185 * three interesting cases:
187 * 1. Regular file in fs_entries and not in db_files
188 * This is a new file to add_message into the database.
190 * 2. Filename in db_files not in fs_entries.
191 * This is a file that has been removed from the mail store.
193 * 3. Directory in db_subdirs not in fs_entries
194 * This is a directory that has been removed from the mail store.
196 * Note that the addition of a directory is not interesting here,
197 * since that will have been taken care of in pass 1. Also, we
198 * don't immediately act on file/directory removal since we must
199 * ensure that in the case of a rename that the new filename is
200 * added before the old filename is removed, (so that no
201 * information is lost from the database).
203 * o Tell the database to update its time of 'path' to 'fs_mtime'
205 static notmuch_status_t
206 add_files_recursive (notmuch_database_t *notmuch,
208 add_files_state_t *state)
211 struct dirent *entry = NULL;
213 time_t fs_mtime, db_mtime;
214 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
215 notmuch_message_t *message = NULL;
216 struct dirent **fs_entries = NULL;
217 int i, num_fs_entries;
218 notmuch_directory_t *directory;
219 notmuch_filenames_t *db_files = NULL;
220 notmuch_filenames_t *db_subdirs = NULL;
222 notmuch_bool_t is_maildir, new_directory;
225 if (stat (path, &st)) {
226 fprintf (stderr, "Error reading directory %s: %s\n",
227 path, strerror (errno));
228 return NOTMUCH_STATUS_FILE_ERROR;
231 /* This is not an error since we may have recursed based on a
232 * symlink to a regular file, not a directory, and we don't know
233 * that until this stat. */
234 if (! S_ISDIR (st.st_mode))
235 return NOTMUCH_STATUS_SUCCESS;
237 fs_mtime = st.st_mtime;
239 directory = notmuch_database_get_directory (notmuch, path);
240 db_mtime = notmuch_directory_get_mtime (directory);
243 new_directory = TRUE;
247 new_directory = FALSE;
248 db_files = notmuch_directory_get_child_files (directory);
249 db_subdirs = notmuch_directory_get_child_directories (directory);
252 /* If the database knows about this directory, then we sort based
253 * on strcmp to match the database sorting. Otherwise, we can do
254 * inode-based sorting for faster filesystem operation. */
255 num_fs_entries = scandir (path, &fs_entries, 0,
257 dirent_sort_inode : dirent_sort_strcmp_name);
259 if (num_fs_entries == -1) {
260 fprintf (stderr, "Error opening directory %s: %s\n",
261 path, strerror (errno));
262 ret = NOTMUCH_STATUS_FILE_ERROR;
266 /* Pass 1: Recurse into all sub-directories. */
267 is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
269 for (i = 0; i < num_fs_entries; i++) {
273 entry = fs_entries[i];
275 /* We only want to descend into directories.
276 * But symlinks can be to directories too, of course.
278 * And if the filesystem doesn't tell us the file type in the
279 * scandir results, then it might be a directory (and if not,
280 * then we'll stat and return immediately in the next level of
282 if (entry->d_type != DT_DIR &&
283 entry->d_type != DT_LNK &&
284 entry->d_type != DT_UNKNOWN)
289 /* Ignore special directories to avoid infinite recursion.
290 * Also ignore the .notmuch directory and any "tmp" directory
291 * that appears within a maildir.
293 /* XXX: Eventually we'll want more sophistication to let the
294 * user specify files to be ignored. */
295 if (strcmp (entry->d_name, ".") == 0 ||
296 strcmp (entry->d_name, "..") == 0 ||
297 (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
298 strcmp (entry->d_name, ".notmuch") ==0)
303 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
304 status = add_files_recursive (notmuch, next, state);
305 if (status && ret == NOTMUCH_STATUS_SUCCESS)
311 /* If the directory's modification time in the filesystem is the
312 * same as what we recorded in the database the last time we
313 * scanned it, then we can skip the second pass entirely.
315 * We test for strict equality here to avoid a bug that can happen
316 * if the system clock jumps backward, (preventing new mail from
317 * being discovered until the clock catches up and the directory
318 * is modified again).
320 if (fs_mtime == db_mtime)
323 /* Pass 2: Scan for new files, removed files, and removed directories. */
324 for (i = 0; i < num_fs_entries; i++)
329 entry = fs_entries[i];
331 /* Check if we've walked past any names in db_files or
332 * db_subdirs. If so, these have been deleted. */
333 while (notmuch_filenames_valid (db_files) &&
334 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
336 char *absolute = talloc_asprintf (state->removed_files,
338 notmuch_filenames_get (db_files));
340 _filename_list_add (state->removed_files, absolute);
342 notmuch_filenames_move_to_next (db_files);
345 while (notmuch_filenames_valid (db_subdirs) &&
346 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
348 const char *filename = notmuch_filenames_get (db_subdirs);
350 if (strcmp (filename, entry->d_name) < 0)
352 char *absolute = talloc_asprintf (state->removed_directories,
353 "%s/%s", path, filename);
355 _filename_list_add (state->removed_directories, absolute);
358 notmuch_filenames_move_to_next (db_subdirs);
361 /* If we're looking at a symlink, we only want to add it if it
362 * links to a regular file, (and not to a directory, say).
364 * Similarly, if the file is of unknown type (due to filesytem
365 * limitations), then we also need to look closer.
367 * In either case, a stat does the trick.
369 if (entry->d_type == DT_LNK || entry->d_type == DT_UNKNOWN) {
372 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
373 err = stat (next, &st);
377 /* Don't emit an error for a link pointing nowhere, since
378 * the directory-traversal pass will have already done
383 if (! S_ISREG (st.st_mode))
385 } else if (entry->d_type != DT_REG) {
389 /* Don't add a file that we've added before. */
390 if (notmuch_filenames_valid (db_files) &&
391 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
393 notmuch_filenames_move_to_next (db_files);
397 /* We're now looking at a regular file that doesn't yet exist
398 * in the database, so add it. */
399 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
401 state->processed_files++;
403 if (state->verbose) {
404 if (state->output_is_a_tty)
408 state->processed_files,
412 putchar((state->output_is_a_tty) ? '\r' : '\n');
416 status = notmuch_database_add_message (notmuch, next, &message);
419 case NOTMUCH_STATUS_SUCCESS:
420 state->added_messages++;
421 for (tag=state->new_tags; *tag != NULL; tag++)
422 notmuch_message_add_tag (message, *tag);
423 /* Defer sync of maildir flags until after old filenames
424 * are removed in the case of a rename. */
425 if (state->synchronize_flags == TRUE)
426 _filename_list_add (state->message_ids_to_sync,
427 notmuch_message_get_message_id (message));
429 /* Non-fatal issues (go on to next file) */
430 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
431 /* Defer sync of maildir flags until after old filenames
432 * are removed in the case of a rename. */
433 if (state->synchronize_flags == TRUE)
434 _filename_list_add (state->message_ids_to_sync,
435 notmuch_message_get_message_id (message));
437 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
438 fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
441 /* Fatal issues. Don't process anymore. */
442 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
443 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
444 case NOTMUCH_STATUS_OUT_OF_MEMORY:
445 fprintf (stderr, "Error: %s. Halting processing.\n",
446 notmuch_status_to_string (status));
450 case NOTMUCH_STATUS_FILE_ERROR:
451 case NOTMUCH_STATUS_NULL_POINTER:
452 case NOTMUCH_STATUS_TAG_TOO_LONG:
453 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
454 case NOTMUCH_STATUS_LAST_STATUS:
455 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
460 notmuch_message_destroy (message);
464 if (do_add_files_print_progress) {
465 do_add_files_print_progress = 0;
466 add_files_print_progress (state);
476 /* Now that we've walked the whole filesystem list, anything left
477 * over in the database lists has been deleted. */
478 while (notmuch_filenames_valid (db_files))
480 char *absolute = talloc_asprintf (state->removed_files,
482 notmuch_filenames_get (db_files));
484 _filename_list_add (state->removed_files, absolute);
486 notmuch_filenames_move_to_next (db_files);
489 while (notmuch_filenames_valid (db_subdirs))
491 char *absolute = talloc_asprintf (state->removed_directories,
493 notmuch_filenames_get (db_subdirs));
495 _filename_list_add (state->removed_directories, absolute);
497 notmuch_filenames_move_to_next (db_subdirs);
501 status = notmuch_directory_set_mtime (directory, fs_mtime);
502 if (status && ret == NOTMUCH_STATUS_SUCCESS)
516 notmuch_filenames_destroy (db_subdirs);
518 notmuch_filenames_destroy (db_files);
520 notmuch_directory_destroy (directory);
525 /* This is the top-level entry point for add_files. It does a couple
526 * of error checks, sets up the progress-printing timer and then calls
527 * into the recursive function. */
528 static notmuch_status_t
529 add_files (notmuch_database_t *notmuch,
531 add_files_state_t *state)
533 notmuch_status_t status;
534 struct sigaction action;
535 struct itimerval timerval;
536 notmuch_bool_t timer_is_active = FALSE;
539 if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
540 /* Setup our handler for SIGALRM */
541 memset (&action, 0, sizeof (struct sigaction));
542 action.sa_handler = handle_sigalrm;
543 sigemptyset (&action.sa_mask);
544 action.sa_flags = SA_RESTART;
545 sigaction (SIGALRM, &action, NULL);
547 /* Then start a timer to send SIGALRM once per second. */
548 timerval.it_interval.tv_sec = 1;
549 timerval.it_interval.tv_usec = 0;
550 timerval.it_value.tv_sec = 1;
551 timerval.it_value.tv_usec = 0;
552 setitimer (ITIMER_REAL, &timerval, NULL);
554 timer_is_active = TRUE;
557 if (stat (path, &st)) {
558 fprintf (stderr, "Error reading directory %s: %s\n",
559 path, strerror (errno));
560 return NOTMUCH_STATUS_FILE_ERROR;
563 if (! S_ISDIR (st.st_mode)) {
564 fprintf (stderr, "Error: %s is not a directory.\n", path);
565 return NOTMUCH_STATUS_FILE_ERROR;
568 status = add_files_recursive (notmuch, path, state);
570 if (timer_is_active) {
571 /* Now stop the timer. */
572 timerval.it_interval.tv_sec = 0;
573 timerval.it_interval.tv_usec = 0;
574 timerval.it_value.tv_sec = 0;
575 timerval.it_value.tv_usec = 0;
576 setitimer (ITIMER_REAL, &timerval, NULL);
578 /* And disable the signal handler. */
579 action.sa_handler = SIG_IGN;
580 sigaction (SIGALRM, &action, NULL);
586 /* XXX: This should be merged with the add_files function since it
587 * shares a lot of logic with it. */
588 /* Recursively count all regular files in path and all sub-directories
589 * of path. The result is added to *count (which should be
590 * initialized to zero by the top-level caller before calling
593 count_files (const char *path, int *count)
595 struct dirent *entry = NULL;
598 struct dirent **fs_entries = NULL;
599 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
602 if (num_fs_entries == -1) {
603 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
604 path, strerror (errno));
608 while (!interrupted) {
609 if (i == num_fs_entries)
612 entry = fs_entries[i++];
614 /* Ignore special directories to avoid infinite recursion.
615 * Also ignore the .notmuch directory.
617 /* XXX: Eventually we'll want more sophistication to let the
618 * user specify files to be ignored. */
619 if (strcmp (entry->d_name, ".") == 0 ||
620 strcmp (entry->d_name, "..") == 0 ||
621 strcmp (entry->d_name, ".notmuch") == 0)
626 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
628 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
629 path, entry->d_name);
635 if (S_ISREG (st.st_mode)) {
637 if (*count % 1000 == 0) {
638 printf ("Found %d files so far.\r", *count);
641 } else if (S_ISDIR (st.st_mode)) {
642 count_files (next, count);
656 upgrade_print_progress (void *closure,
659 add_files_state_t *state = closure;
661 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
664 struct timeval tv_now;
665 double elapsed, time_remaining;
667 gettimeofday (&tv_now, NULL);
669 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
670 time_remaining = (elapsed / progress) * (1.0 - progress);
672 notmuch_time_print_formatted_seconds (time_remaining);
673 printf (" remaining)");
681 /* Recursively remove all filenames from the database referring to
682 * 'path' (or to any of its children). */
684 _remove_directory (void *ctx,
685 notmuch_database_t *notmuch,
690 notmuch_directory_t *directory;
691 notmuch_filenames_t *files, *subdirs;
692 notmuch_status_t status;
695 directory = notmuch_database_get_directory (notmuch, path);
697 for (files = notmuch_directory_get_child_files (directory);
698 notmuch_filenames_valid (files);
699 notmuch_filenames_move_to_next (files))
701 absolute = talloc_asprintf (ctx, "%s/%s", path,
702 notmuch_filenames_get (files));
703 status = notmuch_database_remove_message (notmuch, absolute);
704 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
705 *renamed_files = *renamed_files + 1;
707 *removed_files = *removed_files + 1;
708 talloc_free (absolute);
711 for (subdirs = notmuch_directory_get_child_directories (directory);
712 notmuch_filenames_valid (subdirs);
713 notmuch_filenames_move_to_next (subdirs))
715 absolute = talloc_asprintf (ctx, "%s/%s", path,
716 notmuch_filenames_get (subdirs));
717 _remove_directory (ctx, notmuch, absolute, renamed_files, removed_files);
718 talloc_free (absolute);
721 notmuch_directory_destroy (directory);
725 notmuch_new_command (void *ctx, int argc, char *argv[])
727 notmuch_config_t *config;
728 notmuch_database_t *notmuch;
729 add_files_state_t add_files_state;
731 struct timeval tv_now;
735 char *dot_notmuch_path;
736 struct sigaction action;
738 int renamed_files, removed_files;
739 notmuch_status_t status;
742 add_files_state.verbose = 0;
743 add_files_state.output_is_a_tty = isatty (fileno (stdout));
745 for (i = 0; i < argc && argv[i][0] == '-'; i++) {
746 if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
747 add_files_state.verbose = 1;
749 fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
754 config = notmuch_config_open (ctx, NULL, NULL);
758 add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
759 add_files_state.synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
760 add_files_state.message_ids_to_sync = _filename_list_create (ctx);
761 db_path = notmuch_config_get_database_path (config);
763 dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
765 if (stat (dot_notmuch_path, &st)) {
769 count_files (db_path, &count);
773 printf ("Found %d total files (that's not much mail).\n", count);
774 notmuch = notmuch_database_create (db_path);
775 add_files_state.total_files = count;
777 notmuch = notmuch_database_open (db_path,
778 NOTMUCH_DATABASE_MODE_READ_WRITE);
782 if (notmuch_database_needs_upgrade (notmuch)) {
783 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
784 gettimeofday (&add_files_state.tv_start, NULL);
785 notmuch_database_upgrade (notmuch, upgrade_print_progress,
787 printf ("Your notmuch database has now been upgraded to database format version %u.\n",
788 notmuch_database_get_version (notmuch));
791 add_files_state.total_files = 0;
797 /* Setup our handler for SIGINT. We do this after having
798 * potentially done a database upgrade we this interrupt handler
800 memset (&action, 0, sizeof (struct sigaction));
801 action.sa_handler = handle_sigint;
802 sigemptyset (&action.sa_mask);
803 action.sa_flags = SA_RESTART;
804 sigaction (SIGINT, &action, NULL);
806 talloc_free (dot_notmuch_path);
807 dot_notmuch_path = NULL;
809 add_files_state.processed_files = 0;
810 add_files_state.added_messages = 0;
811 gettimeofday (&add_files_state.tv_start, NULL);
813 add_files_state.removed_files = _filename_list_create (ctx);
814 add_files_state.removed_directories = _filename_list_create (ctx);
816 ret = add_files (notmuch, db_path, &add_files_state);
820 for (f = add_files_state.removed_files->head; f; f = f->next) {
821 status = notmuch_database_remove_message (notmuch, f->filename);
822 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
828 for (f = add_files_state.removed_directories->head; f; f = f->next) {
829 _remove_directory (ctx, notmuch, f->filename,
830 &renamed_files, &removed_files);
833 talloc_free (add_files_state.removed_files);
834 talloc_free (add_files_state.removed_directories);
836 /* Now that removals are done (hence the database is aware of all
837 * renames), we can synchronize maildir_flags to tags for all
838 * messages that had new filenames appear on this run. */
839 if (add_files_state.synchronize_flags) {
840 _filename_node_t *node;
841 notmuch_message_t *message;
842 for (node = add_files_state.message_ids_to_sync->head;
846 message = notmuch_database_find_message (notmuch, node->filename);
847 notmuch_message_maildir_flags_to_tags (message);
848 notmuch_message_destroy (message);
852 talloc_free (add_files_state.message_ids_to_sync);
853 add_files_state.message_ids_to_sync = NULL;
855 gettimeofday (&tv_now, NULL);
856 elapsed = notmuch_time_elapsed (add_files_state.tv_start,
859 if (add_files_state.processed_files) {
860 printf ("Processed %d %s in ", add_files_state.processed_files,
861 add_files_state.processed_files == 1 ?
862 "file" : "total files");
863 notmuch_time_print_formatted_seconds (elapsed);
865 printf (" (%d files/sec.). \n",
866 (int) (add_files_state.processed_files / elapsed));
872 if (add_files_state.added_messages) {
873 printf ("Added %d new %s to the database.",
874 add_files_state.added_messages,
875 add_files_state.added_messages == 1 ?
876 "message" : "messages");
878 printf ("No new mail.");
882 printf (" Removed %d %s.",
884 removed_files == 1 ? "message" : "messages");
888 printf (" Detected %d file %s.",
890 renamed_files == 1 ? "rename" : "renames");
896 printf ("\nNote: At least one error was encountered: %s\n",
897 notmuch_status_to_string (ret));
900 notmuch_database_close (notmuch);
902 return ret || interrupted;