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 * TIMESTAMP: 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[] = {
107 { "ref", "XREFERENCE" },
108 { "replyto", "XREPLYTO" },
109 { "timestamp", "XTIMESTAMP" },
110 { "contact", "XCONTACT" }
113 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
119 prefix_t PROBABILISTIC_PREFIX[]= {
122 { "attachment", "XATTACHMENT" },
123 { "subject", "XSUBJECT"}
127 _internal_error (const char *format, ...)
131 va_start (va_args, format);
133 fprintf (stderr, "Internal error: ");
134 vfprintf (stderr, format, va_args);
142 _find_prefix (const char *name)
146 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++)
147 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
148 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
150 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++)
151 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
152 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
154 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++)
155 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
156 return PROBABILISTIC_PREFIX[i].prefix;
158 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
164 notmuch_status_to_string (notmuch_status_t status)
167 case NOTMUCH_STATUS_SUCCESS:
168 return "No error occurred";
169 case NOTMUCH_STATUS_OUT_OF_MEMORY:
170 return "Out of memory";
171 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
172 return "A Xapian exception occurred";
173 case NOTMUCH_STATUS_FILE_ERROR:
174 return "Something went wrong trying to read or write a file";
175 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
176 return "File is not an email";
177 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
178 return "Message ID is identical to a message in database";
179 case NOTMUCH_STATUS_NULL_POINTER:
180 return "Erroneous NULL pointer";
181 case NOTMUCH_STATUS_TAG_TOO_LONG:
182 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
183 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
184 return "Unblanced number of calls to notmuch_message_freeze/thaw";
186 case NOTMUCH_STATUS_LAST_STATUS:
187 return "Unknown error status value";
192 find_doc_ids (notmuch_database_t *notmuch,
193 const char *prefix_name,
195 Xapian::PostingIterator *begin,
196 Xapian::PostingIterator *end)
198 Xapian::PostingIterator i;
201 term = talloc_asprintf (notmuch, "%s%s",
202 _find_prefix (prefix_name), value);
204 *begin = notmuch->xapian_db->postlist_begin (term);
206 *end = notmuch->xapian_db->postlist_end (term);
211 static notmuch_private_status_t
212 find_unique_doc_id (notmuch_database_t *notmuch,
213 const char *prefix_name,
215 unsigned int *doc_id)
217 Xapian::PostingIterator i, end;
219 find_doc_ids (notmuch, prefix_name, value, &i, &end);
223 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
226 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
230 static Xapian::Document
231 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
233 return notmuch->xapian_db->get_document (doc_id);
236 static notmuch_private_status_t
237 find_unique_document (notmuch_database_t *notmuch,
238 const char *prefix_name,
240 Xapian::Document *document,
241 unsigned int *doc_id)
243 notmuch_private_status_t status;
245 status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
248 *document = Xapian::Document ();
252 *document = find_document_for_doc_id (notmuch, *doc_id);
253 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
257 notmuch_database_find_message (notmuch_database_t *notmuch,
258 const char *message_id)
260 notmuch_private_status_t status;
263 status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
265 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
268 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
271 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
272 * a (potentially nested) parenthesized sequence with '\' used to
273 * escape any character (including parentheses).
275 * If the sequence to be skipped continues to the end of the string,
276 * then 'str' will be left pointing at the final terminating '\0'
280 skip_space_and_comments (const char **str)
285 while (*s && (isspace (*s) || *s == '(')) {
286 while (*s && isspace (*s))
291 while (*s && nesting) {
307 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
308 * comments, and the '<' and '>' delimeters.
310 * If not NULL, then *next will be made to point to the first character
311 * not parsed, (possibly pointing to the final '\0' terminator.
313 * Returns a newly talloc'ed string belonging to 'ctx'.
315 * Returns NULL if there is any error parsing the message-id. */
317 parse_message_id (void *ctx, const char *message_id, const char **next)
322 if (message_id == NULL)
327 skip_space_and_comments (&s);
329 /* Skip any unstructured text as well. */
330 while (*s && *s != '<')
341 skip_space_and_comments (&s);
344 while (*end && *end != '>')
353 if (end > s && *end == '>')
358 result = talloc_strndup (ctx, s, end - s + 1);
360 /* Finally, collapse any whitespace that is within the message-id
366 for (r = result, len = strlen (r); *r; r++, len--)
367 if (*r == ' ' || *r == '\t')
368 memmove (r, r+1, len);
374 /* Parse a References header value, putting a (talloc'ed under 'ctx')
375 * copy of each referenced message-id into 'hash'. */
377 parse_references (void *ctx,
387 ref = parse_message_id (ctx, refs, &refs);
390 g_hash_table_insert (hash, ref, NULL);
395 notmuch_database_create (const char *path)
397 notmuch_database_t *notmuch = NULL;
398 char *notmuch_path = NULL;
403 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
407 err = stat (path, &st);
409 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
410 path, strerror (errno));
414 if (! S_ISDIR (st.st_mode)) {
415 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
420 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
422 err = mkdir (notmuch_path, 0755);
425 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
426 notmuch_path, strerror (errno));
430 notmuch = notmuch_database_open (path);
434 talloc_free (notmuch_path);
440 notmuch_database_open (const char *path)
442 notmuch_database_t *notmuch = NULL;
443 char *notmuch_path = NULL, *xapian_path = NULL;
448 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
450 fprintf (stderr, "Out of memory\n");
454 err = stat (notmuch_path, &st);
456 fprintf (stderr, "Error opening database at %s: %s\n",
457 notmuch_path, strerror (errno));
461 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
463 fprintf (stderr, "Out of memory\n");
467 notmuch = talloc (NULL, notmuch_database_t);
468 notmuch->path = talloc_strdup (notmuch, path);
470 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
471 notmuch->path[strlen (notmuch->path) - 1] = '\0';
474 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
475 Xapian::DB_CREATE_OR_OPEN);
476 notmuch->query_parser = new Xapian::QueryParser;
477 notmuch->term_gen = new Xapian::TermGenerator;
478 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
480 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
481 notmuch->query_parser->set_database (*notmuch->xapian_db);
482 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
483 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
485 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
486 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
487 notmuch->query_parser->add_boolean_prefix (prefix->name,
491 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
492 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
493 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
495 } catch (const Xapian::Error &error) {
496 fprintf (stderr, "A Xapian exception occurred: %s\n",
497 error.get_msg().c_str());
511 notmuch_database_close (notmuch_database_t *notmuch)
513 notmuch->xapian_db->flush ();
515 delete notmuch->term_gen;
516 delete notmuch->query_parser;
517 delete notmuch->xapian_db;
518 talloc_free (notmuch);
522 notmuch_database_get_path (notmuch_database_t *notmuch)
524 return notmuch->path;
527 static notmuch_private_status_t
528 find_timestamp_document (notmuch_database_t *notmuch, const char *db_key,
529 Xapian::Document *doc, unsigned int *doc_id)
531 return find_unique_document (notmuch, "timestamp", db_key, doc, doc_id);
534 /* We allow the user to use arbitrarily long keys for timestamps,
535 * (they're for filesystem paths after all, which have no limit we
536 * know about). But we have a term-length limit. So if we exceed that,
537 * we'll use the SHA-1 of the user's key as the actual key for
538 * constructing a database term.
540 * Caution: This function returns a newly allocated string which the
541 * caller should free() when finished.
544 timestamp_db_key (const char *key)
546 int term_len = strlen (_find_prefix ("timestamp")) + strlen (key);
548 if (term_len > NOTMUCH_TERM_MAX)
549 return notmuch_sha1_of_string (key);
555 notmuch_database_set_timestamp (notmuch_database_t *notmuch,
556 const char *key, time_t timestamp)
558 Xapian::Document doc;
560 notmuch_private_status_t status;
561 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
564 db_key = timestamp_db_key (key);
567 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
569 doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
570 Xapian::sortable_serialise (timestamp));
572 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
573 char *term = talloc_asprintf (NULL, "%s%s",
574 _find_prefix ("timestamp"), db_key);
578 notmuch->xapian_db->add_document (doc);
580 notmuch->xapian_db->replace_document (doc_id, doc);
583 } catch (Xapian::Error &error) {
584 fprintf (stderr, "A Xapian exception occurred: %s.\n",
585 error.get_msg().c_str());
586 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
596 notmuch_database_get_timestamp (notmuch_database_t *notmuch, const char *key)
598 Xapian::Document doc;
600 notmuch_private_status_t status;
604 db_key = timestamp_db_key (key);
607 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
609 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
612 ret = Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
613 } catch (Xapian::Error &error) {
624 /* Find the thread ID to which the message with 'message_id' belongs.
626 * Returns NULL if no message with message ID 'message_id' is in the
629 * Otherwise, returns a newly talloced string belonging to 'ctx'.
632 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
634 const char *message_id)
636 notmuch_message_t *message;
637 const char *ret = NULL;
639 message = notmuch_database_find_message (notmuch, message_id);
643 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
647 notmuch_message_destroy (message);
652 static notmuch_status_t
653 _merge_threads (notmuch_database_t *notmuch,
654 const char *winner_thread_id,
655 const char *loser_thread_id)
657 Xapian::PostingIterator loser, loser_end;
658 notmuch_message_t *message = NULL;
659 notmuch_private_status_t private_status;
660 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
662 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
664 for ( ; loser != loser_end; loser++) {
665 message = _notmuch_message_create (notmuch, notmuch,
666 *loser, &private_status);
667 if (message == NULL) {
668 ret = COERCE_STATUS (private_status,
669 "Cannot find document for doc_id from query");
673 _notmuch_message_remove_term (message, "thread", loser_thread_id);
674 _notmuch_message_add_term (message, "thread", winner_thread_id);
675 _notmuch_message_sync (message);
677 notmuch_message_destroy (message);
683 notmuch_message_destroy (message);
689 _my_talloc_free_for_g_hash (void *ptr)
694 static notmuch_status_t
695 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
696 notmuch_message_t *message,
697 notmuch_message_file_t *message_file,
698 const char **thread_id)
700 GHashTable *parents = NULL;
701 const char *refs, *in_reply_to;
702 GList *l, *keys = NULL;
703 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
705 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
706 _my_talloc_free_for_g_hash, NULL);
708 refs = notmuch_message_file_get_header (message_file, "references");
709 parse_references (message, parents, refs);
711 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
712 parse_references (message, parents, in_reply_to);
713 _notmuch_message_add_term (message, "replyto",
714 parse_message_id (message, in_reply_to, NULL));
716 keys = g_hash_table_get_keys (parents);
717 for (l = keys; l; l = l->next) {
718 char *parent_message_id;
719 const char *parent_thread_id;
721 parent_message_id = (char *) l->data;
722 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
726 if (parent_thread_id == NULL) {
727 _notmuch_message_add_term (message, "ref", parent_message_id);
729 if (*thread_id == NULL) {
730 *thread_id = talloc_strdup (message, parent_thread_id);
731 _notmuch_message_add_term (message, "thread", *thread_id);
732 } else if (strcmp (*thread_id, parent_thread_id)) {
733 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
744 g_hash_table_unref (parents);
749 static notmuch_status_t
750 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
751 notmuch_message_t *message,
752 const char **thread_id)
754 const char *message_id = notmuch_message_get_message_id (message);
755 Xapian::PostingIterator child, children_end;
756 notmuch_message_t *child_message = NULL;
757 const char *child_thread_id;
758 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
759 notmuch_private_status_t private_status;
761 find_doc_ids (notmuch, "ref", message_id, &child, &children_end);
763 for ( ; child != children_end; child++) {
765 child_message = _notmuch_message_create (message, notmuch,
766 *child, &private_status);
767 if (child_message == NULL) {
768 ret = COERCE_STATUS (private_status,
769 "Cannot find document for doc_id from query");
773 child_thread_id = notmuch_message_get_thread_id (child_message);
774 if (*thread_id == NULL) {
775 *thread_id = talloc_strdup (message, child_thread_id);
776 _notmuch_message_add_term (message, "thread", *thread_id);
777 } else if (strcmp (*thread_id, child_thread_id)) {
778 _notmuch_message_remove_term (child_message, "ref",
780 _notmuch_message_sync (child_message);
781 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
786 notmuch_message_destroy (child_message);
787 child_message = NULL;
792 notmuch_message_destroy (child_message);
797 /* Given a (mostly empty) 'message' and its corresponding
798 * 'message_file' link it to existing threads in the database.
800 * We first looke at 'message_file' and its link-relevant headers
801 * (References and In-Reply-To) for message IDs. We also look in the
802 * database for existing message that reference 'message'.p
804 * The end result is to call _notmuch_message_add_thread_id with one
805 * or more thread IDs to which this message belongs, (including
806 * generating a new thread ID if necessary if the message doesn't
807 * connect to any existing threads).
809 static notmuch_status_t
810 _notmuch_database_link_message (notmuch_database_t *notmuch,
811 notmuch_message_t *message,
812 notmuch_message_file_t *message_file)
814 notmuch_status_t status;
815 const char *thread_id = NULL;
817 status = _notmuch_database_link_message_to_parents (notmuch, message,
823 status = _notmuch_database_link_message_to_children (notmuch, message,
828 if (thread_id == NULL)
829 _notmuch_message_ensure_thread_id (message);
831 return NOTMUCH_STATUS_SUCCESS;
835 notmuch_database_add_message (notmuch_database_t *notmuch,
836 const char *filename,
837 notmuch_message_t **message_ret)
839 notmuch_message_file_t *message_file;
840 notmuch_message_t *message = NULL;
841 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
842 notmuch_private_status_t private_status;
844 const char *date, *header;
845 const char *from, *to, *subject;
851 message_file = notmuch_message_file_open (filename);
852 if (message_file == NULL) {
853 ret = NOTMUCH_STATUS_FILE_ERROR;
857 notmuch_message_file_restrict_headers (message_file,
868 /* Before we do any real work, (especially before doing a
869 * potential SHA-1 computation on the entire file's contents),
870 * let's make sure that what we're looking at looks like an
871 * actual email message.
873 from = notmuch_message_file_get_header (message_file, "from");
874 subject = notmuch_message_file_get_header (message_file, "subject");
875 to = notmuch_message_file_get_header (message_file, "to");
881 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
885 /* Now that we're sure it's mail, the first order of business
886 * is to find a message ID (or else create one ourselves). */
888 header = notmuch_message_file_get_header (message_file, "message-id");
890 message_id = parse_message_id (message_file, header, NULL);
891 /* So the header value isn't RFC-compliant, but it's
892 * better than no message-id at all. */
893 if (message_id == NULL)
894 message_id = talloc_strdup (message_file, header);
896 /* No message-id at all, let's generate one by taking a
897 * hash over the file's contents. */
898 char *sha1 = notmuch_sha1_of_file (filename);
900 /* If that failed too, something is really wrong. Give up. */
902 ret = NOTMUCH_STATUS_FILE_ERROR;
906 message_id = talloc_asprintf (message_file,
907 "notmuch-sha1-%s", sha1);
911 /* Now that we have a message ID, we get a message object,
912 * (which may or may not reference an existing document in the
915 /* Use NULL for owner since we want to free this locally. */
916 message = _notmuch_message_create_for_message_id (NULL,
921 talloc_free (message_id);
926 /* Is this a newly created message object? */
927 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
928 _notmuch_message_set_filename (message, filename);
929 _notmuch_message_add_term (message, "type", "mail");
931 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
935 ret = _notmuch_database_link_message (notmuch, message, message_file);
939 date = notmuch_message_file_get_header (message_file, "date");
940 _notmuch_message_set_date (message, date);
942 _notmuch_message_index_file (message, filename);
944 _notmuch_message_sync (message);
945 } catch (const Xapian::Error &error) {
946 fprintf (stderr, "A Xapian exception occurred: %s.\n",
947 error.get_msg().c_str());
948 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
954 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
955 *message_ret = message;
957 notmuch_message_destroy (message);
961 notmuch_message_file_close (message_file);