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. But the database doesn't really care itself
95 * The data portion of a mail document is empty.
99 * A directory document is used by a client of the notmuch library to
100 * maintain data necessary to allow for efficient polling of mail
103 * All directory documents contain one term:
105 * directory: The directory path (relative to the database path)
106 * Or the SHA1 sum of the directory path (if the
107 * path itself is too long to fit in a Xapian
110 * And all directory documents for directories other than top-level
111 * directories also contain the following term:
113 * directory-direntry: A colon-separated pair of values
114 * (INTEGER:STRING), where INTEGER is the
115 * document ID of the parent directory
116 * document, and STRING is the name of this
117 * directory within that parent.
119 * All directory documents have a single value:
121 * TIMESTAMP: The mtime of the directory (at last scan)
123 * The data portion of a directory document contains the path of the
124 * directory (relative to the database path).
128 * Xapian allows us to store arbitrary name-value pairs as
129 * "metadata". We currently use the following metadata names with the
132 * version The database schema version, (which is distinct
133 * from both the notmuch package version (see
134 * notmuch --version) and the libnotmuch library
135 * version. The version is stored as an base-10
136 * ASCII integer. The initial database version
137 * was 1, (though a schema existed before that
138 * were no "version" database value existed at
139 * all). Succesive versions are allocated as
140 * changes are made to the database (such as by
141 * indexing new fields).
143 * last_thread_id The last thread ID generated. This is stored
144 * as a 16-byte hexadecimal ASCII representation
145 * of a 64-bit unsigned integer. The first ID
146 * generated is 1 and the value will be
147 * incremented for each thread ID.
149 * thread_id_* A pre-allocated thread ID for a particular
150 * message. This is actually an arbitarily large
151 * family of metadata name. Any particular name is
152 * formed by concatenating "thread_id_" with a message
153 * ID (or the SHA1 sum of a message ID if it is very
154 * long---see description of 'id' in the mail
155 * document). The value stored is a thread ID.
157 * These thread ID metadata values are stored
158 * whenever a message references a parent message
159 * that does not yet exist in the database. A
160 * thread ID will be allocated and stored, and if
161 * the message is later added, the stored thread
162 * ID will be used (and the metadata value will
165 * Even before a message is added, it's
166 * pre-allocated thread ID is useful so that all
167 * descendant messages that reference this common
168 * parent can be recognized as belonging to the
172 /* With these prefix values we follow the conventions published here:
174 * http://xapian.org/docs/omega/termprefixes.html
176 * as much as makes sense. Note that I took some liberty in matching
177 * the reserved prefix values to notmuch concepts, (for example, 'G'
178 * is documented as "newsGroup (or similar entity - e.g. a web forum
179 * name)", for which I think the thread is the closest analogue in
180 * notmuch. This in spite of the fact that we will eventually be
181 * storing mailing-list messages where 'G' for "mailing list name"
182 * might be even a closer analogue. I'm treating the single-character
183 * prefixes preferentially for core notmuch concepts (which will be
184 * nearly universal to all mail messages).
187 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
189 { "reference", "XREFERENCE" },
190 { "replyto", "XREPLYTO" },
191 { "directory", "XDIRECTORY" },
192 { "file-direntry", "XFDIRENTRY" },
193 { "directory-direntry", "XDDIRENTRY" },
196 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
203 static prefix_t PROBABILISTIC_PREFIX[]= {
206 { "attachment", "XATTACHMENT" },
207 { "subject", "XSUBJECT"}
211 _internal_error (const char *format, ...)
215 va_start (va_args, format);
217 fprintf (stderr, "Internal error: ");
218 vfprintf (stderr, format, va_args);
226 _find_prefix (const char *name)
230 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
231 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
232 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
235 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
236 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
237 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
240 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
241 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
242 return PROBABILISTIC_PREFIX[i].prefix;
245 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
251 notmuch_status_to_string (notmuch_status_t status)
254 case NOTMUCH_STATUS_SUCCESS:
255 return "No error occurred";
256 case NOTMUCH_STATUS_OUT_OF_MEMORY:
257 return "Out of memory";
258 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
259 return "Attempt to write to a read-only database";
260 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
261 return "A Xapian exception occurred";
262 case NOTMUCH_STATUS_FILE_ERROR:
263 return "Something went wrong trying to read or write a file";
264 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
265 return "File is not an email";
266 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
267 return "Message ID is identical to a message in database";
268 case NOTMUCH_STATUS_NULL_POINTER:
269 return "Erroneous NULL pointer";
270 case NOTMUCH_STATUS_TAG_TOO_LONG:
271 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
272 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
273 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
275 case NOTMUCH_STATUS_LAST_STATUS:
276 return "Unknown error status value";
281 find_doc_ids_for_term (notmuch_database_t *notmuch,
283 Xapian::PostingIterator *begin,
284 Xapian::PostingIterator *end)
286 *begin = notmuch->xapian_db->postlist_begin (term);
288 *end = notmuch->xapian_db->postlist_end (term);
292 find_doc_ids (notmuch_database_t *notmuch,
293 const char *prefix_name,
295 Xapian::PostingIterator *begin,
296 Xapian::PostingIterator *end)
300 term = talloc_asprintf (notmuch, "%s%s",
301 _find_prefix (prefix_name), value);
303 find_doc_ids_for_term (notmuch, term, begin, end);
308 notmuch_private_status_t
309 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
310 const char *prefix_name,
312 unsigned int *doc_id)
314 Xapian::PostingIterator i, end;
316 find_doc_ids (notmuch, prefix_name, value, &i, &end);
320 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
325 #if DEBUG_DATABASE_SANITY
329 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
333 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
336 static Xapian::Document
337 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
339 return notmuch->xapian_db->get_document (doc_id);
342 /* Generate a compressed version of 'message_id' of the form:
344 * notmuch-sha1-<sha1_sum_of_message_id>
347 _message_id_compressed (void *ctx, const char *message_id)
349 char *sha1, *compressed;
351 sha1 = notmuch_sha1_of_string (message_id);
353 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
360 notmuch_database_find_message (notmuch_database_t *notmuch,
361 const char *message_id)
363 notmuch_private_status_t status;
366 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
367 message_id = _message_id_compressed (notmuch, message_id);
370 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
371 message_id, &doc_id);
373 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
376 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
377 } catch (const Xapian::Error &error) {
378 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
379 error.get_msg().c_str());
380 notmuch->exception_reported = TRUE;
385 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
386 * a (potentially nested) parenthesized sequence with '\' used to
387 * escape any character (including parentheses).
389 * If the sequence to be skipped continues to the end of the string,
390 * then 'str' will be left pointing at the final terminating '\0'
394 skip_space_and_comments (const char **str)
399 while (*s && (isspace (*s) || *s == '(')) {
400 while (*s && isspace (*s))
405 while (*s && nesting) {
408 } else if (*s == ')') {
410 } else if (*s == '\\') {
422 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
423 * comments, and the '<' and '>' delimeters.
425 * If not NULL, then *next will be made to point to the first character
426 * not parsed, (possibly pointing to the final '\0' terminator.
428 * Returns a newly talloc'ed string belonging to 'ctx'.
430 * Returns NULL if there is any error parsing the message-id. */
432 _parse_message_id (void *ctx, const char *message_id, const char **next)
437 if (message_id == NULL || *message_id == '\0')
442 skip_space_and_comments (&s);
444 /* Skip any unstructured text as well. */
445 while (*s && *s != '<')
456 skip_space_and_comments (&s);
459 while (*end && *end != '>')
468 if (end > s && *end == '>')
473 result = talloc_strndup (ctx, s, end - s + 1);
475 /* Finally, collapse any whitespace that is within the message-id
481 for (r = result, len = strlen (r); *r; r++, len--)
482 if (*r == ' ' || *r == '\t')
483 memmove (r, r+1, len);
489 /* Parse a References header value, putting a (talloc'ed under 'ctx')
490 * copy of each referenced message-id into 'hash'.
492 * We explicitly avoid including any reference identical to
493 * 'message_id' in the result (to avoid mass confusion when a single
494 * message references itself cyclically---and yes, mail messages are
495 * not infrequent in the wild that do this---don't ask me why).
498 parse_references (void *ctx,
499 const char *message_id,
505 if (refs == NULL || *refs == '\0')
509 ref = _parse_message_id (ctx, refs, &refs);
511 if (ref && strcmp (ref, message_id))
512 g_hash_table_insert (hash, ref, NULL);
517 notmuch_database_create (const char *path)
519 notmuch_database_t *notmuch = NULL;
520 char *notmuch_path = NULL;
525 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
529 err = stat (path, &st);
531 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
532 path, strerror (errno));
536 if (! S_ISDIR (st.st_mode)) {
537 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
542 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
544 err = mkdir (notmuch_path, 0755);
547 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
548 notmuch_path, strerror (errno));
552 notmuch = notmuch_database_open (path,
553 NOTMUCH_DATABASE_MODE_READ_WRITE);
554 notmuch_database_upgrade (notmuch, NULL, NULL);
558 talloc_free (notmuch_path);
564 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
566 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
567 fprintf (stderr, "Cannot write to a read-only database.\n");
568 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
571 return NOTMUCH_STATUS_SUCCESS;
575 notmuch_database_open (const char *path,
576 notmuch_database_mode_t mode)
578 notmuch_database_t *notmuch = NULL;
579 char *notmuch_path = NULL, *xapian_path = NULL;
582 unsigned int i, version;
584 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
586 fprintf (stderr, "Out of memory\n");
590 err = stat (notmuch_path, &st);
592 fprintf (stderr, "Error opening database at %s: %s\n",
593 notmuch_path, strerror (errno));
597 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
599 fprintf (stderr, "Out of memory\n");
603 notmuch = talloc (NULL, notmuch_database_t);
604 notmuch->exception_reported = FALSE;
605 notmuch->path = talloc_strdup (notmuch, path);
607 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
608 notmuch->path[strlen (notmuch->path) - 1] = '\0';
610 notmuch->needs_upgrade = FALSE;
611 notmuch->mode = mode;
613 string last_thread_id;
615 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
616 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
617 Xapian::DB_CREATE_OR_OPEN);
618 version = notmuch_database_get_version (notmuch);
620 if (version > NOTMUCH_DATABASE_VERSION) {
622 "Error: Notmuch database at %s\n"
623 " has a newer database format version (%u) than supported by this\n"
624 " version of notmuch (%u). Refusing to open this database in\n"
625 " read-write mode.\n",
626 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
627 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
628 notmuch_database_close (notmuch);
633 if (version < NOTMUCH_DATABASE_VERSION)
634 notmuch->needs_upgrade = TRUE;
636 notmuch->xapian_db = new Xapian::Database (xapian_path);
637 version = notmuch_database_get_version (notmuch);
638 if (version > NOTMUCH_DATABASE_VERSION)
641 "Warning: Notmuch database at %s\n"
642 " has a newer database format version (%u) than supported by this\n"
643 " version of notmuch (%u). Some operations may behave incorrectly,\n"
644 " (but the database will not be harmed since it is being opened\n"
645 " in read-only mode).\n",
646 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
650 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
651 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
652 if (last_thread_id.empty ()) {
653 notmuch->last_thread_id = 0;
658 str = last_thread_id.c_str ();
659 notmuch->last_thread_id = strtoull (str, &end, 16);
661 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
664 notmuch->query_parser = new Xapian::QueryParser;
665 notmuch->term_gen = new Xapian::TermGenerator;
666 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
667 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
669 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
670 notmuch->query_parser->set_database (*notmuch->xapian_db);
671 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
672 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
673 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
675 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
676 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
677 notmuch->query_parser->add_boolean_prefix (prefix->name,
681 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
682 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
683 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
685 } catch (const Xapian::Error &error) {
686 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
687 error.get_msg().c_str());
701 notmuch_database_close (notmuch_database_t *notmuch)
704 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
705 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
706 } catch (const Xapian::Error &error) {
707 if (! notmuch->exception_reported) {
708 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
709 error.get_msg().c_str());
713 delete notmuch->term_gen;
714 delete notmuch->query_parser;
715 delete notmuch->xapian_db;
716 delete notmuch->value_range_processor;
717 talloc_free (notmuch);
721 notmuch_database_get_path (notmuch_database_t *notmuch)
723 return notmuch->path;
727 notmuch_database_get_version (notmuch_database_t *notmuch)
729 unsigned int version;
730 string version_string;
734 version_string = notmuch->xapian_db->get_metadata ("version");
735 if (version_string.empty ())
738 str = version_string.c_str ();
739 if (str == NULL || *str == '\0')
742 version = strtoul (str, &end, 10);
744 INTERNAL_ERROR ("Malformed database version: %s", str);
750 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
752 return notmuch->needs_upgrade;
755 static volatile sig_atomic_t do_progress_notify = 0;
758 handle_sigalrm (unused (int signal))
760 do_progress_notify = 1;
763 /* Upgrade the current database.
765 * After opening a database in read-write mode, the client should
766 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
767 * if so, upgrade with this function before making any modifications.
769 * The optional progress_notify callback can be used by the caller to
770 * provide progress indication to the user. If non-NULL it will be
771 * called periodically with 'count' as the number of messages upgraded
772 * so far and 'total' the overall number of messages that will be
776 notmuch_database_upgrade (notmuch_database_t *notmuch,
777 void (*progress_notify) (void *closure,
781 Xapian::WritableDatabase *db;
782 struct sigaction action;
783 struct itimerval timerval;
784 notmuch_bool_t timer_is_active = FALSE;
785 unsigned int version;
786 notmuch_status_t status;
787 unsigned int count = 0, total = 0;
789 status = _notmuch_database_ensure_writable (notmuch);
793 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
795 version = notmuch_database_get_version (notmuch);
797 if (version >= NOTMUCH_DATABASE_VERSION)
798 return NOTMUCH_STATUS_SUCCESS;
800 if (progress_notify) {
801 /* Setup our handler for SIGALRM */
802 memset (&action, 0, sizeof (struct sigaction));
803 action.sa_handler = handle_sigalrm;
804 sigemptyset (&action.sa_mask);
805 action.sa_flags = SA_RESTART;
806 sigaction (SIGALRM, &action, NULL);
808 /* Then start a timer to send SIGALRM once per second. */
809 timerval.it_interval.tv_sec = 1;
810 timerval.it_interval.tv_usec = 0;
811 timerval.it_value.tv_sec = 1;
812 timerval.it_value.tv_usec = 0;
813 setitimer (ITIMER_REAL, &timerval, NULL);
815 timer_is_active = TRUE;
818 /* Before version 1, each message document had its filename in the
819 * data field. Copy that into the new format by calling
820 * notmuch_message_add_filename.
823 notmuch_query_t *query = notmuch_query_create (notmuch, "");
824 notmuch_messages_t *messages;
825 notmuch_message_t *message;
827 Xapian::TermIterator t, t_end;
829 total = notmuch_query_count_messages (query);
831 for (messages = notmuch_query_search_messages (query);
832 notmuch_messages_valid (messages);
833 notmuch_messages_move_to_next (messages))
835 if (do_progress_notify) {
836 progress_notify (closure, (double) count / total);
837 do_progress_notify = 0;
840 message = notmuch_messages_get (messages);
842 filename = _notmuch_message_talloc_copy_data (message);
843 if (filename && *filename != '\0') {
844 _notmuch_message_add_filename (message, filename);
845 _notmuch_message_sync (message);
847 talloc_free (filename);
849 notmuch_message_destroy (message);
854 notmuch_query_destroy (query);
856 /* Also, before version 1 we stored directory timestamps in
857 * XTIMESTAMP documents instead of the current XDIRECTORY
858 * documents. So copy those as well. */
860 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
862 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
866 Xapian::PostingIterator p, p_end;
867 std::string term = *t;
869 p_end = notmuch->xapian_db->postlist_end (term);
871 for (p = notmuch->xapian_db->postlist_begin (term);
875 Xapian::Document document;
877 notmuch_directory_t *directory;
879 if (do_progress_notify) {
880 progress_notify (closure, (double) count / total);
881 do_progress_notify = 0;
884 document = find_document_for_doc_id (notmuch, *p);
885 mtime = Xapian::sortable_unserialise (
886 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
888 directory = notmuch_database_get_directory (notmuch,
890 notmuch_directory_set_mtime (directory, mtime);
891 notmuch_directory_destroy (directory);
896 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
899 /* Now that the upgrade is complete we can remove the old data
900 * and documents that are no longer needed. */
902 notmuch_query_t *query = notmuch_query_create (notmuch, "");
903 notmuch_messages_t *messages;
904 notmuch_message_t *message;
907 for (messages = notmuch_query_search_messages (query);
908 notmuch_messages_valid (messages);
909 notmuch_messages_move_to_next (messages))
911 if (do_progress_notify) {
912 progress_notify (closure, (double) count / total);
913 do_progress_notify = 0;
916 message = notmuch_messages_get (messages);
918 filename = _notmuch_message_talloc_copy_data (message);
919 if (filename && *filename != '\0') {
920 _notmuch_message_clear_data (message);
921 _notmuch_message_sync (message);
923 talloc_free (filename);
925 notmuch_message_destroy (message);
928 notmuch_query_destroy (query);
932 Xapian::TermIterator t, t_end;
934 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
936 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
940 Xapian::PostingIterator p, p_end;
941 std::string term = *t;
943 p_end = notmuch->xapian_db->postlist_end (term);
945 for (p = notmuch->xapian_db->postlist_begin (term);
949 if (do_progress_notify) {
950 progress_notify (closure, (double) count / total);
951 do_progress_notify = 0;
954 db->delete_document (*p);
959 if (timer_is_active) {
960 /* Now stop the timer. */
961 timerval.it_interval.tv_sec = 0;
962 timerval.it_interval.tv_usec = 0;
963 timerval.it_value.tv_sec = 0;
964 timerval.it_value.tv_usec = 0;
965 setitimer (ITIMER_REAL, &timerval, NULL);
967 /* And disable the signal handler. */
968 action.sa_handler = SIG_IGN;
969 sigaction (SIGALRM, &action, NULL);
972 return NOTMUCH_STATUS_SUCCESS;
975 /* We allow the user to use arbitrarily long paths for directories. But
976 * we have a term-length limit. So if we exceed that, we'll use the
977 * SHA-1 of the path for the database term.
979 * Note: This function may return the original value of 'path'. If it
980 * does not, then the caller is responsible to free() the returned
984 _notmuch_database_get_directory_db_path (const char *path)
986 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
988 if (term_len > NOTMUCH_TERM_MAX)
989 return notmuch_sha1_of_string (path);
994 /* Given a path, split it into two parts: the directory part is all
995 * components except for the last, and the basename is that last
996 * component. Getting the return-value for either part is optional
997 * (the caller can pass NULL).
999 * The original 'path' can represent either a regular file or a
1000 * directory---the splitting will be carried out in the same way in
1001 * either case. Trailing slashes on 'path' will be ignored, and any
1002 * cases of multiple '/' characters appearing in series will be
1003 * treated as a single '/'.
1005 * Allocation (if any) will have 'ctx' as the talloc owner. But
1006 * pointers will be returned within the original path string whenever
1009 * Note: If 'path' is non-empty and contains no non-trailing slash,
1010 * (that is, consists of a filename with no parent directory), then
1011 * the directory returned will be an empty string. However, if 'path'
1012 * is an empty string, then both directory and basename will be
1016 _notmuch_database_split_path (void *ctx,
1018 const char **directory,
1019 const char **basename)
1023 if (path == NULL || *path == '\0') {
1028 return NOTMUCH_STATUS_SUCCESS;
1031 /* Find the last slash (not counting a trailing slash), if any. */
1033 slash = path + strlen (path) - 1;
1035 /* First, skip trailing slashes. */
1036 while (slash != path) {
1043 /* Then, find a slash. */
1044 while (slash != path) {
1054 /* Finally, skip multiple slashes. */
1055 while (slash != path) {
1062 if (slash == path) {
1064 *directory = talloc_strdup (ctx, "");
1069 *directory = talloc_strndup (ctx, path, slash - path + 1);
1072 return NOTMUCH_STATUS_SUCCESS;
1076 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1078 unsigned int *directory_id)
1080 notmuch_directory_t *directory;
1081 notmuch_status_t status;
1085 return NOTMUCH_STATUS_SUCCESS;
1088 directory = _notmuch_directory_create (notmuch, path, &status);
1094 *directory_id = _notmuch_directory_get_document_id (directory);
1096 notmuch_directory_destroy (directory);
1098 return NOTMUCH_STATUS_SUCCESS;
1102 _notmuch_database_get_directory_path (void *ctx,
1103 notmuch_database_t *notmuch,
1104 unsigned int doc_id)
1106 Xapian::Document document;
1108 document = find_document_for_doc_id (notmuch, doc_id);
1110 return talloc_strdup (ctx, document.get_data ().c_str ());
1113 /* Given a legal 'filename' for the database, (either relative to
1114 * database path or absolute with initial components identical to
1115 * database path), return a new string (with 'ctx' as the talloc
1116 * owner) suitable for use as a direntry term value.
1118 * The necessary directory documents will be created in the database
1122 _notmuch_database_filename_to_direntry (void *ctx,
1123 notmuch_database_t *notmuch,
1124 const char *filename,
1127 const char *relative, *directory, *basename;
1128 Xapian::docid directory_id;
1129 notmuch_status_t status;
1131 relative = _notmuch_database_relative_path (notmuch, filename);
1133 status = _notmuch_database_split_path (ctx, relative,
1134 &directory, &basename);
1138 status = _notmuch_database_find_directory_id (notmuch, directory,
1143 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1145 return NOTMUCH_STATUS_SUCCESS;
1148 /* Given a legal 'path' for the database, return the relative path.
1150 * The return value will be a pointer to the originl path contents,
1151 * and will be either the original string (if 'path' was relative) or
1152 * a portion of the string (if path was absolute and begins with the
1156 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1159 const char *db_path, *relative;
1160 unsigned int db_path_len;
1162 db_path = notmuch_database_get_path (notmuch);
1163 db_path_len = strlen (db_path);
1167 if (*relative == '/') {
1168 while (*relative == '/' && *(relative+1) == '/')
1171 if (strncmp (relative, db_path, db_path_len) == 0)
1173 relative += db_path_len;
1174 while (*relative == '/')
1182 notmuch_directory_t *
1183 notmuch_database_get_directory (notmuch_database_t *notmuch,
1186 notmuch_status_t status;
1189 return _notmuch_directory_create (notmuch, path, &status);
1190 } catch (const Xapian::Error &error) {
1191 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1192 error.get_msg().c_str());
1193 notmuch->exception_reported = TRUE;
1198 /* Allocate a document ID that satisfies the following criteria:
1200 * 1. The ID does not exist for any document in the Xapian database
1202 * 2. The ID was not previously returned from this function
1204 * 3. The ID is the smallest integer satisfying (1) and (2)
1206 * This function will trigger an internal error if these constraints
1207 * cannot all be satisfied, (that is, the pool of available document
1208 * IDs has been exhausted).
1211 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1213 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1215 notmuch->last_doc_id++;
1217 if (notmuch->last_doc_id == 0)
1218 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1220 return notmuch->last_doc_id;
1224 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1226 /* 16 bytes (+ terminator) for hexadecimal representation of
1227 * a 64-bit integer. */
1228 static char thread_id[17];
1229 Xapian::WritableDatabase *db;
1231 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1233 notmuch->last_thread_id++;
1235 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1237 db->set_metadata ("last_thread_id", thread_id);
1243 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1245 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1246 message_id = _message_id_compressed (ctx, message_id);
1248 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1252 /* Find the thread ID to which the message with 'message_id' belongs.
1254 * Always returns a newly talloced string belonging to 'ctx'.
1256 * Note: If there is no message in the database with the given
1257 * 'message_id' then a new thread_id will be allocated for this
1258 * message and stored in the database metadata, (where this same
1259 * thread ID can be looked up if the message is added to the database
1263 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1265 const char *message_id)
1267 notmuch_message_t *message;
1268 string thread_id_string;
1269 const char *thread_id;
1271 Xapian::WritableDatabase *db;
1273 message = notmuch_database_find_message (notmuch, message_id);
1276 thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1278 notmuch_message_destroy (message);
1283 /* Message has not been seen yet.
1285 * We may have seen a reference to it already, in which case, we
1286 * can return the thread ID stored in the metadata. Otherwise, we
1287 * generate a new thread ID and store it there.
1289 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1290 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1291 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1293 if (thread_id_string.empty()) {
1294 thread_id = _notmuch_database_generate_thread_id (notmuch);
1295 db->set_metadata (metadata_key, thread_id);
1297 thread_id = thread_id_string.c_str();
1300 talloc_free (metadata_key);
1302 return talloc_strdup (ctx, thread_id);
1305 static notmuch_status_t
1306 _merge_threads (notmuch_database_t *notmuch,
1307 const char *winner_thread_id,
1308 const char *loser_thread_id)
1310 Xapian::PostingIterator loser, loser_end;
1311 notmuch_message_t *message = NULL;
1312 notmuch_private_status_t private_status;
1313 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1315 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1317 for ( ; loser != loser_end; loser++) {
1318 message = _notmuch_message_create (notmuch, notmuch,
1319 *loser, &private_status);
1320 if (message == NULL) {
1321 ret = COERCE_STATUS (private_status,
1322 "Cannot find document for doc_id from query");
1326 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1327 _notmuch_message_add_term (message, "thread", winner_thread_id);
1328 _notmuch_message_sync (message);
1330 notmuch_message_destroy (message);
1336 notmuch_message_destroy (message);
1342 _my_talloc_free_for_g_hash (void *ptr)
1347 static notmuch_status_t
1348 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1349 notmuch_message_t *message,
1350 notmuch_message_file_t *message_file,
1351 const char **thread_id)
1353 GHashTable *parents = NULL;
1354 const char *refs, *in_reply_to, *in_reply_to_message_id;
1355 GList *l, *keys = NULL;
1356 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1358 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1359 _my_talloc_free_for_g_hash, NULL);
1361 refs = notmuch_message_file_get_header (message_file, "references");
1362 parse_references (message, notmuch_message_get_message_id (message),
1365 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1366 parse_references (message, notmuch_message_get_message_id (message),
1367 parents, in_reply_to);
1369 /* Carefully avoid adding any self-referential in-reply-to term. */
1370 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1371 if (in_reply_to_message_id &&
1372 strcmp (in_reply_to_message_id,
1373 notmuch_message_get_message_id (message)))
1375 _notmuch_message_add_term (message, "replyto",
1376 _parse_message_id (message, in_reply_to, NULL));
1379 keys = g_hash_table_get_keys (parents);
1380 for (l = keys; l; l = l->next) {
1381 char *parent_message_id;
1382 const char *parent_thread_id;
1384 parent_message_id = (char *) l->data;
1386 _notmuch_message_add_term (message, "reference",
1389 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1393 if (*thread_id == NULL) {
1394 *thread_id = talloc_strdup (message, parent_thread_id);
1395 _notmuch_message_add_term (message, "thread", *thread_id);
1396 } else if (strcmp (*thread_id, parent_thread_id)) {
1397 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1407 g_hash_table_unref (parents);
1412 static notmuch_status_t
1413 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1414 notmuch_message_t *message,
1415 const char **thread_id)
1417 const char *message_id = notmuch_message_get_message_id (message);
1418 Xapian::PostingIterator child, children_end;
1419 notmuch_message_t *child_message = NULL;
1420 const char *child_thread_id;
1421 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1422 notmuch_private_status_t private_status;
1424 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1426 for ( ; child != children_end; child++) {
1428 child_message = _notmuch_message_create (message, notmuch,
1429 *child, &private_status);
1430 if (child_message == NULL) {
1431 ret = COERCE_STATUS (private_status,
1432 "Cannot find document for doc_id from query");
1436 child_thread_id = notmuch_message_get_thread_id (child_message);
1437 if (*thread_id == NULL) {
1438 *thread_id = talloc_strdup (message, child_thread_id);
1439 _notmuch_message_add_term (message, "thread", *thread_id);
1440 } else if (strcmp (*thread_id, child_thread_id)) {
1441 _notmuch_message_remove_term (child_message, "reference",
1443 _notmuch_message_sync (child_message);
1444 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1449 notmuch_message_destroy (child_message);
1450 child_message = NULL;
1455 notmuch_message_destroy (child_message);
1460 /* Given a (mostly empty) 'message' and its corresponding
1461 * 'message_file' link it to existing threads in the database.
1463 * The first check is in the metadata of the database to see if we
1464 * have pre-allocated a thread_id in advance for this message, (which
1465 * would have happened if a message was previously added that
1466 * referenced this one).
1468 * Second, we look at 'message_file' and its link-relevant headers
1469 * (References and In-Reply-To) for message IDs.
1471 * Finally, we look in the database for existing message that
1472 * reference 'message'.
1474 * In all cases, we assign to the current message the first thread_id
1475 * found (through either parent or child). We will also merge any
1476 * existing, distinct threads where this message belongs to both,
1477 * (which is not uncommon when mesages are processed out of order).
1479 * Finally, if no thread ID has been found through parent or child, we
1480 * call _notmuch_message_generate_thread_id to generate a new thread
1481 * ID. This should only happen for new, top-level messages, (no
1482 * References or In-Reply-To header in this message, and no previously
1483 * added message refers to this message).
1485 static notmuch_status_t
1486 _notmuch_database_link_message (notmuch_database_t *notmuch,
1487 notmuch_message_t *message,
1488 notmuch_message_file_t *message_file)
1490 notmuch_status_t status;
1491 const char *message_id, *thread_id = NULL;
1495 message_id = notmuch_message_get_message_id (message);
1496 metadata_key = _get_metadata_thread_id_key (message, message_id);
1498 /* Check if we have already seen related messages to this one.
1499 * If we have then use the thread_id that we stored at that time.
1501 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1502 if (! stored_id.empty()) {
1503 Xapian::WritableDatabase *db;
1505 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1507 /* Clear the metadata for this message ID. We don't need it
1509 db->set_metadata (metadata_key, "");
1510 thread_id = stored_id.c_str();
1512 _notmuch_message_add_term (message, "thread", thread_id);
1514 talloc_free (metadata_key);
1516 status = _notmuch_database_link_message_to_parents (notmuch, message,
1522 status = _notmuch_database_link_message_to_children (notmuch, message,
1527 /* If not part of any existing thread, generate a new thread ID. */
1528 if (thread_id == NULL) {
1529 thread_id = _notmuch_database_generate_thread_id (notmuch);
1531 _notmuch_message_add_term (message, "thread", thread_id);
1534 return NOTMUCH_STATUS_SUCCESS;
1538 notmuch_database_add_message (notmuch_database_t *notmuch,
1539 const char *filename,
1540 notmuch_message_t **message_ret)
1542 notmuch_message_file_t *message_file;
1543 notmuch_message_t *message = NULL;
1544 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1545 notmuch_private_status_t private_status;
1547 const char *date, *header;
1548 const char *from, *to, *subject;
1549 char *message_id = NULL;
1552 *message_ret = NULL;
1554 ret = _notmuch_database_ensure_writable (notmuch);
1558 message_file = notmuch_message_file_open (filename);
1559 if (message_file == NULL)
1560 return NOTMUCH_STATUS_FILE_ERROR;
1562 notmuch_message_file_restrict_headers (message_file,
1573 /* Before we do any real work, (especially before doing a
1574 * potential SHA-1 computation on the entire file's contents),
1575 * let's make sure that what we're looking at looks like an
1576 * actual email message.
1578 from = notmuch_message_file_get_header (message_file, "from");
1579 subject = notmuch_message_file_get_header (message_file, "subject");
1580 to = notmuch_message_file_get_header (message_file, "to");
1582 if ((from == NULL || *from == '\0') &&
1583 (subject == NULL || *subject == '\0') &&
1584 (to == NULL || *to == '\0'))
1586 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1590 /* Now that we're sure it's mail, the first order of business
1591 * is to find a message ID (or else create one ourselves). */
1593 header = notmuch_message_file_get_header (message_file, "message-id");
1594 if (header && *header != '\0') {
1595 message_id = _parse_message_id (message_file, header, NULL);
1597 /* So the header value isn't RFC-compliant, but it's
1598 * better than no message-id at all. */
1599 if (message_id == NULL)
1600 message_id = talloc_strdup (message_file, header);
1602 /* If a message ID is too long, substitute its sha1 instead. */
1603 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1604 char *compressed = _message_id_compressed (message_file,
1606 talloc_free (message_id);
1607 message_id = compressed;
1611 if (message_id == NULL ) {
1612 /* No message-id at all, let's generate one by taking a
1613 * hash over the file's contents. */
1614 char *sha1 = notmuch_sha1_of_file (filename);
1616 /* If that failed too, something is really wrong. Give up. */
1618 ret = NOTMUCH_STATUS_FILE_ERROR;
1622 message_id = talloc_asprintf (message_file,
1623 "notmuch-sha1-%s", sha1);
1627 /* Now that we have a message ID, we get a message object,
1628 * (which may or may not reference an existing document in the
1631 message = _notmuch_message_create_for_message_id (notmuch,
1635 talloc_free (message_id);
1637 if (message == NULL) {
1638 ret = COERCE_STATUS (private_status,
1639 "Unexpected status value from _notmuch_message_create_for_message_id");
1643 _notmuch_message_add_filename (message, filename);
1645 /* Is this a newly created message object? */
1646 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1647 _notmuch_message_add_term (message, "type", "mail");
1649 ret = _notmuch_database_link_message (notmuch, message,
1654 date = notmuch_message_file_get_header (message_file, "date");
1655 _notmuch_message_set_date (message, date);
1657 _notmuch_message_index_file (message, filename);
1659 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1662 _notmuch_message_sync (message);
1663 } catch (const Xapian::Error &error) {
1664 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1665 error.get_msg().c_str());
1666 notmuch->exception_reported = TRUE;
1667 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1673 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1674 *message_ret = message;
1676 notmuch_message_destroy (message);
1680 notmuch_message_file_close (message_file);
1686 notmuch_database_remove_message (notmuch_database_t *notmuch,
1687 const char *filename)
1689 Xapian::WritableDatabase *db;
1691 const char *prefix = _find_prefix ("file-direntry");
1692 char *direntry, *term;
1693 Xapian::PostingIterator i, end;
1694 Xapian::Document document;
1695 notmuch_status_t status;
1697 status = _notmuch_database_ensure_writable (notmuch);
1701 local = talloc_new (notmuch);
1703 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1707 status = _notmuch_database_filename_to_direntry (local, notmuch,
1708 filename, &direntry);
1712 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1714 find_doc_ids_for_term (notmuch, term, &i, &end);
1716 for ( ; i != end; i++) {
1717 Xapian::TermIterator j;
1719 document = find_document_for_doc_id (notmuch, *i);
1721 document.remove_term (term);
1723 j = document.termlist_begin ();
1726 /* Was this the last file-direntry in the message? */
1727 if (j == document.termlist_end () ||
1728 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1730 db->delete_document (document.get_docid ());
1731 status = NOTMUCH_STATUS_SUCCESS;
1733 db->replace_document (document.get_docid (), document);
1734 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1737 } catch (const Xapian::Error &error) {
1738 fprintf (stderr, "Error: A Xapian exception occurred removing message: %s\n",
1739 error.get_msg().c_str());
1740 notmuch->exception_reported = TRUE;
1741 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1744 talloc_free (local);
1750 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1751 Xapian::TermIterator &end)
1753 const char *prefix = _find_prefix ("tag");
1754 notmuch_tags_t *tags;
1757 /* Currently this iteration is written with the assumption that
1758 * "tag" has a single-character prefix. */
1759 assert (strlen (prefix) == 1);
1761 tags = _notmuch_tags_create (ctx);
1762 if (unlikely (tags == NULL))
1770 if (tag.empty () || tag[0] != *prefix)
1773 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1778 _notmuch_tags_prepare_iterator (tags);
1784 notmuch_database_get_all_tags (notmuch_database_t *db)
1786 Xapian::TermIterator i, end;
1789 i = db->xapian_db->allterms_begin();
1790 end = db->xapian_db->allterms_end();
1791 return _notmuch_convert_tags(db, i, end);
1792 } catch (const Xapian::Error &error) {
1793 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1794 error.get_msg().c_str());
1795 db->exception_reported = TRUE;