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"
22 #include "parse-time-vrp.h"
23 #include "string-util.h"
32 #include <glib.h> /* g_free, GPtrArray, GHashTable */
33 #include <glib-object.h> /* g_type_init */
35 #include <gmime/gmime.h> /* g_mime_init */
39 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
46 #define NOTMUCH_DATABASE_VERSION 3
48 #define STRINGIFY(s) _SUB_STRINGIFY(s)
49 #define _SUB_STRINGIFY(s) #s
51 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
53 * We currently have three different types of documents (mail, ghost,
54 * and directory) and also some metadata.
58 * A mail document is associated with a particular email message. It
59 * is stored in one or more files on disk (though only one has its
60 * content indexed) and is uniquely identified by its "id" field
61 * (which is generally the message ID). It is indexed with the
62 * following prefixed terms which the database uses to construct
65 * Single terms of given prefix:
69 * id: Unique ID of mail. This is from the Message-ID header
70 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
71 * If it's present and too long, then we use
72 * "notmuch-sha1-<sha1_sum_of_message_id>".
73 * If this header is not present, we use
74 * "notmuch-sha1-<sha1_sum_of_entire_file>".
76 * thread: The ID of the thread to which the mail belongs
78 * replyto: The ID from the In-Reply-To header of the mail (if any).
80 * Multiple terms of given prefix:
82 * reference: All message IDs from In-Reply-To and References
83 * headers in the message.
85 * tag: Any tags associated with this message by the user.
87 * file-direntry: A colon-separated pair of values
88 * (INTEGER:STRING), where INTEGER is the
89 * document ID of a directory document, and
90 * STRING is the name of a file within that
91 * directory for this mail message.
93 * A mail document also has four values:
95 * TIMESTAMP: The time_t value corresponding to the message's
98 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
100 * FROM: The value of the "From" header
102 * SUBJECT: The value of the "Subject" header
104 * In addition, terms from the content of the message are added with
105 * "from", "to", "attachment", and "subject" prefixes for use by the
106 * user in searching. Similarly, terms from the path of the mail
107 * message are added with "folder" and "path" prefixes. But the
108 * database doesn't really care itself about any of these.
110 * The data portion of a mail document is empty.
112 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
113 * -----------------------------------------------
114 * A ghost mail document is like a mail document, but where we don't
115 * have the message content. These are used to track thread reference
116 * information for messages we haven't received.
118 * A ghost mail document has type: ghost; id and thread fields that
119 * are identical to the mail document fields; and a MESSAGE_ID value.
123 * A directory document is used by a client of the notmuch library to
124 * maintain data necessary to allow for efficient polling of mail
127 * All directory documents contain one term:
129 * directory: The directory path (relative to the database path)
130 * Or the SHA1 sum of the directory path (if the
131 * path itself is too long to fit in a Xapian
134 * And all directory documents for directories other than top-level
135 * directories also contain the following term:
137 * directory-direntry: A colon-separated pair of values
138 * (INTEGER:STRING), where INTEGER is the
139 * document ID of the parent directory
140 * document, and STRING is the name of this
141 * directory within that parent.
143 * All directory documents have a single value:
145 * TIMESTAMP: The mtime of the directory (at last scan)
147 * The data portion of a directory document contains the path of the
148 * directory (relative to the database path).
152 * Xapian allows us to store arbitrary name-value pairs as
153 * "metadata". We currently use the following metadata names with the
156 * version The database schema version, (which is distinct
157 * from both the notmuch package version (see
158 * notmuch --version) and the libnotmuch library
159 * version. The version is stored as an base-10
160 * ASCII integer. The initial database version
161 * was 1, (though a schema existed before that
162 * were no "version" database value existed at
163 * all). Successive versions are allocated as
164 * changes are made to the database (such as by
165 * indexing new fields).
167 * features The set of features supported by this
168 * database. This consists of a set of
169 * '\n'-separated lines, where each is a feature
170 * name, a '\t', and compatibility flags. If the
171 * compatibility flags contain 'w', then the
172 * opener must support this feature to safely
173 * write this database. If the compatibility
174 * flags contain 'r', then the opener must
175 * support this feature to read this database.
176 * Introduced in database version 3.
178 * last_thread_id The last thread ID generated. This is stored
179 * as a 16-byte hexadecimal ASCII representation
180 * of a 64-bit unsigned integer. The first ID
181 * generated is 1 and the value will be
182 * incremented for each thread ID.
187 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
188 * Instead, the database has the following additional database
191 * thread_id_* A pre-allocated thread ID for a particular
192 * message. This is actually an arbitrarily large
193 * family of metadata name. Any particular name is
194 * formed by concatenating "thread_id_" with a message
195 * ID (or the SHA1 sum of a message ID if it is very
196 * long---see description of 'id' in the mail
197 * document). The value stored is a thread ID.
199 * These thread ID metadata values are stored
200 * whenever a message references a parent message
201 * that does not yet exist in the database. A
202 * thread ID will be allocated and stored, and if
203 * the message is later added, the stored thread
204 * ID will be used (and the metadata value will
207 * Even before a message is added, it's
208 * pre-allocated thread ID is useful so that all
209 * descendant messages that reference this common
210 * parent can be recognized as belonging to the
214 /* With these prefix values we follow the conventions published here:
216 * http://xapian.org/docs/omega/termprefixes.html
218 * as much as makes sense. Note that I took some liberty in matching
219 * the reserved prefix values to notmuch concepts, (for example, 'G'
220 * is documented as "newsGroup (or similar entity - e.g. a web forum
221 * name)", for which I think the thread is the closest analogue in
222 * notmuch. This in spite of the fact that we will eventually be
223 * storing mailing-list messages where 'G' for "mailing list name"
224 * might be even a closer analogue. I'm treating the single-character
225 * prefixes preferentially for core notmuch concepts (which will be
226 * nearly universal to all mail messages).
229 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
231 { "reference", "XREFERENCE" },
232 { "replyto", "XREPLYTO" },
233 { "directory", "XDIRECTORY" },
234 { "file-direntry", "XFDIRENTRY" },
235 { "directory-direntry", "XDDIRENTRY" },
238 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
245 * Without the ":", since this is a multi-letter prefix, Xapian
246 * will add a colon itself if the first letter of the path is
247 * upper-case ASCII. Including the ":" forces there to always be a
248 * colon, which keeps our own logic simpler.
250 { "folder", "XFOLDER:" },
253 static prefix_t PROBABILISTIC_PREFIX[]= {
256 { "attachment", "XATTACHMENT" },
257 { "mimetype", "XMIMETYPE"},
258 { "subject", "XSUBJECT"},
262 _find_prefix (const char *name)
266 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
267 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
268 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
271 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
272 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
273 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
276 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
277 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
278 return PROBABILISTIC_PREFIX[i].prefix;
281 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
286 static const struct {
287 /* NOTMUCH_FEATURE_* value. */
288 _notmuch_features value;
289 /* Feature name as it appears in the database. This name should
290 * be appropriate for displaying to the user if an older version
291 * of notmuch doesn't support this feature. */
293 /* Compatibility flags when this feature is declared. */
295 } feature_names[] = {
296 { NOTMUCH_FEATURE_FILE_TERMS,
297 "multiple paths per message", "rw" },
298 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
299 "relative directory paths", "rw" },
300 /* Header values are not required for reading a database because a
301 * reader can just refer to the message file. */
302 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
303 "from/subject/message-ID in database", "w" },
304 { NOTMUCH_FEATURE_BOOL_FOLDER,
305 "exact folder:/path: search", "rw" },
306 { NOTMUCH_FEATURE_GHOSTS,
307 "mail documents for missing messages", "w"},
308 /* Knowledge of the index mime-types are not required for reading
309 * a database because a reader will just be unable to query
311 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
312 "indexed MIME types", "w"},
316 notmuch_status_to_string (notmuch_status_t status)
319 case NOTMUCH_STATUS_SUCCESS:
320 return "No error occurred";
321 case NOTMUCH_STATUS_OUT_OF_MEMORY:
322 return "Out of memory";
323 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
324 return "Attempt to write to a read-only database";
325 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
326 return "A Xapian exception occurred";
327 case NOTMUCH_STATUS_FILE_ERROR:
328 return "Something went wrong trying to read or write a file";
329 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
330 return "File is not an email";
331 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
332 return "Message ID is identical to a message in database";
333 case NOTMUCH_STATUS_NULL_POINTER:
334 return "Erroneous NULL pointer";
335 case NOTMUCH_STATUS_TAG_TOO_LONG:
336 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
337 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
338 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
339 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
340 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
341 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
342 return "Unsupported operation";
343 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
344 return "Operation requires a database upgrade";
346 case NOTMUCH_STATUS_LAST_STATUS:
347 return "Unknown error status value";
352 find_doc_ids_for_term (notmuch_database_t *notmuch,
354 Xapian::PostingIterator *begin,
355 Xapian::PostingIterator *end)
357 *begin = notmuch->xapian_db->postlist_begin (term);
359 *end = notmuch->xapian_db->postlist_end (term);
363 find_doc_ids (notmuch_database_t *notmuch,
364 const char *prefix_name,
366 Xapian::PostingIterator *begin,
367 Xapian::PostingIterator *end)
371 term = talloc_asprintf (notmuch, "%s%s",
372 _find_prefix (prefix_name), value);
374 find_doc_ids_for_term (notmuch, term, begin, end);
379 notmuch_private_status_t
380 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
381 const char *prefix_name,
383 unsigned int *doc_id)
385 Xapian::PostingIterator i, end;
387 find_doc_ids (notmuch, prefix_name, value, &i, &end);
391 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
396 #if DEBUG_DATABASE_SANITY
400 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
404 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
407 static Xapian::Document
408 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
410 return notmuch->xapian_db->get_document (doc_id);
413 /* Generate a compressed version of 'message_id' of the form:
415 * notmuch-sha1-<sha1_sum_of_message_id>
418 _notmuch_message_id_compressed (void *ctx, const char *message_id)
420 char *sha1, *compressed;
422 sha1 = _notmuch_sha1_of_string (message_id);
424 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
431 notmuch_database_find_message (notmuch_database_t *notmuch,
432 const char *message_id,
433 notmuch_message_t **message_ret)
435 notmuch_private_status_t status;
438 if (message_ret == NULL)
439 return NOTMUCH_STATUS_NULL_POINTER;
441 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
442 message_id = _notmuch_message_id_compressed (notmuch, message_id);
445 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
446 message_id, &doc_id);
448 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
451 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
453 if (*message_ret == NULL)
454 return NOTMUCH_STATUS_OUT_OF_MEMORY;
457 return NOTMUCH_STATUS_SUCCESS;
458 } catch (const Xapian::Error &error) {
459 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
460 error.get_msg().c_str());
461 notmuch->exception_reported = TRUE;
463 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
467 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
468 * a (potentially nested) parenthesized sequence with '\' used to
469 * escape any character (including parentheses).
471 * If the sequence to be skipped continues to the end of the string,
472 * then 'str' will be left pointing at the final terminating '\0'
476 skip_space_and_comments (const char **str)
481 while (*s && (isspace (*s) || *s == '(')) {
482 while (*s && isspace (*s))
487 while (*s && nesting) {
490 } else if (*s == ')') {
492 } else if (*s == '\\') {
504 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
505 * comments, and the '<' and '>' delimiters.
507 * If not NULL, then *next will be made to point to the first character
508 * not parsed, (possibly pointing to the final '\0' terminator.
510 * Returns a newly talloc'ed string belonging to 'ctx'.
512 * Returns NULL if there is any error parsing the message-id. */
514 _parse_message_id (void *ctx, const char *message_id, const char **next)
519 if (message_id == NULL || *message_id == '\0')
524 skip_space_and_comments (&s);
526 /* Skip any unstructured text as well. */
527 while (*s && *s != '<')
538 skip_space_and_comments (&s);
541 while (*end && *end != '>')
550 if (end > s && *end == '>')
555 result = talloc_strndup (ctx, s, end - s + 1);
557 /* Finally, collapse any whitespace that is within the message-id
563 for (r = result, len = strlen (r); *r; r++, len--)
564 if (*r == ' ' || *r == '\t')
565 memmove (r, r+1, len);
571 /* Parse a References header value, putting a (talloc'ed under 'ctx')
572 * copy of each referenced message-id into 'hash'.
574 * We explicitly avoid including any reference identical to
575 * 'message_id' in the result (to avoid mass confusion when a single
576 * message references itself cyclically---and yes, mail messages are
577 * not infrequent in the wild that do this---don't ask me why).
579 * Return the last reference parsed, if it is not equal to message_id.
582 parse_references (void *ctx,
583 const char *message_id,
587 char *ref, *last_ref = NULL;
589 if (refs == NULL || *refs == '\0')
593 ref = _parse_message_id (ctx, refs, &refs);
595 if (ref && strcmp (ref, message_id)) {
596 g_hash_table_insert (hash, ref, NULL);
601 /* The return value of this function is used to add a parent
602 * reference to the database. We should avoid making a message
603 * its own parent, thus the above check.
609 notmuch_database_create (const char *path, notmuch_database_t **database)
611 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
612 notmuch_database_t *notmuch = NULL;
613 char *notmuch_path = NULL;
618 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
619 status = NOTMUCH_STATUS_NULL_POINTER;
623 err = stat (path, &st);
625 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
626 path, strerror (errno));
627 status = NOTMUCH_STATUS_FILE_ERROR;
631 if (! S_ISDIR (st.st_mode)) {
632 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
634 status = NOTMUCH_STATUS_FILE_ERROR;
638 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
640 err = mkdir (notmuch_path, 0755);
643 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
644 notmuch_path, strerror (errno));
645 status = NOTMUCH_STATUS_FILE_ERROR;
649 status = notmuch_database_open (path,
650 NOTMUCH_DATABASE_MODE_READ_WRITE,
655 /* Upgrade doesn't add these feature to existing databases, but
656 * new databases have them. */
657 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
658 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
660 status = notmuch_database_upgrade (notmuch, NULL, NULL);
662 notmuch_database_close(notmuch);
668 talloc_free (notmuch_path);
673 talloc_free (notmuch);
678 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
680 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
681 fprintf (stderr, "Cannot write to a read-only database.\n");
682 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
685 return NOTMUCH_STATUS_SUCCESS;
688 /* Parse a database features string from the given database version.
689 * Returns the feature bit set.
691 * For version < 3, this ignores the features string and returns a
692 * hard-coded set of features.
694 * If there are unrecognized features that are required to open the
695 * database in mode (which should be 'r' or 'w'), return a
696 * comma-separated list of unrecognized but required features in
697 * *incompat_out suitable for presenting to the user. *incompat_out
698 * will be allocated from ctx.
700 static _notmuch_features
701 _parse_features (const void *ctx, const char *features, unsigned int version,
702 char mode, char **incompat_out)
704 _notmuch_features res = static_cast<_notmuch_features>(0);
705 unsigned int namelen, i;
709 /* Prior to database version 3, features were implied by the
712 return NOTMUCH_FEATURES_V0;
713 else if (version == 1)
714 return NOTMUCH_FEATURES_V1;
715 else if (version == 2)
716 return NOTMUCH_FEATURES_V2;
718 /* Parse the features string */
719 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
720 flags = strchr (features, '\t');
721 if (! flags || flags > features + llen)
723 namelen = flags - features;
725 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
726 if (strlen (feature_names[i].name) == namelen &&
727 strncmp (feature_names[i].name, features, namelen) == 0) {
728 res |= feature_names[i].value;
733 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
734 /* Unrecognized feature */
735 const char *have = strchr (flags, mode);
736 if (have && have < features + llen) {
737 /* This feature is required to access this database in
738 * 'mode', but we don't understand it. */
740 *incompat_out = talloc_strdup (ctx, "");
741 *incompat_out = talloc_asprintf_append_buffer (
742 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
752 _print_features (const void *ctx, unsigned int features)
755 char *res = talloc_strdup (ctx, "");
757 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
758 if (features & feature_names[i].value)
759 res = talloc_asprintf_append_buffer (
760 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
766 notmuch_database_open (const char *path,
767 notmuch_database_mode_t mode,
768 notmuch_database_t **database)
770 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
771 void *local = talloc_new (NULL);
772 notmuch_database_t *notmuch = NULL;
773 char *notmuch_path, *xapian_path, *incompat_features;
776 unsigned int i, version;
777 static int initialized = 0;
780 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
781 status = NOTMUCH_STATUS_NULL_POINTER;
785 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
786 fprintf (stderr, "Out of memory\n");
787 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
791 err = stat (notmuch_path, &st);
793 fprintf (stderr, "Error opening database at %s: %s\n",
794 notmuch_path, strerror (errno));
795 status = NOTMUCH_STATUS_FILE_ERROR;
799 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
800 fprintf (stderr, "Out of memory\n");
801 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
805 /* Initialize the GLib type system and threads */
806 #if !GLIB_CHECK_VERSION(2, 35, 1)
810 /* Initialize gmime */
812 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
816 notmuch = talloc_zero (NULL, notmuch_database_t);
817 notmuch->exception_reported = FALSE;
818 notmuch->path = talloc_strdup (notmuch, path);
820 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
821 notmuch->path[strlen (notmuch->path) - 1] = '\0';
823 notmuch->mode = mode;
824 notmuch->atomic_nesting = 0;
826 string last_thread_id;
828 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
829 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
830 Xapian::DB_CREATE_OR_OPEN);
832 notmuch->xapian_db = new Xapian::Database (xapian_path);
835 /* Check version. As of database version 3, we represent
836 * changes in terms of features, so assume a version bump
837 * means a dramatically incompatible change. */
838 version = notmuch_database_get_version (notmuch);
839 if (version > NOTMUCH_DATABASE_VERSION) {
841 "Error: Notmuch database at %s\n"
842 " has a newer database format version (%u) than supported by this\n"
843 " version of notmuch (%u).\n",
844 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
845 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
846 notmuch_database_destroy (notmuch);
848 status = NOTMUCH_STATUS_FILE_ERROR;
852 /* Check features. */
853 incompat_features = NULL;
854 notmuch->features = _parse_features (
855 local, notmuch->xapian_db->get_metadata ("features").c_str (),
856 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
858 if (incompat_features) {
860 "Error: Notmuch database at %s\n"
861 " requires features (%s)\n"
862 " not supported by this version of notmuch.\n",
863 notmuch_path, incompat_features);
864 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
865 notmuch_database_destroy (notmuch);
867 status = NOTMUCH_STATUS_FILE_ERROR;
871 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
872 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
873 if (last_thread_id.empty ()) {
874 notmuch->last_thread_id = 0;
879 str = last_thread_id.c_str ();
880 notmuch->last_thread_id = strtoull (str, &end, 16);
882 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
885 notmuch->query_parser = new Xapian::QueryParser;
886 notmuch->term_gen = new Xapian::TermGenerator;
887 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
888 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
889 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
891 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
892 notmuch->query_parser->set_database (*notmuch->xapian_db);
893 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
894 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
895 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
896 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
898 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
899 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
900 notmuch->query_parser->add_boolean_prefix (prefix->name,
904 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
905 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
906 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
908 } catch (const Xapian::Error &error) {
909 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
910 error.get_msg().c_str());
911 notmuch_database_destroy (notmuch);
913 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
922 talloc_free (notmuch);
927 notmuch_database_close (notmuch_database_t *notmuch)
929 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
931 /* Many Xapian objects (and thus notmuch objects) hold references to
932 * the database, so merely deleting the database may not suffice to
933 * close it. Thus, we explicitly close it here. */
934 if (notmuch->xapian_db != NULL) {
936 /* If there's an outstanding transaction, it's unclear if
937 * closing the Xapian database commits everything up to
938 * that transaction, or may discard committed (but
939 * unflushed) transactions. To be certain, explicitly
940 * cancel any outstanding transaction before closing. */
941 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
942 notmuch->atomic_nesting)
943 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
944 ->cancel_transaction ();
946 /* Close the database. This implicitly flushes
947 * outstanding changes. */
948 notmuch->xapian_db->close();
949 } catch (const Xapian::Error &error) {
950 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
951 if (! notmuch->exception_reported) {
952 fprintf (stderr, "Error: A Xapian exception occurred closing database: %s\n",
953 error.get_msg().c_str());
958 delete notmuch->term_gen;
959 notmuch->term_gen = NULL;
960 delete notmuch->query_parser;
961 notmuch->query_parser = NULL;
962 delete notmuch->xapian_db;
963 notmuch->xapian_db = NULL;
964 delete notmuch->value_range_processor;
965 notmuch->value_range_processor = NULL;
966 delete notmuch->date_range_processor;
967 notmuch->date_range_processor = NULL;
972 #if HAVE_XAPIAN_COMPACT
974 unlink_cb (const char *path,
975 unused (const struct stat *sb),
977 unused (struct FTW *ftw))
979 return remove (path);
983 rmtree (const char *path)
985 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
988 class NotmuchCompactor : public Xapian::Compactor
990 notmuch_compact_status_cb_t status_cb;
991 void *status_closure;
994 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
995 status_cb (cb), status_closure (closure) { }
998 set_status (const std::string &table, const std::string &status)
1002 if (status_cb == NULL)
1005 if (status.length () == 0)
1006 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1008 msg = talloc_asprintf (NULL, " %s", status.c_str());
1014 status_cb (msg, status_closure);
1019 /* Compacts the given database, optionally saving the original database
1020 * in backup_path. Additionally, a callback function can be provided to
1021 * give the user feedback on the progress of the (likely long-lived)
1022 * compaction process.
1024 * The backup path must point to a directory on the same volume as the
1025 * original database. Passing a NULL backup_path will result in the
1026 * uncompacted database being deleted after compaction has finished.
1027 * Note that the database write lock will be held during the
1028 * compaction process to protect data integrity.
1031 notmuch_database_compact (const char *path,
1032 const char *backup_path,
1033 notmuch_compact_status_cb_t status_cb,
1037 char *notmuch_path, *xapian_path, *compact_xapian_path;
1038 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1039 notmuch_database_t *notmuch = NULL;
1040 struct stat statbuf;
1041 notmuch_bool_t keep_backup;
1043 local = talloc_new (NULL);
1045 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1047 ret = notmuch_database_open (path, NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much);
1052 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1053 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1057 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1058 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1062 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1063 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1067 if (backup_path == NULL) {
1068 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1069 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1072 keep_backup = FALSE;
1078 if (stat (backup_path, &statbuf) != -1) {
1079 fprintf (stderr, "Path already exists: %s\n", backup_path);
1080 ret = NOTMUCH_STATUS_FILE_ERROR;
1083 if (errno != ENOENT) {
1084 fprintf (stderr, "Unknown error while stat()ing path: %s\n",
1086 ret = NOTMUCH_STATUS_FILE_ERROR;
1090 /* Unconditionally attempt to remove old work-in-progress database (if
1091 * any). This is "protected" by database lock. If this fails due to write
1092 * errors (etc), the following code will fail and provide error message.
1094 (void) rmtree (compact_xapian_path);
1097 NotmuchCompactor compactor (status_cb, closure);
1099 compactor.set_renumber (false);
1100 compactor.add_source (xapian_path);
1101 compactor.set_destdir (compact_xapian_path);
1102 compactor.compact ();
1103 } catch (const Xapian::Error &error) {
1104 fprintf (stderr, "Error while compacting: %s\n", error.get_msg().c_str());
1105 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1109 if (rename (xapian_path, backup_path)) {
1110 fprintf (stderr, "Error moving %s to %s: %s\n",
1111 xapian_path, backup_path, strerror (errno));
1112 ret = NOTMUCH_STATUS_FILE_ERROR;
1116 if (rename (compact_xapian_path, xapian_path)) {
1117 fprintf (stderr, "Error moving %s to %s: %s\n",
1118 compact_xapian_path, xapian_path, strerror (errno));
1119 ret = NOTMUCH_STATUS_FILE_ERROR;
1123 if (! keep_backup) {
1124 if (rmtree (backup_path)) {
1125 fprintf (stderr, "Error removing old database %s: %s\n",
1126 backup_path, strerror (errno));
1127 ret = NOTMUCH_STATUS_FILE_ERROR;
1134 notmuch_status_t ret2;
1136 ret2 = notmuch_database_destroy (notmuch);
1138 /* don't clobber previous error status */
1139 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1143 talloc_free (local);
1149 notmuch_database_compact (unused (const char *path),
1150 unused (const char *backup_path),
1151 unused (notmuch_compact_status_cb_t status_cb),
1152 unused (void *closure))
1154 fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
1155 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1160 notmuch_database_destroy (notmuch_database_t *notmuch)
1162 notmuch_status_t status;
1164 status = notmuch_database_close (notmuch);
1165 talloc_free (notmuch);
1171 notmuch_database_get_path (notmuch_database_t *notmuch)
1173 return notmuch->path;
1177 notmuch_database_get_version (notmuch_database_t *notmuch)
1179 unsigned int version;
1180 string version_string;
1184 version_string = notmuch->xapian_db->get_metadata ("version");
1185 if (version_string.empty ())
1188 str = version_string.c_str ();
1189 if (str == NULL || *str == '\0')
1192 version = strtoul (str, &end, 10);
1194 INTERNAL_ERROR ("Malformed database version: %s", str);
1200 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1202 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1203 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1204 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1207 static volatile sig_atomic_t do_progress_notify = 0;
1210 handle_sigalrm (unused (int signal))
1212 do_progress_notify = 1;
1215 /* Upgrade the current database.
1217 * After opening a database in read-write mode, the client should
1218 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1219 * if so, upgrade with this function before making any modifications.
1221 * The optional progress_notify callback can be used by the caller to
1222 * provide progress indication to the user. If non-NULL it will be
1223 * called periodically with 'count' as the number of messages upgraded
1224 * so far and 'total' the overall number of messages that will be
1228 notmuch_database_upgrade (notmuch_database_t *notmuch,
1229 void (*progress_notify) (void *closure,
1233 void *local = talloc_new (NULL);
1234 Xapian::TermIterator t, t_end;
1235 Xapian::WritableDatabase *db;
1236 struct sigaction action;
1237 struct itimerval timerval;
1238 notmuch_bool_t timer_is_active = FALSE;
1239 enum _notmuch_features target_features, new_features;
1240 notmuch_status_t status;
1241 notmuch_private_status_t private_status;
1242 unsigned int count = 0, total = 0;
1244 status = _notmuch_database_ensure_writable (notmuch);
1248 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1250 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1251 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1253 if (! notmuch_database_needs_upgrade (notmuch))
1254 return NOTMUCH_STATUS_SUCCESS;
1256 if (progress_notify) {
1257 /* Setup our handler for SIGALRM */
1258 memset (&action, 0, sizeof (struct sigaction));
1259 action.sa_handler = handle_sigalrm;
1260 sigemptyset (&action.sa_mask);
1261 action.sa_flags = SA_RESTART;
1262 sigaction (SIGALRM, &action, NULL);
1264 /* Then start a timer to send SIGALRM once per second. */
1265 timerval.it_interval.tv_sec = 1;
1266 timerval.it_interval.tv_usec = 0;
1267 timerval.it_value.tv_sec = 1;
1268 timerval.it_value.tv_usec = 0;
1269 setitimer (ITIMER_REAL, &timerval, NULL);
1271 timer_is_active = TRUE;
1274 /* Figure out how much total work we need to do. */
1276 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1277 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1278 total += notmuch_query_count_messages (query);
1279 notmuch_query_destroy (query);
1281 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1282 t_end = db->allterms_end ("XTIMESTAMP");
1283 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1286 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1287 /* The ghost message upgrade converts all thread_id_*
1288 * metadata values into ghost message documents. */
1289 t_end = db->metadata_keys_end ("thread_id_");
1290 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1294 /* Perform the upgrade in a transaction. */
1295 db->begin_transaction (true);
1297 /* Set the target features so we write out changes in the desired
1299 notmuch->features = target_features;
1301 /* Perform per-message upgrades. */
1303 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1304 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1305 notmuch_messages_t *messages;
1306 notmuch_message_t *message;
1309 for (messages = notmuch_query_search_messages (query);
1310 notmuch_messages_valid (messages);
1311 notmuch_messages_move_to_next (messages))
1313 if (do_progress_notify) {
1314 progress_notify (closure, (double) count / total);
1315 do_progress_notify = 0;
1318 message = notmuch_messages_get (messages);
1320 /* Before version 1, each message document had its
1321 * filename in the data field. Copy that into the new
1322 * format by calling notmuch_message_add_filename.
1324 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1325 filename = _notmuch_message_talloc_copy_data (message);
1326 if (filename && *filename != '\0') {
1327 _notmuch_message_add_filename (message, filename);
1328 _notmuch_message_clear_data (message);
1330 talloc_free (filename);
1333 /* Prior to version 2, the "folder:" prefix was
1334 * probabilistic and stemmed. Change it to the current
1335 * boolean prefix. Add "path:" prefixes while at it.
1337 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1338 _notmuch_message_upgrade_folder (message);
1340 _notmuch_message_sync (message);
1342 notmuch_message_destroy (message);
1347 notmuch_query_destroy (query);
1350 /* Perform per-directory upgrades. */
1352 /* Before version 1 we stored directory timestamps in
1353 * XTIMESTAMP documents instead of the current XDIRECTORY
1354 * documents. So copy those as well. */
1355 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1356 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1358 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1362 Xapian::PostingIterator p, p_end;
1363 std::string term = *t;
1365 p_end = notmuch->xapian_db->postlist_end (term);
1367 for (p = notmuch->xapian_db->postlist_begin (term);
1371 Xapian::Document document;
1373 notmuch_directory_t *directory;
1375 if (do_progress_notify) {
1376 progress_notify (closure, (double) count / total);
1377 do_progress_notify = 0;
1380 document = find_document_for_doc_id (notmuch, *p);
1381 mtime = Xapian::sortable_unserialise (
1382 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1384 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1385 NOTMUCH_FIND_CREATE, &status);
1386 notmuch_directory_set_mtime (directory, mtime);
1387 notmuch_directory_destroy (directory);
1389 db->delete_document (*p);
1396 /* Perform metadata upgrades. */
1398 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1399 * messages were stored as database metadata. Change these to
1402 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1403 notmuch_message_t *message;
1404 std::string message_id, thread_id;
1406 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1407 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1409 if (do_progress_notify) {
1410 progress_notify (closure, (double) count / total);
1411 do_progress_notify = 0;
1414 message_id = (*t).substr (
1415 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1416 thread_id = db->get_metadata (*t);
1418 /* Create ghost message */
1419 message = _notmuch_message_create_for_message_id (
1420 notmuch, message_id.c_str (), &private_status);
1421 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1422 /* Document already exists; ignore the stored thread ID */
1423 } else if (private_status ==
1424 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1425 private_status = _notmuch_message_initialize_ghost (
1426 message, thread_id.c_str ());
1427 if (! private_status)
1428 _notmuch_message_sync (message);
1431 if (private_status) {
1433 "Upgrade failed while creating ghost messages.\n");
1434 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1438 /* Clear saved metadata thread ID */
1439 db->set_metadata (*t, "");
1445 status = NOTMUCH_STATUS_SUCCESS;
1446 db->set_metadata ("features", _print_features (local, notmuch->features));
1447 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1450 if (status == NOTMUCH_STATUS_SUCCESS)
1451 db->commit_transaction ();
1453 db->cancel_transaction ();
1455 if (timer_is_active) {
1456 /* Now stop the timer. */
1457 timerval.it_interval.tv_sec = 0;
1458 timerval.it_interval.tv_usec = 0;
1459 timerval.it_value.tv_sec = 0;
1460 timerval.it_value.tv_usec = 0;
1461 setitimer (ITIMER_REAL, &timerval, NULL);
1463 /* And disable the signal handler. */
1464 action.sa_handler = SIG_IGN;
1465 sigaction (SIGALRM, &action, NULL);
1468 talloc_free (local);
1473 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1475 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1476 notmuch->atomic_nesting > 0)
1480 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1481 } catch (const Xapian::Error &error) {
1482 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1483 error.get_msg().c_str());
1484 notmuch->exception_reported = TRUE;
1485 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1489 notmuch->atomic_nesting++;
1490 return NOTMUCH_STATUS_SUCCESS;
1494 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1496 Xapian::WritableDatabase *db;
1498 if (notmuch->atomic_nesting == 0)
1499 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1501 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1502 notmuch->atomic_nesting > 1)
1505 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1507 db->commit_transaction ();
1509 /* This is a hack for testing. Xapian never flushes on a
1510 * non-flushed commit, even if the flush threshold is 1.
1511 * However, we rely on flushing to test atomicity. */
1512 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1513 if (thresh && atoi (thresh) == 1)
1515 } catch (const Xapian::Error &error) {
1516 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1517 error.get_msg().c_str());
1518 notmuch->exception_reported = TRUE;
1519 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1523 notmuch->atomic_nesting--;
1524 return NOTMUCH_STATUS_SUCCESS;
1527 /* We allow the user to use arbitrarily long paths for directories. But
1528 * we have a term-length limit. So if we exceed that, we'll use the
1529 * SHA-1 of the path for the database term.
1531 * Note: This function may return the original value of 'path'. If it
1532 * does not, then the caller is responsible to free() the returned
1536 _notmuch_database_get_directory_db_path (const char *path)
1538 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1540 if (term_len > NOTMUCH_TERM_MAX)
1541 return _notmuch_sha1_of_string (path);
1546 /* Given a path, split it into two parts: the directory part is all
1547 * components except for the last, and the basename is that last
1548 * component. Getting the return-value for either part is optional
1549 * (the caller can pass NULL).
1551 * The original 'path' can represent either a regular file or a
1552 * directory---the splitting will be carried out in the same way in
1553 * either case. Trailing slashes on 'path' will be ignored, and any
1554 * cases of multiple '/' characters appearing in series will be
1555 * treated as a single '/'.
1557 * Allocation (if any) will have 'ctx' as the talloc owner. But
1558 * pointers will be returned within the original path string whenever
1561 * Note: If 'path' is non-empty and contains no non-trailing slash,
1562 * (that is, consists of a filename with no parent directory), then
1563 * the directory returned will be an empty string. However, if 'path'
1564 * is an empty string, then both directory and basename will be
1568 _notmuch_database_split_path (void *ctx,
1570 const char **directory,
1571 const char **basename)
1575 if (path == NULL || *path == '\0') {
1580 return NOTMUCH_STATUS_SUCCESS;
1583 /* Find the last slash (not counting a trailing slash), if any. */
1585 slash = path + strlen (path) - 1;
1587 /* First, skip trailing slashes. */
1588 while (slash != path) {
1595 /* Then, find a slash. */
1596 while (slash != path) {
1606 /* Finally, skip multiple slashes. */
1607 while (slash != path) {
1614 if (slash == path) {
1616 *directory = talloc_strdup (ctx, "");
1621 *directory = talloc_strndup (ctx, path, slash - path + 1);
1624 return NOTMUCH_STATUS_SUCCESS;
1627 /* Find the document ID of the specified directory.
1629 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1630 * created if one does not exist for 'path'. Otherwise, if the
1631 * directory document does not exist, this sets *directory_id to
1632 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1635 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1637 notmuch_find_flags_t flags,
1638 unsigned int *directory_id)
1640 notmuch_directory_t *directory;
1641 notmuch_status_t status;
1645 return NOTMUCH_STATUS_SUCCESS;
1648 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1649 if (status || !directory) {
1654 *directory_id = _notmuch_directory_get_document_id (directory);
1656 notmuch_directory_destroy (directory);
1658 return NOTMUCH_STATUS_SUCCESS;
1662 _notmuch_database_get_directory_path (void *ctx,
1663 notmuch_database_t *notmuch,
1664 unsigned int doc_id)
1666 Xapian::Document document;
1668 document = find_document_for_doc_id (notmuch, doc_id);
1670 return talloc_strdup (ctx, document.get_data ().c_str ());
1673 /* Given a legal 'filename' for the database, (either relative to
1674 * database path or absolute with initial components identical to
1675 * database path), return a new string (with 'ctx' as the talloc
1676 * owner) suitable for use as a direntry term value.
1678 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1679 * will be created in the database as needed. Otherwise, if the
1680 * necessary directory documents do not exist, this sets
1681 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1684 _notmuch_database_filename_to_direntry (void *ctx,
1685 notmuch_database_t *notmuch,
1686 const char *filename,
1687 notmuch_find_flags_t flags,
1690 const char *relative, *directory, *basename;
1691 Xapian::docid directory_id;
1692 notmuch_status_t status;
1694 relative = _notmuch_database_relative_path (notmuch, filename);
1696 status = _notmuch_database_split_path (ctx, relative,
1697 &directory, &basename);
1701 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1703 if (status || directory_id == (unsigned int)-1) {
1708 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1710 return NOTMUCH_STATUS_SUCCESS;
1713 /* Given a legal 'path' for the database, return the relative path.
1715 * The return value will be a pointer to the original path contents,
1716 * and will be either the original string (if 'path' was relative) or
1717 * a portion of the string (if path was absolute and begins with the
1721 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1724 const char *db_path, *relative;
1725 unsigned int db_path_len;
1727 db_path = notmuch_database_get_path (notmuch);
1728 db_path_len = strlen (db_path);
1732 if (*relative == '/') {
1733 while (*relative == '/' && *(relative+1) == '/')
1736 if (strncmp (relative, db_path, db_path_len) == 0)
1738 relative += db_path_len;
1739 while (*relative == '/')
1748 notmuch_database_get_directory (notmuch_database_t *notmuch,
1750 notmuch_directory_t **directory)
1752 notmuch_status_t status;
1754 if (directory == NULL)
1755 return NOTMUCH_STATUS_NULL_POINTER;
1759 *directory = _notmuch_directory_create (notmuch, path,
1760 NOTMUCH_FIND_LOOKUP, &status);
1761 } catch (const Xapian::Error &error) {
1762 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1763 error.get_msg().c_str());
1764 notmuch->exception_reported = TRUE;
1765 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1770 /* Allocate a document ID that satisfies the following criteria:
1772 * 1. The ID does not exist for any document in the Xapian database
1774 * 2. The ID was not previously returned from this function
1776 * 3. The ID is the smallest integer satisfying (1) and (2)
1778 * This function will trigger an internal error if these constraints
1779 * cannot all be satisfied, (that is, the pool of available document
1780 * IDs has been exhausted).
1783 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1785 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1787 notmuch->last_doc_id++;
1789 if (notmuch->last_doc_id == 0)
1790 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1792 return notmuch->last_doc_id;
1796 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1798 /* 16 bytes (+ terminator) for hexadecimal representation of
1799 * a 64-bit integer. */
1800 static char thread_id[17];
1801 Xapian::WritableDatabase *db;
1803 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1805 notmuch->last_thread_id++;
1807 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1809 db->set_metadata ("last_thread_id", thread_id);
1815 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1817 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1818 message_id = _notmuch_message_id_compressed (ctx, message_id);
1820 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1824 static notmuch_status_t
1825 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1827 const char *message_id,
1828 const char **thread_id_ret);
1830 /* Find the thread ID to which the message with 'message_id' belongs.
1832 * Note: 'thread_id_ret' must not be NULL!
1833 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1836 * Note: If there is no message in the database with the given
1837 * 'message_id' then a new thread_id will be allocated for this
1838 * message ID and stored in the database metadata so that the
1839 * thread ID can be looked up if the message is added to the database
1842 static notmuch_status_t
1843 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1845 const char *message_id,
1846 const char **thread_id_ret)
1848 notmuch_private_status_t status;
1849 notmuch_message_t *message;
1851 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
1852 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
1855 /* Look for this message (regular or ghost) */
1856 message = _notmuch_message_create_for_message_id (
1857 notmuch, message_id, &status);
1858 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1859 /* Message exists */
1860 *thread_id_ret = talloc_steal (
1861 ctx, notmuch_message_get_thread_id (message));
1862 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1863 /* Message did not exist. Give it a fresh thread ID and
1864 * populate this message as a ghost message. */
1865 *thread_id_ret = talloc_strdup (
1866 ctx, _notmuch_database_generate_thread_id (notmuch));
1867 if (! *thread_id_ret) {
1868 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
1870 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
1872 /* Commit the new ghost message */
1873 _notmuch_message_sync (message);
1876 /* Create failed. Fall through. */
1879 notmuch_message_destroy (message);
1881 return COERCE_STATUS (status, "Error creating ghost message");
1884 /* Pre-ghost messages _resolve_message_id_to_thread_id */
1885 static notmuch_status_t
1886 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1888 const char *message_id,
1889 const char **thread_id_ret)
1891 notmuch_status_t status;
1892 notmuch_message_t *message;
1893 string thread_id_string;
1895 Xapian::WritableDatabase *db;
1897 status = notmuch_database_find_message (notmuch, message_id, &message);
1903 *thread_id_ret = talloc_steal (ctx,
1904 notmuch_message_get_thread_id (message));
1906 notmuch_message_destroy (message);
1908 return NOTMUCH_STATUS_SUCCESS;
1911 /* Message has not been seen yet.
1913 * We may have seen a reference to it already, in which case, we
1914 * can return the thread ID stored in the metadata. Otherwise, we
1915 * generate a new thread ID and store it there.
1917 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1918 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1919 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1921 if (thread_id_string.empty()) {
1922 *thread_id_ret = talloc_strdup (ctx,
1923 _notmuch_database_generate_thread_id (notmuch));
1924 db->set_metadata (metadata_key, *thread_id_ret);
1926 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1929 talloc_free (metadata_key);
1931 return NOTMUCH_STATUS_SUCCESS;
1934 static notmuch_status_t
1935 _merge_threads (notmuch_database_t *notmuch,
1936 const char *winner_thread_id,
1937 const char *loser_thread_id)
1939 Xapian::PostingIterator loser, loser_end;
1940 notmuch_message_t *message = NULL;
1941 notmuch_private_status_t private_status;
1942 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1944 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1946 for ( ; loser != loser_end; loser++) {
1947 message = _notmuch_message_create (notmuch, notmuch,
1948 *loser, &private_status);
1949 if (message == NULL) {
1950 ret = COERCE_STATUS (private_status,
1951 "Cannot find document for doc_id from query");
1955 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1956 _notmuch_message_add_term (message, "thread", winner_thread_id);
1957 _notmuch_message_sync (message);
1959 notmuch_message_destroy (message);
1965 notmuch_message_destroy (message);
1971 _my_talloc_free_for_g_hash (void *ptr)
1976 static notmuch_status_t
1977 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1978 notmuch_message_t *message,
1979 notmuch_message_file_t *message_file,
1980 const char **thread_id)
1982 GHashTable *parents = NULL;
1983 const char *refs, *in_reply_to, *in_reply_to_message_id;
1984 const char *last_ref_message_id, *this_message_id;
1985 GList *l, *keys = NULL;
1986 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1988 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1989 _my_talloc_free_for_g_hash, NULL);
1990 this_message_id = notmuch_message_get_message_id (message);
1992 refs = _notmuch_message_file_get_header (message_file, "references");
1993 last_ref_message_id = parse_references (message,
1997 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
1998 in_reply_to_message_id = parse_references (message,
2000 parents, in_reply_to);
2002 /* For the parent of this message, use the last message ID of the
2003 * References header, if available. If not, fall back to the
2004 * first message ID in the In-Reply-To header. */
2005 if (last_ref_message_id) {
2006 _notmuch_message_add_term (message, "replyto",
2007 last_ref_message_id);
2008 } else if (in_reply_to_message_id) {
2009 _notmuch_message_add_term (message, "replyto",
2010 in_reply_to_message_id);
2013 keys = g_hash_table_get_keys (parents);
2014 for (l = keys; l; l = l->next) {
2015 char *parent_message_id;
2016 const char *parent_thread_id = NULL;
2018 parent_message_id = (char *) l->data;
2020 _notmuch_message_add_term (message, "reference",
2023 ret = _resolve_message_id_to_thread_id (notmuch,
2030 if (*thread_id == NULL) {
2031 *thread_id = talloc_strdup (message, parent_thread_id);
2032 _notmuch_message_add_term (message, "thread", *thread_id);
2033 } else if (strcmp (*thread_id, parent_thread_id)) {
2034 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2044 g_hash_table_unref (parents);
2049 static notmuch_status_t
2050 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2051 notmuch_message_t *message,
2052 const char **thread_id)
2054 const char *message_id = notmuch_message_get_message_id (message);
2055 Xapian::PostingIterator child, children_end;
2056 notmuch_message_t *child_message = NULL;
2057 const char *child_thread_id;
2058 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2059 notmuch_private_status_t private_status;
2061 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2063 for ( ; child != children_end; child++) {
2065 child_message = _notmuch_message_create (message, notmuch,
2066 *child, &private_status);
2067 if (child_message == NULL) {
2068 ret = COERCE_STATUS (private_status,
2069 "Cannot find document for doc_id from query");
2073 child_thread_id = notmuch_message_get_thread_id (child_message);
2074 if (*thread_id == NULL) {
2075 *thread_id = talloc_strdup (message, child_thread_id);
2076 _notmuch_message_add_term (message, "thread", *thread_id);
2077 } else if (strcmp (*thread_id, child_thread_id)) {
2078 _notmuch_message_remove_term (child_message, "reference",
2080 _notmuch_message_sync (child_message);
2081 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2086 notmuch_message_destroy (child_message);
2087 child_message = NULL;
2092 notmuch_message_destroy (child_message);
2097 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2099 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2100 notmuch_message_t *message)
2102 const char *message_id;
2106 message_id = notmuch_message_get_message_id (message);
2107 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2109 /* Check if we have already seen related messages to this one.
2110 * If we have then use the thread_id that we stored at that time.
2112 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2113 if (stored_id.empty ()) {
2116 Xapian::WritableDatabase *db;
2118 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2120 /* Clear the metadata for this message ID. We don't need it
2122 db->set_metadata (metadata_key, "");
2124 return talloc_strdup (ctx, stored_id.c_str ());
2128 /* Given a blank or ghost 'message' and its corresponding
2129 * 'message_file' link it to existing threads in the database.
2131 * First, if is_ghost, this retrieves the thread ID already stored in
2132 * the message (which will be the case if a message was previously
2133 * added that referenced this one). If the message is blank
2134 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2135 * later in this function). If the database does not support ghost
2136 * messages, this checks for a thread ID stored in database metadata
2137 * for this message ID.
2139 * Second, we look at 'message_file' and its link-relevant headers
2140 * (References and In-Reply-To) for message IDs.
2142 * Finally, we look in the database for existing message that
2143 * reference 'message'.
2145 * In all cases, we assign to the current message the first thread ID
2146 * found. We will also merge any existing, distinct threads where this
2147 * message belongs to both, (which is not uncommon when messages are
2148 * processed out of order).
2150 * Finally, if no thread ID has been found through referenced messages, we
2151 * call _notmuch_message_generate_thread_id to generate a new thread
2152 * ID. This should only happen for new, top-level messages, (no
2153 * References or In-Reply-To header in this message, and no previously
2154 * added message refers to this message).
2156 static notmuch_status_t
2157 _notmuch_database_link_message (notmuch_database_t *notmuch,
2158 notmuch_message_t *message,
2159 notmuch_message_file_t *message_file,
2160 notmuch_bool_t is_ghost)
2162 void *local = talloc_new (NULL);
2163 notmuch_status_t status;
2164 const char *thread_id = NULL;
2166 /* Check if the message already had a thread ID */
2167 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2169 thread_id = notmuch_message_get_thread_id (message);
2171 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2173 _notmuch_message_add_term (message, "thread", thread_id);
2176 status = _notmuch_database_link_message_to_parents (notmuch, message,
2182 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2183 /* In general, it shouldn't be necessary to link children,
2184 * since the earlier indexing of those children will have
2185 * stored a thread ID for the missing parent. However, prior
2186 * to ghost messages, these stored thread IDs were NOT
2187 * rewritten during thread merging (and there was no
2188 * performant way to do so), so if indexed children were
2189 * pulled into a different thread ID by a merge, it was
2190 * necessary to pull them *back* into the stored thread ID of
2191 * the parent. With ghost messages, we just rewrite the
2192 * stored thread IDs during merging, so this workaround isn't
2194 status = _notmuch_database_link_message_to_children (notmuch, message,
2200 /* If not part of any existing thread, generate a new thread ID. */
2201 if (thread_id == NULL) {
2202 thread_id = _notmuch_database_generate_thread_id (notmuch);
2204 _notmuch_message_add_term (message, "thread", thread_id);
2208 talloc_free (local);
2214 notmuch_database_add_message (notmuch_database_t *notmuch,
2215 const char *filename,
2216 notmuch_message_t **message_ret)
2218 notmuch_message_file_t *message_file;
2219 notmuch_message_t *message = NULL;
2220 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2221 notmuch_private_status_t private_status;
2222 notmuch_bool_t is_ghost = false;
2224 const char *date, *header;
2225 const char *from, *to, *subject;
2226 char *message_id = NULL;
2229 *message_ret = NULL;
2231 ret = _notmuch_database_ensure_writable (notmuch);
2235 message_file = _notmuch_message_file_open (filename);
2236 if (message_file == NULL)
2237 return NOTMUCH_STATUS_FILE_ERROR;
2239 /* Adding a message may change many documents. Do this all
2241 ret = notmuch_database_begin_atomic (notmuch);
2245 /* Parse message up front to get better error status. */
2246 ret = _notmuch_message_file_parse (message_file);
2251 /* Before we do any real work, (especially before doing a
2252 * potential SHA-1 computation on the entire file's contents),
2253 * let's make sure that what we're looking at looks like an
2254 * actual email message.
2256 from = _notmuch_message_file_get_header (message_file, "from");
2257 subject = _notmuch_message_file_get_header (message_file, "subject");
2258 to = _notmuch_message_file_get_header (message_file, "to");
2260 if ((from == NULL || *from == '\0') &&
2261 (subject == NULL || *subject == '\0') &&
2262 (to == NULL || *to == '\0'))
2264 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2268 /* Now that we're sure it's mail, the first order of business
2269 * is to find a message ID (or else create one ourselves). */
2271 header = _notmuch_message_file_get_header (message_file, "message-id");
2272 if (header && *header != '\0') {
2273 message_id = _parse_message_id (message_file, header, NULL);
2275 /* So the header value isn't RFC-compliant, but it's
2276 * better than no message-id at all. */
2277 if (message_id == NULL)
2278 message_id = talloc_strdup (message_file, header);
2281 if (message_id == NULL ) {
2282 /* No message-id at all, let's generate one by taking a
2283 * hash over the file's contents. */
2284 char *sha1 = _notmuch_sha1_of_file (filename);
2286 /* If that failed too, something is really wrong. Give up. */
2288 ret = NOTMUCH_STATUS_FILE_ERROR;
2292 message_id = talloc_asprintf (message_file,
2293 "notmuch-sha1-%s", sha1);
2297 /* Now that we have a message ID, we get a message object,
2298 * (which may or may not reference an existing document in the
2301 message = _notmuch_message_create_for_message_id (notmuch,
2305 talloc_free (message_id);
2307 if (message == NULL) {
2308 ret = COERCE_STATUS (private_status,
2309 "Unexpected status value from _notmuch_message_create_for_message_id");
2313 _notmuch_message_add_filename (message, filename);
2315 /* Is this a newly created message object or a ghost
2316 * message? We have to be slightly careful: if this is a
2317 * blank message, it's not safe to call
2318 * notmuch_message_get_flag yet. */
2319 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2320 (is_ghost = notmuch_message_get_flag (
2321 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2322 _notmuch_message_add_term (message, "type", "mail");
2324 /* Convert ghost message to a regular message */
2325 _notmuch_message_remove_term (message, "type", "ghost");
2327 ret = _notmuch_database_link_message (notmuch, message,
2328 message_file, is_ghost);
2332 date = _notmuch_message_file_get_header (message_file, "date");
2333 _notmuch_message_set_header_values (message, date, from, subject);
2335 ret = _notmuch_message_index_file (message, message_file);
2339 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2342 _notmuch_message_sync (message);
2343 } catch (const Xapian::Error &error) {
2344 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2345 error.get_msg().c_str());
2346 notmuch->exception_reported = TRUE;
2347 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2353 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2354 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2355 *message_ret = message;
2357 notmuch_message_destroy (message);
2361 _notmuch_message_file_close (message_file);
2363 ret2 = notmuch_database_end_atomic (notmuch);
2364 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2365 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2366 ret2 != NOTMUCH_STATUS_SUCCESS)
2373 notmuch_database_remove_message (notmuch_database_t *notmuch,
2374 const char *filename)
2376 notmuch_status_t status;
2377 notmuch_message_t *message;
2379 status = notmuch_database_find_message_by_filename (notmuch, filename,
2382 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2383 status = _notmuch_message_remove_filename (message, filename);
2384 if (status == NOTMUCH_STATUS_SUCCESS)
2385 _notmuch_message_delete (message);
2386 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2387 _notmuch_message_sync (message);
2389 notmuch_message_destroy (message);
2396 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2397 const char *filename,
2398 notmuch_message_t **message_ret)
2401 const char *prefix = _find_prefix ("file-direntry");
2402 char *direntry, *term;
2403 Xapian::PostingIterator i, end;
2404 notmuch_status_t status;
2406 if (message_ret == NULL)
2407 return NOTMUCH_STATUS_NULL_POINTER;
2409 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2410 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2412 /* return NULL on any failure */
2413 *message_ret = NULL;
2415 local = talloc_new (notmuch);
2418 status = _notmuch_database_filename_to_direntry (
2419 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2420 if (status || !direntry)
2423 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2425 find_doc_ids_for_term (notmuch, term, &i, &end);
2428 notmuch_private_status_t private_status;
2430 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2432 if (*message_ret == NULL)
2433 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2435 } catch (const Xapian::Error &error) {
2436 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2437 error.get_msg().c_str());
2438 notmuch->exception_reported = TRUE;
2439 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2443 talloc_free (local);
2445 if (status && *message_ret) {
2446 notmuch_message_destroy (*message_ret);
2447 *message_ret = NULL;
2452 notmuch_string_list_t *
2453 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2454 Xapian::TermIterator &end,
2457 int prefix_len = strlen (prefix);
2458 notmuch_string_list_t *list;
2460 list = _notmuch_string_list_create (ctx);
2461 if (unlikely (list == NULL))
2464 for (i.skip_to (prefix); i != end; i++) {
2465 /* Terminate loop at first term without desired prefix. */
2466 if (strncmp ((*i).c_str (), prefix, prefix_len))
2469 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2476 notmuch_database_get_all_tags (notmuch_database_t *db)
2478 Xapian::TermIterator i, end;
2479 notmuch_string_list_t *tags;
2482 i = db->xapian_db->allterms_begin();
2483 end = db->xapian_db->allterms_end();
2484 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2485 _find_prefix ("tag"));
2486 _notmuch_string_list_sort (tags);
2487 return _notmuch_tags_create (db, tags);
2488 } catch (const Xapian::Error &error) {
2489 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2490 error.get_msg().c_str());
2491 db->exception_reported = TRUE;