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[] = {
107 { "ref", "XREFERENCE" },
108 { "timestamp", "XTIMESTAMP" },
109 { "contact", "XCONTACT" }
112 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
118 prefix_t PROBABILISTIC_PREFIX[]= {
121 { "attachment", "XATTACHMENT" },
122 { "subject", "XSUBJECT"}
126 _internal_error (const char *format, ...)
130 va_start (va_args, format);
132 fprintf (stderr, "Internal error: ");
133 vfprintf (stderr, format, va_args);
141 _find_prefix (const char *name)
145 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++)
146 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
147 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
149 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++)
150 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
151 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
153 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++)
154 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
155 return PROBABILISTIC_PREFIX[i].prefix;
157 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
163 notmuch_status_to_string (notmuch_status_t status)
166 case NOTMUCH_STATUS_SUCCESS:
167 return "No error occurred";
168 case NOTMUCH_STATUS_OUT_OF_MEMORY:
169 return "Out of memory";
170 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
171 return "A Xapian exception occurred";
172 case NOTMUCH_STATUS_FILE_ERROR:
173 return "Something went wrong trying to read or write a file";
174 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
175 return "File is not an email";
176 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
177 return "Message ID is identical to a message in database";
178 case NOTMUCH_STATUS_NULL_POINTER:
179 return "Erroneous NULL pointer";
180 case NOTMUCH_STATUS_TAG_TOO_LONG:
181 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
182 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
183 return "Unblanced number of calls to notmuch_message_freeze/thaw";
185 case NOTMUCH_STATUS_LAST_STATUS:
186 return "Unknown error status value";
191 find_doc_ids (notmuch_database_t *notmuch,
192 const char *prefix_name,
194 Xapian::PostingIterator *begin,
195 Xapian::PostingIterator *end)
197 Xapian::PostingIterator i;
200 term = talloc_asprintf (notmuch, "%s%s",
201 _find_prefix (prefix_name), value);
203 *begin = notmuch->xapian_db->postlist_begin (term);
205 *end = notmuch->xapian_db->postlist_end (term);
210 static notmuch_private_status_t
211 find_unique_doc_id (notmuch_database_t *notmuch,
212 const char *prefix_name,
214 unsigned int *doc_id)
216 Xapian::PostingIterator i, end;
218 find_doc_ids (notmuch, prefix_name, value, &i, &end);
222 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
225 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
229 static Xapian::Document
230 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
232 return notmuch->xapian_db->get_document (doc_id);
235 static notmuch_private_status_t
236 find_unique_document (notmuch_database_t *notmuch,
237 const char *prefix_name,
239 Xapian::Document *document,
240 unsigned int *doc_id)
242 notmuch_private_status_t status;
244 status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
247 *document = Xapian::Document ();
251 *document = find_document_for_doc_id (notmuch, *doc_id);
252 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
256 notmuch_database_find_message (notmuch_database_t *notmuch,
257 const char *message_id)
259 notmuch_private_status_t status;
262 status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
264 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
267 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
270 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
271 * a (potentially nested) parenthesized sequence with '\' used to
272 * escape any character (including parentheses).
274 * If the sequence to be skipped continues to the end of the string,
275 * then 'str' will be left pointing at the final terminating '\0'
279 skip_space_and_comments (const char **str)
284 while (*s && (isspace (*s) || *s == '(')) {
285 while (*s && isspace (*s))
290 while (*s && nesting) {
306 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
307 * comments, and the '<' and '>' delimeters.
309 * If not NULL, then *next will be made to point to the first character
310 * not parsed, (possibly pointing to the final '\0' terminator.
312 * Returns a newly talloc'ed string belonging to 'ctx'.
314 * Returns NULL if there is any error parsing the message-id. */
316 parse_message_id (void *ctx, const char *message_id, const char **next)
321 if (message_id == NULL)
326 skip_space_and_comments (&s);
328 /* Skip any unstructured text as well. */
329 while (*s && *s != '<')
340 skip_space_and_comments (&s);
343 while (*end && *end != '>')
352 if (end > s && *end == '>')
357 result = talloc_strndup (ctx, s, end - s + 1);
359 /* Finally, collapse any whitespace that is within the message-id
365 for (r = result, len = strlen (r); *r; r++, len--)
366 if (*r == ' ' || *r == '\t')
367 memmove (r, r+1, len);
373 /* Parse a References header value, putting a (talloc'ed under 'ctx')
374 * copy of each referenced message-id into 'hash'. */
376 parse_references (void *ctx,
386 ref = parse_message_id (ctx, refs, &refs);
389 g_hash_table_insert (hash, ref, NULL);
394 notmuch_database_default_path (void)
398 if (getenv ("NOTMUCH_BASE"))
399 return strdup (getenv ("NOTMUCH_BASE"));
401 if (asprintf (&path, "%s/mail", getenv ("HOME")) == -1) {
402 fprintf (stderr, "Out of memory.\n");
410 notmuch_database_create (const char *path)
412 notmuch_database_t *notmuch = NULL;
413 char *notmuch_path = NULL;
416 char *local_path = NULL;
419 path = local_path = notmuch_database_default_path ();
421 err = stat (path, &st);
423 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
424 path, strerror (errno));
428 if (! S_ISDIR (st.st_mode)) {
429 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
434 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
436 err = mkdir (notmuch_path, 0755);
439 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
440 notmuch_path, strerror (errno));
444 notmuch = notmuch_database_open (path);
448 talloc_free (notmuch_path);
456 notmuch_database_open (const char *path)
458 notmuch_database_t *notmuch = NULL;
459 char *notmuch_path = NULL, *xapian_path = NULL;
462 char *local_path = NULL;
466 path = local_path = notmuch_database_default_path ();
468 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
470 fprintf (stderr, "Out of memory\n");
474 err = stat (notmuch_path, &st);
476 fprintf (stderr, "Error opening database at %s: %s\n",
477 notmuch_path, strerror (errno));
481 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
483 fprintf (stderr, "Out of memory\n");
487 notmuch = talloc (NULL, notmuch_database_t);
488 notmuch->path = talloc_strdup (notmuch, path);
490 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
491 notmuch->path[strlen (notmuch->path) - 1] = '\0';
494 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
495 Xapian::DB_CREATE_OR_OPEN);
496 notmuch->query_parser = new Xapian::QueryParser;
497 notmuch->term_gen = new Xapian::TermGenerator;
498 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
500 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
501 notmuch->query_parser->set_database (*notmuch->xapian_db);
502 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
503 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
505 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
506 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
507 notmuch->query_parser->add_boolean_prefix (prefix->name,
511 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
512 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
513 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
515 } catch (const Xapian::Error &error) {
516 fprintf (stderr, "A Xapian exception occurred: %s\n",
517 error.get_msg().c_str());
533 notmuch_database_close (notmuch_database_t *notmuch)
535 notmuch->xapian_db->flush ();
537 delete notmuch->term_gen;
538 delete notmuch->query_parser;
539 delete notmuch->xapian_db;
540 talloc_free (notmuch);
544 notmuch_database_get_path (notmuch_database_t *notmuch)
546 return notmuch->path;
549 static notmuch_private_status_t
550 find_timestamp_document (notmuch_database_t *notmuch, const char *db_key,
551 Xapian::Document *doc, unsigned int *doc_id)
553 return find_unique_document (notmuch, "timestamp", db_key, doc, doc_id);
556 /* We allow the user to use arbitrarily long keys for timestamps,
557 * (they're for filesystem paths after all, which have no limit we
558 * know about). But we have a term-length limit. So if we exceed that,
559 * we'll use the SHA-1 of the user's key as the actual key for
560 * constructing a database term.
562 * Caution: This function returns a newly allocated string which the
563 * caller should free() when finished.
566 timestamp_db_key (const char *key)
568 int term_len = strlen (_find_prefix ("timestamp")) + strlen (key);
570 if (term_len > NOTMUCH_TERM_MAX)
571 return notmuch_sha1_of_string (key);
577 notmuch_database_set_timestamp (notmuch_database_t *notmuch,
578 const char *key, time_t timestamp)
580 Xapian::Document doc;
582 notmuch_private_status_t status;
583 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
586 db_key = timestamp_db_key (key);
589 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
591 doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
592 Xapian::sortable_serialise (timestamp));
594 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
595 char *term = talloc_asprintf (NULL, "%s%s",
596 _find_prefix ("timestamp"), db_key);
600 notmuch->xapian_db->add_document (doc);
602 notmuch->xapian_db->replace_document (doc_id, doc);
605 } catch (Xapian::Error &error) {
606 fprintf (stderr, "A Xapian exception occurred: %s.\n",
607 error.get_msg().c_str());
608 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
618 notmuch_database_get_timestamp (notmuch_database_t *notmuch, const char *key)
620 Xapian::Document doc;
622 notmuch_private_status_t status;
626 db_key = timestamp_db_key (key);
629 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
631 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
634 ret = Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
635 } catch (Xapian::Error &error) {
646 /* Find the thread ID to which the message with 'message_id' belongs.
648 * Returns NULL if no message with message ID 'message_id' is in the
651 * Otherwise, returns a newly talloced string belonging to 'ctx'.
654 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
656 const char *message_id)
658 notmuch_message_t *message;
659 const char *ret = NULL;
661 message = notmuch_database_find_message (notmuch, message_id);
665 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
669 notmuch_message_destroy (message);
674 static notmuch_status_t
675 _merge_threads (notmuch_database_t *notmuch,
676 const char *winner_thread_id,
677 const char *loser_thread_id)
679 Xapian::PostingIterator loser, loser_end;
680 notmuch_message_t *message = NULL;
681 notmuch_private_status_t private_status;
682 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
684 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
686 for ( ; loser != loser_end; loser++) {
687 message = _notmuch_message_create (notmuch, notmuch,
688 *loser, &private_status);
689 if (message == NULL) {
690 ret = COERCE_STATUS (private_status,
691 "Cannot find document for doc_id from query");
695 _notmuch_message_remove_term (message, "thread", loser_thread_id);
696 _notmuch_message_add_term (message, "thread", winner_thread_id);
697 _notmuch_message_sync (message);
699 notmuch_message_destroy (message);
705 notmuch_message_destroy (message);
711 _my_talloc_free_for_g_hash (void *ptr)
716 static notmuch_status_t
717 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
718 notmuch_message_t *message,
719 notmuch_message_file_t *message_file,
720 const char **thread_id)
722 GHashTable *parents = NULL;
723 const char *refs, *in_reply_to;
724 GList *l, *keys = NULL;
725 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
727 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
728 _my_talloc_free_for_g_hash, NULL);
730 refs = notmuch_message_file_get_header (message_file, "references");
731 parse_references (message, parents, refs);
733 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
734 parse_references (message, parents, in_reply_to);
736 keys = g_hash_table_get_keys (parents);
737 for (l = keys; l; l = l->next) {
738 char *parent_message_id;
739 const char *parent_thread_id;
741 parent_message_id = (char *) l->data;
742 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
746 if (parent_thread_id == NULL) {
747 _notmuch_message_add_term (message, "ref", parent_message_id);
749 if (*thread_id == NULL) {
750 *thread_id = talloc_strdup (message, parent_thread_id);
751 _notmuch_message_add_term (message, "thread", *thread_id);
752 } else if (strcmp (*thread_id, parent_thread_id)) {
753 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
764 g_hash_table_unref (parents);
769 static notmuch_status_t
770 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
771 notmuch_message_t *message,
772 const char **thread_id)
774 const char *message_id = notmuch_message_get_message_id (message);
775 Xapian::PostingIterator child, children_end;
776 notmuch_message_t *child_message = NULL;
777 const char *child_thread_id;
778 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
779 notmuch_private_status_t private_status;
781 find_doc_ids (notmuch, "ref", message_id, &child, &children_end);
783 for ( ; child != children_end; child++) {
785 child_message = _notmuch_message_create (message, notmuch,
786 *child, &private_status);
787 if (child_message == NULL) {
788 ret = COERCE_STATUS (private_status,
789 "Cannot find document for doc_id from query");
793 child_thread_id = notmuch_message_get_thread_id (child_message);
794 if (*thread_id == NULL) {
795 *thread_id = talloc_strdup (message, child_thread_id);
796 _notmuch_message_add_term (message, "thread", *thread_id);
797 } else if (strcmp (*thread_id, child_thread_id)) {
798 _notmuch_message_remove_term (child_message, "ref",
800 _notmuch_message_sync (child_message);
801 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
806 notmuch_message_destroy (child_message);
807 child_message = NULL;
812 notmuch_message_destroy (child_message);
817 /* Given a (mostly empty) 'message' and its corresponding
818 * 'message_file' link it to existing threads in the database.
820 * We first looke at 'message_file' and its link-relevant headers
821 * (References and In-Reply-To) for message IDs. We also look in the
822 * database for existing message that reference 'message'.p
824 * The end result is to call _notmuch_message_add_thread_id with one
825 * or more thread IDs to which this message belongs, (including
826 * generating a new thread ID if necessary if the message doesn't
827 * connect to any existing threads).
829 static notmuch_status_t
830 _notmuch_database_link_message (notmuch_database_t *notmuch,
831 notmuch_message_t *message,
832 notmuch_message_file_t *message_file)
834 notmuch_status_t status;
835 const char *thread_id = NULL;
837 status = _notmuch_database_link_message_to_parents (notmuch, message,
843 status = _notmuch_database_link_message_to_children (notmuch, message,
848 if (thread_id == NULL)
849 _notmuch_message_ensure_thread_id (message);
851 return NOTMUCH_STATUS_SUCCESS;
855 notmuch_database_add_message (notmuch_database_t *notmuch,
856 const char *filename,
857 notmuch_message_t **message_ret)
859 notmuch_message_file_t *message_file;
860 notmuch_message_t *message;
861 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
862 notmuch_private_status_t private_status;
864 const char *date, *header;
865 const char *from, *to, *subject;
871 message_file = notmuch_message_file_open (filename);
872 if (message_file == NULL) {
873 ret = NOTMUCH_STATUS_FILE_ERROR;
877 notmuch_message_file_restrict_headers (message_file,
888 /* Before we do any real work, (especially before doing a
889 * potential SHA-1 computation on the entire file's contents),
890 * let's make sure that what we're looking at looks like an
891 * actual email message.
893 from = notmuch_message_file_get_header (message_file, "from");
894 subject = notmuch_message_file_get_header (message_file, "subject");
895 to = notmuch_message_file_get_header (message_file, "to");
901 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
905 /* Now that we're sure it's mail, the first order of business
906 * is to find a message ID (or else create one ourselves). */
908 header = notmuch_message_file_get_header (message_file, "message-id");
910 message_id = parse_message_id (message_file, header, NULL);
911 /* So the header value isn't RFC-compliant, but it's
912 * better than no message-id at all. */
913 if (message_id == NULL)
914 message_id = talloc_strdup (message_file, header);
916 /* No message-id at all, let's generate one by taking a
917 * hash over the file's contents. */
918 char *sha1 = notmuch_sha1_of_file (filename);
920 /* If that failed too, something is really wrong. Give up. */
922 ret = NOTMUCH_STATUS_FILE_ERROR;
926 message_id = talloc_asprintf (message_file,
927 "notmuch-sha1-%s", sha1);
931 /* Now that we have a message ID, we get a message object,
932 * (which may or may not reference an existing document in the
935 /* Use NULL for owner since we want to free this locally. */
936 message = _notmuch_message_create_for_message_id (NULL,
941 talloc_free (message_id);
946 /* Is this a newly created message object? */
947 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
948 _notmuch_message_set_filename (message, filename);
949 _notmuch_message_add_term (message, "type", "mail");
951 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
955 ret = _notmuch_database_link_message (notmuch, message, message_file);
959 date = notmuch_message_file_get_header (message_file, "date");
960 _notmuch_message_set_date (message, date);
962 _notmuch_message_index_file (message, filename);
964 _notmuch_message_sync (message);
965 } catch (const Xapian::Error &error) {
966 fprintf (stderr, "A Xapian exception occurred: %s.\n",
967 error.get_msg().c_str());
968 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
974 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
975 *message_ret = message;
977 notmuch_message_destroy (message);
981 notmuch_message_file_close (message_file);