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 * reference: All message IDs from In-Reply-To and Re ferences
59 * headers in the message.
61 * tag: Any tags associated with this message by the user.
63 * A mail document also has two values:
65 * TIMESTAMP: The time_t value corresponding to the message's
68 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
72 * A timestamp document is used by a client of the notmuch library to
73 * maintain data necessary to allow for efficient polling of mail
74 * directories. The notmuch library does no interpretation of
75 * timestamps, but merely allows the user to store and retrieve
76 * timestamps as name/value pairs.
78 * The timestamp document is indexed with a single prefixed term:
80 * timestamp: The user's key value (likely a directory name)
82 * and has a single value:
84 * TIMESTAMP: The time_t value from the user.
87 /* With these prefix values we follow the conventions published here:
89 * http://xapian.org/docs/omega/termprefixes.html
91 * as much as makes sense. Note that I took some liberty in matching
92 * the reserved prefix values to notmuch concepts, (for example, 'G'
93 * is documented as "newsGroup (or similar entity - e.g. a web forum
94 * name)", for which I think the thread is the closest analogue in
95 * notmuch. This in spite of the fact that we will eventually be
96 * storing mailing-list messages where 'G' for "mailing list name"
97 * might be even a closer analogue. I'm treating the single-character
98 * prefixes preferentially for core notmuch concepts (which will be
99 * nearly universal to all mail messages).
102 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
104 { "reference", "XREFERENCE" },
105 { "replyto", "XREPLYTO" },
106 { "timestamp", "XTIMESTAMP" },
109 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
115 prefix_t PROBABILISTIC_PREFIX[]= {
118 { "attachment", "XATTACHMENT" },
119 { "subject", "XSUBJECT"}
123 _internal_error (const char *format, ...)
127 va_start (va_args, format);
129 fprintf (stderr, "Internal error: ");
130 vfprintf (stderr, format, va_args);
138 _find_prefix (const char *name)
142 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++)
143 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
144 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
146 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++)
147 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
148 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
150 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++)
151 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
152 return PROBABILISTIC_PREFIX[i].prefix;
154 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
160 notmuch_status_to_string (notmuch_status_t status)
163 case NOTMUCH_STATUS_SUCCESS:
164 return "No error occurred";
165 case NOTMUCH_STATUS_OUT_OF_MEMORY:
166 return "Out of memory";
167 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
168 return "A Xapian exception occurred";
169 case NOTMUCH_STATUS_FILE_ERROR:
170 return "Something went wrong trying to read or write a file";
171 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
172 return "File is not an email";
173 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
174 return "Message ID is identical to a message in database";
175 case NOTMUCH_STATUS_NULL_POINTER:
176 return "Erroneous NULL pointer";
177 case NOTMUCH_STATUS_TAG_TOO_LONG:
178 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
179 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
180 return "Unblanced number of calls to notmuch_message_freeze/thaw";
182 case NOTMUCH_STATUS_LAST_STATUS:
183 return "Unknown error status value";
188 find_doc_ids (notmuch_database_t *notmuch,
189 const char *prefix_name,
191 Xapian::PostingIterator *begin,
192 Xapian::PostingIterator *end)
194 Xapian::PostingIterator i;
197 term = talloc_asprintf (notmuch, "%s%s",
198 _find_prefix (prefix_name), value);
200 *begin = notmuch->xapian_db->postlist_begin (term);
202 *end = notmuch->xapian_db->postlist_end (term);
207 static notmuch_private_status_t
208 find_unique_doc_id (notmuch_database_t *notmuch,
209 const char *prefix_name,
211 unsigned int *doc_id)
213 Xapian::PostingIterator i, end;
215 find_doc_ids (notmuch, prefix_name, value, &i, &end);
219 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
222 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
226 static Xapian::Document
227 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
229 return notmuch->xapian_db->get_document (doc_id);
232 static notmuch_private_status_t
233 find_unique_document (notmuch_database_t *notmuch,
234 const char *prefix_name,
236 Xapian::Document *document,
237 unsigned int *doc_id)
239 notmuch_private_status_t status;
241 status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
244 *document = Xapian::Document ();
248 *document = find_document_for_doc_id (notmuch, *doc_id);
249 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
253 notmuch_database_find_message (notmuch_database_t *notmuch,
254 const char *message_id)
256 notmuch_private_status_t status;
259 status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
261 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
264 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
267 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
268 * a (potentially nested) parenthesized sequence with '\' used to
269 * escape any character (including parentheses).
271 * If the sequence to be skipped continues to the end of the string,
272 * then 'str' will be left pointing at the final terminating '\0'
276 skip_space_and_comments (const char **str)
281 while (*s && (isspace (*s) || *s == '(')) {
282 while (*s && isspace (*s))
287 while (*s && nesting) {
303 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
304 * comments, and the '<' and '>' delimeters.
306 * If not NULL, then *next will be made to point to the first character
307 * not parsed, (possibly pointing to the final '\0' terminator.
309 * Returns a newly talloc'ed string belonging to 'ctx'.
311 * Returns NULL if there is any error parsing the message-id. */
313 _parse_message_id (void *ctx, const char *message_id, const char **next)
318 if (message_id == NULL)
323 skip_space_and_comments (&s);
325 /* Skip any unstructured text as well. */
326 while (*s && *s != '<')
337 skip_space_and_comments (&s);
340 while (*end && *end != '>')
349 if (end > s && *end == '>')
354 result = talloc_strndup (ctx, s, end - s + 1);
356 /* Finally, collapse any whitespace that is within the message-id
362 for (r = result, len = strlen (r); *r; r++, len--)
363 if (*r == ' ' || *r == '\t')
364 memmove (r, r+1, len);
370 /* Parse a References header value, putting a (talloc'ed under 'ctx')
371 * copy of each referenced message-id into 'hash'.
373 * We explicitly avoid including any reference identical to
374 * 'message_id' in the result (to avoid mass confusion when a single
375 * message references itself cyclically---and yes, mail messages are
376 * not infrequent in the wild that do this---don't ask me why).
379 parse_references (void *ctx,
380 const char *message_id,
390 ref = _parse_message_id (ctx, refs, &refs);
392 if (ref && strcmp (ref, message_id))
393 g_hash_table_insert (hash, ref, NULL);
398 notmuch_database_create (const char *path)
400 notmuch_database_t *notmuch = NULL;
401 char *notmuch_path = NULL;
406 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
410 err = stat (path, &st);
412 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
413 path, strerror (errno));
417 if (! S_ISDIR (st.st_mode)) {
418 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
423 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
425 err = mkdir (notmuch_path, 0755);
428 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
429 notmuch_path, strerror (errno));
433 notmuch = notmuch_database_open (path);
437 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;
451 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
453 fprintf (stderr, "Out of memory\n");
457 err = stat (notmuch_path, &st);
459 fprintf (stderr, "Error opening database at %s: %s\n",
460 notmuch_path, strerror (errno));
464 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
466 fprintf (stderr, "Out of memory\n");
470 notmuch = talloc (NULL, notmuch_database_t);
471 notmuch->path = talloc_strdup (notmuch, path);
473 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
474 notmuch->path[strlen (notmuch->path) - 1] = '\0';
477 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
478 Xapian::DB_CREATE_OR_OPEN);
479 notmuch->query_parser = new Xapian::QueryParser;
480 notmuch->term_gen = new Xapian::TermGenerator;
481 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
483 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
484 notmuch->query_parser->set_database (*notmuch->xapian_db);
485 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
486 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
488 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
489 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
490 notmuch->query_parser->add_boolean_prefix (prefix->name,
494 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
495 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
496 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
498 } catch (const Xapian::Error &error) {
499 fprintf (stderr, "A Xapian exception occurred: %s\n",
500 error.get_msg().c_str());
514 notmuch_database_close (notmuch_database_t *notmuch)
516 notmuch->xapian_db->flush ();
518 delete notmuch->term_gen;
519 delete notmuch->query_parser;
520 delete notmuch->xapian_db;
521 talloc_free (notmuch);
525 notmuch_database_get_path (notmuch_database_t *notmuch)
527 return notmuch->path;
530 static notmuch_private_status_t
531 find_timestamp_document (notmuch_database_t *notmuch, const char *db_key,
532 Xapian::Document *doc, unsigned int *doc_id)
534 return find_unique_document (notmuch, "timestamp", db_key, doc, doc_id);
537 /* We allow the user to use arbitrarily long keys for timestamps,
538 * (they're for filesystem paths after all, which have no limit we
539 * know about). But we have a term-length limit. So if we exceed that,
540 * we'll use the SHA-1 of the user's key as the actual key for
541 * constructing a database term.
543 * Caution: This function returns a newly allocated string which the
544 * caller should free() when finished.
547 timestamp_db_key (const char *key)
549 int term_len = strlen (_find_prefix ("timestamp")) + strlen (key);
551 if (term_len > NOTMUCH_TERM_MAX)
552 return notmuch_sha1_of_string (key);
558 notmuch_database_set_timestamp (notmuch_database_t *notmuch,
559 const char *key, time_t timestamp)
561 Xapian::Document doc;
563 notmuch_private_status_t status;
564 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
567 db_key = timestamp_db_key (key);
570 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
572 doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
573 Xapian::sortable_serialise (timestamp));
575 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
576 char *term = talloc_asprintf (NULL, "%s%s",
577 _find_prefix ("timestamp"), db_key);
581 notmuch->xapian_db->add_document (doc);
583 notmuch->xapian_db->replace_document (doc_id, doc);
586 } catch (Xapian::Error &error) {
587 fprintf (stderr, "A Xapian exception occurred: %s.\n",
588 error.get_msg().c_str());
589 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
599 notmuch_database_get_timestamp (notmuch_database_t *notmuch, const char *key)
601 Xapian::Document doc;
603 notmuch_private_status_t status;
607 db_key = timestamp_db_key (key);
610 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
612 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
615 ret = Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
616 } catch (Xapian::Error &error) {
627 /* Find the thread ID to which the message with 'message_id' belongs.
629 * Returns NULL if no message with message ID 'message_id' is in the
632 * Otherwise, returns a newly talloced string belonging to 'ctx'.
635 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
637 const char *message_id)
639 notmuch_message_t *message;
640 const char *ret = NULL;
642 message = notmuch_database_find_message (notmuch, message_id);
646 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
650 notmuch_message_destroy (message);
655 static notmuch_status_t
656 _merge_threads (notmuch_database_t *notmuch,
657 const char *winner_thread_id,
658 const char *loser_thread_id)
660 Xapian::PostingIterator loser, loser_end;
661 notmuch_message_t *message = NULL;
662 notmuch_private_status_t private_status;
663 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
665 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
667 for ( ; loser != loser_end; loser++) {
668 message = _notmuch_message_create (notmuch, notmuch,
669 *loser, &private_status);
670 if (message == NULL) {
671 ret = COERCE_STATUS (private_status,
672 "Cannot find document for doc_id from query");
676 _notmuch_message_remove_term (message, "thread", loser_thread_id);
677 _notmuch_message_add_term (message, "thread", winner_thread_id);
678 _notmuch_message_sync (message);
680 notmuch_message_destroy (message);
686 notmuch_message_destroy (message);
692 _my_talloc_free_for_g_hash (void *ptr)
697 static notmuch_status_t
698 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
699 notmuch_message_t *message,
700 notmuch_message_file_t *message_file,
701 const char **thread_id)
703 GHashTable *parents = NULL;
704 const char *refs, *in_reply_to, *in_reply_to_message_id;
705 GList *l, *keys = NULL;
706 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
708 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
709 _my_talloc_free_for_g_hash, NULL);
711 refs = notmuch_message_file_get_header (message_file, "references");
712 parse_references (message, notmuch_message_get_message_id (message),
715 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
716 parse_references (message, notmuch_message_get_message_id (message),
717 parents, in_reply_to);
719 /* Carefully avoid adding any self-referential in-reply-to term. */
720 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
721 if (strcmp (in_reply_to_message_id,
722 notmuch_message_get_message_id (message)))
724 _notmuch_message_add_term (message, "replyto",
725 _parse_message_id (message, in_reply_to, NULL));
728 keys = g_hash_table_get_keys (parents);
729 for (l = keys; l; l = l->next) {
730 char *parent_message_id;
731 const char *parent_thread_id;
733 parent_message_id = (char *) l->data;
734 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
738 if (parent_thread_id == NULL) {
739 _notmuch_message_add_term (message, "reference",
742 if (*thread_id == NULL) {
743 *thread_id = talloc_strdup (message, parent_thread_id);
744 _notmuch_message_add_term (message, "thread", *thread_id);
745 } else if (strcmp (*thread_id, parent_thread_id)) {
746 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
757 g_hash_table_unref (parents);
762 static notmuch_status_t
763 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
764 notmuch_message_t *message,
765 const char **thread_id)
767 const char *message_id = notmuch_message_get_message_id (message);
768 Xapian::PostingIterator child, children_end;
769 notmuch_message_t *child_message = NULL;
770 const char *child_thread_id;
771 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
772 notmuch_private_status_t private_status;
774 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
776 for ( ; child != children_end; child++) {
778 child_message = _notmuch_message_create (message, notmuch,
779 *child, &private_status);
780 if (child_message == NULL) {
781 ret = COERCE_STATUS (private_status,
782 "Cannot find document for doc_id from query");
786 child_thread_id = notmuch_message_get_thread_id (child_message);
787 if (*thread_id == NULL) {
788 *thread_id = talloc_strdup (message, child_thread_id);
789 _notmuch_message_add_term (message, "thread", *thread_id);
790 } else if (strcmp (*thread_id, child_thread_id)) {
791 _notmuch_message_remove_term (child_message, "reference",
793 _notmuch_message_sync (child_message);
794 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
799 notmuch_message_destroy (child_message);
800 child_message = NULL;
805 notmuch_message_destroy (child_message);
810 /* Given a (mostly empty) 'message' and its corresponding
811 * 'message_file' link it to existing threads in the database.
813 * We first look at 'message_file' and its link-relevant headers
814 * (References and In-Reply-To) for message IDs. We also look in the
815 * database for existing message that reference 'message'.p
817 * The end result is to call _notmuch_message_add_thread_id with one
818 * or more thread IDs to which this message belongs, (including
819 * generating a new thread ID if necessary if the message doesn't
820 * connect to any existing threads).
822 static notmuch_status_t
823 _notmuch_database_link_message (notmuch_database_t *notmuch,
824 notmuch_message_t *message,
825 notmuch_message_file_t *message_file)
827 notmuch_status_t status;
828 const char *thread_id = NULL;
830 status = _notmuch_database_link_message_to_parents (notmuch, message,
836 status = _notmuch_database_link_message_to_children (notmuch, message,
841 if (thread_id == NULL)
842 _notmuch_message_ensure_thread_id (message);
844 return NOTMUCH_STATUS_SUCCESS;
848 notmuch_database_add_message (notmuch_database_t *notmuch,
849 const char *filename,
850 notmuch_message_t **message_ret)
852 notmuch_message_file_t *message_file;
853 notmuch_message_t *message = NULL;
854 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
855 notmuch_private_status_t private_status;
857 const char *date, *header;
858 const char *from, *to, *subject;
864 message_file = notmuch_message_file_open (filename);
865 if (message_file == NULL) {
866 ret = NOTMUCH_STATUS_FILE_ERROR;
870 notmuch_message_file_restrict_headers (message_file,
881 /* Before we do any real work, (especially before doing a
882 * potential SHA-1 computation on the entire file's contents),
883 * let's make sure that what we're looking at looks like an
884 * actual email message.
886 from = notmuch_message_file_get_header (message_file, "from");
887 subject = notmuch_message_file_get_header (message_file, "subject");
888 to = notmuch_message_file_get_header (message_file, "to");
894 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
898 /* Now that we're sure it's mail, the first order of business
899 * is to find a message ID (or else create one ourselves). */
901 header = notmuch_message_file_get_header (message_file, "message-id");
903 message_id = _parse_message_id (message_file, header, NULL);
904 /* So the header value isn't RFC-compliant, but it's
905 * better than no message-id at all. */
906 if (message_id == NULL)
907 message_id = talloc_strdup (message_file, header);
909 /* No message-id at all, let's generate one by taking a
910 * hash over the file's contents. */
911 char *sha1 = notmuch_sha1_of_file (filename);
913 /* If that failed too, something is really wrong. Give up. */
915 ret = NOTMUCH_STATUS_FILE_ERROR;
919 message_id = talloc_asprintf (message_file,
920 "notmuch-sha1-%s", sha1);
924 /* Now that we have a message ID, we get a message object,
925 * (which may or may not reference an existing document in the
928 message = _notmuch_message_create_for_message_id (notmuch,
932 talloc_free (message_id);
937 /* Is this a newly created message object? */
938 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
939 _notmuch_message_set_filename (message, filename);
940 _notmuch_message_add_term (message, "type", "mail");
942 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
946 ret = _notmuch_database_link_message (notmuch, message, message_file);
950 date = notmuch_message_file_get_header (message_file, "date");
951 _notmuch_message_set_date (message, date);
953 _notmuch_message_index_file (message, filename);
955 _notmuch_message_sync (message);
956 } catch (const Xapian::Error &error) {
957 fprintf (stderr, "A Xapian exception occurred: %s.\n",
958 error.get_msg().c_str());
959 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
965 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
966 *message_ret = message;
968 notmuch_message_destroy (message);
972 notmuch_message_file_close (message_file);