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;
48 notmuch_bool_t maildir_sync;
51 static volatile sig_atomic_t do_add_files_print_progress = 0;
54 handle_sigalrm (unused (int signal))
56 do_add_files_print_progress = 1;
59 static volatile sig_atomic_t interrupted;
62 handle_sigint (unused (int sig))
65 static char msg[] = "Stopping... \n";
67 ignored = write(2, msg, sizeof(msg)-1);
71 static _filename_list_t *
72 _filename_list_create (const void *ctx)
74 _filename_list_t *list;
76 list = talloc (ctx, _filename_list_t);
81 list->tail = &list->head;
87 _filename_list_add (_filename_list_t *list,
90 _filename_node_t *node = talloc (list, _filename_node_t);
92 node->filename = talloc_strdup (list, filename);
96 list->tail = &node->next;
100 add_files_print_progress (add_files_state_t *state)
102 struct timeval tv_now;
103 double elapsed_overall, rate_overall;
105 gettimeofday (&tv_now, NULL);
107 elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
108 rate_overall = (state->processed_files) / elapsed_overall;
110 printf ("Processed %d", state->processed_files);
112 if (state->total_files) {
113 double time_remaining;
115 time_remaining = ((state->total_files - state->processed_files) /
117 printf (" of %d files (", state->total_files);
118 notmuch_time_print_formatted_seconds (time_remaining);
119 printf (" remaining). \r");
121 printf (" files (%d files/sec.) \r", (int) rate_overall);
128 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
130 return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
134 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
136 return strcmp ((*a)->d_name, (*b)->d_name);
139 /* Test if the directory looks like a Maildir directory.
141 * Search through the array of directory entries to see if we can find all
142 * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
144 * Return 1 if the directory looks like a Maildir and 0 otherwise.
147 _entries_resemble_maildir (struct dirent **entries, int count)
151 for (i = 0; i < count; i++) {
152 if (entries[i]->d_type != DT_DIR && entries[i]->d_type != DT_UNKNOWN)
155 if (strcmp(entries[i]->d_name, "new") == 0 ||
156 strcmp(entries[i]->d_name, "cur") == 0 ||
157 strcmp(entries[i]->d_name, "tmp") == 0)
168 /* Examine 'path' recursively as follows:
170 * o Ask the filesystem for the mtime of 'path' (fs_mtime)
171 * o Ask the database for its timestamp of 'path' (db_mtime)
173 * o Ask the filesystem for files and directories within 'path'
174 * (via scandir and stored in fs_entries)
175 * o Ask the database for files and directories within 'path'
176 * (db_files and db_subdirs)
178 * o Pass 1: For each directory in fs_entries, recursively call into
179 * this same function.
181 * o Pass 2: If 'fs_mtime' > 'db_mtime', then walk fs_entries
182 * simultaneously with db_files and db_subdirs. Look for one of
183 * three interesting cases:
185 * 1. Regular file in fs_entries and not in db_files
186 * This is a new file to add_message into the database.
188 * 2. Filename in db_files not in fs_entries.
189 * This is a file that has been removed from the mail store.
191 * 3. Directory in db_subdirs not in fs_entries
192 * This is a directory that has been removed from the mail store.
194 * Note that the addition of a directory is not interesting here,
195 * since that will have been taken care of in pass 1. Also, we
196 * don't immediately act on file/directory removal since we must
197 * ensure that in the case of a rename that the new filename is
198 * added before the old filename is removed, (so that no
199 * information is lost from the database).
201 * o Tell the database to update its time of 'path' to 'fs_mtime'
203 static notmuch_status_t
204 add_files_recursive (notmuch_database_t *notmuch,
206 add_files_state_t *state)
209 struct dirent *entry = NULL;
211 time_t fs_mtime, db_mtime;
212 notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
213 notmuch_message_t *message = NULL;
214 struct dirent **fs_entries = NULL;
215 int i, num_fs_entries;
216 notmuch_directory_t *directory;
217 notmuch_filenames_t *db_files = NULL;
218 notmuch_filenames_t *db_subdirs = NULL;
220 notmuch_bool_t is_maildir, new_directory;
223 if (stat (path, &st)) {
224 fprintf (stderr, "Error reading directory %s: %s\n",
225 path, strerror (errno));
226 return NOTMUCH_STATUS_FILE_ERROR;
229 /* This is not an error since we may have recursed based on a
230 * symlink to a regular file, not a directory, and we don't know
231 * that until this stat. */
232 if (! S_ISDIR (st.st_mode))
233 return NOTMUCH_STATUS_SUCCESS;
235 fs_mtime = st.st_mtime;
237 directory = notmuch_database_get_directory (notmuch, path);
238 db_mtime = notmuch_directory_get_mtime (directory);
241 new_directory = TRUE;
245 new_directory = FALSE;
246 db_files = notmuch_directory_get_child_files (directory);
247 db_subdirs = notmuch_directory_get_child_directories (directory);
250 /* If the database knows about this directory, then we sort based
251 * on strcmp to match the database sorting. Otherwise, we can do
252 * inode-based sorting for faster filesystem operation. */
253 num_fs_entries = scandir (path, &fs_entries, 0,
255 dirent_sort_inode : dirent_sort_strcmp_name);
257 if (num_fs_entries == -1) {
258 fprintf (stderr, "Error opening directory %s: %s\n",
259 path, strerror (errno));
260 ret = NOTMUCH_STATUS_FILE_ERROR;
264 /* Pass 1: Recurse into all sub-directories. */
265 is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
267 for (i = 0; i < num_fs_entries; i++) {
271 entry = fs_entries[i];
273 /* We only want to descend into directories.
274 * But symlinks can be to directories too, of course.
276 * And if the filesystem doesn't tell us the file type in the
277 * scandir results, then it might be a directory (and if not,
278 * then we'll stat and return immediately in the next level of
280 if (entry->d_type != DT_DIR &&
281 entry->d_type != DT_LNK &&
282 entry->d_type != DT_UNKNOWN)
287 /* Ignore special directories to avoid infinite recursion.
288 * Also ignore the .notmuch directory and any "tmp" directory
289 * that appears within a maildir.
291 /* XXX: Eventually we'll want more sophistication to let the
292 * user specify files to be ignored. */
293 if (strcmp (entry->d_name, ".") == 0 ||
294 strcmp (entry->d_name, "..") == 0 ||
295 (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
296 strcmp (entry->d_name, ".notmuch") ==0)
301 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
302 status = add_files_recursive (notmuch, next, state);
303 if (status && ret == NOTMUCH_STATUS_SUCCESS)
309 /* If this directory hasn't been modified since the last
310 * "notmuch new", then we can skip the second pass entirely. */
311 if (fs_mtime <= db_mtime)
314 /* Pass 2: Scan for new files, removed files, and removed directories. */
315 for (i = 0; i < num_fs_entries; i++)
320 entry = fs_entries[i];
322 /* Check if we've walked past any names in db_files or
323 * db_subdirs. If so, these have been deleted. */
324 while (notmuch_filenames_valid (db_files) &&
325 strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
327 char *absolute = talloc_asprintf (state->removed_files,
329 notmuch_filenames_get (db_files));
331 _filename_list_add (state->removed_files, absolute);
333 notmuch_filenames_move_to_next (db_files);
336 while (notmuch_filenames_valid (db_subdirs) &&
337 strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
339 const char *filename = notmuch_filenames_get (db_subdirs);
341 if (strcmp (filename, entry->d_name) < 0)
343 char *absolute = talloc_asprintf (state->removed_directories,
344 "%s/%s", path, filename);
346 _filename_list_add (state->removed_directories, absolute);
349 notmuch_filenames_move_to_next (db_subdirs);
352 /* If we're looking at a symlink, we only want to add it if it
353 * links to a regular file, (and not to a directory, say).
355 * Similarly, if the file is of unknown type (due to filesytem
356 * limitations), then we also need to look closer.
358 * In either case, a stat does the trick.
360 if (entry->d_type == DT_LNK || entry->d_type == DT_UNKNOWN) {
363 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
364 err = stat (next, &st);
368 /* Don't emit an error for a link pointing nowhere, since
369 * the directory-traversal pass will have already done
374 if (! S_ISREG (st.st_mode))
376 } else if (entry->d_type != DT_REG) {
380 /* Don't add a file that we've added before. */
381 if (notmuch_filenames_valid (db_files) &&
382 strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
384 notmuch_filenames_move_to_next (db_files);
388 /* We're now looking at a regular file that doesn't yet exist
389 * in the database, so add it. */
390 next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
392 state->processed_files++;
394 if (state->verbose) {
395 if (state->output_is_a_tty)
399 state->processed_files,
403 putchar((state->output_is_a_tty) ? '\r' : '\n');
407 status = notmuch_database_add_message (notmuch, next, &message);
410 case NOTMUCH_STATUS_SUCCESS:
411 state->added_messages++;
412 for (tag=state->new_tags; *tag != NULL; tag++)
413 notmuch_message_add_tag (message, *tag);
414 if (state->maildir_sync == TRUE)
415 notmuch_message_maildir_to_tags (message, next);
417 /* Non-fatal issues (go on to next file) */
418 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
419 if (state->maildir_sync == TRUE)
420 notmuch_message_maildir_to_tags (message, next);
422 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
423 fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
426 /* Fatal issues. Don't process anymore. */
427 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
428 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
429 case NOTMUCH_STATUS_OUT_OF_MEMORY:
430 fprintf (stderr, "Error: %s. Halting processing.\n",
431 notmuch_status_to_string (status));
435 case NOTMUCH_STATUS_FILE_ERROR:
436 case NOTMUCH_STATUS_NULL_POINTER:
437 case NOTMUCH_STATUS_TAG_TOO_LONG:
438 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
439 case NOTMUCH_STATUS_LAST_STATUS:
440 INTERNAL_ERROR ("add_message returned unexpected value: %d", status);
445 notmuch_message_destroy (message);
449 if (do_add_files_print_progress) {
450 do_add_files_print_progress = 0;
451 add_files_print_progress (state);
461 /* Now that we've walked the whole filesystem list, anything left
462 * over in the database lists has been deleted. */
463 while (notmuch_filenames_valid (db_files))
465 char *absolute = talloc_asprintf (state->removed_files,
467 notmuch_filenames_get (db_files));
469 _filename_list_add (state->removed_files, absolute);
471 notmuch_filenames_move_to_next (db_files);
474 while (notmuch_filenames_valid (db_subdirs))
476 char *absolute = talloc_asprintf (state->removed_directories,
478 notmuch_filenames_get (db_subdirs));
480 _filename_list_add (state->removed_directories, absolute);
482 notmuch_filenames_move_to_next (db_subdirs);
486 status = notmuch_directory_set_mtime (directory, fs_mtime);
487 if (status && ret == NOTMUCH_STATUS_SUCCESS)
501 notmuch_filenames_destroy (db_subdirs);
503 notmuch_filenames_destroy (db_files);
505 notmuch_directory_destroy (directory);
510 /* This is the top-level entry point for add_files. It does a couple
511 * of error checks, sets up the progress-printing timer and then calls
512 * into the recursive function. */
513 static notmuch_status_t
514 add_files (notmuch_database_t *notmuch,
516 add_files_state_t *state)
518 notmuch_status_t status;
519 struct sigaction action;
520 struct itimerval timerval;
521 notmuch_bool_t timer_is_active = FALSE;
524 if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
525 /* Setup our handler for SIGALRM */
526 memset (&action, 0, sizeof (struct sigaction));
527 action.sa_handler = handle_sigalrm;
528 sigemptyset (&action.sa_mask);
529 action.sa_flags = SA_RESTART;
530 sigaction (SIGALRM, &action, NULL);
532 /* Then start a timer to send SIGALRM once per second. */
533 timerval.it_interval.tv_sec = 1;
534 timerval.it_interval.tv_usec = 0;
535 timerval.it_value.tv_sec = 1;
536 timerval.it_value.tv_usec = 0;
537 setitimer (ITIMER_REAL, &timerval, NULL);
539 timer_is_active = TRUE;
542 if (stat (path, &st)) {
543 fprintf (stderr, "Error reading directory %s: %s\n",
544 path, strerror (errno));
545 return NOTMUCH_STATUS_FILE_ERROR;
548 if (! S_ISDIR (st.st_mode)) {
549 fprintf (stderr, "Error: %s is not a directory.\n", path);
550 return NOTMUCH_STATUS_FILE_ERROR;
553 status = add_files_recursive (notmuch, path, state);
555 if (timer_is_active) {
556 /* Now stop the timer. */
557 timerval.it_interval.tv_sec = 0;
558 timerval.it_interval.tv_usec = 0;
559 timerval.it_value.tv_sec = 0;
560 timerval.it_value.tv_usec = 0;
561 setitimer (ITIMER_REAL, &timerval, NULL);
563 /* And disable the signal handler. */
564 action.sa_handler = SIG_IGN;
565 sigaction (SIGALRM, &action, NULL);
571 /* XXX: This should be merged with the add_files function since it
572 * shares a lot of logic with it. */
573 /* Recursively count all regular files in path and all sub-directories
574 * of path. The result is added to *count (which should be
575 * initialized to zero by the top-level caller before calling
578 count_files (const char *path, int *count)
580 struct dirent *entry = NULL;
583 struct dirent **fs_entries = NULL;
584 int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
587 if (num_fs_entries == -1) {
588 fprintf (stderr, "Warning: failed to open directory %s: %s\n",
589 path, strerror (errno));
593 while (!interrupted) {
594 if (i == num_fs_entries)
597 entry = fs_entries[i++];
599 /* Ignore special directories to avoid infinite recursion.
600 * Also ignore the .notmuch directory.
602 /* XXX: Eventually we'll want more sophistication to let the
603 * user specify files to be ignored. */
604 if (strcmp (entry->d_name, ".") == 0 ||
605 strcmp (entry->d_name, "..") == 0 ||
606 strcmp (entry->d_name, ".notmuch") == 0)
611 if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
613 fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
614 path, entry->d_name);
620 if (S_ISREG (st.st_mode)) {
622 if (*count % 1000 == 0) {
623 printf ("Found %d files so far.\r", *count);
626 } else if (S_ISDIR (st.st_mode)) {
627 count_files (next, count);
641 upgrade_print_progress (void *closure,
644 add_files_state_t *state = closure;
646 printf ("Upgrading database: %.2f%% complete", progress * 100.0);
649 struct timeval tv_now;
650 double elapsed, time_remaining;
652 gettimeofday (&tv_now, NULL);
654 elapsed = notmuch_time_elapsed (state->tv_start, tv_now);
655 time_remaining = (elapsed / progress) * (1.0 - progress);
657 notmuch_time_print_formatted_seconds (time_remaining);
658 printf (" remaining)");
666 /* Recursively remove all filenames from the database referring to
667 * 'path' (or to any of its children). */
669 _remove_directory (void *ctx,
670 notmuch_database_t *notmuch,
675 notmuch_directory_t *directory;
676 notmuch_filenames_t *files, *subdirs;
677 notmuch_status_t status;
680 directory = notmuch_database_get_directory (notmuch, path);
682 for (files = notmuch_directory_get_child_files (directory);
683 notmuch_filenames_valid (files);
684 notmuch_filenames_move_to_next (files))
686 absolute = talloc_asprintf (ctx, "%s/%s", path,
687 notmuch_filenames_get (files));
688 status = notmuch_database_remove_message (notmuch, absolute);
689 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
690 *renamed_files = *renamed_files + 1;
692 *removed_files = *removed_files + 1;
693 talloc_free (absolute);
696 for (subdirs = notmuch_directory_get_child_directories (directory);
697 notmuch_filenames_valid (subdirs);
698 notmuch_filenames_move_to_next (subdirs))
700 absolute = talloc_asprintf (ctx, "%s/%s", path,
701 notmuch_filenames_get (subdirs));
702 _remove_directory (ctx, notmuch, absolute, renamed_files, removed_files);
703 talloc_free (absolute);
706 notmuch_directory_destroy (directory);
710 notmuch_new_command (void *ctx, int argc, char *argv[])
712 notmuch_config_t *config;
713 notmuch_database_t *notmuch;
714 add_files_state_t add_files_state;
716 struct timeval tv_now;
720 char *dot_notmuch_path;
721 struct sigaction action;
723 int renamed_files, removed_files;
724 notmuch_status_t status;
727 add_files_state.verbose = 0;
728 add_files_state.output_is_a_tty = isatty (fileno (stdout));
730 for (i = 0; i < argc && argv[i][0] == '-'; i++) {
731 if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
732 add_files_state.verbose = 1;
734 fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
739 config = notmuch_config_open (ctx, NULL, NULL);
743 add_files_state.new_tags = notmuch_config_get_new_tags (config, &add_files_state.new_tags_length);
744 add_files_state.maildir_sync = notmuch_config_get_maildir_sync (config);
745 db_path = notmuch_config_get_database_path (config);
747 dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
749 if (stat (dot_notmuch_path, &st)) {
753 count_files (db_path, &count);
757 printf ("Found %d total files (that's not much mail).\n", count);
758 notmuch = notmuch_database_create (db_path);
759 add_files_state.total_files = count;
761 notmuch = notmuch_database_open (db_path,
762 NOTMUCH_DATABASE_MODE_READ_WRITE);
766 if (notmuch_database_needs_upgrade (notmuch)) {
767 printf ("Welcome to a new version of notmuch! Your database will now be upgraded.\n");
768 gettimeofday (&add_files_state.tv_start, NULL);
769 notmuch_database_upgrade (notmuch, upgrade_print_progress,
771 printf ("Your notmuch database has now been upgraded to database format version %u.\n",
772 notmuch_database_get_version (notmuch));
775 add_files_state.total_files = 0;
781 /* Setup our handler for SIGINT. We do this after having
782 * potentially done a database upgrade we this interrupt handler
784 memset (&action, 0, sizeof (struct sigaction));
785 action.sa_handler = handle_sigint;
786 sigemptyset (&action.sa_mask);
787 action.sa_flags = SA_RESTART;
788 sigaction (SIGINT, &action, NULL);
790 talloc_free (dot_notmuch_path);
791 dot_notmuch_path = NULL;
793 add_files_state.processed_files = 0;
794 add_files_state.added_messages = 0;
795 gettimeofday (&add_files_state.tv_start, NULL);
797 add_files_state.removed_files = _filename_list_create (ctx);
798 add_files_state.removed_directories = _filename_list_create (ctx);
800 ret = add_files (notmuch, db_path, &add_files_state);
804 for (f = add_files_state.removed_files->head; f; f = f->next) {
805 status = notmuch_database_remove_message (notmuch, f->filename);
806 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
812 for (f = add_files_state.removed_directories->head; f; f = f->next) {
813 _remove_directory (ctx, notmuch, f->filename,
814 &renamed_files, &removed_files);
817 talloc_free (add_files_state.removed_files);
818 talloc_free (add_files_state.removed_directories);
820 gettimeofday (&tv_now, NULL);
821 elapsed = notmuch_time_elapsed (add_files_state.tv_start,
824 if (add_files_state.processed_files) {
825 printf ("Processed %d %s in ", add_files_state.processed_files,
826 add_files_state.processed_files == 1 ?
827 "file" : "total files");
828 notmuch_time_print_formatted_seconds (elapsed);
830 printf (" (%d files/sec.). \n",
831 (int) (add_files_state.processed_files / elapsed));
837 if (add_files_state.added_messages) {
838 printf ("Added %d new %s to the database.",
839 add_files_state.added_messages,
840 add_files_state.added_messages == 1 ?
841 "message" : "messages");
843 printf ("No new mail.");
847 printf (" Removed %d %s.",
849 removed_files == 1 ? "message" : "messages");
853 printf (" Detected %d file %s.",
855 renamed_files == 1 ? "rename" : "renames");
861 printf ("\nNote: At least one error was encountered: %s\n",
862 notmuch_status_to_string (ret));
865 notmuch_database_close (notmuch);
867 return ret || interrupted;