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 two different types of documents (mail and
54 * 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.
114 * A directory document is used by a client of the notmuch library to
115 * maintain data necessary to allow for efficient polling of mail
118 * All directory documents contain one term:
120 * directory: The directory path (relative to the database path)
121 * Or the SHA1 sum of the directory path (if the
122 * path itself is too long to fit in a Xapian
125 * And all directory documents for directories other than top-level
126 * directories also contain the following term:
128 * directory-direntry: A colon-separated pair of values
129 * (INTEGER:STRING), where INTEGER is the
130 * document ID of the parent directory
131 * document, and STRING is the name of this
132 * directory within that parent.
134 * All directory documents have a single value:
136 * TIMESTAMP: The mtime of the directory (at last scan)
138 * The data portion of a directory document contains the path of the
139 * directory (relative to the database path).
143 * Xapian allows us to store arbitrary name-value pairs as
144 * "metadata". We currently use the following metadata names with the
147 * version The database schema version, (which is distinct
148 * from both the notmuch package version (see
149 * notmuch --version) and the libnotmuch library
150 * version. The version is stored as an base-10
151 * ASCII integer. The initial database version
152 * was 1, (though a schema existed before that
153 * were no "version" database value existed at
154 * all). Successive versions are allocated as
155 * changes are made to the database (such as by
156 * indexing new fields).
158 * features The set of features supported by this
159 * database. This consists of a set of
160 * '\n'-separated lines, where each is a feature
161 * name, a '\t', and compatibility flags. If the
162 * compatibility flags contain 'w', then the
163 * opener must support this feature to safely
164 * write this database. If the compatibility
165 * flags contain 'r', then the opener must
166 * support this feature to read this database.
167 * Introduced in database version 3.
169 * last_thread_id The last thread ID generated. This is stored
170 * as a 16-byte hexadecimal ASCII representation
171 * of a 64-bit unsigned integer. The first ID
172 * generated is 1 and the value will be
173 * incremented for each thread ID.
175 * thread_id_* A pre-allocated thread ID for a particular
176 * message. This is actually an arbitrarily large
177 * family of metadata name. Any particular name is
178 * formed by concatenating "thread_id_" with a message
179 * ID (or the SHA1 sum of a message ID if it is very
180 * long---see description of 'id' in the mail
181 * document). The value stored is a thread ID.
183 * These thread ID metadata values are stored
184 * whenever a message references a parent message
185 * that does not yet exist in the database. A
186 * thread ID will be allocated and stored, and if
187 * the message is later added, the stored thread
188 * ID will be used (and the metadata value will
191 * Even before a message is added, it's
192 * pre-allocated thread ID is useful so that all
193 * descendant messages that reference this common
194 * parent can be recognized as belonging to the
198 /* With these prefix values we follow the conventions published here:
200 * http://xapian.org/docs/omega/termprefixes.html
202 * as much as makes sense. Note that I took some liberty in matching
203 * the reserved prefix values to notmuch concepts, (for example, 'G'
204 * is documented as "newsGroup (or similar entity - e.g. a web forum
205 * name)", for which I think the thread is the closest analogue in
206 * notmuch. This in spite of the fact that we will eventually be
207 * storing mailing-list messages where 'G' for "mailing list name"
208 * might be even a closer analogue. I'm treating the single-character
209 * prefixes preferentially for core notmuch concepts (which will be
210 * nearly universal to all mail messages).
213 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
215 { "reference", "XREFERENCE" },
216 { "replyto", "XREPLYTO" },
217 { "directory", "XDIRECTORY" },
218 { "file-direntry", "XFDIRENTRY" },
219 { "directory-direntry", "XDDIRENTRY" },
222 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
229 * Without the ":", since this is a multi-letter prefix, Xapian
230 * will add a colon itself if the first letter of the path is
231 * upper-case ASCII. Including the ":" forces there to always be a
232 * colon, which keeps our own logic simpler.
234 { "folder", "XFOLDER:" },
237 static prefix_t PROBABILISTIC_PREFIX[]= {
240 { "attachment", "XATTACHMENT" },
241 { "subject", "XSUBJECT"},
245 _find_prefix (const char *name)
249 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
250 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
251 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
254 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
255 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
256 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
259 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
260 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
261 return PROBABILISTIC_PREFIX[i].prefix;
264 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
269 static const struct {
270 /* NOTMUCH_FEATURE_* value. */
271 _notmuch_features value;
272 /* Feature name as it appears in the database. This name should
273 * be appropriate for displaying to the user if an older version
274 * of notmuch doesn't support this feature. */
276 /* Compatibility flags when this feature is declared. */
278 } feature_names[] = {
279 { NOTMUCH_FEATURE_FILE_TERMS,
280 "multiple paths per message", "rw" },
281 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
282 "relative directory paths", "rw" },
283 /* Header values are not required for reading a database because a
284 * reader can just refer to the message file. */
285 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
286 "from/subject/message-ID in database", "w" },
287 { NOTMUCH_FEATURE_BOOL_FOLDER,
288 "exact folder:/path: search", "rw" },
292 notmuch_status_to_string (notmuch_status_t status)
295 case NOTMUCH_STATUS_SUCCESS:
296 return "No error occurred";
297 case NOTMUCH_STATUS_OUT_OF_MEMORY:
298 return "Out of memory";
299 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
300 return "Attempt to write to a read-only database";
301 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
302 return "A Xapian exception occurred";
303 case NOTMUCH_STATUS_FILE_ERROR:
304 return "Something went wrong trying to read or write a file";
305 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
306 return "File is not an email";
307 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
308 return "Message ID is identical to a message in database";
309 case NOTMUCH_STATUS_NULL_POINTER:
310 return "Erroneous NULL pointer";
311 case NOTMUCH_STATUS_TAG_TOO_LONG:
312 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
313 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
314 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
315 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
316 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
317 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
318 return "Unsupported operation";
320 case NOTMUCH_STATUS_LAST_STATUS:
321 return "Unknown error status value";
326 find_doc_ids_for_term (notmuch_database_t *notmuch,
328 Xapian::PostingIterator *begin,
329 Xapian::PostingIterator *end)
331 *begin = notmuch->xapian_db->postlist_begin (term);
333 *end = notmuch->xapian_db->postlist_end (term);
337 find_doc_ids (notmuch_database_t *notmuch,
338 const char *prefix_name,
340 Xapian::PostingIterator *begin,
341 Xapian::PostingIterator *end)
345 term = talloc_asprintf (notmuch, "%s%s",
346 _find_prefix (prefix_name), value);
348 find_doc_ids_for_term (notmuch, term, begin, end);
353 notmuch_private_status_t
354 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
355 const char *prefix_name,
357 unsigned int *doc_id)
359 Xapian::PostingIterator i, end;
361 find_doc_ids (notmuch, prefix_name, value, &i, &end);
365 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
370 #if DEBUG_DATABASE_SANITY
374 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
378 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
381 static Xapian::Document
382 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
384 return notmuch->xapian_db->get_document (doc_id);
387 /* Generate a compressed version of 'message_id' of the form:
389 * notmuch-sha1-<sha1_sum_of_message_id>
392 _message_id_compressed (void *ctx, const char *message_id)
394 char *sha1, *compressed;
396 sha1 = _notmuch_sha1_of_string (message_id);
398 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
405 notmuch_database_find_message (notmuch_database_t *notmuch,
406 const char *message_id,
407 notmuch_message_t **message_ret)
409 notmuch_private_status_t status;
412 if (message_ret == NULL)
413 return NOTMUCH_STATUS_NULL_POINTER;
415 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
416 message_id = _message_id_compressed (notmuch, message_id);
419 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
420 message_id, &doc_id);
422 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
425 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
427 if (*message_ret == NULL)
428 return NOTMUCH_STATUS_OUT_OF_MEMORY;
431 return NOTMUCH_STATUS_SUCCESS;
432 } catch (const Xapian::Error &error) {
433 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
434 error.get_msg().c_str());
435 notmuch->exception_reported = TRUE;
437 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
441 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
442 * a (potentially nested) parenthesized sequence with '\' used to
443 * escape any character (including parentheses).
445 * If the sequence to be skipped continues to the end of the string,
446 * then 'str' will be left pointing at the final terminating '\0'
450 skip_space_and_comments (const char **str)
455 while (*s && (isspace (*s) || *s == '(')) {
456 while (*s && isspace (*s))
461 while (*s && nesting) {
464 } else if (*s == ')') {
466 } else if (*s == '\\') {
478 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
479 * comments, and the '<' and '>' delimiters.
481 * If not NULL, then *next will be made to point to the first character
482 * not parsed, (possibly pointing to the final '\0' terminator.
484 * Returns a newly talloc'ed string belonging to 'ctx'.
486 * Returns NULL if there is any error parsing the message-id. */
488 _parse_message_id (void *ctx, const char *message_id, const char **next)
493 if (message_id == NULL || *message_id == '\0')
498 skip_space_and_comments (&s);
500 /* Skip any unstructured text as well. */
501 while (*s && *s != '<')
512 skip_space_and_comments (&s);
515 while (*end && *end != '>')
524 if (end > s && *end == '>')
529 result = talloc_strndup (ctx, s, end - s + 1);
531 /* Finally, collapse any whitespace that is within the message-id
537 for (r = result, len = strlen (r); *r; r++, len--)
538 if (*r == ' ' || *r == '\t')
539 memmove (r, r+1, len);
545 /* Parse a References header value, putting a (talloc'ed under 'ctx')
546 * copy of each referenced message-id into 'hash'.
548 * We explicitly avoid including any reference identical to
549 * 'message_id' in the result (to avoid mass confusion when a single
550 * message references itself cyclically---and yes, mail messages are
551 * not infrequent in the wild that do this---don't ask me why).
553 * Return the last reference parsed, if it is not equal to message_id.
556 parse_references (void *ctx,
557 const char *message_id,
561 char *ref, *last_ref = NULL;
563 if (refs == NULL || *refs == '\0')
567 ref = _parse_message_id (ctx, refs, &refs);
569 if (ref && strcmp (ref, message_id)) {
570 g_hash_table_insert (hash, ref, NULL);
575 /* The return value of this function is used to add a parent
576 * reference to the database. We should avoid making a message
577 * its own parent, thus the above check.
583 notmuch_database_create (const char *path, notmuch_database_t **database)
585 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
586 notmuch_database_t *notmuch = NULL;
587 char *notmuch_path = NULL;
592 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
593 status = NOTMUCH_STATUS_NULL_POINTER;
597 err = stat (path, &st);
599 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
600 path, strerror (errno));
601 status = NOTMUCH_STATUS_FILE_ERROR;
605 if (! S_ISDIR (st.st_mode)) {
606 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
608 status = NOTMUCH_STATUS_FILE_ERROR;
612 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
614 err = mkdir (notmuch_path, 0755);
617 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
618 notmuch_path, strerror (errno));
619 status = NOTMUCH_STATUS_FILE_ERROR;
623 status = notmuch_database_open (path,
624 NOTMUCH_DATABASE_MODE_READ_WRITE,
629 /* Upgrade doesn't add this feature to existing databases, but new
630 * databases have it. */
631 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
633 status = notmuch_database_upgrade (notmuch, NULL, NULL);
635 notmuch_database_close(notmuch);
641 talloc_free (notmuch_path);
646 talloc_free (notmuch);
651 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
653 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
654 fprintf (stderr, "Cannot write to a read-only database.\n");
655 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
658 return NOTMUCH_STATUS_SUCCESS;
661 /* Parse a database features string from the given database version.
662 * Returns the feature bit set.
664 * For version < 3, this ignores the features string and returns a
665 * hard-coded set of features.
667 * If there are unrecognized features that are required to open the
668 * database in mode (which should be 'r' or 'w'), return a
669 * comma-separated list of unrecognized but required features in
670 * *incompat_out suitable for presenting to the user. *incompat_out
671 * will be allocated from ctx.
673 static _notmuch_features
674 _parse_features (const void *ctx, const char *features, unsigned int version,
675 char mode, char **incompat_out)
677 _notmuch_features res = static_cast<_notmuch_features>(0);
678 unsigned int namelen, i;
682 /* Prior to database version 3, features were implied by the
685 return NOTMUCH_FEATURES_V0;
686 else if (version == 1)
687 return NOTMUCH_FEATURES_V1;
688 else if (version == 2)
689 return NOTMUCH_FEATURES_V2;
691 /* Parse the features string */
692 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
693 flags = strchr (features, '\t');
694 if (! flags || flags > features + llen)
696 namelen = flags - features;
698 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
699 if (strlen (feature_names[i].name) == namelen &&
700 strncmp (feature_names[i].name, features, namelen) == 0) {
701 res |= feature_names[i].value;
706 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
707 /* Unrecognized feature */
708 const char *have = strchr (flags, mode);
709 if (have && have < features + llen) {
710 /* This feature is required to access this database in
711 * 'mode', but we don't understand it. */
713 *incompat_out = talloc_strdup (ctx, "");
714 *incompat_out = talloc_asprintf_append_buffer (
715 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
725 _print_features (const void *ctx, unsigned int features)
728 char *res = talloc_strdup (ctx, "");
730 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
731 if (features & feature_names[i].value)
732 res = talloc_asprintf_append_buffer (
733 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
739 notmuch_database_open (const char *path,
740 notmuch_database_mode_t mode,
741 notmuch_database_t **database)
743 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
744 void *local = talloc_new (NULL);
745 notmuch_database_t *notmuch = NULL;
746 char *notmuch_path, *xapian_path, *incompat_features;
749 unsigned int i, version;
750 static int initialized = 0;
753 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
754 status = NOTMUCH_STATUS_NULL_POINTER;
758 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
759 fprintf (stderr, "Out of memory\n");
760 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
764 err = stat (notmuch_path, &st);
766 fprintf (stderr, "Error opening database at %s: %s\n",
767 notmuch_path, strerror (errno));
768 status = NOTMUCH_STATUS_FILE_ERROR;
772 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
773 fprintf (stderr, "Out of memory\n");
774 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
778 /* Initialize the GLib type system and threads */
779 #if !GLIB_CHECK_VERSION(2, 35, 1)
783 /* Initialize gmime */
785 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
789 notmuch = talloc_zero (NULL, notmuch_database_t);
790 notmuch->exception_reported = FALSE;
791 notmuch->path = talloc_strdup (notmuch, path);
793 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
794 notmuch->path[strlen (notmuch->path) - 1] = '\0';
796 notmuch->mode = mode;
797 notmuch->atomic_nesting = 0;
799 string last_thread_id;
801 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
802 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
803 Xapian::DB_CREATE_OR_OPEN);
805 notmuch->xapian_db = new Xapian::Database (xapian_path);
808 /* Check version. As of database version 3, we represent
809 * changes in terms of features, so assume a version bump
810 * means a dramatically incompatible change. */
811 version = notmuch_database_get_version (notmuch);
812 if (version > NOTMUCH_DATABASE_VERSION) {
814 "Error: Notmuch database at %s\n"
815 " has a newer database format version (%u) than supported by this\n"
816 " version of notmuch (%u).\n",
817 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
818 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
819 notmuch_database_destroy (notmuch);
821 status = NOTMUCH_STATUS_FILE_ERROR;
825 /* Check features. */
826 incompat_features = NULL;
827 notmuch->features = _parse_features (
828 local, notmuch->xapian_db->get_metadata ("features").c_str (),
829 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
831 if (incompat_features) {
833 "Error: Notmuch database at %s\n"
834 " requires features (%s)\n"
835 " not supported by this version of notmuch.\n",
836 notmuch_path, incompat_features);
837 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
838 notmuch_database_destroy (notmuch);
840 status = NOTMUCH_STATUS_FILE_ERROR;
844 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
845 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
846 if (last_thread_id.empty ()) {
847 notmuch->last_thread_id = 0;
852 str = last_thread_id.c_str ();
853 notmuch->last_thread_id = strtoull (str, &end, 16);
855 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
858 notmuch->query_parser = new Xapian::QueryParser;
859 notmuch->term_gen = new Xapian::TermGenerator;
860 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
861 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
862 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
864 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
865 notmuch->query_parser->set_database (*notmuch->xapian_db);
866 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
867 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
868 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
869 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
871 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
872 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
873 notmuch->query_parser->add_boolean_prefix (prefix->name,
877 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
878 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
879 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
881 } catch (const Xapian::Error &error) {
882 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
883 error.get_msg().c_str());
884 notmuch_database_destroy (notmuch);
886 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
895 talloc_free (notmuch);
900 notmuch_database_close (notmuch_database_t *notmuch)
902 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
905 if (notmuch->xapian_db != NULL &&
906 notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
907 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
908 } catch (const Xapian::Error &error) {
909 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
910 if (! notmuch->exception_reported) {
911 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
912 error.get_msg().c_str());
916 /* Many Xapian objects (and thus notmuch objects) hold references to
917 * the database, so merely deleting the database may not suffice to
918 * close it. Thus, we explicitly close it here. */
919 if (notmuch->xapian_db != NULL) {
921 notmuch->xapian_db->close();
922 } catch (const Xapian::Error &error) {
923 /* don't clobber previous error status */
924 if (status == NOTMUCH_STATUS_SUCCESS)
925 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
929 delete notmuch->term_gen;
930 notmuch->term_gen = NULL;
931 delete notmuch->query_parser;
932 notmuch->query_parser = NULL;
933 delete notmuch->xapian_db;
934 notmuch->xapian_db = NULL;
935 delete notmuch->value_range_processor;
936 notmuch->value_range_processor = NULL;
937 delete notmuch->date_range_processor;
938 notmuch->date_range_processor = NULL;
943 #if HAVE_XAPIAN_COMPACT
945 unlink_cb (const char *path,
946 unused (const struct stat *sb),
948 unused (struct FTW *ftw))
950 return remove (path);
954 rmtree (const char *path)
956 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
959 class NotmuchCompactor : public Xapian::Compactor
961 notmuch_compact_status_cb_t status_cb;
962 void *status_closure;
965 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
966 status_cb (cb), status_closure (closure) { }
969 set_status (const std::string &table, const std::string &status)
973 if (status_cb == NULL)
976 if (status.length () == 0)
977 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
979 msg = talloc_asprintf (NULL, " %s", status.c_str());
985 status_cb (msg, status_closure);
990 /* Compacts the given database, optionally saving the original database
991 * in backup_path. Additionally, a callback function can be provided to
992 * give the user feedback on the progress of the (likely long-lived)
993 * compaction process.
995 * The backup path must point to a directory on the same volume as the
996 * original database. Passing a NULL backup_path will result in the
997 * uncompacted database being deleted after compaction has finished.
998 * Note that the database write lock will be held during the
999 * compaction process to protect data integrity.
1002 notmuch_database_compact (const char *path,
1003 const char *backup_path,
1004 notmuch_compact_status_cb_t status_cb,
1008 char *notmuch_path, *xapian_path, *compact_xapian_path;
1009 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1010 notmuch_database_t *notmuch = NULL;
1011 struct stat statbuf;
1012 notmuch_bool_t keep_backup;
1014 local = talloc_new (NULL);
1016 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1018 ret = notmuch_database_open (path, NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much);
1023 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1024 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1028 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1029 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1033 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1034 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1038 if (backup_path == NULL) {
1039 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1040 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1043 keep_backup = FALSE;
1049 if (stat (backup_path, &statbuf) != -1) {
1050 fprintf (stderr, "Path already exists: %s\n", backup_path);
1051 ret = NOTMUCH_STATUS_FILE_ERROR;
1054 if (errno != ENOENT) {
1055 fprintf (stderr, "Unknown error while stat()ing path: %s\n",
1057 ret = NOTMUCH_STATUS_FILE_ERROR;
1061 /* Unconditionally attempt to remove old work-in-progress database (if
1062 * any). This is "protected" by database lock. If this fails due to write
1063 * errors (etc), the following code will fail and provide error message.
1065 (void) rmtree (compact_xapian_path);
1068 NotmuchCompactor compactor (status_cb, closure);
1070 compactor.set_renumber (false);
1071 compactor.add_source (xapian_path);
1072 compactor.set_destdir (compact_xapian_path);
1073 compactor.compact ();
1074 } catch (const Xapian::Error &error) {
1075 fprintf (stderr, "Error while compacting: %s\n", error.get_msg().c_str());
1076 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1080 if (rename (xapian_path, backup_path)) {
1081 fprintf (stderr, "Error moving %s to %s: %s\n",
1082 xapian_path, backup_path, strerror (errno));
1083 ret = NOTMUCH_STATUS_FILE_ERROR;
1087 if (rename (compact_xapian_path, xapian_path)) {
1088 fprintf (stderr, "Error moving %s to %s: %s\n",
1089 compact_xapian_path, xapian_path, strerror (errno));
1090 ret = NOTMUCH_STATUS_FILE_ERROR;
1094 if (! keep_backup) {
1095 if (rmtree (backup_path)) {
1096 fprintf (stderr, "Error removing old database %s: %s\n",
1097 backup_path, strerror (errno));
1098 ret = NOTMUCH_STATUS_FILE_ERROR;
1105 notmuch_status_t ret2;
1107 ret2 = notmuch_database_destroy (notmuch);
1109 /* don't clobber previous error status */
1110 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1114 talloc_free (local);
1120 notmuch_database_compact (unused (const char *path),
1121 unused (const char *backup_path),
1122 unused (notmuch_compact_status_cb_t status_cb),
1123 unused (void *closure))
1125 fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
1126 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1131 notmuch_database_destroy (notmuch_database_t *notmuch)
1133 notmuch_status_t status;
1135 status = notmuch_database_close (notmuch);
1136 talloc_free (notmuch);
1142 notmuch_database_get_path (notmuch_database_t *notmuch)
1144 return notmuch->path;
1148 notmuch_database_get_version (notmuch_database_t *notmuch)
1150 unsigned int version;
1151 string version_string;
1155 version_string = notmuch->xapian_db->get_metadata ("version");
1156 if (version_string.empty ())
1159 str = version_string.c_str ();
1160 if (str == NULL || *str == '\0')
1163 version = strtoul (str, &end, 10);
1165 INTERNAL_ERROR ("Malformed database version: %s", str);
1171 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1173 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1174 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1175 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1178 static volatile sig_atomic_t do_progress_notify = 0;
1181 handle_sigalrm (unused (int signal))
1183 do_progress_notify = 1;
1186 /* Upgrade the current database.
1188 * After opening a database in read-write mode, the client should
1189 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1190 * if so, upgrade with this function before making any modifications.
1192 * The optional progress_notify callback can be used by the caller to
1193 * provide progress indication to the user. If non-NULL it will be
1194 * called periodically with 'count' as the number of messages upgraded
1195 * so far and 'total' the overall number of messages that will be
1199 notmuch_database_upgrade (notmuch_database_t *notmuch,
1200 void (*progress_notify) (void *closure,
1204 void *local = talloc_new (NULL);
1205 Xapian::TermIterator t, t_end;
1206 Xapian::WritableDatabase *db;
1207 struct sigaction action;
1208 struct itimerval timerval;
1209 notmuch_bool_t timer_is_active = FALSE;
1210 enum _notmuch_features target_features, new_features;
1211 notmuch_status_t status;
1212 unsigned int count = 0, total = 0;
1214 status = _notmuch_database_ensure_writable (notmuch);
1218 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1220 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1221 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1224 return NOTMUCH_STATUS_SUCCESS;
1226 if (progress_notify) {
1227 /* Setup our handler for SIGALRM */
1228 memset (&action, 0, sizeof (struct sigaction));
1229 action.sa_handler = handle_sigalrm;
1230 sigemptyset (&action.sa_mask);
1231 action.sa_flags = SA_RESTART;
1232 sigaction (SIGALRM, &action, NULL);
1234 /* Then start a timer to send SIGALRM once per second. */
1235 timerval.it_interval.tv_sec = 1;
1236 timerval.it_interval.tv_usec = 0;
1237 timerval.it_value.tv_sec = 1;
1238 timerval.it_value.tv_usec = 0;
1239 setitimer (ITIMER_REAL, &timerval, NULL);
1241 timer_is_active = TRUE;
1244 /* Perform the upgrade in a transaction. */
1245 db->begin_transaction (true);
1247 /* Set the target features so we write out changes in the desired
1249 notmuch->features = target_features;
1251 /* Before version 1, each message document had its filename in the
1252 * data field. Copy that into the new format by calling
1253 * notmuch_message_add_filename.
1255 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1256 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1257 notmuch_messages_t *messages;
1258 notmuch_message_t *message;
1261 total = notmuch_query_count_messages (query);
1263 for (messages = notmuch_query_search_messages (query);
1264 notmuch_messages_valid (messages);
1265 notmuch_messages_move_to_next (messages))
1267 if (do_progress_notify) {
1268 progress_notify (closure, (double) count / total);
1269 do_progress_notify = 0;
1272 message = notmuch_messages_get (messages);
1274 filename = _notmuch_message_talloc_copy_data (message);
1275 if (filename && *filename != '\0') {
1276 _notmuch_message_add_filename (message, filename);
1277 _notmuch_message_clear_data (message);
1278 _notmuch_message_sync (message);
1280 talloc_free (filename);
1282 notmuch_message_destroy (message);
1287 notmuch_query_destroy (query);
1290 /* Also, before version 1 we stored directory timestamps in
1291 * XTIMESTAMP documents instead of the current XDIRECTORY
1292 * documents. So copy those as well. */
1293 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1294 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1296 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1300 Xapian::PostingIterator p, p_end;
1301 std::string term = *t;
1303 p_end = notmuch->xapian_db->postlist_end (term);
1305 for (p = notmuch->xapian_db->postlist_begin (term);
1309 Xapian::Document document;
1311 notmuch_directory_t *directory;
1313 if (do_progress_notify) {
1314 progress_notify (closure, (double) count / total);
1315 do_progress_notify = 0;
1318 document = find_document_for_doc_id (notmuch, *p);
1319 mtime = Xapian::sortable_unserialise (
1320 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1322 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1323 NOTMUCH_FIND_CREATE, &status);
1324 notmuch_directory_set_mtime (directory, mtime);
1325 notmuch_directory_destroy (directory);
1327 db->delete_document (*p);
1333 * Prior to version 2, the "folder:" prefix was probabilistic and
1334 * stemmed. Change it to the current boolean prefix. Add "path:"
1335 * prefixes while at it.
1337 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER) {
1338 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1339 notmuch_messages_t *messages;
1340 notmuch_message_t *message;
1343 total = notmuch_query_count_messages (query);
1345 for (messages = notmuch_query_search_messages (query);
1346 notmuch_messages_valid (messages);
1347 notmuch_messages_move_to_next (messages)) {
1348 if (do_progress_notify) {
1349 progress_notify (closure, (double) count / total);
1350 do_progress_notify = 0;
1353 message = notmuch_messages_get (messages);
1355 _notmuch_message_upgrade_folder (message);
1356 _notmuch_message_sync (message);
1358 notmuch_message_destroy (message);
1363 notmuch_query_destroy (query);
1366 db->set_metadata ("features", _print_features (local, notmuch->features));
1367 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1369 db->commit_transaction ();
1371 if (timer_is_active) {
1372 /* Now stop the timer. */
1373 timerval.it_interval.tv_sec = 0;
1374 timerval.it_interval.tv_usec = 0;
1375 timerval.it_value.tv_sec = 0;
1376 timerval.it_value.tv_usec = 0;
1377 setitimer (ITIMER_REAL, &timerval, NULL);
1379 /* And disable the signal handler. */
1380 action.sa_handler = SIG_IGN;
1381 sigaction (SIGALRM, &action, NULL);
1384 talloc_free (local);
1385 return NOTMUCH_STATUS_SUCCESS;
1389 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1391 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1392 notmuch->atomic_nesting > 0)
1396 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1397 } catch (const Xapian::Error &error) {
1398 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1399 error.get_msg().c_str());
1400 notmuch->exception_reported = TRUE;
1401 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1405 notmuch->atomic_nesting++;
1406 return NOTMUCH_STATUS_SUCCESS;
1410 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1412 Xapian::WritableDatabase *db;
1414 if (notmuch->atomic_nesting == 0)
1415 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1417 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1418 notmuch->atomic_nesting > 1)
1421 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1423 db->commit_transaction ();
1425 /* This is a hack for testing. Xapian never flushes on a
1426 * non-flushed commit, even if the flush threshold is 1.
1427 * However, we rely on flushing to test atomicity. */
1428 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1429 if (thresh && atoi (thresh) == 1)
1431 } catch (const Xapian::Error &error) {
1432 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1433 error.get_msg().c_str());
1434 notmuch->exception_reported = TRUE;
1435 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1439 notmuch->atomic_nesting--;
1440 return NOTMUCH_STATUS_SUCCESS;
1443 /* We allow the user to use arbitrarily long paths for directories. But
1444 * we have a term-length limit. So if we exceed that, we'll use the
1445 * SHA-1 of the path for the database term.
1447 * Note: This function may return the original value of 'path'. If it
1448 * does not, then the caller is responsible to free() the returned
1452 _notmuch_database_get_directory_db_path (const char *path)
1454 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1456 if (term_len > NOTMUCH_TERM_MAX)
1457 return _notmuch_sha1_of_string (path);
1462 /* Given a path, split it into two parts: the directory part is all
1463 * components except for the last, and the basename is that last
1464 * component. Getting the return-value for either part is optional
1465 * (the caller can pass NULL).
1467 * The original 'path' can represent either a regular file or a
1468 * directory---the splitting will be carried out in the same way in
1469 * either case. Trailing slashes on 'path' will be ignored, and any
1470 * cases of multiple '/' characters appearing in series will be
1471 * treated as a single '/'.
1473 * Allocation (if any) will have 'ctx' as the talloc owner. But
1474 * pointers will be returned within the original path string whenever
1477 * Note: If 'path' is non-empty and contains no non-trailing slash,
1478 * (that is, consists of a filename with no parent directory), then
1479 * the directory returned will be an empty string. However, if 'path'
1480 * is an empty string, then both directory and basename will be
1484 _notmuch_database_split_path (void *ctx,
1486 const char **directory,
1487 const char **basename)
1491 if (path == NULL || *path == '\0') {
1496 return NOTMUCH_STATUS_SUCCESS;
1499 /* Find the last slash (not counting a trailing slash), if any. */
1501 slash = path + strlen (path) - 1;
1503 /* First, skip trailing slashes. */
1504 while (slash != path) {
1511 /* Then, find a slash. */
1512 while (slash != path) {
1522 /* Finally, skip multiple slashes. */
1523 while (slash != path) {
1530 if (slash == path) {
1532 *directory = talloc_strdup (ctx, "");
1537 *directory = talloc_strndup (ctx, path, slash - path + 1);
1540 return NOTMUCH_STATUS_SUCCESS;
1543 /* Find the document ID of the specified directory.
1545 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1546 * created if one does not exist for 'path'. Otherwise, if the
1547 * directory document does not exist, this sets *directory_id to
1548 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1551 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1553 notmuch_find_flags_t flags,
1554 unsigned int *directory_id)
1556 notmuch_directory_t *directory;
1557 notmuch_status_t status;
1561 return NOTMUCH_STATUS_SUCCESS;
1564 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1565 if (status || !directory) {
1570 *directory_id = _notmuch_directory_get_document_id (directory);
1572 notmuch_directory_destroy (directory);
1574 return NOTMUCH_STATUS_SUCCESS;
1578 _notmuch_database_get_directory_path (void *ctx,
1579 notmuch_database_t *notmuch,
1580 unsigned int doc_id)
1582 Xapian::Document document;
1584 document = find_document_for_doc_id (notmuch, doc_id);
1586 return talloc_strdup (ctx, document.get_data ().c_str ());
1589 /* Given a legal 'filename' for the database, (either relative to
1590 * database path or absolute with initial components identical to
1591 * database path), return a new string (with 'ctx' as the talloc
1592 * owner) suitable for use as a direntry term value.
1594 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1595 * will be created in the database as needed. Otherwise, if the
1596 * necessary directory documents do not exist, this sets
1597 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1600 _notmuch_database_filename_to_direntry (void *ctx,
1601 notmuch_database_t *notmuch,
1602 const char *filename,
1603 notmuch_find_flags_t flags,
1606 const char *relative, *directory, *basename;
1607 Xapian::docid directory_id;
1608 notmuch_status_t status;
1610 relative = _notmuch_database_relative_path (notmuch, filename);
1612 status = _notmuch_database_split_path (ctx, relative,
1613 &directory, &basename);
1617 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1619 if (status || directory_id == (unsigned int)-1) {
1624 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1626 return NOTMUCH_STATUS_SUCCESS;
1629 /* Given a legal 'path' for the database, return the relative path.
1631 * The return value will be a pointer to the original path contents,
1632 * and will be either the original string (if 'path' was relative) or
1633 * a portion of the string (if path was absolute and begins with the
1637 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1640 const char *db_path, *relative;
1641 unsigned int db_path_len;
1643 db_path = notmuch_database_get_path (notmuch);
1644 db_path_len = strlen (db_path);
1648 if (*relative == '/') {
1649 while (*relative == '/' && *(relative+1) == '/')
1652 if (strncmp (relative, db_path, db_path_len) == 0)
1654 relative += db_path_len;
1655 while (*relative == '/')
1664 notmuch_database_get_directory (notmuch_database_t *notmuch,
1666 notmuch_directory_t **directory)
1668 notmuch_status_t status;
1670 if (directory == NULL)
1671 return NOTMUCH_STATUS_NULL_POINTER;
1675 *directory = _notmuch_directory_create (notmuch, path,
1676 NOTMUCH_FIND_LOOKUP, &status);
1677 } catch (const Xapian::Error &error) {
1678 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1679 error.get_msg().c_str());
1680 notmuch->exception_reported = TRUE;
1681 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1686 /* Allocate a document ID that satisfies the following criteria:
1688 * 1. The ID does not exist for any document in the Xapian database
1690 * 2. The ID was not previously returned from this function
1692 * 3. The ID is the smallest integer satisfying (1) and (2)
1694 * This function will trigger an internal error if these constraints
1695 * cannot all be satisfied, (that is, the pool of available document
1696 * IDs has been exhausted).
1699 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1701 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1703 notmuch->last_doc_id++;
1705 if (notmuch->last_doc_id == 0)
1706 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1708 return notmuch->last_doc_id;
1712 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1714 /* 16 bytes (+ terminator) for hexadecimal representation of
1715 * a 64-bit integer. */
1716 static char thread_id[17];
1717 Xapian::WritableDatabase *db;
1719 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1721 notmuch->last_thread_id++;
1723 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1725 db->set_metadata ("last_thread_id", thread_id);
1731 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1733 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1734 message_id = _message_id_compressed (ctx, message_id);
1736 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1740 /* Find the thread ID to which the message with 'message_id' belongs.
1742 * Note: 'thread_id_ret' must not be NULL!
1743 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1746 * Note: If there is no message in the database with the given
1747 * 'message_id' then a new thread_id will be allocated for this
1748 * message and stored in the database metadata, (where this same
1749 * thread ID can be looked up if the message is added to the database
1752 static notmuch_status_t
1753 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1755 const char *message_id,
1756 const char **thread_id_ret)
1758 notmuch_status_t status;
1759 notmuch_message_t *message;
1760 string thread_id_string;
1762 Xapian::WritableDatabase *db;
1764 status = notmuch_database_find_message (notmuch, message_id, &message);
1770 *thread_id_ret = talloc_steal (ctx,
1771 notmuch_message_get_thread_id (message));
1773 notmuch_message_destroy (message);
1775 return NOTMUCH_STATUS_SUCCESS;
1778 /* Message has not been seen yet.
1780 * We may have seen a reference to it already, in which case, we
1781 * can return the thread ID stored in the metadata. Otherwise, we
1782 * generate a new thread ID and store it there.
1784 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1785 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1786 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1788 if (thread_id_string.empty()) {
1789 *thread_id_ret = talloc_strdup (ctx,
1790 _notmuch_database_generate_thread_id (notmuch));
1791 db->set_metadata (metadata_key, *thread_id_ret);
1793 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1796 talloc_free (metadata_key);
1798 return NOTMUCH_STATUS_SUCCESS;
1801 static notmuch_status_t
1802 _merge_threads (notmuch_database_t *notmuch,
1803 const char *winner_thread_id,
1804 const char *loser_thread_id)
1806 Xapian::PostingIterator loser, loser_end;
1807 notmuch_message_t *message = NULL;
1808 notmuch_private_status_t private_status;
1809 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1811 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1813 for ( ; loser != loser_end; loser++) {
1814 message = _notmuch_message_create (notmuch, notmuch,
1815 *loser, &private_status);
1816 if (message == NULL) {
1817 ret = COERCE_STATUS (private_status,
1818 "Cannot find document for doc_id from query");
1822 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1823 _notmuch_message_add_term (message, "thread", winner_thread_id);
1824 _notmuch_message_sync (message);
1826 notmuch_message_destroy (message);
1832 notmuch_message_destroy (message);
1838 _my_talloc_free_for_g_hash (void *ptr)
1843 static notmuch_status_t
1844 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1845 notmuch_message_t *message,
1846 notmuch_message_file_t *message_file,
1847 const char **thread_id)
1849 GHashTable *parents = NULL;
1850 const char *refs, *in_reply_to, *in_reply_to_message_id;
1851 const char *last_ref_message_id, *this_message_id;
1852 GList *l, *keys = NULL;
1853 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1855 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1856 _my_talloc_free_for_g_hash, NULL);
1857 this_message_id = notmuch_message_get_message_id (message);
1859 refs = _notmuch_message_file_get_header (message_file, "references");
1860 last_ref_message_id = parse_references (message,
1864 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
1865 in_reply_to_message_id = parse_references (message,
1867 parents, in_reply_to);
1869 /* For the parent of this message, use the last message ID of the
1870 * References header, if available. If not, fall back to the
1871 * first message ID in the In-Reply-To header. */
1872 if (last_ref_message_id) {
1873 _notmuch_message_add_term (message, "replyto",
1874 last_ref_message_id);
1875 } else if (in_reply_to_message_id) {
1876 _notmuch_message_add_term (message, "replyto",
1877 in_reply_to_message_id);
1880 keys = g_hash_table_get_keys (parents);
1881 for (l = keys; l; l = l->next) {
1882 char *parent_message_id;
1883 const char *parent_thread_id = NULL;
1885 parent_message_id = (char *) l->data;
1887 _notmuch_message_add_term (message, "reference",
1890 ret = _resolve_message_id_to_thread_id (notmuch,
1897 if (*thread_id == NULL) {
1898 *thread_id = talloc_strdup (message, parent_thread_id);
1899 _notmuch_message_add_term (message, "thread", *thread_id);
1900 } else if (strcmp (*thread_id, parent_thread_id)) {
1901 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1911 g_hash_table_unref (parents);
1916 static notmuch_status_t
1917 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1918 notmuch_message_t *message,
1919 const char **thread_id)
1921 const char *message_id = notmuch_message_get_message_id (message);
1922 Xapian::PostingIterator child, children_end;
1923 notmuch_message_t *child_message = NULL;
1924 const char *child_thread_id;
1925 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1926 notmuch_private_status_t private_status;
1928 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1930 for ( ; child != children_end; child++) {
1932 child_message = _notmuch_message_create (message, notmuch,
1933 *child, &private_status);
1934 if (child_message == NULL) {
1935 ret = COERCE_STATUS (private_status,
1936 "Cannot find document for doc_id from query");
1940 child_thread_id = notmuch_message_get_thread_id (child_message);
1941 if (*thread_id == NULL) {
1942 *thread_id = talloc_strdup (message, child_thread_id);
1943 _notmuch_message_add_term (message, "thread", *thread_id);
1944 } else if (strcmp (*thread_id, child_thread_id)) {
1945 _notmuch_message_remove_term (child_message, "reference",
1947 _notmuch_message_sync (child_message);
1948 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1953 notmuch_message_destroy (child_message);
1954 child_message = NULL;
1959 notmuch_message_destroy (child_message);
1964 /* Given a (mostly empty) 'message' and its corresponding
1965 * 'message_file' link it to existing threads in the database.
1967 * The first check is in the metadata of the database to see if we
1968 * have pre-allocated a thread_id in advance for this message, (which
1969 * would have happened if a message was previously added that
1970 * referenced this one).
1972 * Second, we look at 'message_file' and its link-relevant headers
1973 * (References and In-Reply-To) for message IDs.
1975 * Finally, we look in the database for existing message that
1976 * reference 'message'.
1978 * In all cases, we assign to the current message the first thread_id
1979 * found (through either parent or child). We will also merge any
1980 * existing, distinct threads where this message belongs to both,
1981 * (which is not uncommon when messages are processed out of order).
1983 * Finally, if no thread ID has been found through parent or child, we
1984 * call _notmuch_message_generate_thread_id to generate a new thread
1985 * ID. This should only happen for new, top-level messages, (no
1986 * References or In-Reply-To header in this message, and no previously
1987 * added message refers to this message).
1989 static notmuch_status_t
1990 _notmuch_database_link_message (notmuch_database_t *notmuch,
1991 notmuch_message_t *message,
1992 notmuch_message_file_t *message_file)
1994 notmuch_status_t status;
1995 const char *message_id, *thread_id = NULL;
1999 message_id = notmuch_message_get_message_id (message);
2000 metadata_key = _get_metadata_thread_id_key (message, message_id);
2002 /* Check if we have already seen related messages to this one.
2003 * If we have then use the thread_id that we stored at that time.
2005 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2006 if (! stored_id.empty()) {
2007 Xapian::WritableDatabase *db;
2009 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2011 /* Clear the metadata for this message ID. We don't need it
2013 db->set_metadata (metadata_key, "");
2014 thread_id = stored_id.c_str();
2016 _notmuch_message_add_term (message, "thread", thread_id);
2018 talloc_free (metadata_key);
2020 status = _notmuch_database_link_message_to_parents (notmuch, message,
2026 status = _notmuch_database_link_message_to_children (notmuch, message,
2031 /* If not part of any existing thread, generate a new thread ID. */
2032 if (thread_id == NULL) {
2033 thread_id = _notmuch_database_generate_thread_id (notmuch);
2035 _notmuch_message_add_term (message, "thread", thread_id);
2038 return NOTMUCH_STATUS_SUCCESS;
2042 notmuch_database_add_message (notmuch_database_t *notmuch,
2043 const char *filename,
2044 notmuch_message_t **message_ret)
2046 notmuch_message_file_t *message_file;
2047 notmuch_message_t *message = NULL;
2048 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2049 notmuch_private_status_t private_status;
2051 const char *date, *header;
2052 const char *from, *to, *subject;
2053 char *message_id = NULL;
2056 *message_ret = NULL;
2058 ret = _notmuch_database_ensure_writable (notmuch);
2062 message_file = _notmuch_message_file_open (filename);
2063 if (message_file == NULL)
2064 return NOTMUCH_STATUS_FILE_ERROR;
2066 /* Adding a message may change many documents. Do this all
2068 ret = notmuch_database_begin_atomic (notmuch);
2072 /* Parse message up front to get better error status. */
2073 ret = _notmuch_message_file_parse (message_file);
2078 /* Before we do any real work, (especially before doing a
2079 * potential SHA-1 computation on the entire file's contents),
2080 * let's make sure that what we're looking at looks like an
2081 * actual email message.
2083 from = _notmuch_message_file_get_header (message_file, "from");
2084 subject = _notmuch_message_file_get_header (message_file, "subject");
2085 to = _notmuch_message_file_get_header (message_file, "to");
2087 if ((from == NULL || *from == '\0') &&
2088 (subject == NULL || *subject == '\0') &&
2089 (to == NULL || *to == '\0'))
2091 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2095 /* Now that we're sure it's mail, the first order of business
2096 * is to find a message ID (or else create one ourselves). */
2098 header = _notmuch_message_file_get_header (message_file, "message-id");
2099 if (header && *header != '\0') {
2100 message_id = _parse_message_id (message_file, header, NULL);
2102 /* So the header value isn't RFC-compliant, but it's
2103 * better than no message-id at all. */
2104 if (message_id == NULL)
2105 message_id = talloc_strdup (message_file, header);
2107 /* If a message ID is too long, substitute its sha1 instead. */
2108 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
2109 char *compressed = _message_id_compressed (message_file,
2111 talloc_free (message_id);
2112 message_id = compressed;
2116 if (message_id == NULL ) {
2117 /* No message-id at all, let's generate one by taking a
2118 * hash over the file's contents. */
2119 char *sha1 = _notmuch_sha1_of_file (filename);
2121 /* If that failed too, something is really wrong. Give up. */
2123 ret = NOTMUCH_STATUS_FILE_ERROR;
2127 message_id = talloc_asprintf (message_file,
2128 "notmuch-sha1-%s", sha1);
2132 /* Now that we have a message ID, we get a message object,
2133 * (which may or may not reference an existing document in the
2136 message = _notmuch_message_create_for_message_id (notmuch,
2140 talloc_free (message_id);
2142 if (message == NULL) {
2143 ret = COERCE_STATUS (private_status,
2144 "Unexpected status value from _notmuch_message_create_for_message_id");
2148 _notmuch_message_add_filename (message, filename);
2150 /* Is this a newly created message object? */
2151 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2152 _notmuch_message_add_term (message, "type", "mail");
2154 ret = _notmuch_database_link_message (notmuch, message,
2159 date = _notmuch_message_file_get_header (message_file, "date");
2160 _notmuch_message_set_header_values (message, date, from, subject);
2162 ret = _notmuch_message_index_file (message, message_file);
2166 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2169 _notmuch_message_sync (message);
2170 } catch (const Xapian::Error &error) {
2171 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2172 error.get_msg().c_str());
2173 notmuch->exception_reported = TRUE;
2174 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2180 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2181 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2182 *message_ret = message;
2184 notmuch_message_destroy (message);
2188 _notmuch_message_file_close (message_file);
2190 ret2 = notmuch_database_end_atomic (notmuch);
2191 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2192 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2193 ret2 != NOTMUCH_STATUS_SUCCESS)
2200 notmuch_database_remove_message (notmuch_database_t *notmuch,
2201 const char *filename)
2203 notmuch_status_t status;
2204 notmuch_message_t *message;
2206 status = notmuch_database_find_message_by_filename (notmuch, filename,
2209 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2210 status = _notmuch_message_remove_filename (message, filename);
2211 if (status == NOTMUCH_STATUS_SUCCESS)
2212 _notmuch_message_delete (message);
2213 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2214 _notmuch_message_sync (message);
2216 notmuch_message_destroy (message);
2223 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2224 const char *filename,
2225 notmuch_message_t **message_ret)
2228 const char *prefix = _find_prefix ("file-direntry");
2229 char *direntry, *term;
2230 Xapian::PostingIterator i, end;
2231 notmuch_status_t status;
2233 if (message_ret == NULL)
2234 return NOTMUCH_STATUS_NULL_POINTER;
2236 /* return NULL on any failure */
2237 *message_ret = NULL;
2239 local = talloc_new (notmuch);
2242 status = _notmuch_database_filename_to_direntry (
2243 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2244 if (status || !direntry)
2247 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2249 find_doc_ids_for_term (notmuch, term, &i, &end);
2252 notmuch_private_status_t private_status;
2254 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2256 if (*message_ret == NULL)
2257 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2259 } catch (const Xapian::Error &error) {
2260 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2261 error.get_msg().c_str());
2262 notmuch->exception_reported = TRUE;
2263 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2267 talloc_free (local);
2269 if (status && *message_ret) {
2270 notmuch_message_destroy (*message_ret);
2271 *message_ret = NULL;
2276 notmuch_string_list_t *
2277 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2278 Xapian::TermIterator &end,
2281 int prefix_len = strlen (prefix);
2282 notmuch_string_list_t *list;
2284 list = _notmuch_string_list_create (ctx);
2285 if (unlikely (list == NULL))
2288 for (i.skip_to (prefix); i != end; i++) {
2289 /* Terminate loop at first term without desired prefix. */
2290 if (strncmp ((*i).c_str (), prefix, prefix_len))
2293 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2300 notmuch_database_get_all_tags (notmuch_database_t *db)
2302 Xapian::TermIterator i, end;
2303 notmuch_string_list_t *tags;
2306 i = db->xapian_db->allterms_begin();
2307 end = db->xapian_db->allterms_end();
2308 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2309 _find_prefix ("tag"));
2310 _notmuch_string_list_sort (tags);
2311 return _notmuch_tags_create (db, tags);
2312 } catch (const Xapian::Error &error) {
2313 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2314 error.get_msg().c_str());
2315 db->exception_reported = TRUE;