1 /* database.cc - The database interfaces of the notmuch mail library
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 "database-private.h"
28 #include <glib.h> /* g_free, GPtrArray, GHashTable */
32 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
39 #define NOTMUCH_DATABASE_VERSION 1
41 #define STRINGIFY(s) _SUB_STRINGIFY(s)
42 #define _SUB_STRINGIFY(s) #s
44 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
46 * We currently have two different types of documents (mail and
47 * directory) and also some metadata.
51 * A mail document is associated with a particular email message file
52 * on disk. It is indexed with the following prefixed terms which the
53 * database uses to construct threads, etc.:
55 * Single terms of given prefix:
59 * id: Unique ID of mail. This is from the Message-ID header
60 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
61 * If it's present and too long, then we use
62 * "notmuch-sha1-<sha1_sum_of_message_id>".
63 * If this header is not present, we use
64 * "notmuch-sha1-<sha1_sum_of_entire_file>".
66 * thread: The ID of the thread to which the mail belongs
68 * replyto: The ID from the In-Reply-To header of the mail (if any).
70 * Multiple terms of given prefix:
72 * reference: All message IDs from In-Reply-To and Re ferences
73 * headers in the message.
75 * tag: Any tags associated with this message by the user.
77 * file-direntry: A colon-separated pair of values
78 * (INTEGER:STRING), where INTEGER is the
79 * document ID of a directory document, and
80 * STRING is the name of a file within that
81 * directory for this mail message.
83 * A mail document also has two values:
85 * TIMESTAMP: The time_t value corresponding to the message's
88 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
90 * In addition, terms from the content of the message are added with
91 * "from", "to", "attachment", and "subject" prefixes for use by the
92 * user in searching. Similarly, terms from the path of the mail
93 * message are added with a "folder" prefix. But the database doesn't
94 * really care itself about any of these.
96 * The data portion of a mail document is empty.
100 * A directory document is used by a client of the notmuch library to
101 * maintain data necessary to allow for efficient polling of mail
104 * All directory documents contain one term:
106 * directory: The directory path (relative to the database path)
107 * Or the SHA1 sum of the directory path (if the
108 * path itself is too long to fit in a Xapian
111 * And all directory documents for directories other than top-level
112 * directories also contain the following term:
114 * directory-direntry: A colon-separated pair of values
115 * (INTEGER:STRING), where INTEGER is the
116 * document ID of the parent directory
117 * document, and STRING is the name of this
118 * directory within that parent.
120 * All directory documents have a single value:
122 * TIMESTAMP: The mtime of the directory (at last scan)
124 * The data portion of a directory document contains the path of the
125 * directory (relative to the database path).
129 * Xapian allows us to store arbitrary name-value pairs as
130 * "metadata". We currently use the following metadata names with the
133 * version The database schema version, (which is distinct
134 * from both the notmuch package version (see
135 * notmuch --version) and the libnotmuch library
136 * version. The version is stored as an base-10
137 * ASCII integer. The initial database version
138 * was 1, (though a schema existed before that
139 * were no "version" database value existed at
140 * all). Succesive versions are allocated as
141 * changes are made to the database (such as by
142 * indexing new fields).
144 * last_thread_id The last thread ID generated. This is stored
145 * as a 16-byte hexadecimal ASCII representation
146 * of a 64-bit unsigned integer. The first ID
147 * generated is 1 and the value will be
148 * incremented for each thread ID.
150 * thread_id_* A pre-allocated thread ID for a particular
151 * message. This is actually an arbitarily large
152 * family of metadata name. Any particular name is
153 * formed by concatenating "thread_id_" with a message
154 * ID (or the SHA1 sum of a message ID if it is very
155 * long---see description of 'id' in the mail
156 * document). The value stored is a thread ID.
158 * These thread ID metadata values are stored
159 * whenever a message references a parent message
160 * that does not yet exist in the database. A
161 * thread ID will be allocated and stored, and if
162 * the message is later added, the stored thread
163 * ID will be used (and the metadata value will
166 * Even before a message is added, it's
167 * pre-allocated thread ID is useful so that all
168 * descendant messages that reference this common
169 * parent can be recognized as belonging to the
173 /* With these prefix values we follow the conventions published here:
175 * http://xapian.org/docs/omega/termprefixes.html
177 * as much as makes sense. Note that I took some liberty in matching
178 * the reserved prefix values to notmuch concepts, (for example, 'G'
179 * is documented as "newsGroup (or similar entity - e.g. a web forum
180 * name)", for which I think the thread is the closest analogue in
181 * notmuch. This in spite of the fact that we will eventually be
182 * storing mailing-list messages where 'G' for "mailing list name"
183 * might be even a closer analogue. I'm treating the single-character
184 * prefixes preferentially for core notmuch concepts (which will be
185 * nearly universal to all mail messages).
188 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
190 { "reference", "XREFERENCE" },
191 { "replyto", "XREPLYTO" },
192 { "directory", "XDIRECTORY" },
193 { "file-direntry", "XFDIRENTRY" },
194 { "directory-direntry", "XDDIRENTRY" },
197 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
204 static prefix_t PROBABILISTIC_PREFIX[]= {
207 { "attachment", "XATTACHMENT" },
208 { "subject", "XSUBJECT"},
209 { "folder", "XFOLDER"}
213 _internal_error (const char *format, ...)
217 va_start (va_args, format);
219 fprintf (stderr, "Internal error: ");
220 vfprintf (stderr, format, va_args);
228 _find_prefix (const char *name)
232 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
233 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
234 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
237 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
238 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
239 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
242 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
243 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
244 return PROBABILISTIC_PREFIX[i].prefix;
247 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
253 notmuch_status_to_string (notmuch_status_t status)
256 case NOTMUCH_STATUS_SUCCESS:
257 return "No error occurred";
258 case NOTMUCH_STATUS_OUT_OF_MEMORY:
259 return "Out of memory";
260 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
261 return "Attempt to write to a read-only database";
262 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
263 return "A Xapian exception occurred";
264 case NOTMUCH_STATUS_FILE_ERROR:
265 return "Something went wrong trying to read or write a file";
266 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
267 return "File is not an email";
268 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
269 return "Message ID is identical to a message in database";
270 case NOTMUCH_STATUS_NULL_POINTER:
271 return "Erroneous NULL pointer";
272 case NOTMUCH_STATUS_TAG_TOO_LONG:
273 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
274 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
275 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
277 case NOTMUCH_STATUS_LAST_STATUS:
278 return "Unknown error status value";
283 find_doc_ids_for_term (notmuch_database_t *notmuch,
285 Xapian::PostingIterator *begin,
286 Xapian::PostingIterator *end)
288 *begin = notmuch->xapian_db->postlist_begin (term);
290 *end = notmuch->xapian_db->postlist_end (term);
294 find_doc_ids (notmuch_database_t *notmuch,
295 const char *prefix_name,
297 Xapian::PostingIterator *begin,
298 Xapian::PostingIterator *end)
302 term = talloc_asprintf (notmuch, "%s%s",
303 _find_prefix (prefix_name), value);
305 find_doc_ids_for_term (notmuch, term, begin, end);
310 notmuch_private_status_t
311 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
312 const char *prefix_name,
314 unsigned int *doc_id)
316 Xapian::PostingIterator i, end;
318 find_doc_ids (notmuch, prefix_name, value, &i, &end);
322 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
327 #if DEBUG_DATABASE_SANITY
331 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
335 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
338 static Xapian::Document
339 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
341 return notmuch->xapian_db->get_document (doc_id);
344 /* Generate a compressed version of 'message_id' of the form:
346 * notmuch-sha1-<sha1_sum_of_message_id>
349 _message_id_compressed (void *ctx, const char *message_id)
351 char *sha1, *compressed;
353 sha1 = notmuch_sha1_of_string (message_id);
355 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
362 notmuch_database_find_message (notmuch_database_t *notmuch,
363 const char *message_id)
365 notmuch_private_status_t status;
368 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
369 message_id = _message_id_compressed (notmuch, message_id);
372 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
373 message_id, &doc_id);
375 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
378 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
379 } catch (const Xapian::Error &error) {
380 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
381 error.get_msg().c_str());
382 notmuch->exception_reported = TRUE;
387 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
388 * a (potentially nested) parenthesized sequence with '\' used to
389 * escape any character (including parentheses).
391 * If the sequence to be skipped continues to the end of the string,
392 * then 'str' will be left pointing at the final terminating '\0'
396 skip_space_and_comments (const char **str)
401 while (*s && (isspace (*s) || *s == '(')) {
402 while (*s && isspace (*s))
407 while (*s && nesting) {
410 } else if (*s == ')') {
412 } else if (*s == '\\') {
424 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
425 * comments, and the '<' and '>' delimeters.
427 * If not NULL, then *next will be made to point to the first character
428 * not parsed, (possibly pointing to the final '\0' terminator.
430 * Returns a newly talloc'ed string belonging to 'ctx'.
432 * Returns NULL if there is any error parsing the message-id. */
434 _parse_message_id (void *ctx, const char *message_id, const char **next)
439 if (message_id == NULL || *message_id == '\0')
444 skip_space_and_comments (&s);
446 /* Skip any unstructured text as well. */
447 while (*s && *s != '<')
458 skip_space_and_comments (&s);
461 while (*end && *end != '>')
470 if (end > s && *end == '>')
475 result = talloc_strndup (ctx, s, end - s + 1);
477 /* Finally, collapse any whitespace that is within the message-id
483 for (r = result, len = strlen (r); *r; r++, len--)
484 if (*r == ' ' || *r == '\t')
485 memmove (r, r+1, len);
491 /* Parse a References header value, putting a (talloc'ed under 'ctx')
492 * copy of each referenced message-id into 'hash'.
494 * We explicitly avoid including any reference identical to
495 * 'message_id' in the result (to avoid mass confusion when a single
496 * message references itself cyclically---and yes, mail messages are
497 * not infrequent in the wild that do this---don't ask me why).
500 parse_references (void *ctx,
501 const char *message_id,
507 if (refs == NULL || *refs == '\0')
511 ref = _parse_message_id (ctx, refs, &refs);
513 if (ref && strcmp (ref, message_id))
514 g_hash_table_insert (hash, ref, NULL);
519 notmuch_database_create (const char *path)
521 notmuch_database_t *notmuch = NULL;
522 char *notmuch_path = NULL;
527 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
531 err = stat (path, &st);
533 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
534 path, strerror (errno));
538 if (! S_ISDIR (st.st_mode)) {
539 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
544 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
546 err = mkdir (notmuch_path, 0755);
549 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
550 notmuch_path, strerror (errno));
554 notmuch = notmuch_database_open (path,
555 NOTMUCH_DATABASE_MODE_READ_WRITE);
556 notmuch_database_upgrade (notmuch, NULL, NULL);
560 talloc_free (notmuch_path);
566 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
568 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
569 fprintf (stderr, "Cannot write to a read-only database.\n");
570 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
573 return NOTMUCH_STATUS_SUCCESS;
577 notmuch_database_open (const char *path,
578 notmuch_database_mode_t mode)
580 notmuch_database_t *notmuch = NULL;
581 char *notmuch_path = NULL, *xapian_path = NULL;
584 unsigned int i, version;
586 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
588 fprintf (stderr, "Out of memory\n");
592 err = stat (notmuch_path, &st);
594 fprintf (stderr, "Error opening database at %s: %s\n",
595 notmuch_path, strerror (errno));
599 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
601 fprintf (stderr, "Out of memory\n");
605 notmuch = talloc (NULL, notmuch_database_t);
606 notmuch->exception_reported = FALSE;
607 notmuch->path = talloc_strdup (notmuch, path);
609 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
610 notmuch->path[strlen (notmuch->path) - 1] = '\0';
612 notmuch->needs_upgrade = FALSE;
613 notmuch->mode = mode;
615 string last_thread_id;
617 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
618 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
619 Xapian::DB_CREATE_OR_OPEN);
620 version = notmuch_database_get_version (notmuch);
622 if (version > NOTMUCH_DATABASE_VERSION) {
624 "Error: Notmuch database at %s\n"
625 " has a newer database format version (%u) than supported by this\n"
626 " version of notmuch (%u). Refusing to open this database in\n"
627 " read-write mode.\n",
628 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
629 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
630 notmuch_database_close (notmuch);
635 if (version < NOTMUCH_DATABASE_VERSION)
636 notmuch->needs_upgrade = TRUE;
638 notmuch->xapian_db = new Xapian::Database (xapian_path);
639 version = notmuch_database_get_version (notmuch);
640 if (version > NOTMUCH_DATABASE_VERSION)
643 "Warning: Notmuch database at %s\n"
644 " has a newer database format version (%u) than supported by this\n"
645 " version of notmuch (%u). Some operations may behave incorrectly,\n"
646 " (but the database will not be harmed since it is being opened\n"
647 " in read-only mode).\n",
648 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
652 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
653 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
654 if (last_thread_id.empty ()) {
655 notmuch->last_thread_id = 0;
660 str = last_thread_id.c_str ();
661 notmuch->last_thread_id = strtoull (str, &end, 16);
663 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
666 notmuch->query_parser = new Xapian::QueryParser;
667 notmuch->term_gen = new Xapian::TermGenerator;
668 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
669 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
671 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
672 notmuch->query_parser->set_database (*notmuch->xapian_db);
673 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
674 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
675 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
677 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
678 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
679 notmuch->query_parser->add_boolean_prefix (prefix->name,
683 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
684 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
685 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
687 } catch (const Xapian::Error &error) {
688 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
689 error.get_msg().c_str());
703 notmuch_database_close (notmuch_database_t *notmuch)
706 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
707 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
708 } catch (const Xapian::Error &error) {
709 if (! notmuch->exception_reported) {
710 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
711 error.get_msg().c_str());
715 delete notmuch->term_gen;
716 delete notmuch->query_parser;
717 delete notmuch->xapian_db;
718 delete notmuch->value_range_processor;
719 talloc_free (notmuch);
723 notmuch_database_get_path (notmuch_database_t *notmuch)
725 return notmuch->path;
729 notmuch_database_get_version (notmuch_database_t *notmuch)
731 unsigned int version;
732 string version_string;
736 version_string = notmuch->xapian_db->get_metadata ("version");
737 if (version_string.empty ())
740 str = version_string.c_str ();
741 if (str == NULL || *str == '\0')
744 version = strtoul (str, &end, 10);
746 INTERNAL_ERROR ("Malformed database version: %s", str);
752 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
754 return notmuch->needs_upgrade;
757 static volatile sig_atomic_t do_progress_notify = 0;
760 handle_sigalrm (unused (int signal))
762 do_progress_notify = 1;
765 /* Upgrade the current database.
767 * After opening a database in read-write mode, the client should
768 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
769 * if so, upgrade with this function before making any modifications.
771 * The optional progress_notify callback can be used by the caller to
772 * provide progress indication to the user. If non-NULL it will be
773 * called periodically with 'count' as the number of messages upgraded
774 * so far and 'total' the overall number of messages that will be
778 notmuch_database_upgrade (notmuch_database_t *notmuch,
779 void (*progress_notify) (void *closure,
783 Xapian::WritableDatabase *db;
784 struct sigaction action;
785 struct itimerval timerval;
786 notmuch_bool_t timer_is_active = FALSE;
787 unsigned int version;
788 notmuch_status_t status;
789 unsigned int count = 0, total = 0;
791 status = _notmuch_database_ensure_writable (notmuch);
795 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
797 version = notmuch_database_get_version (notmuch);
799 if (version >= NOTMUCH_DATABASE_VERSION)
800 return NOTMUCH_STATUS_SUCCESS;
802 if (progress_notify) {
803 /* Setup our handler for SIGALRM */
804 memset (&action, 0, sizeof (struct sigaction));
805 action.sa_handler = handle_sigalrm;
806 sigemptyset (&action.sa_mask);
807 action.sa_flags = SA_RESTART;
808 sigaction (SIGALRM, &action, NULL);
810 /* Then start a timer to send SIGALRM once per second. */
811 timerval.it_interval.tv_sec = 1;
812 timerval.it_interval.tv_usec = 0;
813 timerval.it_value.tv_sec = 1;
814 timerval.it_value.tv_usec = 0;
815 setitimer (ITIMER_REAL, &timerval, NULL);
817 timer_is_active = TRUE;
820 /* Before version 1, each message document had its filename in the
821 * data field. Copy that into the new format by calling
822 * notmuch_message_add_filename.
825 notmuch_query_t *query = notmuch_query_create (notmuch, "");
826 notmuch_messages_t *messages;
827 notmuch_message_t *message;
829 Xapian::TermIterator t, t_end;
831 total = notmuch_query_count_messages (query);
833 for (messages = notmuch_query_search_messages (query);
834 notmuch_messages_valid (messages);
835 notmuch_messages_move_to_next (messages))
837 if (do_progress_notify) {
838 progress_notify (closure, (double) count / total);
839 do_progress_notify = 0;
842 message = notmuch_messages_get (messages);
844 filename = _notmuch_message_talloc_copy_data (message);
845 if (filename && *filename != '\0') {
846 _notmuch_message_add_filename (message, filename);
847 _notmuch_message_sync (message);
849 talloc_free (filename);
851 notmuch_message_destroy (message);
856 notmuch_query_destroy (query);
858 /* Also, before version 1 we stored directory timestamps in
859 * XTIMESTAMP documents instead of the current XDIRECTORY
860 * documents. So copy those as well. */
862 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
864 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
868 Xapian::PostingIterator p, p_end;
869 std::string term = *t;
871 p_end = notmuch->xapian_db->postlist_end (term);
873 for (p = notmuch->xapian_db->postlist_begin (term);
877 Xapian::Document document;
879 notmuch_directory_t *directory;
881 if (do_progress_notify) {
882 progress_notify (closure, (double) count / total);
883 do_progress_notify = 0;
886 document = find_document_for_doc_id (notmuch, *p);
887 mtime = Xapian::sortable_unserialise (
888 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
890 directory = notmuch_database_get_directory (notmuch,
892 notmuch_directory_set_mtime (directory, mtime);
893 notmuch_directory_destroy (directory);
898 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
901 /* Now that the upgrade is complete we can remove the old data
902 * and documents that are no longer needed. */
904 notmuch_query_t *query = notmuch_query_create (notmuch, "");
905 notmuch_messages_t *messages;
906 notmuch_message_t *message;
909 for (messages = notmuch_query_search_messages (query);
910 notmuch_messages_valid (messages);
911 notmuch_messages_move_to_next (messages))
913 if (do_progress_notify) {
914 progress_notify (closure, (double) count / total);
915 do_progress_notify = 0;
918 message = notmuch_messages_get (messages);
920 filename = _notmuch_message_talloc_copy_data (message);
921 if (filename && *filename != '\0') {
922 _notmuch_message_clear_data (message);
923 _notmuch_message_sync (message);
925 talloc_free (filename);
927 notmuch_message_destroy (message);
930 notmuch_query_destroy (query);
934 Xapian::TermIterator t, t_end;
936 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
938 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
942 Xapian::PostingIterator p, p_end;
943 std::string term = *t;
945 p_end = notmuch->xapian_db->postlist_end (term);
947 for (p = notmuch->xapian_db->postlist_begin (term);
951 if (do_progress_notify) {
952 progress_notify (closure, (double) count / total);
953 do_progress_notify = 0;
956 db->delete_document (*p);
961 if (timer_is_active) {
962 /* Now stop the timer. */
963 timerval.it_interval.tv_sec = 0;
964 timerval.it_interval.tv_usec = 0;
965 timerval.it_value.tv_sec = 0;
966 timerval.it_value.tv_usec = 0;
967 setitimer (ITIMER_REAL, &timerval, NULL);
969 /* And disable the signal handler. */
970 action.sa_handler = SIG_IGN;
971 sigaction (SIGALRM, &action, NULL);
974 return NOTMUCH_STATUS_SUCCESS;
977 /* We allow the user to use arbitrarily long paths for directories. But
978 * we have a term-length limit. So if we exceed that, we'll use the
979 * SHA-1 of the path for the database term.
981 * Note: This function may return the original value of 'path'. If it
982 * does not, then the caller is responsible to free() the returned
986 _notmuch_database_get_directory_db_path (const char *path)
988 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
990 if (term_len > NOTMUCH_TERM_MAX)
991 return notmuch_sha1_of_string (path);
996 /* Given a path, split it into two parts: the directory part is all
997 * components except for the last, and the basename is that last
998 * component. Getting the return-value for either part is optional
999 * (the caller can pass NULL).
1001 * The original 'path' can represent either a regular file or a
1002 * directory---the splitting will be carried out in the same way in
1003 * either case. Trailing slashes on 'path' will be ignored, and any
1004 * cases of multiple '/' characters appearing in series will be
1005 * treated as a single '/'.
1007 * Allocation (if any) will have 'ctx' as the talloc owner. But
1008 * pointers will be returned within the original path string whenever
1011 * Note: If 'path' is non-empty and contains no non-trailing slash,
1012 * (that is, consists of a filename with no parent directory), then
1013 * the directory returned will be an empty string. However, if 'path'
1014 * is an empty string, then both directory and basename will be
1018 _notmuch_database_split_path (void *ctx,
1020 const char **directory,
1021 const char **basename)
1025 if (path == NULL || *path == '\0') {
1030 return NOTMUCH_STATUS_SUCCESS;
1033 /* Find the last slash (not counting a trailing slash), if any. */
1035 slash = path + strlen (path) - 1;
1037 /* First, skip trailing slashes. */
1038 while (slash != path) {
1045 /* Then, find a slash. */
1046 while (slash != path) {
1056 /* Finally, skip multiple slashes. */
1057 while (slash != path) {
1064 if (slash == path) {
1066 *directory = talloc_strdup (ctx, "");
1071 *directory = talloc_strndup (ctx, path, slash - path + 1);
1074 return NOTMUCH_STATUS_SUCCESS;
1078 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1080 unsigned int *directory_id)
1082 notmuch_directory_t *directory;
1083 notmuch_status_t status;
1087 return NOTMUCH_STATUS_SUCCESS;
1090 directory = _notmuch_directory_create (notmuch, path, &status);
1096 *directory_id = _notmuch_directory_get_document_id (directory);
1098 notmuch_directory_destroy (directory);
1100 return NOTMUCH_STATUS_SUCCESS;
1104 _notmuch_database_get_directory_path (void *ctx,
1105 notmuch_database_t *notmuch,
1106 unsigned int doc_id)
1108 Xapian::Document document;
1110 document = find_document_for_doc_id (notmuch, doc_id);
1112 return talloc_strdup (ctx, document.get_data ().c_str ());
1115 /* Given a legal 'filename' for the database, (either relative to
1116 * database path or absolute with initial components identical to
1117 * database path), return a new string (with 'ctx' as the talloc
1118 * owner) suitable for use as a direntry term value.
1120 * The necessary directory documents will be created in the database
1124 _notmuch_database_filename_to_direntry (void *ctx,
1125 notmuch_database_t *notmuch,
1126 const char *filename,
1129 const char *relative, *directory, *basename;
1130 Xapian::docid directory_id;
1131 notmuch_status_t status;
1133 relative = _notmuch_database_relative_path (notmuch, filename);
1135 status = _notmuch_database_split_path (ctx, relative,
1136 &directory, &basename);
1140 status = _notmuch_database_find_directory_id (notmuch, directory,
1145 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1147 return NOTMUCH_STATUS_SUCCESS;
1150 /* Given a legal 'path' for the database, return the relative path.
1152 * The return value will be a pointer to the originl path contents,
1153 * and will be either the original string (if 'path' was relative) or
1154 * a portion of the string (if path was absolute and begins with the
1158 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1161 const char *db_path, *relative;
1162 unsigned int db_path_len;
1164 db_path = notmuch_database_get_path (notmuch);
1165 db_path_len = strlen (db_path);
1169 if (*relative == '/') {
1170 while (*relative == '/' && *(relative+1) == '/')
1173 if (strncmp (relative, db_path, db_path_len) == 0)
1175 relative += db_path_len;
1176 while (*relative == '/')
1184 notmuch_directory_t *
1185 notmuch_database_get_directory (notmuch_database_t *notmuch,
1188 notmuch_status_t status;
1191 return _notmuch_directory_create (notmuch, path, &status);
1192 } catch (const Xapian::Error &error) {
1193 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1194 error.get_msg().c_str());
1195 notmuch->exception_reported = TRUE;
1200 /* Allocate a document ID that satisfies the following criteria:
1202 * 1. The ID does not exist for any document in the Xapian database
1204 * 2. The ID was not previously returned from this function
1206 * 3. The ID is the smallest integer satisfying (1) and (2)
1208 * This function will trigger an internal error if these constraints
1209 * cannot all be satisfied, (that is, the pool of available document
1210 * IDs has been exhausted).
1213 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1215 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1217 notmuch->last_doc_id++;
1219 if (notmuch->last_doc_id == 0)
1220 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1222 return notmuch->last_doc_id;
1226 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1228 /* 16 bytes (+ terminator) for hexadecimal representation of
1229 * a 64-bit integer. */
1230 static char thread_id[17];
1231 Xapian::WritableDatabase *db;
1233 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1235 notmuch->last_thread_id++;
1237 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1239 db->set_metadata ("last_thread_id", thread_id);
1245 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1247 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1248 message_id = _message_id_compressed (ctx, message_id);
1250 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1254 /* Find the thread ID to which the message with 'message_id' belongs.
1256 * Always returns a newly talloced string belonging to 'ctx'.
1258 * Note: If there is no message in the database with the given
1259 * 'message_id' then a new thread_id will be allocated for this
1260 * message and stored in the database metadata, (where this same
1261 * thread ID can be looked up if the message is added to the database
1265 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1267 const char *message_id)
1269 notmuch_message_t *message;
1270 string thread_id_string;
1271 const char *thread_id;
1273 Xapian::WritableDatabase *db;
1275 message = notmuch_database_find_message (notmuch, message_id);
1278 thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1280 notmuch_message_destroy (message);
1285 /* Message has not been seen yet.
1287 * We may have seen a reference to it already, in which case, we
1288 * can return the thread ID stored in the metadata. Otherwise, we
1289 * generate a new thread ID and store it there.
1291 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1292 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1293 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1295 if (thread_id_string.empty()) {
1296 thread_id = _notmuch_database_generate_thread_id (notmuch);
1297 db->set_metadata (metadata_key, thread_id);
1299 thread_id = thread_id_string.c_str();
1302 talloc_free (metadata_key);
1304 return talloc_strdup (ctx, thread_id);
1307 static notmuch_status_t
1308 _merge_threads (notmuch_database_t *notmuch,
1309 const char *winner_thread_id,
1310 const char *loser_thread_id)
1312 Xapian::PostingIterator loser, loser_end;
1313 notmuch_message_t *message = NULL;
1314 notmuch_private_status_t private_status;
1315 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1317 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1319 for ( ; loser != loser_end; loser++) {
1320 message = _notmuch_message_create (notmuch, notmuch,
1321 *loser, &private_status);
1322 if (message == NULL) {
1323 ret = COERCE_STATUS (private_status,
1324 "Cannot find document for doc_id from query");
1328 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1329 _notmuch_message_add_term (message, "thread", winner_thread_id);
1330 _notmuch_message_sync (message);
1332 notmuch_message_destroy (message);
1338 notmuch_message_destroy (message);
1344 _my_talloc_free_for_g_hash (void *ptr)
1349 static notmuch_status_t
1350 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1351 notmuch_message_t *message,
1352 notmuch_message_file_t *message_file,
1353 const char **thread_id)
1355 GHashTable *parents = NULL;
1356 const char *refs, *in_reply_to, *in_reply_to_message_id;
1357 GList *l, *keys = NULL;
1358 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1360 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1361 _my_talloc_free_for_g_hash, NULL);
1363 refs = notmuch_message_file_get_header (message_file, "references");
1364 parse_references (message, notmuch_message_get_message_id (message),
1367 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1368 parse_references (message, notmuch_message_get_message_id (message),
1369 parents, in_reply_to);
1371 /* Carefully avoid adding any self-referential in-reply-to term. */
1372 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1373 if (in_reply_to_message_id &&
1374 strcmp (in_reply_to_message_id,
1375 notmuch_message_get_message_id (message)))
1377 _notmuch_message_add_term (message, "replyto",
1378 _parse_message_id (message, in_reply_to, NULL));
1381 keys = g_hash_table_get_keys (parents);
1382 for (l = keys; l; l = l->next) {
1383 char *parent_message_id;
1384 const char *parent_thread_id;
1386 parent_message_id = (char *) l->data;
1388 _notmuch_message_add_term (message, "reference",
1391 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1395 if (*thread_id == NULL) {
1396 *thread_id = talloc_strdup (message, parent_thread_id);
1397 _notmuch_message_add_term (message, "thread", *thread_id);
1398 } else if (strcmp (*thread_id, parent_thread_id)) {
1399 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1409 g_hash_table_unref (parents);
1414 static notmuch_status_t
1415 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1416 notmuch_message_t *message,
1417 const char **thread_id)
1419 const char *message_id = notmuch_message_get_message_id (message);
1420 Xapian::PostingIterator child, children_end;
1421 notmuch_message_t *child_message = NULL;
1422 const char *child_thread_id;
1423 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1424 notmuch_private_status_t private_status;
1426 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1428 for ( ; child != children_end; child++) {
1430 child_message = _notmuch_message_create (message, notmuch,
1431 *child, &private_status);
1432 if (child_message == NULL) {
1433 ret = COERCE_STATUS (private_status,
1434 "Cannot find document for doc_id from query");
1438 child_thread_id = notmuch_message_get_thread_id (child_message);
1439 if (*thread_id == NULL) {
1440 *thread_id = talloc_strdup (message, child_thread_id);
1441 _notmuch_message_add_term (message, "thread", *thread_id);
1442 } else if (strcmp (*thread_id, child_thread_id)) {
1443 _notmuch_message_remove_term (child_message, "reference",
1445 _notmuch_message_sync (child_message);
1446 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1451 notmuch_message_destroy (child_message);
1452 child_message = NULL;
1457 notmuch_message_destroy (child_message);
1462 /* Given a (mostly empty) 'message' and its corresponding
1463 * 'message_file' link it to existing threads in the database.
1465 * The first check is in the metadata of the database to see if we
1466 * have pre-allocated a thread_id in advance for this message, (which
1467 * would have happened if a message was previously added that
1468 * referenced this one).
1470 * Second, we look at 'message_file' and its link-relevant headers
1471 * (References and In-Reply-To) for message IDs.
1473 * Finally, we look in the database for existing message that
1474 * reference 'message'.
1476 * In all cases, we assign to the current message the first thread_id
1477 * found (through either parent or child). We will also merge any
1478 * existing, distinct threads where this message belongs to both,
1479 * (which is not uncommon when mesages are processed out of order).
1481 * Finally, if no thread ID has been found through parent or child, we
1482 * call _notmuch_message_generate_thread_id to generate a new thread
1483 * ID. This should only happen for new, top-level messages, (no
1484 * References or In-Reply-To header in this message, and no previously
1485 * added message refers to this message).
1487 static notmuch_status_t
1488 _notmuch_database_link_message (notmuch_database_t *notmuch,
1489 notmuch_message_t *message,
1490 notmuch_message_file_t *message_file)
1492 notmuch_status_t status;
1493 const char *message_id, *thread_id = NULL;
1497 message_id = notmuch_message_get_message_id (message);
1498 metadata_key = _get_metadata_thread_id_key (message, message_id);
1500 /* Check if we have already seen related messages to this one.
1501 * If we have then use the thread_id that we stored at that time.
1503 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1504 if (! stored_id.empty()) {
1505 Xapian::WritableDatabase *db;
1507 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1509 /* Clear the metadata for this message ID. We don't need it
1511 db->set_metadata (metadata_key, "");
1512 thread_id = stored_id.c_str();
1514 _notmuch_message_add_term (message, "thread", thread_id);
1516 talloc_free (metadata_key);
1518 status = _notmuch_database_link_message_to_parents (notmuch, message,
1524 status = _notmuch_database_link_message_to_children (notmuch, message,
1529 /* If not part of any existing thread, generate a new thread ID. */
1530 if (thread_id == NULL) {
1531 thread_id = _notmuch_database_generate_thread_id (notmuch);
1533 _notmuch_message_add_term (message, "thread", thread_id);
1536 return NOTMUCH_STATUS_SUCCESS;
1540 notmuch_database_add_message (notmuch_database_t *notmuch,
1541 const char *filename,
1542 notmuch_message_t **message_ret)
1544 notmuch_message_file_t *message_file;
1545 notmuch_message_t *message = NULL;
1546 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1547 notmuch_private_status_t private_status;
1549 const char *date, *header;
1550 const char *from, *to, *subject;
1551 char *message_id = NULL;
1554 *message_ret = NULL;
1556 ret = _notmuch_database_ensure_writable (notmuch);
1560 message_file = notmuch_message_file_open (filename);
1561 if (message_file == NULL)
1562 return NOTMUCH_STATUS_FILE_ERROR;
1564 notmuch_message_file_restrict_headers (message_file,
1575 /* Before we do any real work, (especially before doing a
1576 * potential SHA-1 computation on the entire file's contents),
1577 * let's make sure that what we're looking at looks like an
1578 * actual email message.
1580 from = notmuch_message_file_get_header (message_file, "from");
1581 subject = notmuch_message_file_get_header (message_file, "subject");
1582 to = notmuch_message_file_get_header (message_file, "to");
1584 if ((from == NULL || *from == '\0') &&
1585 (subject == NULL || *subject == '\0') &&
1586 (to == NULL || *to == '\0'))
1588 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1592 /* Now that we're sure it's mail, the first order of business
1593 * is to find a message ID (or else create one ourselves). */
1595 header = notmuch_message_file_get_header (message_file, "message-id");
1596 if (header && *header != '\0') {
1597 message_id = _parse_message_id (message_file, header, NULL);
1599 /* So the header value isn't RFC-compliant, but it's
1600 * better than no message-id at all. */
1601 if (message_id == NULL)
1602 message_id = talloc_strdup (message_file, header);
1604 /* If a message ID is too long, substitute its sha1 instead. */
1605 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1606 char *compressed = _message_id_compressed (message_file,
1608 talloc_free (message_id);
1609 message_id = compressed;
1613 if (message_id == NULL ) {
1614 /* No message-id at all, let's generate one by taking a
1615 * hash over the file's contents. */
1616 char *sha1 = notmuch_sha1_of_file (filename);
1618 /* If that failed too, something is really wrong. Give up. */
1620 ret = NOTMUCH_STATUS_FILE_ERROR;
1624 message_id = talloc_asprintf (message_file,
1625 "notmuch-sha1-%s", sha1);
1629 /* Now that we have a message ID, we get a message object,
1630 * (which may or may not reference an existing document in the
1633 message = _notmuch_message_create_for_message_id (notmuch,
1637 talloc_free (message_id);
1639 if (message == NULL) {
1640 ret = COERCE_STATUS (private_status,
1641 "Unexpected status value from _notmuch_message_create_for_message_id");
1645 _notmuch_message_add_filename (message, filename);
1647 /* Is this a newly created message object? */
1648 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1649 _notmuch_message_add_term (message, "type", "mail");
1651 ret = _notmuch_database_link_message (notmuch, message,
1656 date = notmuch_message_file_get_header (message_file, "date");
1657 _notmuch_message_set_date (message, date);
1659 _notmuch_message_index_file (message, filename);
1661 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1664 _notmuch_message_sync (message);
1665 } catch (const Xapian::Error &error) {
1666 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1667 error.get_msg().c_str());
1668 notmuch->exception_reported = TRUE;
1669 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1675 if ((ret == NOTMUCH_STATUS_SUCCESS ||
1676 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
1677 *message_ret = message;
1679 notmuch_message_destroy (message);
1683 notmuch_message_file_close (message_file);
1689 notmuch_database_remove_message (notmuch_database_t *notmuch,
1690 const char *filename)
1692 Xapian::WritableDatabase *db;
1694 const char *prefix = _find_prefix ("file-direntry");
1695 char *direntry, *term;
1696 Xapian::PostingIterator i, end;
1697 Xapian::Document document;
1698 notmuch_status_t status;
1700 status = _notmuch_database_ensure_writable (notmuch);
1704 local = talloc_new (notmuch);
1706 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1710 status = _notmuch_database_filename_to_direntry (local, notmuch,
1711 filename, &direntry);
1715 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1717 find_doc_ids_for_term (notmuch, term, &i, &end);
1719 for ( ; i != end; i++) {
1720 Xapian::TermIterator j;
1721 notmuch_message_t *message;
1722 notmuch_private_status_t private_status;
1724 message = _notmuch_message_create (local, notmuch,
1725 *i, &private_status);
1726 if (message == NULL)
1727 return COERCE_STATUS (private_status,
1728 "Inconsistent document ID in datbase.");
1730 _notmuch_message_remove_filename (message, filename);
1731 _notmuch_message_sync (message);
1733 /* Take care to find document after sync'ing filename removal. */
1734 document = find_document_for_doc_id (notmuch, *i);
1735 j = document.termlist_begin ();
1738 /* Was this the last file-direntry in the message? */
1739 if (j == document.termlist_end () ||
1740 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1742 db->delete_document (document.get_docid ());
1743 status = NOTMUCH_STATUS_SUCCESS;
1745 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1748 } catch (const Xapian::Error &error) {
1749 fprintf (stderr, "Error: A Xapian exception occurred removing message: %s\n",
1750 error.get_msg().c_str());
1751 notmuch->exception_reported = TRUE;
1752 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1755 talloc_free (local);
1760 notmuch_string_list_t *
1761 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1762 Xapian::TermIterator &end,
1765 int prefix_len = strlen (prefix);
1766 notmuch_string_list_t *list;
1768 list = _notmuch_string_list_create (ctx);
1769 if (unlikely (list == NULL))
1772 for (i.skip_to (prefix); i != end; i++) {
1773 /* Terminate loop at first term without desired prefix. */
1774 if (strncmp ((*i).c_str (), prefix, prefix_len))
1777 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1784 notmuch_database_get_all_tags (notmuch_database_t *db)
1786 Xapian::TermIterator i, end;
1787 notmuch_string_list_t *tags;
1790 i = db->xapian_db->allterms_begin();
1791 end = db->xapian_db->allterms_end();
1792 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1793 _find_prefix ("tag"));
1794 _notmuch_string_list_sort (tags);
1795 return _notmuch_tags_create (db, tags);
1796 } catch (const Xapian::Error &error) {
1797 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1798 error.get_msg().c_str());
1799 db->exception_reported = TRUE;