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"
29 #include <glib.h> /* g_free, GPtrArray, GHashTable */
33 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
40 #define NOTMUCH_DATABASE_VERSION 1
42 #define STRINGIFY(s) _SUB_STRINGIFY(s)
43 #define _SUB_STRINGIFY(s) #s
45 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
47 * We currently have two different types of documents (mail and
48 * directory) and also some metadata.
52 * A mail document is associated with a particular email message file
53 * on disk. It is indexed with the following prefixed terms which the
54 * database uses to construct threads, etc.:
56 * Single terms of given prefix:
60 * id: Unique ID of mail. This is from the Message-ID header
61 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
62 * If it's present and too long, then we use
63 * "notmuch-sha1-<sha1_sum_of_message_id>".
64 * If this header is not present, we use
65 * "notmuch-sha1-<sha1_sum_of_entire_file>".
67 * thread: The ID of the thread to which the mail belongs
69 * replyto: The ID from the In-Reply-To header of the mail (if any).
71 * Multiple terms of given prefix:
73 * reference: All message IDs from In-Reply-To and Re ferences
74 * headers in the message.
76 * tag: Any tags associated with this message by the user.
78 * file-direntry: A colon-separated pair of values
79 * (INTEGER:STRING), where INTEGER is the
80 * document ID of a directory document, and
81 * STRING is the name of a file within that
82 * directory for this mail message.
84 * A mail document also has two values:
86 * TIMESTAMP: The time_t value corresponding to the message's
89 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
91 * In addition, terms from the content of the message are added with
92 * "from", "to", "attachment", and "subject" prefixes for use by the
93 * user in searching. But the database doesn't really care itself
96 * The data portion of a mail document is empty.
100 * A directory document is used by a client of the notmuch library to
101 * maintain data necessary to allow for efficient polling of mail
104 * All directory documents contain one term:
106 * directory: The directory path (relative to the database path)
107 * Or the SHA1 sum of the directory path (if the
108 * path itself is too long to fit in a Xapian
111 * And all directory documents for directories other than top-level
112 * directories also contain the following term:
114 * directory-direntry: A colon-separated pair of values
115 * (INTEGER:STRING), where INTEGER is the
116 * document ID of the parent directory
117 * document, and STRING is the name of this
118 * directory within that parent.
120 * All directory documents have a single value:
122 * TIMESTAMP: The mtime of the directory (at last scan)
124 * The data portion of a directory document contains the path of the
125 * directory (relative to the database path).
129 * Xapian allows us to store arbitrary name-value pairs as
130 * "metadata". We currently use the following metadata names with the
133 * version The database schema version, (which is distinct
134 * from both the notmuch package version (see
135 * notmuch --version) and the libnotmuch library
136 * version. The version is stored as an base-10
137 * ASCII integer. The initial database version
138 * was 1, (though a schema existed before that
139 * were no "version" database value existed at
140 * all). Succesive versions are allocated as
141 * changes are made to the database (such as by
142 * indexing new fields).
144 * last_thread_id The last thread ID generated. This is stored
145 * as a 16-byte hexadecimal ASCII representation
146 * of a 64-bit unsigned integer. The first ID
147 * generated is 1 and the value will be
148 * incremented for each thread ID.
150 * thread_id_* A pre-allocated thread ID for a particular
151 * message. This is actually an arbitarily large
152 * family of metadata name. Any particular name is
153 * formed by concatenating "thread_id_" with a message
154 * ID (or the SHA1 sum of a message ID if it is very
155 * long---see description of 'id' in the mail
156 * document). The value stored is a thread ID.
158 * These thread ID metadata values are stored
159 * whenever a message references a parent message
160 * that does not yet exist in the database. A
161 * thread ID will be allocated and stored, and if
162 * the message is later added, the stored thread
163 * ID will be used (and the metadata value will
166 * Even before a message is added, it's
167 * pre-allocated thread ID is useful so that all
168 * descendant messages that reference this common
169 * parent can be recognized as belonging to the
173 /* With these prefix values we follow the conventions published here:
175 * http://xapian.org/docs/omega/termprefixes.html
177 * as much as makes sense. Note that I took some liberty in matching
178 * the reserved prefix values to notmuch concepts, (for example, 'G'
179 * is documented as "newsGroup (or similar entity - e.g. a web forum
180 * name)", for which I think the thread is the closest analogue in
181 * notmuch. This in spite of the fact that we will eventually be
182 * storing mailing-list messages where 'G' for "mailing list name"
183 * might be even a closer analogue. I'm treating the single-character
184 * prefixes preferentially for core notmuch concepts (which will be
185 * nearly universal to all mail messages).
188 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
190 { "reference", "XREFERENCE" },
191 { "replyto", "XREPLYTO" },
192 { "directory", "XDIRECTORY" },
193 { "file-direntry", "XFDIRENTRY" },
194 { "directory-direntry", "XDDIRENTRY" },
197 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
204 prefix_t PROBABILISTIC_PREFIX[]= {
207 { "attachment", "XATTACHMENT" },
208 { "subject", "XSUBJECT"}
212 _internal_error (const char *format, ...)
216 va_start (va_args, format);
218 fprintf (stderr, "Internal error: ");
219 vfprintf (stderr, format, va_args);
227 _find_prefix (const char *name)
231 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
232 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
233 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
236 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
237 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
238 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
241 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
242 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
243 return PROBABILISTIC_PREFIX[i].prefix;
246 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
252 notmuch_status_to_string (notmuch_status_t status)
255 case NOTMUCH_STATUS_SUCCESS:
256 return "No error occurred";
257 case NOTMUCH_STATUS_OUT_OF_MEMORY:
258 return "Out of memory";
259 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
260 return "Attempt to write to a read-only database";
261 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
262 return "A Xapian exception occurred";
263 case NOTMUCH_STATUS_FILE_ERROR:
264 return "Something went wrong trying to read or write a file";
265 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
266 return "File is not an email";
267 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
268 return "Message ID is identical to a message in database";
269 case NOTMUCH_STATUS_NULL_POINTER:
270 return "Erroneous NULL pointer";
271 case NOTMUCH_STATUS_TAG_TOO_LONG:
272 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
273 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
274 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
276 case NOTMUCH_STATUS_LAST_STATUS:
277 return "Unknown error status value";
282 find_doc_ids_for_term (notmuch_database_t *notmuch,
284 Xapian::PostingIterator *begin,
285 Xapian::PostingIterator *end)
287 *begin = notmuch->xapian_db->postlist_begin (term);
289 *end = notmuch->xapian_db->postlist_end (term);
293 find_doc_ids (notmuch_database_t *notmuch,
294 const char *prefix_name,
296 Xapian::PostingIterator *begin,
297 Xapian::PostingIterator *end)
301 term = talloc_asprintf (notmuch, "%s%s",
302 _find_prefix (prefix_name), value);
304 find_doc_ids_for_term (notmuch, term, begin, end);
309 notmuch_private_status_t
310 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
311 const char *prefix_name,
313 unsigned int *doc_id)
315 Xapian::PostingIterator i, end;
317 find_doc_ids (notmuch, prefix_name, value, &i, &end);
321 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
326 #if DEBUG_DATABASE_SANITY
330 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
334 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
337 static Xapian::Document
338 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
340 return notmuch->xapian_db->get_document (doc_id);
343 /* Generate a compressed version of 'message_id' of the form:
345 * notmuch-sha1-<sha1_sum_of_message_id>
348 _message_id_compressed (void *ctx, const char *message_id)
350 char *sha1, *compressed;
352 sha1 = notmuch_sha1_of_string (message_id);
354 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
361 notmuch_database_find_message (notmuch_database_t *notmuch,
362 const char *message_id)
364 notmuch_private_status_t status;
367 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
368 message_id = _message_id_compressed (notmuch, message_id);
371 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
372 message_id, &doc_id);
374 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
377 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
378 } catch (const Xapian::Error &error) {
379 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
380 error.get_msg().c_str());
381 notmuch->exception_reported = TRUE;
386 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
387 * a (potentially nested) parenthesized sequence with '\' used to
388 * escape any character (including parentheses).
390 * If the sequence to be skipped continues to the end of the string,
391 * then 'str' will be left pointing at the final terminating '\0'
395 skip_space_and_comments (const char **str)
400 while (*s && (isspace (*s) || *s == '(')) {
401 while (*s && isspace (*s))
406 while (*s && nesting) {
409 } else if (*s == ')') {
411 } else if (*s == '\\') {
423 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
424 * comments, and the '<' and '>' delimeters.
426 * If not NULL, then *next will be made to point to the first character
427 * not parsed, (possibly pointing to the final '\0' terminator.
429 * Returns a newly talloc'ed string belonging to 'ctx'.
431 * Returns NULL if there is any error parsing the message-id. */
433 _parse_message_id (void *ctx, const char *message_id, const char **next)
438 if (message_id == NULL || *message_id == '\0')
443 skip_space_and_comments (&s);
445 /* Skip any unstructured text as well. */
446 while (*s && *s != '<')
457 skip_space_and_comments (&s);
460 while (*end && *end != '>')
469 if (end > s && *end == '>')
474 result = talloc_strndup (ctx, s, end - s + 1);
476 /* Finally, collapse any whitespace that is within the message-id
482 for (r = result, len = strlen (r); *r; r++, len--)
483 if (*r == ' ' || *r == '\t')
484 memmove (r, r+1, len);
490 /* Parse a References header value, putting a (talloc'ed under 'ctx')
491 * copy of each referenced message-id into 'hash'.
493 * We explicitly avoid including any reference identical to
494 * 'message_id' in the result (to avoid mass confusion when a single
495 * message references itself cyclically---and yes, mail messages are
496 * not infrequent in the wild that do this---don't ask me why).
499 parse_references (void *ctx,
500 const char *message_id,
506 if (refs == NULL || *refs == '\0')
510 ref = _parse_message_id (ctx, refs, &refs);
512 if (ref && strcmp (ref, message_id))
513 g_hash_table_insert (hash, ref, NULL);
518 notmuch_database_create (const char *path)
520 notmuch_database_t *notmuch = NULL;
521 char *notmuch_path = NULL;
526 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
530 err = stat (path, &st);
532 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
533 path, strerror (errno));
537 if (! S_ISDIR (st.st_mode)) {
538 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
543 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
545 err = mkdir (notmuch_path, 0755);
548 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
549 notmuch_path, strerror (errno));
553 notmuch = notmuch_database_open (path,
554 NOTMUCH_DATABASE_MODE_READ_WRITE);
555 notmuch_database_upgrade (notmuch, NULL, NULL);
559 talloc_free (notmuch_path);
565 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
567 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
568 fprintf (stderr, "Cannot write to a read-only database.\n");
569 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
572 return NOTMUCH_STATUS_SUCCESS;
576 notmuch_database_open (const char *path,
577 notmuch_database_mode_t mode)
579 notmuch_database_t *notmuch = NULL;
580 char *notmuch_path = NULL, *xapian_path = NULL;
583 unsigned int i, version;
585 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
587 fprintf (stderr, "Out of memory\n");
591 err = stat (notmuch_path, &st);
593 fprintf (stderr, "Error opening database at %s: %s\n",
594 notmuch_path, strerror (errno));
598 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
600 fprintf (stderr, "Out of memory\n");
604 notmuch = talloc (NULL, notmuch_database_t);
605 notmuch->exception_reported = FALSE;
606 notmuch->path = talloc_strdup (notmuch, path);
608 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
609 notmuch->path[strlen (notmuch->path) - 1] = '\0';
611 notmuch->needs_upgrade = FALSE;
612 notmuch->mode = mode;
614 string last_thread_id;
616 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
617 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
618 Xapian::DB_CREATE_OR_OPEN);
619 version = notmuch_database_get_version (notmuch);
621 if (version > NOTMUCH_DATABASE_VERSION) {
623 "Error: Notmuch database at %s\n"
624 " has a newer database format version (%u) than supported by this\n"
625 " version of notmuch (%u). Refusing to open this database in\n"
626 " read-write mode.\n",
627 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
628 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
629 notmuch_database_close (notmuch);
634 if (version < NOTMUCH_DATABASE_VERSION)
635 notmuch->needs_upgrade = TRUE;
637 notmuch->xapian_db = new Xapian::Database (xapian_path);
638 version = notmuch_database_get_version (notmuch);
639 if (version > NOTMUCH_DATABASE_VERSION)
642 "Warning: Notmuch database at %s\n"
643 " has a newer database format version (%u) than supported by this\n"
644 " version of notmuch (%u). Some operations may behave incorrectly,\n"
645 " (but the database will not be harmed since it is being opened\n"
646 " in read-only mode).\n",
647 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
651 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
652 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
653 if (last_thread_id.empty ()) {
654 notmuch->last_thread_id = 0;
659 str = last_thread_id.c_str ();
660 notmuch->last_thread_id = strtoull (str, &end, 16);
662 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
665 notmuch->query_parser = new Xapian::QueryParser;
666 notmuch->term_gen = new Xapian::TermGenerator;
667 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
668 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
670 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
671 notmuch->query_parser->set_database (*notmuch->xapian_db);
672 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
673 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
674 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
676 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
677 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
678 notmuch->query_parser->add_boolean_prefix (prefix->name,
682 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
683 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
684 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
686 } catch (const Xapian::Error &error) {
687 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
688 error.get_msg().c_str());
702 notmuch_database_close (notmuch_database_t *notmuch)
705 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
706 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
707 } catch (const Xapian::Error &error) {
708 if (! notmuch->exception_reported) {
709 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
710 error.get_msg().c_str());
714 delete notmuch->term_gen;
715 delete notmuch->query_parser;
716 delete notmuch->xapian_db;
717 delete notmuch->value_range_processor;
718 talloc_free (notmuch);
722 notmuch_database_get_path (notmuch_database_t *notmuch)
724 return notmuch->path;
728 notmuch_database_get_version (notmuch_database_t *notmuch)
730 unsigned int version;
731 string version_string;
735 version_string = notmuch->xapian_db->get_metadata ("version");
736 if (version_string.empty ())
739 str = version_string.c_str ();
740 if (str == NULL || *str == '\0')
743 version = strtoul (str, &end, 10);
745 INTERNAL_ERROR ("Malformed database version: %s", str);
751 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
753 return notmuch->needs_upgrade;
756 static volatile sig_atomic_t do_progress_notify = 0;
759 handle_sigalrm (unused (int signal))
761 do_progress_notify = 1;
764 /* Upgrade the current database.
766 * After opening a database in read-write mode, the client should
767 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
768 * if so, upgrade with this function before making any modifications.
770 * The optional progress_notify callback can be used by the caller to
771 * provide progress indication to the user. If non-NULL it will be
772 * called periodically with 'count' as the number of messages upgraded
773 * so far and 'total' the overall number of messages that will be
777 notmuch_database_upgrade (notmuch_database_t *notmuch,
778 void (*progress_notify) (void *closure,
782 Xapian::WritableDatabase *db;
783 struct sigaction action;
784 struct itimerval timerval;
785 notmuch_bool_t timer_is_active = FALSE;
786 unsigned int version;
787 notmuch_status_t status;
788 unsigned int count = 0, total = 0;
790 status = _notmuch_database_ensure_writable (notmuch);
794 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
796 version = notmuch_database_get_version (notmuch);
798 if (version >= NOTMUCH_DATABASE_VERSION)
799 return NOTMUCH_STATUS_SUCCESS;
801 if (progress_notify) {
802 /* Setup our handler for SIGALRM */
803 memset (&action, 0, sizeof (struct sigaction));
804 action.sa_handler = handle_sigalrm;
805 sigemptyset (&action.sa_mask);
806 action.sa_flags = SA_RESTART;
807 sigaction (SIGALRM, &action, NULL);
809 /* Then start a timer to send SIGALRM once per second. */
810 timerval.it_interval.tv_sec = 1;
811 timerval.it_interval.tv_usec = 0;
812 timerval.it_value.tv_sec = 1;
813 timerval.it_value.tv_usec = 0;
814 setitimer (ITIMER_REAL, &timerval, NULL);
816 timer_is_active = TRUE;
819 /* Before version 1, each message document had its filename in the
820 * data field. Copy that into the new format by calling
821 * notmuch_message_add_filename.
824 notmuch_query_t *query = notmuch_query_create (notmuch, "");
825 notmuch_messages_t *messages;
826 notmuch_message_t *message;
828 Xapian::TermIterator t, t_end;
830 total = notmuch_query_count_messages (query);
832 for (messages = notmuch_query_search_messages (query);
833 notmuch_messages_valid (messages);
834 notmuch_messages_move_to_next (messages))
836 if (do_progress_notify) {
837 progress_notify (closure, (double) count / total);
838 do_progress_notify = 0;
841 message = notmuch_messages_get (messages);
843 filename = _notmuch_message_talloc_copy_data (message);
844 if (filename && *filename != '\0') {
845 _notmuch_message_add_filename (message, filename);
846 _notmuch_message_sync (message);
848 talloc_free (filename);
850 notmuch_message_destroy (message);
855 notmuch_query_destroy (query);
857 /* Also, before version 1 we stored directory timestamps in
858 * XTIMESTAMP documents instead of the current XDIRECTORY
859 * documents. So copy those as well. */
861 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
863 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
867 Xapian::PostingIterator p, p_end;
868 std::string term = *t;
870 p_end = notmuch->xapian_db->postlist_end (term);
872 for (p = notmuch->xapian_db->postlist_begin (term);
876 Xapian::Document document;
878 notmuch_directory_t *directory;
880 if (do_progress_notify) {
881 progress_notify (closure, (double) count / total);
882 do_progress_notify = 0;
885 document = find_document_for_doc_id (notmuch, *p);
886 mtime = Xapian::sortable_unserialise (
887 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
889 directory = notmuch_database_get_directory (notmuch,
891 notmuch_directory_set_mtime (directory, mtime);
892 notmuch_directory_destroy (directory);
897 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
900 /* Now that the upgrade is complete we can remove the old data
901 * and documents that are no longer needed. */
903 notmuch_query_t *query = notmuch_query_create (notmuch, "");
904 notmuch_messages_t *messages;
905 notmuch_message_t *message;
908 for (messages = notmuch_query_search_messages (query);
909 notmuch_messages_valid (messages);
910 notmuch_messages_move_to_next (messages))
912 if (do_progress_notify) {
913 progress_notify (closure, (double) count / total);
914 do_progress_notify = 0;
917 message = notmuch_messages_get (messages);
919 filename = _notmuch_message_talloc_copy_data (message);
920 if (filename && *filename != '\0') {
921 _notmuch_message_clear_data (message);
922 _notmuch_message_sync (message);
924 talloc_free (filename);
926 notmuch_message_destroy (message);
929 notmuch_query_destroy (query);
933 Xapian::TermIterator t, t_end;
935 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
937 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
941 Xapian::PostingIterator p, p_end;
942 std::string term = *t;
944 p_end = notmuch->xapian_db->postlist_end (term);
946 for (p = notmuch->xapian_db->postlist_begin (term);
950 if (do_progress_notify) {
951 progress_notify (closure, (double) count / total);
952 do_progress_notify = 0;
955 db->delete_document (*p);
960 if (timer_is_active) {
961 /* Now stop the timer. */
962 timerval.it_interval.tv_sec = 0;
963 timerval.it_interval.tv_usec = 0;
964 timerval.it_value.tv_sec = 0;
965 timerval.it_value.tv_usec = 0;
966 setitimer (ITIMER_REAL, &timerval, NULL);
968 /* And disable the signal handler. */
969 action.sa_handler = SIG_IGN;
970 sigaction (SIGALRM, &action, NULL);
973 return NOTMUCH_STATUS_SUCCESS;
976 /* We allow the user to use arbitrarily long paths for directories. But
977 * we have a term-length limit. So if we exceed that, we'll use the
978 * SHA-1 of the path for the database term.
980 * Note: This function may return the original value of 'path'. If it
981 * does not, then the caller is responsible to free() the returned
985 _notmuch_database_get_directory_db_path (const char *path)
987 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
989 if (term_len > NOTMUCH_TERM_MAX)
990 return notmuch_sha1_of_string (path);
995 /* Given a path, split it into two parts: the directory part is all
996 * components except for the last, and the basename is that last
997 * component. Getting the return-value for either part is optional
998 * (the caller can pass NULL).
1000 * The original 'path' can represent either a regular file or a
1001 * directory---the splitting will be carried out in the same way in
1002 * either case. Trailing slashes on 'path' will be ignored, and any
1003 * cases of multiple '/' characters appearing in series will be
1004 * treated as a single '/'.
1006 * Allocation (if any) will have 'ctx' as the talloc owner. But
1007 * pointers will be returned within the original path string whenever
1010 * Note: If 'path' is non-empty and contains no non-trailing slash,
1011 * (that is, consists of a filename with no parent directory), then
1012 * the directory returned will be an empty string. However, if 'path'
1013 * is an empty string, then both directory and basename will be
1017 _notmuch_database_split_path (void *ctx,
1019 const char **directory,
1020 const char **basename)
1024 if (path == NULL || *path == '\0') {
1029 return NOTMUCH_STATUS_SUCCESS;
1032 /* Find the last slash (not counting a trailing slash), if any. */
1034 slash = path + strlen (path) - 1;
1036 /* First, skip trailing slashes. */
1037 while (slash != path) {
1044 /* Then, find a slash. */
1045 while (slash != path) {
1055 /* Finally, skip multiple slashes. */
1056 while (slash != path) {
1063 if (slash == path) {
1065 *directory = talloc_strdup (ctx, "");
1070 *directory = talloc_strndup (ctx, path, slash - path + 1);
1073 return NOTMUCH_STATUS_SUCCESS;
1077 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1079 unsigned int *directory_id)
1081 notmuch_directory_t *directory;
1082 notmuch_status_t status;
1086 return NOTMUCH_STATUS_SUCCESS;
1089 directory = _notmuch_directory_create (notmuch, path, &status);
1095 *directory_id = _notmuch_directory_get_document_id (directory);
1097 notmuch_directory_destroy (directory);
1099 return NOTMUCH_STATUS_SUCCESS;
1103 _notmuch_database_get_directory_path (void *ctx,
1104 notmuch_database_t *notmuch,
1105 unsigned int doc_id)
1107 Xapian::Document document;
1109 document = find_document_for_doc_id (notmuch, doc_id);
1111 return talloc_strdup (ctx, document.get_data ().c_str ());
1114 /* Given a legal 'filename' for the database, (either relative to
1115 * database path or absolute with initial components identical to
1116 * database path), return a new string (with 'ctx' as the talloc
1117 * owner) suitable for use as a direntry term value.
1119 * The necessary directory documents will be created in the database
1123 _notmuch_database_filename_to_direntry (void *ctx,
1124 notmuch_database_t *notmuch,
1125 const char *filename,
1128 const char *relative, *directory, *basename;
1129 Xapian::docid directory_id;
1130 notmuch_status_t status;
1132 relative = _notmuch_database_relative_path (notmuch, filename);
1134 status = _notmuch_database_split_path (ctx, relative,
1135 &directory, &basename);
1139 status = _notmuch_database_find_directory_id (notmuch, directory,
1144 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1146 return NOTMUCH_STATUS_SUCCESS;
1149 /* Given a legal 'path' for the database, return the relative path.
1151 * The return value will be a pointer to the originl path contents,
1152 * and will be either the original string (if 'path' was relative) or
1153 * a portion of the string (if path was absolute and begins with the
1157 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1160 const char *db_path, *relative;
1161 unsigned int db_path_len;
1163 db_path = notmuch_database_get_path (notmuch);
1164 db_path_len = strlen (db_path);
1168 if (*relative == '/') {
1169 while (*relative == '/' && *(relative+1) == '/')
1172 if (strncmp (relative, db_path, db_path_len) == 0)
1174 relative += db_path_len;
1175 while (*relative == '/')
1183 notmuch_directory_t *
1184 notmuch_database_get_directory (notmuch_database_t *notmuch,
1187 notmuch_status_t status;
1190 return _notmuch_directory_create (notmuch, path, &status);
1191 } catch (const Xapian::Error &error) {
1192 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1193 error.get_msg().c_str());
1194 notmuch->exception_reported = TRUE;
1199 /* Allocate a document ID that satisfies the following criteria:
1201 * 1. The ID does not exist for any document in the Xapian database
1203 * 2. The ID was not previously returned from this function
1205 * 3. The ID is the smallest integer satisfying (1) and (2)
1207 * This function will trigger an internal error if these constraints
1208 * cannot all be satisfied, (that is, the pool of available document
1209 * IDs has been exhausted).
1212 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1214 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1216 notmuch->last_doc_id++;
1218 if (notmuch->last_doc_id == 0)
1219 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1221 return notmuch->last_doc_id;
1225 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1227 /* 16 bytes (+ terminator) for hexadecimal representation of
1228 * a 64-bit integer. */
1229 static char thread_id[17];
1230 Xapian::WritableDatabase *db;
1232 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1234 notmuch->last_thread_id++;
1236 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1238 db->set_metadata ("last_thread_id", thread_id);
1244 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1246 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1247 message_id = _message_id_compressed (ctx, message_id);
1249 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1253 /* Find the thread ID to which the message with 'message_id' belongs.
1255 * Always returns a newly talloced string belonging to 'ctx'.
1257 * Note: If there is no message in the database with the given
1258 * 'message_id' then a new thread_id will be allocated for this
1259 * message and stored in the database metadata, (where this same
1260 * thread ID can be looked up if the message is added to the database
1264 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1266 const char *message_id)
1268 notmuch_message_t *message;
1269 string thread_id_string;
1270 const char *thread_id;
1272 Xapian::WritableDatabase *db;
1274 message = notmuch_database_find_message (notmuch, message_id);
1277 thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1279 notmuch_message_destroy (message);
1284 /* Message has not been seen yet.
1286 * We may have seen a reference to it already, in which case, we
1287 * can return the thread ID stored in the metadata. Otherwise, we
1288 * generate a new thread ID and store it there.
1290 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1291 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1292 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1294 if (thread_id_string.empty()) {
1295 thread_id = _notmuch_database_generate_thread_id (notmuch);
1296 db->set_metadata (metadata_key, thread_id);
1298 thread_id = thread_id_string.c_str();
1301 talloc_free (metadata_key);
1303 return talloc_strdup (ctx, thread_id);
1306 static notmuch_status_t
1307 _merge_threads (notmuch_database_t *notmuch,
1308 const char *winner_thread_id,
1309 const char *loser_thread_id)
1311 Xapian::PostingIterator loser, loser_end;
1312 notmuch_message_t *message = NULL;
1313 notmuch_private_status_t private_status;
1314 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1316 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1318 for ( ; loser != loser_end; loser++) {
1319 message = _notmuch_message_create (notmuch, notmuch,
1320 *loser, &private_status);
1321 if (message == NULL) {
1322 ret = COERCE_STATUS (private_status,
1323 "Cannot find document for doc_id from query");
1327 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1328 _notmuch_message_add_term (message, "thread", winner_thread_id);
1329 _notmuch_message_sync (message);
1331 notmuch_message_destroy (message);
1337 notmuch_message_destroy (message);
1343 _my_talloc_free_for_g_hash (void *ptr)
1348 static notmuch_status_t
1349 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1350 notmuch_message_t *message,
1351 notmuch_message_file_t *message_file,
1352 const char **thread_id)
1354 GHashTable *parents = NULL;
1355 const char *refs, *in_reply_to, *in_reply_to_message_id;
1356 GList *l, *keys = NULL;
1357 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1359 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1360 _my_talloc_free_for_g_hash, NULL);
1362 refs = notmuch_message_file_get_header (message_file, "references");
1363 parse_references (message, notmuch_message_get_message_id (message),
1366 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1367 parse_references (message, notmuch_message_get_message_id (message),
1368 parents, in_reply_to);
1370 /* Carefully avoid adding any self-referential in-reply-to term. */
1371 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1372 if (in_reply_to_message_id &&
1373 strcmp (in_reply_to_message_id,
1374 notmuch_message_get_message_id (message)))
1376 _notmuch_message_add_term (message, "replyto",
1377 _parse_message_id (message, in_reply_to, NULL));
1380 keys = g_hash_table_get_keys (parents);
1381 for (l = keys; l; l = l->next) {
1382 char *parent_message_id;
1383 const char *parent_thread_id;
1385 parent_message_id = (char *) l->data;
1387 _notmuch_message_add_term (message, "reference",
1390 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1394 if (*thread_id == NULL) {
1395 *thread_id = talloc_strdup (message, parent_thread_id);
1396 _notmuch_message_add_term (message, "thread", *thread_id);
1397 } else if (strcmp (*thread_id, parent_thread_id)) {
1398 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1408 g_hash_table_unref (parents);
1413 static notmuch_status_t
1414 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1415 notmuch_message_t *message,
1416 const char **thread_id)
1418 const char *message_id = notmuch_message_get_message_id (message);
1419 Xapian::PostingIterator child, children_end;
1420 notmuch_message_t *child_message = NULL;
1421 const char *child_thread_id;
1422 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1423 notmuch_private_status_t private_status;
1425 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1427 for ( ; child != children_end; child++) {
1429 child_message = _notmuch_message_create (message, notmuch,
1430 *child, &private_status);
1431 if (child_message == NULL) {
1432 ret = COERCE_STATUS (private_status,
1433 "Cannot find document for doc_id from query");
1437 child_thread_id = notmuch_message_get_thread_id (child_message);
1438 if (*thread_id == NULL) {
1439 *thread_id = talloc_strdup (message, child_thread_id);
1440 _notmuch_message_add_term (message, "thread", *thread_id);
1441 } else if (strcmp (*thread_id, child_thread_id)) {
1442 _notmuch_message_remove_term (child_message, "reference",
1444 _notmuch_message_sync (child_message);
1445 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1450 notmuch_message_destroy (child_message);
1451 child_message = NULL;
1456 notmuch_message_destroy (child_message);
1461 /* Given a (mostly empty) 'message' and its corresponding
1462 * 'message_file' link it to existing threads in the database.
1464 * The first check is in the metadata of the database to see if we
1465 * have pre-allocated a thread_id in advance for this message, (which
1466 * would have happened if a message was previously added that
1467 * referenced this one).
1469 * Second, we look at 'message_file' and its link-relevant headers
1470 * (References and In-Reply-To) for message IDs.
1472 * Finally, we look in the database for existing message that
1473 * reference 'message'.
1475 * In all cases, we assign to the current message the first thread_id
1476 * found (through either parent or child). We will also merge any
1477 * existing, distinct threads where this message belongs to both,
1478 * (which is not uncommon when mesages are processed out of order).
1480 * Finally, if no thread ID has been found through parent or child, we
1481 * call _notmuch_message_generate_thread_id to generate a new thread
1482 * ID. This should only happen for new, top-level messages, (no
1483 * References or In-Reply-To header in this message, and no previously
1484 * added message refers to this message).
1486 static notmuch_status_t
1487 _notmuch_database_link_message (notmuch_database_t *notmuch,
1488 notmuch_message_t *message,
1489 notmuch_message_file_t *message_file)
1491 notmuch_status_t status;
1492 const char *message_id, *thread_id = NULL;
1496 message_id = notmuch_message_get_message_id (message);
1497 metadata_key = _get_metadata_thread_id_key (message, message_id);
1499 /* Check if we have already seen related messages to this one.
1500 * If we have then use the thread_id that we stored at that time.
1502 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1503 if (! stored_id.empty()) {
1504 Xapian::WritableDatabase *db;
1506 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1508 /* Clear the metadata for this message ID. We don't need it
1510 db->set_metadata (metadata_key, "");
1511 thread_id = stored_id.c_str();
1513 _notmuch_message_add_term (message, "thread", thread_id);
1515 talloc_free (metadata_key);
1517 status = _notmuch_database_link_message_to_parents (notmuch, message,
1523 status = _notmuch_database_link_message_to_children (notmuch, message,
1528 /* If not part of any existing thread, generate a new thread ID. */
1529 if (thread_id == NULL) {
1530 thread_id = _notmuch_database_generate_thread_id (notmuch);
1532 _notmuch_message_add_term (message, "thread", thread_id);
1535 return NOTMUCH_STATUS_SUCCESS;
1539 notmuch_database_add_message (notmuch_database_t *notmuch,
1540 const char *filename,
1541 notmuch_message_t **message_ret)
1543 notmuch_message_file_t *message_file;
1544 notmuch_message_t *message = NULL;
1545 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1546 notmuch_private_status_t private_status;
1548 const char *date, *header;
1549 const char *from, *to, *subject;
1550 char *message_id = NULL;
1553 *message_ret = NULL;
1555 ret = _notmuch_database_ensure_writable (notmuch);
1559 message_file = notmuch_message_file_open (filename);
1560 if (message_file == NULL)
1561 return NOTMUCH_STATUS_FILE_ERROR;
1563 notmuch_message_file_restrict_headers (message_file,
1574 /* Before we do any real work, (especially before doing a
1575 * potential SHA-1 computation on the entire file's contents),
1576 * let's make sure that what we're looking at looks like an
1577 * actual email message.
1579 from = notmuch_message_file_get_header (message_file, "from");
1580 subject = notmuch_message_file_get_header (message_file, "subject");
1581 to = notmuch_message_file_get_header (message_file, "to");
1583 if ((from == NULL || *from == '\0') &&
1584 (subject == NULL || *subject == '\0') &&
1585 (to == NULL || *to == '\0'))
1587 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1591 /* Now that we're sure it's mail, the first order of business
1592 * is to find a message ID (or else create one ourselves). */
1594 header = notmuch_message_file_get_header (message_file, "message-id");
1595 if (header && *header != '\0') {
1596 message_id = _parse_message_id (message_file, header, NULL);
1598 /* So the header value isn't RFC-compliant, but it's
1599 * better than no message-id at all. */
1600 if (message_id == NULL)
1601 message_id = talloc_strdup (message_file, header);
1603 /* If a message ID is too long, substitute its sha1 instead. */
1604 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1605 char *compressed = _message_id_compressed (message_file,
1607 talloc_free (message_id);
1608 message_id = compressed;
1612 if (message_id == NULL ) {
1613 /* No message-id at all, let's generate one by taking a
1614 * hash over the file's contents. */
1615 char *sha1 = notmuch_sha1_of_file (filename);
1617 /* If that failed too, something is really wrong. Give up. */
1619 ret = NOTMUCH_STATUS_FILE_ERROR;
1623 message_id = talloc_asprintf (message_file,
1624 "notmuch-sha1-%s", sha1);
1628 /* Now that we have a message ID, we get a message object,
1629 * (which may or may not reference an existing document in the
1632 message = _notmuch_message_create_for_message_id (notmuch,
1636 talloc_free (message_id);
1638 if (message == NULL) {
1639 ret = COERCE_STATUS (private_status,
1640 "Unexpected status value from _notmuch_message_create_for_message_id");
1644 _notmuch_message_add_filename (message, filename);
1646 /* Is this a newly created message object? */
1647 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1648 _notmuch_message_add_term (message, "type", "mail");
1650 ret = _notmuch_database_link_message (notmuch, message,
1655 date = notmuch_message_file_get_header (message_file, "date");
1656 _notmuch_message_set_date (message, date);
1658 _notmuch_message_index_file (message, filename);
1660 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1663 _notmuch_message_sync (message);
1664 } catch (const Xapian::Error &error) {
1665 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1666 error.get_msg().c_str());
1667 notmuch->exception_reported = TRUE;
1668 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1674 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1675 *message_ret = message;
1677 notmuch_message_destroy (message);
1681 notmuch_message_file_close (message_file);
1687 notmuch_database_remove_message (notmuch_database_t *notmuch,
1688 const char *filename)
1690 Xapian::WritableDatabase *db;
1692 const char *prefix = _find_prefix ("file-direntry");
1693 char *direntry, *term;
1694 Xapian::PostingIterator i, end;
1695 Xapian::Document document;
1696 notmuch_status_t status;
1698 status = _notmuch_database_ensure_writable (notmuch);
1702 local = talloc_new (notmuch);
1704 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1708 status = _notmuch_database_filename_to_direntry (local, notmuch,
1709 filename, &direntry);
1713 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1715 find_doc_ids_for_term (notmuch, term, &i, &end);
1717 for ( ; i != end; i++) {
1718 Xapian::TermIterator j;
1720 document = find_document_for_doc_id (notmuch, *i);
1722 document.remove_term (term);
1724 j = document.termlist_begin ();
1727 /* Was this the last file-direntry in the message? */
1728 if (j == document.termlist_end () ||
1729 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1731 db->delete_document (document.get_docid ());
1732 status = NOTMUCH_STATUS_SUCCESS;
1734 db->replace_document (document.get_docid (), document);
1735 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1738 } catch (const Xapian::Error &error) {
1739 fprintf (stderr, "Error: A Xapian exception occurred removing message: %s\n",
1740 error.get_msg().c_str());
1741 notmuch->exception_reported = TRUE;
1742 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1745 talloc_free (local);
1751 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1752 Xapian::TermIterator &end)
1754 const char *prefix = _find_prefix ("tag");
1755 notmuch_tags_t *tags;
1758 /* Currently this iteration is written with the assumption that
1759 * "tag" has a single-character prefix. */
1760 assert (strlen (prefix) == 1);
1762 tags = _notmuch_tags_create (ctx);
1763 if (unlikely (tags == NULL))
1771 if (tag.empty () || tag[0] != *prefix)
1774 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1779 _notmuch_tags_prepare_iterator (tags);
1785 notmuch_database_get_all_tags (notmuch_database_t *db)
1787 Xapian::TermIterator i, end;
1790 i = db->xapian_db->allterms_begin();
1791 end = db->xapian_db->allterms_end();
1792 return _notmuch_convert_tags(db, i, end);
1793 } catch (const Xapian::Error &error) {
1794 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1795 error.get_msg().c_str());
1796 db->exception_reported = TRUE;