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_strdup_printf, 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 * Multiple terms of given prefix:
56 * ref: The message IDs from all In-Reply-To and References
57 * headers in the message.
59 * tag: Any tags associated with this message by the user.
61 * thread: The thread ID of all threads to which the mail belongs
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 * TIMETAMPS: 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[] = {
105 { "ref", "XREFERENCE" },
106 { "timestamp", "XTIMESTAMP" },
109 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
115 _find_prefix (const char *name)
119 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++)
120 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
121 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
123 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++)
124 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
125 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
127 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
133 notmuch_status_to_string (notmuch_status_t status)
136 case NOTMUCH_STATUS_SUCCESS:
137 return "No error occurred";
138 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
139 return "A Xapian exception occurred";
140 case NOTMUCH_STATUS_FILE_ERROR:
141 return "Something went wrong trying to read or write a file";
142 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
143 return "File is not an email";
144 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
145 return "Message ID is identical to a message in database";
146 case NOTMUCH_STATUS_NULL_POINTER:
147 return "Erroneous NULL pointer";
148 case NOTMUCH_STATUS_TAG_TOO_LONG:
149 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
151 case NOTMUCH_STATUS_LAST_STATUS:
152 return "Unknown error status value";
156 /* XXX: We should drop this function and convert all callers to call
157 * _notmuch_message_add_term instead. */
159 add_term (Xapian::Document doc,
160 const char *prefix_name,
169 prefix = _find_prefix (prefix_name);
171 term = g_strdup_printf ("%s%s", prefix, value);
173 if (strlen (term) <= NOTMUCH_TERM_MAX)
180 find_doc_ids (notmuch_database_t *notmuch,
181 const char *prefix_name,
183 Xapian::PostingIterator *begin,
184 Xapian::PostingIterator *end)
186 Xapian::PostingIterator i;
189 term = g_strdup_printf ("%s%s", _find_prefix (prefix_name), value);
191 *begin = notmuch->xapian_db->postlist_begin (term);
193 *end = notmuch->xapian_db->postlist_end (term);
198 static notmuch_private_status_t
199 find_unique_doc_id (notmuch_database_t *notmuch,
200 const char *prefix_name,
202 unsigned int *doc_id)
204 Xapian::PostingIterator i, end;
206 find_doc_ids (notmuch, prefix_name, value, &i, &end);
210 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
213 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
217 static Xapian::Document
218 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
220 return notmuch->xapian_db->get_document (doc_id);
223 static notmuch_private_status_t
224 find_unique_document (notmuch_database_t *notmuch,
225 const char *prefix_name,
227 Xapian::Document *document,
228 unsigned int *doc_id)
230 notmuch_private_status_t status;
232 status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
235 *document = Xapian::Document ();
239 *document = find_document_for_doc_id (notmuch, *doc_id);
240 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
243 /* XXX: Should rewrite this to accept a notmuch_message_t* instead of
244 * a Xapian:Document and then we could just use
245 * notmuch_message_get_thread_ids instead of duplicating its logic
248 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
251 Xapian::TermIterator i;
252 const char *prefix_str = _find_prefix ("thread");
255 assert (strlen (prefix_str) == 1);
257 prefix = *prefix_str;
259 i = doc.termlist_begin ();
260 i.skip_to (prefix_str);
263 if (i == doc.termlist_end ())
266 if (value_string.empty () || value_string[0] != prefix)
268 g_hash_table_insert (thread_ids,
269 strdup (value_string.c_str () + 1), NULL);
275 notmuch_database_find_message (notmuch_database_t *notmuch,
276 const char *message_id)
278 notmuch_private_status_t status;
281 status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
283 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
286 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
289 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
290 * given message based on looking into the database for any messages
291 * referenced in parents, and also for any messages in the database
292 * referencing message_id.
294 * Caller should free all strings in the array and the array itself,
295 * (g_ptr_array_free) when done. */
297 find_thread_ids (notmuch_database_t *notmuch,
299 const char *message_id)
301 Xapian::PostingIterator child, children_end;
302 Xapian::Document doc;
303 GHashTable *thread_ids;
306 const char *parent_message_id;
309 thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
312 find_doc_ids (notmuch, "ref", message_id, &child, &children_end);
313 for ( ; child != children_end; child++) {
314 doc = find_document_for_doc_id (notmuch, *child);
315 insert_thread_id (thread_ids, doc);
318 for (i = 0; i < parents->len; i++) {
319 notmuch_message_t *parent;
320 notmuch_thread_ids_t *ids;
322 parent_message_id = (char *) g_ptr_array_index (parents, i);
323 parent = notmuch_database_find_message (notmuch, parent_message_id);
327 for (ids = notmuch_message_get_thread_ids (parent);
328 notmuch_thread_ids_has_more (ids);
329 notmuch_thread_ids_advance (ids))
333 id = notmuch_thread_ids_get (ids);
334 g_hash_table_insert (thread_ids, strdup (id), NULL);
337 notmuch_message_destroy (parent);
340 result = g_ptr_array_new ();
342 keys = g_hash_table_get_keys (thread_ids);
343 for (l = keys; l; l = l->next) {
344 char *id = (char *) l->data;
345 g_ptr_array_add (result, id);
349 /* We're done with the hash table, but we've taken the pointers to
350 * the allocated strings and put them into our result array, so
351 * tell the hash not to free them on its way out. */
352 g_hash_table_steal_all (thread_ids);
353 g_hash_table_unref (thread_ids);
358 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
359 * a (potentially nested) parenthesized sequence with '\' used to
360 * escape any character (including parentheses).
362 * If the sequence to be skipped continues to the end of the string,
363 * then 'str' will be left pointing at the final terminating '\0'
367 skip_space_and_comments (const char **str)
372 while (*s && (isspace (*s) || *s == '(')) {
373 while (*s && isspace (*s))
378 while (*s && nesting) {
394 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
395 * comments, and the '<' and '>' delimeters.
397 * If not NULL, then *next will be made to point to the first character
398 * not parsed, (possibly pointing to the final '\0' terminator.
400 * Returns a newly allocated string which the caller should free()
403 * Returns NULL if there is any error parsing the message-id. */
405 parse_message_id (const char *message_id, const char **next)
410 if (message_id == NULL)
415 skip_space_and_comments (&s);
417 /* Skip any unstructured text as well. */
418 while (*s && *s != '<')
429 skip_space_and_comments (&s);
432 while (*end && *end != '>')
441 if (end > s && *end == '>')
446 result = strndup (s, end - s + 1);
448 /* Finally, collapse any whitespace that is within the message-id
454 for (r = result, len = strlen (r); *r; r++, len--)
455 if (*r == ' ' || *r == '\t')
456 memmove (r, r+1, len);
462 /* Parse a References header value, putting a copy of each referenced
463 * message-id into 'array'. */
465 parse_references (GPtrArray *array,
474 ref = parse_message_id (refs, &refs);
477 g_ptr_array_add (array, ref);
482 notmuch_database_default_path (void)
484 if (getenv ("NOTMUCH_BASE"))
485 return strdup (getenv ("NOTMUCH_BASE"));
487 return g_strdup_printf ("%s/mail", getenv ("HOME"));
491 notmuch_database_create (const char *path)
493 notmuch_database_t *notmuch = NULL;
494 char *notmuch_path = NULL;
497 char *local_path = NULL;
500 path = local_path = notmuch_database_default_path ();
502 err = stat (path, &st);
504 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
505 path, strerror (errno));
509 if (! S_ISDIR (st.st_mode)) {
510 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
515 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
517 err = mkdir (notmuch_path, 0755);
520 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
521 notmuch_path, strerror (errno));
525 notmuch = notmuch_database_open (path);
537 notmuch_database_open (const char *path)
539 notmuch_database_t *notmuch = NULL;
540 char *notmuch_path = NULL, *xapian_path = NULL;
543 char *local_path = NULL;
547 path = local_path = notmuch_database_default_path ();
549 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
551 err = stat (notmuch_path, &st);
553 fprintf (stderr, "Error opening database at %s: %s\n",
554 notmuch_path, strerror (errno));
558 xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
560 notmuch = talloc (NULL, notmuch_database_t);
561 notmuch->path = talloc_strdup (notmuch, path);
564 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
565 Xapian::DB_CREATE_OR_OPEN);
566 notmuch->query_parser = new Xapian::QueryParser;
567 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
568 notmuch->query_parser->set_database (*notmuch->xapian_db);
570 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
571 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
572 notmuch->query_parser->add_boolean_prefix (prefix->name,
575 } catch (const Xapian::Error &error) {
576 fprintf (stderr, "A Xapian exception occurred: %s\n",
577 error.get_msg().c_str());
592 notmuch_database_close (notmuch_database_t *notmuch)
594 delete notmuch->query_parser;
595 delete notmuch->xapian_db;
596 talloc_free (notmuch);
600 notmuch_database_get_path (notmuch_database_t *notmuch)
602 return notmuch->path;
605 notmuch_private_status_t
606 find_timestamp_document (notmuch_database_t *notmuch, const char *db_key,
607 Xapian::Document *doc, unsigned int *doc_id)
609 return find_unique_document (notmuch, "timestamp", db_key, doc, doc_id);
612 /* We allow the user to use arbitrarily long keys for timestamps,
613 * (they're for filesystem paths after all, which have no limit we
614 * know about). But we have a term-length limit. So if we exceed that,
615 * we'll use the SHA-1 of the user's key as the actual key for
616 * constructing a database term.
618 * Caution: This function returns a newly allocated string which the
619 * caller should free() when finished.
622 timestamp_db_key (const char *key)
624 int term_len = strlen (_find_prefix ("timestamp")) + strlen (key);
626 if (term_len > NOTMUCH_TERM_MAX)
627 return notmuch_sha1_of_string (key);
633 notmuch_database_set_timestamp (notmuch_database_t *notmuch,
634 const char *key, time_t timestamp)
636 Xapian::Document doc;
638 notmuch_private_status_t status;
639 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
642 db_key = timestamp_db_key (key);
645 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
647 doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
648 Xapian::sortable_serialise (timestamp));
650 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
651 char *term = talloc_asprintf (NULL, "%s%s",
652 _find_prefix ("timestamp"), db_key);
656 notmuch->xapian_db->add_document (doc);
658 notmuch->xapian_db->replace_document (doc_id, doc);
661 } catch (Xapian::Error &error) {
662 fprintf (stderr, "A Xapian exception occurred: %s.\n",
663 error.get_msg().c_str());
664 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
674 notmuch_database_get_timestamp (notmuch_database_t *notmuch, const char *key)
676 Xapian::Document doc;
678 notmuch_private_status_t status;
682 db_key = timestamp_db_key (key);
685 status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
687 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
690 ret = Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
691 } catch (Xapian::Error &error) {
702 /* Given a (mostly empty) 'message' and its corresponding
703 * 'message_file' link it to existing threads in the database.
705 * We first looke at 'message_file' and its link-relevant headers
706 * (References and In-Reply-To) for message IDs. We also look in the
707 * database for existing message that reference 'message'.p
709 * The end result is to call _notmuch_message_add_thread_id with one
710 * or more thread IDs to which this message belongs, (including
711 * generating a new thread ID if necessary if the message doesn't
712 * connect to any existing threads).
714 static notmuch_status_t
715 _notmuch_database_link_message (notmuch_database_t *notmuch,
716 notmuch_message_t *message,
717 notmuch_message_file_t *message_file)
719 GPtrArray *parents, *thread_ids;
720 const char *refs, *in_reply_to;
721 const char *message_id = notmuch_message_get_message_id (message);
724 parents = g_ptr_array_new ();
726 refs = notmuch_message_file_get_header (message_file, "references");
727 parse_references (parents, refs);
729 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
730 parse_references (parents, in_reply_to);
732 for (i = 0; i < parents->len; i++)
733 _notmuch_message_add_term (message, "ref",
734 (char *) g_ptr_array_index (parents, i));
736 thread_ids = find_thread_ids (notmuch, parents, message_id);
738 for (i = 0; i < parents->len; i++)
739 g_free (g_ptr_array_index (parents, i));
740 g_ptr_array_free (parents, TRUE);
742 if (thread_ids->len) {
746 for (i = 0; i < thread_ids->len; i++) {
747 id = (char *) thread_ids->pdata[i];
748 _notmuch_message_add_thread_id (message, id);
750 thread_id = g_string_new (id);
752 g_string_append_printf (thread_id, ",%s", id);
756 g_string_free (thread_id, TRUE);
758 _notmuch_message_ensure_thread_id (message);
761 g_ptr_array_free (thread_ids, TRUE);
763 return NOTMUCH_STATUS_SUCCESS;
767 notmuch_database_add_message (notmuch_database_t *notmuch,
768 const char *filename)
770 notmuch_message_file_t *message_file;
771 notmuch_message_t *message;
772 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
774 const char *date, *header;
775 const char *from, *to, *subject, *old_filename;
778 message_file = notmuch_message_file_open (filename);
779 if (message_file == NULL) {
780 ret = NOTMUCH_STATUS_FILE_ERROR;
784 notmuch_message_file_restrict_headers (message_file,
795 /* The first order of business is to find/create a message ID. */
797 header = notmuch_message_file_get_header (message_file, "message-id");
799 message_id = parse_message_id (header, NULL);
800 /* So the header value isn't RFC-compliant, but it's
801 * better than no message-id at all. */
802 if (message_id == NULL)
803 message_id = xstrdup (header);
805 /* No message-id at all, let's generate one by taking a
806 * hash over the file's contents. */
807 char *sha1 = notmuch_sha1_of_file (filename);
809 /* If that failed too, something is really wrong. Give up. */
811 ret = NOTMUCH_STATUS_FILE_ERROR;
815 message_id = g_strdup_printf ("notmuch-sha1-%s", sha1);
819 /* Now that we have a message ID, we get a message object,
820 * (which may or may not reference an existing document in the
823 /* Use NULL for owner since we want to free this locally. */
824 message = _notmuch_message_create_for_message_id (NULL,
833 /* Has a message previously been added with the same ID? */
834 old_filename = notmuch_message_get_filename (message);
835 if (old_filename && strlen (old_filename)) {
836 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
839 _notmuch_message_set_filename (message, filename);
840 _notmuch_message_add_term (message, "type", "mail");
843 ret = _notmuch_database_link_message (notmuch, message, message_file);
847 date = notmuch_message_file_get_header (message_file, "date");
848 _notmuch_message_set_date (message, date);
850 from = notmuch_message_file_get_header (message_file, "from");
851 subject = notmuch_message_file_get_header (message_file, "subject");
852 to = notmuch_message_file_get_header (message_file, "to");
858 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
861 _notmuch_message_sync (message);
863 } catch (const Xapian::Error &error) {
864 fprintf (stderr, "A Xapian exception occurred: %s.\n",
865 error.get_msg().c_str());
866 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
872 notmuch_message_destroy (message);
874 notmuch_message_file_close (message_file);