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"
27 #include <glib.h> /* g_free, GPtrArray, GHashTable */
31 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
38 /* Here's the current schema for our database:
40 * We currently have two different types of documents: mail and timestamps.
44 * A mail document is associated with a particular email message file
45 * on disk. It is indexed with the following prefixed terms:
47 * Single terms of given prefix:
51 * id: Unique ID of mail, (from Message-ID header or generated
52 * as "notmuch-sha1-<sha1_sum_of_entire_file>.
54 * thread: The ID of the thread to which the mail belongs
56 * Multiple terms of given prefix:
58 * ref: All unresolved message IDs from In-Reply-To and
59 * References headers in the message. (Once a referenced
60 * message is added to the database and the thread IDs
61 * are linked the corresponding "ref" term is dropped
62 * from the message document.)
64 * tag: Any tags associated with this message by the user.
66 * A mail document also has two values:
68 * TIMESTAMP: The time_t value corresponding to the message's
71 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
75 * A timestamp document is used by a client of the notmuch library to
76 * maintain data necessary to allow for efficient polling of mail
77 * directories. The notmuch library does no interpretation of
78 * timestamps, but merely allows the user to store and retrieve
79 * timestamps as name/value pairs.
81 * The timestamp document is indexed with a single prefixed term:
83 * timestamp: The user's key value (likely a directory name)
85 * and has a single value:
87 * TIMETAMPS: The time_t value from the user.
90 /* With these prefix values we follow the conventions published here:
92 * http://xapian.org/docs/omega/termprefixes.html
94 * as much as makes sense. Note that I took some liberty in matching
95 * the reserved prefix values to notmuch concepts, (for example, 'G'
96 * is documented as "newsGroup (or similar entity - e.g. a web forum
97 * name)", for which I think the thread is the closest analogue in
98 * notmuch. This in spite of the fact that we will eventually be
99 * storing mailing-list messages where 'G' for "mailing list name"
100 * might be even a closer analogue. I'm treating the single-character
101 * prefixes preferentially for core notmuch concepts (which will be
102 * nearly universal to all mail messages).
105 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
108 { "ref", "XREFERENCE" },
109 { "timestamp", "XTIMESTAMP" },
112 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
118 _internal_error (const char *format, ...)
122 va_start (va_args, format);
124 vfprintf (stderr, format, va_args);
132 _find_prefix (const char *name)
136 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++)
137 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
138 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
140 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++)
141 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
142 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
144 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
150 notmuch_status_to_string (notmuch_status_t status)
153 case NOTMUCH_STATUS_SUCCESS:
154 return "No error occurred";
155 case NOTMUCH_STATUS_OUT_OF_MEMORY:
156 return "Out of memory";
157 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
158 return "A Xapian exception occurred";
159 case NOTMUCH_STATUS_FILE_ERROR:
160 return "Something went wrong trying to read or write a file";
161 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
162 return "File is not an email";
163 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
164 return "Message ID is identical to a message in database";
165 case NOTMUCH_STATUS_NULL_POINTER:
166 return "Erroneous NULL pointer";
167 case NOTMUCH_STATUS_TAG_TOO_LONG:
168 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
169 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
170 return "Unblanced number of calls to notmuch_message_freeze/thaw";
172 case NOTMUCH_STATUS_LAST_STATUS:
173 return "Unknown error status value";
178 find_doc_ids (notmuch_database_t *notmuch,
179 const char *prefix_name,
181 Xapian::PostingIterator *begin,
182 Xapian::PostingIterator *end)
184 Xapian::PostingIterator i;
187 term = talloc_asprintf (notmuch, "%s%s",
188 _find_prefix (prefix_name), value);
190 *begin = notmuch->xapian_db->postlist_begin (term);
192 *end = notmuch->xapian_db->postlist_end (term);
197 static notmuch_private_status_t
198 find_unique_doc_id (notmuch_database_t *notmuch,
199 const char *prefix_name,
201 unsigned int *doc_id)
203 Xapian::PostingIterator i, end;
205 find_doc_ids (notmuch, prefix_name, value, &i, &end);
209 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
212 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
216 static Xapian::Document
217 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
219 return notmuch->xapian_db->get_document (doc_id);
222 static notmuch_private_status_t
223 find_unique_document (notmuch_database_t *notmuch,
224 const char *prefix_name,
226 Xapian::Document *document,
227 unsigned int *doc_id)
229 notmuch_private_status_t status;
231 status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
234 *document = Xapian::Document ();
238 *document = find_document_for_doc_id (notmuch, *doc_id);
239 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
243 notmuch_database_find_message (notmuch_database_t *notmuch,
244 const char *message_id)
246 notmuch_private_status_t status;
249 status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
251 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
254 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
257 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
258 * a (potentially nested) parenthesized sequence with '\' used to
259 * escape any character (including parentheses).
261 * If the sequence to be skipped continues to the end of the string,
262 * then 'str' will be left pointing at the final terminating '\0'
266 skip_space_and_comments (const char **str)
271 while (*s && (isspace (*s) || *s == '(')) {
272 while (*s && isspace (*s))
277 while (*s && nesting) {
293 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
294 * comments, and the '<' and '>' delimeters.
296 * If not NULL, then *next will be made to point to the first character
297 * not parsed, (possibly pointing to the final '\0' terminator.
299 * Returns a newly talloc'ed string belonging to 'ctx'.
301 * Returns NULL if there is any error parsing the message-id. */
303 parse_message_id (void *ctx, const char *message_id, const char **next)
308 if (message_id == NULL)
313 skip_space_and_comments (&s);
315 /* Skip any unstructured text as well. */
316 while (*s && *s != '<')
327 skip_space_and_comments (&s);
330 while (*end && *end != '>')
339 if (end > s && *end == '>')
344 result = talloc_strndup (ctx, s, end - s + 1);
346 /* Finally, collapse any whitespace that is within the message-id
352 for (r = result, len = strlen (r); *r; r++, len--)
353 if (*r == ' ' || *r == '\t')
354 memmove (r, r+1, len);
360 /* Parse a References header value, putting a (talloc'ed under 'ctx')
361 * copy of each referenced message-id into 'hash'. */
363 parse_references (void *ctx,
373 ref = parse_message_id (ctx, refs, &refs);
376 g_hash_table_insert (hash, ref, NULL);
381 notmuch_database_default_path (void)
385 if (getenv ("NOTMUCH_BASE"))
386 return strdup (getenv ("NOTMUCH_BASE"));
388 if (asprintf (&path, "%s/mail", getenv ("HOME")) == -1) {
389 fprintf (stderr, "Out of memory.\n");
397 notmuch_database_create (const char *path)
399 notmuch_database_t *notmuch = NULL;
400 char *notmuch_path = NULL;
403 char *local_path = NULL;
406 path = local_path = notmuch_database_default_path ();
408 err = stat (path, &st);
410 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
411 path, strerror (errno));
415 if (! S_ISDIR (st.st_mode)) {
416 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
421 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
423 err = mkdir (notmuch_path, 0755);
426 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
427 notmuch_path, strerror (errno));
431 notmuch = notmuch_database_open (path);
435 talloc_free (notmuch_path);
443 notmuch_database_open (const char *path)
445 notmuch_database_t *notmuch = NULL;
446 char *notmuch_path = NULL, *xapian_path = NULL;
449 char *local_path = NULL;
453 path = local_path = notmuch_database_default_path ();
455 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
457 fprintf (stderr, "Out of memory\n");
461 err = stat (notmuch_path, &st);
463 fprintf (stderr, "Error opening database at %s: %s\n",
464 notmuch_path, strerror (errno));
468 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
470 fprintf (stderr, "Out of memory\n");
474 notmuch = talloc (NULL, notmuch_database_t);
475 notmuch->path = talloc_strdup (notmuch, path);
478 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
479 Xapian::DB_CREATE_OR_OPEN);
480 notmuch->query_parser = new Xapian::QueryParser;
481 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
482 notmuch->query_parser->set_database (*notmuch->xapian_db);
484 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
485 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
486 notmuch->query_parser->add_boolean_prefix (prefix->name,
489 } catch (const Xapian::Error &error) {
490 fprintf (stderr, "A Xapian exception occurred: %s\n",
491 error.get_msg().c_str());
506 notmuch_database_close (notmuch_database_t *notmuch)
508 delete notmuch->query_parser;
509 delete notmuch->xapian_db;
510 talloc_free (notmuch);
514 notmuch_database_get_path (notmuch_database_t *notmuch)
516 return notmuch->path;
519 static notmuch_private_status_t
520 find_timestamp_document (notmuch_database_t *notmuch, const char *db_key,
521 Xapian::Document *doc, unsigned int *doc_id)
523 return find_unique_document (notmuch, "timestamp", db_key, doc, doc_id);
526 /* We allow the user to use arbitrarily long keys for timestamps,
527 * (they're for filesystem paths after all, which have no limit we
528 * know about). But we have a term-length limit. So if we exceed that,
529 * we'll use the SHA-1 of the user's key as the actual key for
530 * constructing a database term.
532 * Caution: This function returns a newly allocated string which the
533 * caller should free() when finished.
536 timestamp_db_key (const char *key)
538 int term_len = strlen (_find_prefix ("timestamp")) + strlen (key);
540 if (term_len > NOTMUCH_TERM_MAX)
541 return notmuch_sha1_of_string (key);
547 notmuch_database_set_timestamp (notmuch_database_t *notmuch,
548 const char *key, time_t timestamp)
550 Xapian::Document doc;
552 notmuch_private_status_t status;
553 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
556 db_key = timestamp_db_key (key);
559 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
561 doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
562 Xapian::sortable_serialise (timestamp));
564 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
565 char *term = talloc_asprintf (NULL, "%s%s",
566 _find_prefix ("timestamp"), db_key);
570 notmuch->xapian_db->add_document (doc);
572 notmuch->xapian_db->replace_document (doc_id, doc);
575 } catch (Xapian::Error &error) {
576 fprintf (stderr, "A Xapian exception occurred: %s.\n",
577 error.get_msg().c_str());
578 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
588 notmuch_database_get_timestamp (notmuch_database_t *notmuch, const char *key)
590 Xapian::Document doc;
592 notmuch_private_status_t status;
596 db_key = timestamp_db_key (key);
599 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
601 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
604 ret = Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
605 } catch (Xapian::Error &error) {
616 /* Find the thread ID to which the message with 'message_id' belongs.
618 * Returns NULL if no message with message ID 'message_id' is in the
621 * Otherwise, returns a newly talloced string belonging to 'ctx'.
624 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
626 const char *message_id)
628 notmuch_message_t *message;
629 const char *ret = NULL;
631 message = notmuch_database_find_message (notmuch, message_id);
635 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
639 notmuch_message_destroy (message);
644 static notmuch_status_t
645 _merge_threads (notmuch_database_t *notmuch,
646 const char *winner_thread_id,
647 const char *loser_thread_id)
649 Xapian::PostingIterator loser, loser_end;
650 notmuch_message_t *message = NULL;
651 notmuch_private_status_t private_status;
652 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
654 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
656 for ( ; loser != loser_end; loser++) {
657 message = _notmuch_message_create (notmuch, notmuch,
658 *loser, &private_status);
659 if (message == NULL) {
660 ret = COERCE_STATUS (private_status,
661 "Cannot find document for doc_id from query");
665 _notmuch_message_remove_term (message, "thread", loser_thread_id);
666 _notmuch_message_add_term (message, "thread", winner_thread_id);
667 _notmuch_message_sync (message);
669 notmuch_message_destroy (message);
675 notmuch_message_destroy (message);
681 _my_talloc_free_for_g_hash (void *ptr)
686 static notmuch_status_t
687 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
688 notmuch_message_t *message,
689 notmuch_message_file_t *message_file,
690 const char **thread_id)
692 GHashTable *parents = NULL;
693 const char *refs, *in_reply_to;
694 GList *l, *keys = NULL;
695 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
697 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
698 _my_talloc_free_for_g_hash, NULL);
700 refs = notmuch_message_file_get_header (message_file, "references");
701 parse_references (message, parents, refs);
703 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
704 parse_references (message, parents, in_reply_to);
706 keys = g_hash_table_get_keys (parents);
707 for (l = keys; l; l = l->next) {
708 char *parent_message_id;
709 const char *parent_thread_id;
711 parent_message_id = (char *) l->data;
712 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
716 if (parent_thread_id == NULL) {
717 _notmuch_message_add_term (message, "ref", parent_message_id);
719 if (*thread_id == NULL) {
720 *thread_id = talloc_strdup (message, parent_thread_id);
721 _notmuch_message_add_term (message, "thread", *thread_id);
722 } else if (strcmp (*thread_id, parent_thread_id)) {
723 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
734 g_hash_table_unref (parents);
739 static notmuch_status_t
740 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
741 notmuch_message_t *message,
742 const char **thread_id)
744 const char *message_id = notmuch_message_get_message_id (message);
745 Xapian::PostingIterator child, children_end;
746 notmuch_message_t *child_message = NULL;
747 const char *child_thread_id;
748 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
749 notmuch_private_status_t private_status;
751 find_doc_ids (notmuch, "ref", message_id, &child, &children_end);
753 for ( ; child != children_end; child++) {
755 child_message = _notmuch_message_create (message, notmuch,
756 *child, &private_status);
757 if (child_message == NULL) {
758 ret = COERCE_STATUS (private_status,
759 "Cannot find document for doc_id from query");
763 child_thread_id = notmuch_message_get_thread_id (child_message);
764 if (*thread_id == NULL) {
765 *thread_id = talloc_strdup (message, child_thread_id);
766 _notmuch_message_add_term (message, "thread", *thread_id);
767 } else if (strcmp (*thread_id, child_thread_id)) {
768 _notmuch_message_remove_term (child_message, "ref",
770 _notmuch_message_sync (child_message);
771 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
776 notmuch_message_destroy (child_message);
777 child_message = NULL;
782 notmuch_message_destroy (child_message);
787 /* Given a (mostly empty) 'message' and its corresponding
788 * 'message_file' link it to existing threads in the database.
790 * We first looke at 'message_file' and its link-relevant headers
791 * (References and In-Reply-To) for message IDs. We also look in the
792 * database for existing message that reference 'message'.p
794 * The end result is to call _notmuch_message_add_thread_id with one
795 * or more thread IDs to which this message belongs, (including
796 * generating a new thread ID if necessary if the message doesn't
797 * connect to any existing threads).
799 static notmuch_status_t
800 _notmuch_database_link_message (notmuch_database_t *notmuch,
801 notmuch_message_t *message,
802 notmuch_message_file_t *message_file)
804 notmuch_status_t status;
805 const char *thread_id = NULL;
807 status = _notmuch_database_link_message_to_parents (notmuch, message,
813 status = _notmuch_database_link_message_to_children (notmuch, message,
818 if (thread_id == NULL)
819 _notmuch_message_ensure_thread_id (message);
821 return NOTMUCH_STATUS_SUCCESS;
825 notmuch_database_add_message (notmuch_database_t *notmuch,
826 const char *filename,
827 notmuch_message_t **message_ret)
829 notmuch_message_file_t *message_file;
830 notmuch_message_t *message;
831 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
833 const char *date, *header;
834 const char *from, *to, *subject, *old_filename;
837 message_file = notmuch_message_file_open (filename);
838 if (message_file == NULL) {
839 ret = NOTMUCH_STATUS_FILE_ERROR;
843 notmuch_message_file_restrict_headers (message_file,
854 /* The first order of business is to find/create a message ID. */
856 header = notmuch_message_file_get_header (message_file, "message-id");
858 message_id = parse_message_id (message_file, header, NULL);
859 /* So the header value isn't RFC-compliant, but it's
860 * better than no message-id at all. */
861 if (message_id == NULL)
862 message_id = talloc_strdup (message_file, header);
864 /* No message-id at all, let's generate one by taking a
865 * hash over the file's contents. */
866 char *sha1 = notmuch_sha1_of_file (filename);
868 /* If that failed too, something is really wrong. Give up. */
870 ret = NOTMUCH_STATUS_FILE_ERROR;
874 message_id = talloc_asprintf (message_file,
875 "notmuch-sha1-%s", sha1);
879 /* Now that we have a message ID, we get a message object,
880 * (which may or may not reference an existing document in the
883 /* Use NULL for owner since we want to free this locally. */
884 message = _notmuch_message_create_for_message_id (NULL,
889 talloc_free (message_id);
894 /* Has a message previously been added with the same ID? */
895 old_filename = notmuch_message_get_filename (message);
896 if (old_filename && strlen (old_filename)) {
897 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
900 _notmuch_message_set_filename (message, filename);
901 _notmuch_message_add_term (message, "type", "mail");
904 ret = _notmuch_database_link_message (notmuch, message, message_file);
908 date = notmuch_message_file_get_header (message_file, "date");
909 _notmuch_message_set_date (message, date);
911 from = notmuch_message_file_get_header (message_file, "from");
912 subject = notmuch_message_file_get_header (message_file, "subject");
913 to = notmuch_message_file_get_header (message_file, "to");
919 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
922 _notmuch_message_sync (message);
924 } catch (const Xapian::Error &error) {
925 fprintf (stderr, "A Xapian exception occurred: %s.\n",
926 error.get_msg().c_str());
927 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
934 *message_ret = message;
936 notmuch_message_destroy (message);
940 notmuch_message_file_close (message_file);