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 { "subject", "XSUBJECT"},
261 _find_prefix (const char *name)
265 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
266 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
267 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
270 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
271 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
272 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
275 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
276 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
277 return PROBABILISTIC_PREFIX[i].prefix;
280 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
285 static const struct {
286 /* NOTMUCH_FEATURE_* value. */
287 _notmuch_features value;
288 /* Feature name as it appears in the database. This name should
289 * be appropriate for displaying to the user if an older version
290 * of notmuch doesn't support this feature. */
292 /* Compatibility flags when this feature is declared. */
294 } feature_names[] = {
295 { NOTMUCH_FEATURE_FILE_TERMS,
296 "multiple paths per message", "rw" },
297 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
298 "relative directory paths", "rw" },
299 /* Header values are not required for reading a database because a
300 * reader can just refer to the message file. */
301 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
302 "from/subject/message-ID in database", "w" },
303 { NOTMUCH_FEATURE_BOOL_FOLDER,
304 "exact folder:/path: search", "rw" },
305 { NOTMUCH_FEATURE_GHOSTS,
306 "mail documents for missing messages", "w"},
310 notmuch_status_to_string (notmuch_status_t status)
313 case NOTMUCH_STATUS_SUCCESS:
314 return "No error occurred";
315 case NOTMUCH_STATUS_OUT_OF_MEMORY:
316 return "Out of memory";
317 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
318 return "Attempt to write to a read-only database";
319 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
320 return "A Xapian exception occurred";
321 case NOTMUCH_STATUS_FILE_ERROR:
322 return "Something went wrong trying to read or write a file";
323 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
324 return "File is not an email";
325 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
326 return "Message ID is identical to a message in database";
327 case NOTMUCH_STATUS_NULL_POINTER:
328 return "Erroneous NULL pointer";
329 case NOTMUCH_STATUS_TAG_TOO_LONG:
330 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
331 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
332 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
333 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
334 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
335 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
336 return "Unsupported operation";
337 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
338 return "Operation requires a database upgrade";
340 case NOTMUCH_STATUS_LAST_STATUS:
341 return "Unknown error status value";
346 find_doc_ids_for_term (notmuch_database_t *notmuch,
348 Xapian::PostingIterator *begin,
349 Xapian::PostingIterator *end)
351 *begin = notmuch->xapian_db->postlist_begin (term);
353 *end = notmuch->xapian_db->postlist_end (term);
357 find_doc_ids (notmuch_database_t *notmuch,
358 const char *prefix_name,
360 Xapian::PostingIterator *begin,
361 Xapian::PostingIterator *end)
365 term = talloc_asprintf (notmuch, "%s%s",
366 _find_prefix (prefix_name), value);
368 find_doc_ids_for_term (notmuch, term, begin, end);
373 notmuch_private_status_t
374 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
375 const char *prefix_name,
377 unsigned int *doc_id)
379 Xapian::PostingIterator i, end;
381 find_doc_ids (notmuch, prefix_name, value, &i, &end);
385 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
390 #if DEBUG_DATABASE_SANITY
394 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
398 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
401 static Xapian::Document
402 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
404 return notmuch->xapian_db->get_document (doc_id);
407 /* Generate a compressed version of 'message_id' of the form:
409 * notmuch-sha1-<sha1_sum_of_message_id>
412 _notmuch_message_id_compressed (void *ctx, const char *message_id)
414 char *sha1, *compressed;
416 sha1 = _notmuch_sha1_of_string (message_id);
418 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
425 notmuch_database_find_message (notmuch_database_t *notmuch,
426 const char *message_id,
427 notmuch_message_t **message_ret)
429 notmuch_private_status_t status;
432 if (message_ret == NULL)
433 return NOTMUCH_STATUS_NULL_POINTER;
435 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
436 message_id = _notmuch_message_id_compressed (notmuch, message_id);
439 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
440 message_id, &doc_id);
442 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
445 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
447 if (*message_ret == NULL)
448 return NOTMUCH_STATUS_OUT_OF_MEMORY;
451 return NOTMUCH_STATUS_SUCCESS;
452 } catch (const Xapian::Error &error) {
453 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
454 error.get_msg().c_str());
455 notmuch->exception_reported = TRUE;
457 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
461 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
462 * a (potentially nested) parenthesized sequence with '\' used to
463 * escape any character (including parentheses).
465 * If the sequence to be skipped continues to the end of the string,
466 * then 'str' will be left pointing at the final terminating '\0'
470 skip_space_and_comments (const char **str)
475 while (*s && (isspace (*s) || *s == '(')) {
476 while (*s && isspace (*s))
481 while (*s && nesting) {
484 } else if (*s == ')') {
486 } else if (*s == '\\') {
498 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
499 * comments, and the '<' and '>' delimiters.
501 * If not NULL, then *next will be made to point to the first character
502 * not parsed, (possibly pointing to the final '\0' terminator.
504 * Returns a newly talloc'ed string belonging to 'ctx'.
506 * Returns NULL if there is any error parsing the message-id. */
508 _parse_message_id (void *ctx, const char *message_id, const char **next)
513 if (message_id == NULL || *message_id == '\0')
518 skip_space_and_comments (&s);
520 /* Skip any unstructured text as well. */
521 while (*s && *s != '<')
532 skip_space_and_comments (&s);
535 while (*end && *end != '>')
544 if (end > s && *end == '>')
549 result = talloc_strndup (ctx, s, end - s + 1);
551 /* Finally, collapse any whitespace that is within the message-id
557 for (r = result, len = strlen (r); *r; r++, len--)
558 if (*r == ' ' || *r == '\t')
559 memmove (r, r+1, len);
565 /* Parse a References header value, putting a (talloc'ed under 'ctx')
566 * copy of each referenced message-id into 'hash'.
568 * We explicitly avoid including any reference identical to
569 * 'message_id' in the result (to avoid mass confusion when a single
570 * message references itself cyclically---and yes, mail messages are
571 * not infrequent in the wild that do this---don't ask me why).
573 * Return the last reference parsed, if it is not equal to message_id.
576 parse_references (void *ctx,
577 const char *message_id,
581 char *ref, *last_ref = NULL;
583 if (refs == NULL || *refs == '\0')
587 ref = _parse_message_id (ctx, refs, &refs);
589 if (ref && strcmp (ref, message_id)) {
590 g_hash_table_insert (hash, ref, NULL);
595 /* The return value of this function is used to add a parent
596 * reference to the database. We should avoid making a message
597 * its own parent, thus the above check.
603 notmuch_database_create (const char *path, notmuch_database_t **database)
605 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
606 notmuch_database_t *notmuch = NULL;
607 char *notmuch_path = NULL;
612 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
613 status = NOTMUCH_STATUS_NULL_POINTER;
617 err = stat (path, &st);
619 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
620 path, strerror (errno));
621 status = NOTMUCH_STATUS_FILE_ERROR;
625 if (! S_ISDIR (st.st_mode)) {
626 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
628 status = NOTMUCH_STATUS_FILE_ERROR;
632 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
634 err = mkdir (notmuch_path, 0755);
637 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
638 notmuch_path, strerror (errno));
639 status = NOTMUCH_STATUS_FILE_ERROR;
643 status = notmuch_database_open (path,
644 NOTMUCH_DATABASE_MODE_READ_WRITE,
649 /* Upgrade doesn't add this feature to existing databases, but new
650 * databases have it. */
651 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
653 status = notmuch_database_upgrade (notmuch, NULL, NULL);
655 notmuch_database_close(notmuch);
661 talloc_free (notmuch_path);
666 talloc_free (notmuch);
671 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
673 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
674 fprintf (stderr, "Cannot write to a read-only database.\n");
675 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
678 return NOTMUCH_STATUS_SUCCESS;
681 /* Parse a database features string from the given database version.
682 * Returns the feature bit set.
684 * For version < 3, this ignores the features string and returns a
685 * hard-coded set of features.
687 * If there are unrecognized features that are required to open the
688 * database in mode (which should be 'r' or 'w'), return a
689 * comma-separated list of unrecognized but required features in
690 * *incompat_out suitable for presenting to the user. *incompat_out
691 * will be allocated from ctx.
693 static _notmuch_features
694 _parse_features (const void *ctx, const char *features, unsigned int version,
695 char mode, char **incompat_out)
697 _notmuch_features res = static_cast<_notmuch_features>(0);
698 unsigned int namelen, i;
702 /* Prior to database version 3, features were implied by the
705 return NOTMUCH_FEATURES_V0;
706 else if (version == 1)
707 return NOTMUCH_FEATURES_V1;
708 else if (version == 2)
709 return NOTMUCH_FEATURES_V2;
711 /* Parse the features string */
712 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
713 flags = strchr (features, '\t');
714 if (! flags || flags > features + llen)
716 namelen = flags - features;
718 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
719 if (strlen (feature_names[i].name) == namelen &&
720 strncmp (feature_names[i].name, features, namelen) == 0) {
721 res |= feature_names[i].value;
726 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
727 /* Unrecognized feature */
728 const char *have = strchr (flags, mode);
729 if (have && have < features + llen) {
730 /* This feature is required to access this database in
731 * 'mode', but we don't understand it. */
733 *incompat_out = talloc_strdup (ctx, "");
734 *incompat_out = talloc_asprintf_append_buffer (
735 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
745 _print_features (const void *ctx, unsigned int features)
748 char *res = talloc_strdup (ctx, "");
750 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
751 if (features & feature_names[i].value)
752 res = talloc_asprintf_append_buffer (
753 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
759 notmuch_database_open (const char *path,
760 notmuch_database_mode_t mode,
761 notmuch_database_t **database)
763 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
764 void *local = talloc_new (NULL);
765 notmuch_database_t *notmuch = NULL;
766 char *notmuch_path, *xapian_path, *incompat_features;
769 unsigned int i, version;
770 static int initialized = 0;
773 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
774 status = NOTMUCH_STATUS_NULL_POINTER;
778 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
779 fprintf (stderr, "Out of memory\n");
780 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
784 err = stat (notmuch_path, &st);
786 fprintf (stderr, "Error opening database at %s: %s\n",
787 notmuch_path, strerror (errno));
788 status = NOTMUCH_STATUS_FILE_ERROR;
792 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
793 fprintf (stderr, "Out of memory\n");
794 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
798 /* Initialize the GLib type system and threads */
799 #if !GLIB_CHECK_VERSION(2, 35, 1)
803 /* Initialize gmime */
805 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
809 notmuch = talloc_zero (NULL, notmuch_database_t);
810 notmuch->exception_reported = FALSE;
811 notmuch->path = talloc_strdup (notmuch, path);
813 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
814 notmuch->path[strlen (notmuch->path) - 1] = '\0';
816 notmuch->mode = mode;
817 notmuch->atomic_nesting = 0;
819 string last_thread_id;
821 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
822 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
823 Xapian::DB_CREATE_OR_OPEN);
825 notmuch->xapian_db = new Xapian::Database (xapian_path);
828 /* Check version. As of database version 3, we represent
829 * changes in terms of features, so assume a version bump
830 * means a dramatically incompatible change. */
831 version = notmuch_database_get_version (notmuch);
832 if (version > NOTMUCH_DATABASE_VERSION) {
834 "Error: Notmuch database at %s\n"
835 " has a newer database format version (%u) than supported by this\n"
836 " version of notmuch (%u).\n",
837 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
838 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
839 notmuch_database_destroy (notmuch);
841 status = NOTMUCH_STATUS_FILE_ERROR;
845 /* Check features. */
846 incompat_features = NULL;
847 notmuch->features = _parse_features (
848 local, notmuch->xapian_db->get_metadata ("features").c_str (),
849 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
851 if (incompat_features) {
853 "Error: Notmuch database at %s\n"
854 " requires features (%s)\n"
855 " not supported by this version of notmuch.\n",
856 notmuch_path, incompat_features);
857 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
858 notmuch_database_destroy (notmuch);
860 status = NOTMUCH_STATUS_FILE_ERROR;
864 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
865 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
866 if (last_thread_id.empty ()) {
867 notmuch->last_thread_id = 0;
872 str = last_thread_id.c_str ();
873 notmuch->last_thread_id = strtoull (str, &end, 16);
875 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
878 notmuch->query_parser = new Xapian::QueryParser;
879 notmuch->term_gen = new Xapian::TermGenerator;
880 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
881 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
882 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
884 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
885 notmuch->query_parser->set_database (*notmuch->xapian_db);
886 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
887 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
888 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
889 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
891 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
892 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
893 notmuch->query_parser->add_boolean_prefix (prefix->name,
897 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
898 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
899 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
901 } catch (const Xapian::Error &error) {
902 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
903 error.get_msg().c_str());
904 notmuch_database_destroy (notmuch);
906 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
915 talloc_free (notmuch);
920 notmuch_database_close (notmuch_database_t *notmuch)
922 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
924 /* Many Xapian objects (and thus notmuch objects) hold references to
925 * the database, so merely deleting the database may not suffice to
926 * close it. Thus, we explicitly close it here. */
927 if (notmuch->xapian_db != NULL) {
929 /* If there's an outstanding transaction, it's unclear if
930 * closing the Xapian database commits everything up to
931 * that transaction, or may discard committed (but
932 * unflushed) transactions. To be certain, explicitly
933 * cancel any outstanding transaction before closing. */
934 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
935 notmuch->atomic_nesting)
936 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
937 ->cancel_transaction ();
939 /* Close the database. This implicitly flushes
940 * outstanding changes. */
941 notmuch->xapian_db->close();
942 } catch (const Xapian::Error &error) {
943 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
944 if (! notmuch->exception_reported) {
945 fprintf (stderr, "Error: A Xapian exception occurred closing database: %s\n",
946 error.get_msg().c_str());
951 delete notmuch->term_gen;
952 notmuch->term_gen = NULL;
953 delete notmuch->query_parser;
954 notmuch->query_parser = NULL;
955 delete notmuch->xapian_db;
956 notmuch->xapian_db = NULL;
957 delete notmuch->value_range_processor;
958 notmuch->value_range_processor = NULL;
959 delete notmuch->date_range_processor;
960 notmuch->date_range_processor = NULL;
965 #if HAVE_XAPIAN_COMPACT
967 unlink_cb (const char *path,
968 unused (const struct stat *sb),
970 unused (struct FTW *ftw))
972 return remove (path);
976 rmtree (const char *path)
978 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
981 class NotmuchCompactor : public Xapian::Compactor
983 notmuch_compact_status_cb_t status_cb;
984 void *status_closure;
987 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
988 status_cb (cb), status_closure (closure) { }
991 set_status (const std::string &table, const std::string &status)
995 if (status_cb == NULL)
998 if (status.length () == 0)
999 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1001 msg = talloc_asprintf (NULL, " %s", status.c_str());
1007 status_cb (msg, status_closure);
1012 /* Compacts the given database, optionally saving the original database
1013 * in backup_path. Additionally, a callback function can be provided to
1014 * give the user feedback on the progress of the (likely long-lived)
1015 * compaction process.
1017 * The backup path must point to a directory on the same volume as the
1018 * original database. Passing a NULL backup_path will result in the
1019 * uncompacted database being deleted after compaction has finished.
1020 * Note that the database write lock will be held during the
1021 * compaction process to protect data integrity.
1024 notmuch_database_compact (const char *path,
1025 const char *backup_path,
1026 notmuch_compact_status_cb_t status_cb,
1030 char *notmuch_path, *xapian_path, *compact_xapian_path;
1031 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1032 notmuch_database_t *notmuch = NULL;
1033 struct stat statbuf;
1034 notmuch_bool_t keep_backup;
1036 local = talloc_new (NULL);
1038 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1040 ret = notmuch_database_open (path, NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much);
1045 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1046 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1050 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1051 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1055 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1056 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1060 if (backup_path == NULL) {
1061 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1062 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1065 keep_backup = FALSE;
1071 if (stat (backup_path, &statbuf) != -1) {
1072 fprintf (stderr, "Path already exists: %s\n", backup_path);
1073 ret = NOTMUCH_STATUS_FILE_ERROR;
1076 if (errno != ENOENT) {
1077 fprintf (stderr, "Unknown error while stat()ing path: %s\n",
1079 ret = NOTMUCH_STATUS_FILE_ERROR;
1083 /* Unconditionally attempt to remove old work-in-progress database (if
1084 * any). This is "protected" by database lock. If this fails due to write
1085 * errors (etc), the following code will fail and provide error message.
1087 (void) rmtree (compact_xapian_path);
1090 NotmuchCompactor compactor (status_cb, closure);
1092 compactor.set_renumber (false);
1093 compactor.add_source (xapian_path);
1094 compactor.set_destdir (compact_xapian_path);
1095 compactor.compact ();
1096 } catch (const Xapian::Error &error) {
1097 fprintf (stderr, "Error while compacting: %s\n", error.get_msg().c_str());
1098 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1102 if (rename (xapian_path, backup_path)) {
1103 fprintf (stderr, "Error moving %s to %s: %s\n",
1104 xapian_path, backup_path, strerror (errno));
1105 ret = NOTMUCH_STATUS_FILE_ERROR;
1109 if (rename (compact_xapian_path, xapian_path)) {
1110 fprintf (stderr, "Error moving %s to %s: %s\n",
1111 compact_xapian_path, xapian_path, strerror (errno));
1112 ret = NOTMUCH_STATUS_FILE_ERROR;
1116 if (! keep_backup) {
1117 if (rmtree (backup_path)) {
1118 fprintf (stderr, "Error removing old database %s: %s\n",
1119 backup_path, strerror (errno));
1120 ret = NOTMUCH_STATUS_FILE_ERROR;
1127 notmuch_status_t ret2;
1129 ret2 = notmuch_database_destroy (notmuch);
1131 /* don't clobber previous error status */
1132 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1136 talloc_free (local);
1142 notmuch_database_compact (unused (const char *path),
1143 unused (const char *backup_path),
1144 unused (notmuch_compact_status_cb_t status_cb),
1145 unused (void *closure))
1147 fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
1148 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1153 notmuch_database_destroy (notmuch_database_t *notmuch)
1155 notmuch_status_t status;
1157 status = notmuch_database_close (notmuch);
1158 talloc_free (notmuch);
1164 notmuch_database_get_path (notmuch_database_t *notmuch)
1166 return notmuch->path;
1170 notmuch_database_get_version (notmuch_database_t *notmuch)
1172 unsigned int version;
1173 string version_string;
1177 version_string = notmuch->xapian_db->get_metadata ("version");
1178 if (version_string.empty ())
1181 str = version_string.c_str ();
1182 if (str == NULL || *str == '\0')
1185 version = strtoul (str, &end, 10);
1187 INTERNAL_ERROR ("Malformed database version: %s", str);
1193 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1195 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1196 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1197 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1200 static volatile sig_atomic_t do_progress_notify = 0;
1203 handle_sigalrm (unused (int signal))
1205 do_progress_notify = 1;
1208 /* Upgrade the current database.
1210 * After opening a database in read-write mode, the client should
1211 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1212 * if so, upgrade with this function before making any modifications.
1214 * The optional progress_notify callback can be used by the caller to
1215 * provide progress indication to the user. If non-NULL it will be
1216 * called periodically with 'count' as the number of messages upgraded
1217 * so far and 'total' the overall number of messages that will be
1221 notmuch_database_upgrade (notmuch_database_t *notmuch,
1222 void (*progress_notify) (void *closure,
1226 void *local = talloc_new (NULL);
1227 Xapian::TermIterator t, t_end;
1228 Xapian::WritableDatabase *db;
1229 struct sigaction action;
1230 struct itimerval timerval;
1231 notmuch_bool_t timer_is_active = FALSE;
1232 enum _notmuch_features target_features, new_features;
1233 notmuch_status_t status;
1234 unsigned int count = 0, total = 0;
1236 status = _notmuch_database_ensure_writable (notmuch);
1240 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1242 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1243 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1245 if (! notmuch_database_needs_upgrade (notmuch))
1246 return NOTMUCH_STATUS_SUCCESS;
1248 if (progress_notify) {
1249 /* Setup our handler for SIGALRM */
1250 memset (&action, 0, sizeof (struct sigaction));
1251 action.sa_handler = handle_sigalrm;
1252 sigemptyset (&action.sa_mask);
1253 action.sa_flags = SA_RESTART;
1254 sigaction (SIGALRM, &action, NULL);
1256 /* Then start a timer to send SIGALRM once per second. */
1257 timerval.it_interval.tv_sec = 1;
1258 timerval.it_interval.tv_usec = 0;
1259 timerval.it_value.tv_sec = 1;
1260 timerval.it_value.tv_usec = 0;
1261 setitimer (ITIMER_REAL, &timerval, NULL);
1263 timer_is_active = TRUE;
1266 /* Figure out how much total work we need to do. */
1268 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1269 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1270 total += notmuch_query_count_messages (query);
1271 notmuch_query_destroy (query);
1273 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1274 t_end = db->allterms_end ("XTIMESTAMP");
1275 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1279 /* Perform the upgrade in a transaction. */
1280 db->begin_transaction (true);
1282 /* Set the target features so we write out changes in the desired
1284 notmuch->features = target_features;
1286 /* Perform per-message upgrades. */
1288 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1289 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1290 notmuch_messages_t *messages;
1291 notmuch_message_t *message;
1294 for (messages = notmuch_query_search_messages (query);
1295 notmuch_messages_valid (messages);
1296 notmuch_messages_move_to_next (messages))
1298 if (do_progress_notify) {
1299 progress_notify (closure, (double) count / total);
1300 do_progress_notify = 0;
1303 message = notmuch_messages_get (messages);
1305 /* Before version 1, each message document had its
1306 * filename in the data field. Copy that into the new
1307 * format by calling notmuch_message_add_filename.
1309 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1310 filename = _notmuch_message_talloc_copy_data (message);
1311 if (filename && *filename != '\0') {
1312 _notmuch_message_add_filename (message, filename);
1313 _notmuch_message_clear_data (message);
1315 talloc_free (filename);
1318 /* Prior to version 2, the "folder:" prefix was
1319 * probabilistic and stemmed. Change it to the current
1320 * boolean prefix. Add "path:" prefixes while at it.
1322 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1323 _notmuch_message_upgrade_folder (message);
1325 _notmuch_message_sync (message);
1327 notmuch_message_destroy (message);
1332 notmuch_query_destroy (query);
1335 /* Perform per-directory upgrades. */
1337 /* Before version 1 we stored directory timestamps in
1338 * XTIMESTAMP documents instead of the current XDIRECTORY
1339 * documents. So copy those as well. */
1340 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1341 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1343 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1347 Xapian::PostingIterator p, p_end;
1348 std::string term = *t;
1350 p_end = notmuch->xapian_db->postlist_end (term);
1352 for (p = notmuch->xapian_db->postlist_begin (term);
1356 Xapian::Document document;
1358 notmuch_directory_t *directory;
1360 if (do_progress_notify) {
1361 progress_notify (closure, (double) count / total);
1362 do_progress_notify = 0;
1365 document = find_document_for_doc_id (notmuch, *p);
1366 mtime = Xapian::sortable_unserialise (
1367 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1369 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1370 NOTMUCH_FIND_CREATE, &status);
1371 notmuch_directory_set_mtime (directory, mtime);
1372 notmuch_directory_destroy (directory);
1374 db->delete_document (*p);
1381 db->set_metadata ("features", _print_features (local, notmuch->features));
1382 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1384 db->commit_transaction ();
1386 if (timer_is_active) {
1387 /* Now stop the timer. */
1388 timerval.it_interval.tv_sec = 0;
1389 timerval.it_interval.tv_usec = 0;
1390 timerval.it_value.tv_sec = 0;
1391 timerval.it_value.tv_usec = 0;
1392 setitimer (ITIMER_REAL, &timerval, NULL);
1394 /* And disable the signal handler. */
1395 action.sa_handler = SIG_IGN;
1396 sigaction (SIGALRM, &action, NULL);
1399 talloc_free (local);
1400 return NOTMUCH_STATUS_SUCCESS;
1404 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1406 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1407 notmuch->atomic_nesting > 0)
1411 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1412 } catch (const Xapian::Error &error) {
1413 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1414 error.get_msg().c_str());
1415 notmuch->exception_reported = TRUE;
1416 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1420 notmuch->atomic_nesting++;
1421 return NOTMUCH_STATUS_SUCCESS;
1425 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1427 Xapian::WritableDatabase *db;
1429 if (notmuch->atomic_nesting == 0)
1430 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1432 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1433 notmuch->atomic_nesting > 1)
1436 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1438 db->commit_transaction ();
1440 /* This is a hack for testing. Xapian never flushes on a
1441 * non-flushed commit, even if the flush threshold is 1.
1442 * However, we rely on flushing to test atomicity. */
1443 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1444 if (thresh && atoi (thresh) == 1)
1446 } catch (const Xapian::Error &error) {
1447 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1448 error.get_msg().c_str());
1449 notmuch->exception_reported = TRUE;
1450 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1454 notmuch->atomic_nesting--;
1455 return NOTMUCH_STATUS_SUCCESS;
1458 /* We allow the user to use arbitrarily long paths for directories. But
1459 * we have a term-length limit. So if we exceed that, we'll use the
1460 * SHA-1 of the path for the database term.
1462 * Note: This function may return the original value of 'path'. If it
1463 * does not, then the caller is responsible to free() the returned
1467 _notmuch_database_get_directory_db_path (const char *path)
1469 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1471 if (term_len > NOTMUCH_TERM_MAX)
1472 return _notmuch_sha1_of_string (path);
1477 /* Given a path, split it into two parts: the directory part is all
1478 * components except for the last, and the basename is that last
1479 * component. Getting the return-value for either part is optional
1480 * (the caller can pass NULL).
1482 * The original 'path' can represent either a regular file or a
1483 * directory---the splitting will be carried out in the same way in
1484 * either case. Trailing slashes on 'path' will be ignored, and any
1485 * cases of multiple '/' characters appearing in series will be
1486 * treated as a single '/'.
1488 * Allocation (if any) will have 'ctx' as the talloc owner. But
1489 * pointers will be returned within the original path string whenever
1492 * Note: If 'path' is non-empty and contains no non-trailing slash,
1493 * (that is, consists of a filename with no parent directory), then
1494 * the directory returned will be an empty string. However, if 'path'
1495 * is an empty string, then both directory and basename will be
1499 _notmuch_database_split_path (void *ctx,
1501 const char **directory,
1502 const char **basename)
1506 if (path == NULL || *path == '\0') {
1511 return NOTMUCH_STATUS_SUCCESS;
1514 /* Find the last slash (not counting a trailing slash), if any. */
1516 slash = path + strlen (path) - 1;
1518 /* First, skip trailing slashes. */
1519 while (slash != path) {
1526 /* Then, find a slash. */
1527 while (slash != path) {
1537 /* Finally, skip multiple slashes. */
1538 while (slash != path) {
1545 if (slash == path) {
1547 *directory = talloc_strdup (ctx, "");
1552 *directory = talloc_strndup (ctx, path, slash - path + 1);
1555 return NOTMUCH_STATUS_SUCCESS;
1558 /* Find the document ID of the specified directory.
1560 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1561 * created if one does not exist for 'path'. Otherwise, if the
1562 * directory document does not exist, this sets *directory_id to
1563 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1566 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1568 notmuch_find_flags_t flags,
1569 unsigned int *directory_id)
1571 notmuch_directory_t *directory;
1572 notmuch_status_t status;
1576 return NOTMUCH_STATUS_SUCCESS;
1579 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1580 if (status || !directory) {
1585 *directory_id = _notmuch_directory_get_document_id (directory);
1587 notmuch_directory_destroy (directory);
1589 return NOTMUCH_STATUS_SUCCESS;
1593 _notmuch_database_get_directory_path (void *ctx,
1594 notmuch_database_t *notmuch,
1595 unsigned int doc_id)
1597 Xapian::Document document;
1599 document = find_document_for_doc_id (notmuch, doc_id);
1601 return talloc_strdup (ctx, document.get_data ().c_str ());
1604 /* Given a legal 'filename' for the database, (either relative to
1605 * database path or absolute with initial components identical to
1606 * database path), return a new string (with 'ctx' as the talloc
1607 * owner) suitable for use as a direntry term value.
1609 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1610 * will be created in the database as needed. Otherwise, if the
1611 * necessary directory documents do not exist, this sets
1612 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1615 _notmuch_database_filename_to_direntry (void *ctx,
1616 notmuch_database_t *notmuch,
1617 const char *filename,
1618 notmuch_find_flags_t flags,
1621 const char *relative, *directory, *basename;
1622 Xapian::docid directory_id;
1623 notmuch_status_t status;
1625 relative = _notmuch_database_relative_path (notmuch, filename);
1627 status = _notmuch_database_split_path (ctx, relative,
1628 &directory, &basename);
1632 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1634 if (status || directory_id == (unsigned int)-1) {
1639 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1641 return NOTMUCH_STATUS_SUCCESS;
1644 /* Given a legal 'path' for the database, return the relative path.
1646 * The return value will be a pointer to the original path contents,
1647 * and will be either the original string (if 'path' was relative) or
1648 * a portion of the string (if path was absolute and begins with the
1652 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1655 const char *db_path, *relative;
1656 unsigned int db_path_len;
1658 db_path = notmuch_database_get_path (notmuch);
1659 db_path_len = strlen (db_path);
1663 if (*relative == '/') {
1664 while (*relative == '/' && *(relative+1) == '/')
1667 if (strncmp (relative, db_path, db_path_len) == 0)
1669 relative += db_path_len;
1670 while (*relative == '/')
1679 notmuch_database_get_directory (notmuch_database_t *notmuch,
1681 notmuch_directory_t **directory)
1683 notmuch_status_t status;
1685 if (directory == NULL)
1686 return NOTMUCH_STATUS_NULL_POINTER;
1690 *directory = _notmuch_directory_create (notmuch, path,
1691 NOTMUCH_FIND_LOOKUP, &status);
1692 } catch (const Xapian::Error &error) {
1693 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1694 error.get_msg().c_str());
1695 notmuch->exception_reported = TRUE;
1696 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1701 /* Allocate a document ID that satisfies the following criteria:
1703 * 1. The ID does not exist for any document in the Xapian database
1705 * 2. The ID was not previously returned from this function
1707 * 3. The ID is the smallest integer satisfying (1) and (2)
1709 * This function will trigger an internal error if these constraints
1710 * cannot all be satisfied, (that is, the pool of available document
1711 * IDs has been exhausted).
1714 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1716 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1718 notmuch->last_doc_id++;
1720 if (notmuch->last_doc_id == 0)
1721 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1723 return notmuch->last_doc_id;
1727 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1729 /* 16 bytes (+ terminator) for hexadecimal representation of
1730 * a 64-bit integer. */
1731 static char thread_id[17];
1732 Xapian::WritableDatabase *db;
1734 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1736 notmuch->last_thread_id++;
1738 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1740 db->set_metadata ("last_thread_id", thread_id);
1746 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1748 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1749 message_id = _notmuch_message_id_compressed (ctx, message_id);
1751 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1755 static notmuch_status_t
1756 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1758 const char *message_id,
1759 const char **thread_id_ret);
1761 /* Find the thread ID to which the message with 'message_id' belongs.
1763 * Note: 'thread_id_ret' must not be NULL!
1764 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1767 * Note: If there is no message in the database with the given
1768 * 'message_id' then a new thread_id will be allocated for this
1769 * message ID and stored in the database metadata so that the
1770 * thread ID can be looked up if the message is added to the database
1773 static notmuch_status_t
1774 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1776 const char *message_id,
1777 const char **thread_id_ret)
1779 notmuch_private_status_t status;
1780 notmuch_message_t *message;
1782 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
1783 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
1786 /* Look for this message (regular or ghost) */
1787 message = _notmuch_message_create_for_message_id (
1788 notmuch, message_id, &status);
1789 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1790 /* Message exists */
1791 *thread_id_ret = talloc_steal (
1792 ctx, notmuch_message_get_thread_id (message));
1793 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1794 /* Message did not exist. Give it a fresh thread ID and
1795 * populate this message as a ghost message. */
1796 *thread_id_ret = talloc_strdup (
1797 ctx, _notmuch_database_generate_thread_id (notmuch));
1798 if (! *thread_id_ret) {
1799 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
1801 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
1803 /* Commit the new ghost message */
1804 _notmuch_message_sync (message);
1807 /* Create failed. Fall through. */
1810 notmuch_message_destroy (message);
1812 return COERCE_STATUS (status, "Error creating ghost message");
1815 /* Pre-ghost messages _resolve_message_id_to_thread_id */
1816 static notmuch_status_t
1817 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1819 const char *message_id,
1820 const char **thread_id_ret)
1822 notmuch_status_t status;
1823 notmuch_message_t *message;
1824 string thread_id_string;
1826 Xapian::WritableDatabase *db;
1828 status = notmuch_database_find_message (notmuch, message_id, &message);
1834 *thread_id_ret = talloc_steal (ctx,
1835 notmuch_message_get_thread_id (message));
1837 notmuch_message_destroy (message);
1839 return NOTMUCH_STATUS_SUCCESS;
1842 /* Message has not been seen yet.
1844 * We may have seen a reference to it already, in which case, we
1845 * can return the thread ID stored in the metadata. Otherwise, we
1846 * generate a new thread ID and store it there.
1848 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1849 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1850 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1852 if (thread_id_string.empty()) {
1853 *thread_id_ret = talloc_strdup (ctx,
1854 _notmuch_database_generate_thread_id (notmuch));
1855 db->set_metadata (metadata_key, *thread_id_ret);
1857 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1860 talloc_free (metadata_key);
1862 return NOTMUCH_STATUS_SUCCESS;
1865 static notmuch_status_t
1866 _merge_threads (notmuch_database_t *notmuch,
1867 const char *winner_thread_id,
1868 const char *loser_thread_id)
1870 Xapian::PostingIterator loser, loser_end;
1871 notmuch_message_t *message = NULL;
1872 notmuch_private_status_t private_status;
1873 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1875 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1877 for ( ; loser != loser_end; loser++) {
1878 message = _notmuch_message_create (notmuch, notmuch,
1879 *loser, &private_status);
1880 if (message == NULL) {
1881 ret = COERCE_STATUS (private_status,
1882 "Cannot find document for doc_id from query");
1886 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1887 _notmuch_message_add_term (message, "thread", winner_thread_id);
1888 _notmuch_message_sync (message);
1890 notmuch_message_destroy (message);
1896 notmuch_message_destroy (message);
1902 _my_talloc_free_for_g_hash (void *ptr)
1907 static notmuch_status_t
1908 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1909 notmuch_message_t *message,
1910 notmuch_message_file_t *message_file,
1911 const char **thread_id)
1913 GHashTable *parents = NULL;
1914 const char *refs, *in_reply_to, *in_reply_to_message_id;
1915 const char *last_ref_message_id, *this_message_id;
1916 GList *l, *keys = NULL;
1917 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1919 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1920 _my_talloc_free_for_g_hash, NULL);
1921 this_message_id = notmuch_message_get_message_id (message);
1923 refs = _notmuch_message_file_get_header (message_file, "references");
1924 last_ref_message_id = parse_references (message,
1928 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
1929 in_reply_to_message_id = parse_references (message,
1931 parents, in_reply_to);
1933 /* For the parent of this message, use the last message ID of the
1934 * References header, if available. If not, fall back to the
1935 * first message ID in the In-Reply-To header. */
1936 if (last_ref_message_id) {
1937 _notmuch_message_add_term (message, "replyto",
1938 last_ref_message_id);
1939 } else if (in_reply_to_message_id) {
1940 _notmuch_message_add_term (message, "replyto",
1941 in_reply_to_message_id);
1944 keys = g_hash_table_get_keys (parents);
1945 for (l = keys; l; l = l->next) {
1946 char *parent_message_id;
1947 const char *parent_thread_id = NULL;
1949 parent_message_id = (char *) l->data;
1951 _notmuch_message_add_term (message, "reference",
1954 ret = _resolve_message_id_to_thread_id (notmuch,
1961 if (*thread_id == NULL) {
1962 *thread_id = talloc_strdup (message, parent_thread_id);
1963 _notmuch_message_add_term (message, "thread", *thread_id);
1964 } else if (strcmp (*thread_id, parent_thread_id)) {
1965 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1975 g_hash_table_unref (parents);
1980 static notmuch_status_t
1981 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1982 notmuch_message_t *message,
1983 const char **thread_id)
1985 const char *message_id = notmuch_message_get_message_id (message);
1986 Xapian::PostingIterator child, children_end;
1987 notmuch_message_t *child_message = NULL;
1988 const char *child_thread_id;
1989 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1990 notmuch_private_status_t private_status;
1992 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1994 for ( ; child != children_end; child++) {
1996 child_message = _notmuch_message_create (message, notmuch,
1997 *child, &private_status);
1998 if (child_message == NULL) {
1999 ret = COERCE_STATUS (private_status,
2000 "Cannot find document for doc_id from query");
2004 child_thread_id = notmuch_message_get_thread_id (child_message);
2005 if (*thread_id == NULL) {
2006 *thread_id = talloc_strdup (message, child_thread_id);
2007 _notmuch_message_add_term (message, "thread", *thread_id);
2008 } else if (strcmp (*thread_id, child_thread_id)) {
2009 _notmuch_message_remove_term (child_message, "reference",
2011 _notmuch_message_sync (child_message);
2012 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2017 notmuch_message_destroy (child_message);
2018 child_message = NULL;
2023 notmuch_message_destroy (child_message);
2028 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2030 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2031 notmuch_message_t *message)
2033 const char *message_id;
2037 message_id = notmuch_message_get_message_id (message);
2038 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2040 /* Check if we have already seen related messages to this one.
2041 * If we have then use the thread_id that we stored at that time.
2043 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2044 if (stored_id.empty ()) {
2047 Xapian::WritableDatabase *db;
2049 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2051 /* Clear the metadata for this message ID. We don't need it
2053 db->set_metadata (metadata_key, "");
2055 return talloc_strdup (ctx, stored_id.c_str ());
2059 /* Given a blank or ghost 'message' and its corresponding
2060 * 'message_file' link it to existing threads in the database.
2062 * First, if is_ghost, this retrieves the thread ID already stored in
2063 * the message (which will be the case if a message was previously
2064 * added that referenced this one). If the message is blank
2065 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2066 * later in this function). If the database does not support ghost
2067 * messages, this checks for a thread ID stored in database metadata
2068 * for this message ID.
2070 * Second, we look at 'message_file' and its link-relevant headers
2071 * (References and In-Reply-To) for message IDs.
2073 * Finally, we look in the database for existing message that
2074 * reference 'message'.
2076 * In all cases, we assign to the current message the first thread ID
2077 * found (through either parent or child). We will also merge any
2078 * existing, distinct threads where this message belongs to both,
2079 * (which is not uncommon when messages are processed out of order).
2081 * Finally, if no thread ID has been found through parent or child, we
2082 * call _notmuch_message_generate_thread_id to generate a new thread
2083 * ID. This should only happen for new, top-level messages, (no
2084 * References or In-Reply-To header in this message, and no previously
2085 * added message refers to this message).
2087 static notmuch_status_t
2088 _notmuch_database_link_message (notmuch_database_t *notmuch,
2089 notmuch_message_t *message,
2090 notmuch_message_file_t *message_file,
2091 notmuch_bool_t is_ghost)
2093 void *local = talloc_new (NULL);
2094 notmuch_status_t status;
2095 const char *thread_id = NULL;
2097 /* Check if the message already had a thread ID */
2098 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2100 thread_id = notmuch_message_get_thread_id (message);
2102 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2104 _notmuch_message_add_term (message, "thread", thread_id);
2107 status = _notmuch_database_link_message_to_parents (notmuch, message,
2113 status = _notmuch_database_link_message_to_children (notmuch, message,
2118 /* If not part of any existing thread, generate a new thread ID. */
2119 if (thread_id == NULL) {
2120 thread_id = _notmuch_database_generate_thread_id (notmuch);
2122 _notmuch_message_add_term (message, "thread", thread_id);
2126 talloc_free (local);
2132 notmuch_database_add_message (notmuch_database_t *notmuch,
2133 const char *filename,
2134 notmuch_message_t **message_ret)
2136 notmuch_message_file_t *message_file;
2137 notmuch_message_t *message = NULL;
2138 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2139 notmuch_private_status_t private_status;
2140 notmuch_bool_t is_ghost = false;
2142 const char *date, *header;
2143 const char *from, *to, *subject;
2144 char *message_id = NULL;
2147 *message_ret = NULL;
2149 ret = _notmuch_database_ensure_writable (notmuch);
2153 message_file = _notmuch_message_file_open (filename);
2154 if (message_file == NULL)
2155 return NOTMUCH_STATUS_FILE_ERROR;
2157 /* Adding a message may change many documents. Do this all
2159 ret = notmuch_database_begin_atomic (notmuch);
2163 /* Parse message up front to get better error status. */
2164 ret = _notmuch_message_file_parse (message_file);
2169 /* Before we do any real work, (especially before doing a
2170 * potential SHA-1 computation on the entire file's contents),
2171 * let's make sure that what we're looking at looks like an
2172 * actual email message.
2174 from = _notmuch_message_file_get_header (message_file, "from");
2175 subject = _notmuch_message_file_get_header (message_file, "subject");
2176 to = _notmuch_message_file_get_header (message_file, "to");
2178 if ((from == NULL || *from == '\0') &&
2179 (subject == NULL || *subject == '\0') &&
2180 (to == NULL || *to == '\0'))
2182 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2186 /* Now that we're sure it's mail, the first order of business
2187 * is to find a message ID (or else create one ourselves). */
2189 header = _notmuch_message_file_get_header (message_file, "message-id");
2190 if (header && *header != '\0') {
2191 message_id = _parse_message_id (message_file, header, NULL);
2193 /* So the header value isn't RFC-compliant, but it's
2194 * better than no message-id at all. */
2195 if (message_id == NULL)
2196 message_id = talloc_strdup (message_file, header);
2199 if (message_id == NULL ) {
2200 /* No message-id at all, let's generate one by taking a
2201 * hash over the file's contents. */
2202 char *sha1 = _notmuch_sha1_of_file (filename);
2204 /* If that failed too, something is really wrong. Give up. */
2206 ret = NOTMUCH_STATUS_FILE_ERROR;
2210 message_id = talloc_asprintf (message_file,
2211 "notmuch-sha1-%s", sha1);
2215 /* Now that we have a message ID, we get a message object,
2216 * (which may or may not reference an existing document in the
2219 message = _notmuch_message_create_for_message_id (notmuch,
2223 talloc_free (message_id);
2225 if (message == NULL) {
2226 ret = COERCE_STATUS (private_status,
2227 "Unexpected status value from _notmuch_message_create_for_message_id");
2231 _notmuch_message_add_filename (message, filename);
2233 /* Is this a newly created message object or a ghost
2234 * message? We have to be slightly careful: if this is a
2235 * blank message, it's not safe to call
2236 * notmuch_message_get_flag yet. */
2237 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2238 (is_ghost = notmuch_message_get_flag (
2239 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2240 _notmuch_message_add_term (message, "type", "mail");
2242 /* Convert ghost message to a regular message */
2243 _notmuch_message_remove_term (message, "type", "ghost");
2245 ret = _notmuch_database_link_message (notmuch, message,
2246 message_file, is_ghost);
2250 date = _notmuch_message_file_get_header (message_file, "date");
2251 _notmuch_message_set_header_values (message, date, from, subject);
2253 ret = _notmuch_message_index_file (message, message_file);
2257 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2260 _notmuch_message_sync (message);
2261 } catch (const Xapian::Error &error) {
2262 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2263 error.get_msg().c_str());
2264 notmuch->exception_reported = TRUE;
2265 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2271 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2272 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2273 *message_ret = message;
2275 notmuch_message_destroy (message);
2279 _notmuch_message_file_close (message_file);
2281 ret2 = notmuch_database_end_atomic (notmuch);
2282 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2283 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2284 ret2 != NOTMUCH_STATUS_SUCCESS)
2291 notmuch_database_remove_message (notmuch_database_t *notmuch,
2292 const char *filename)
2294 notmuch_status_t status;
2295 notmuch_message_t *message;
2297 status = notmuch_database_find_message_by_filename (notmuch, filename,
2300 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2301 status = _notmuch_message_remove_filename (message, filename);
2302 if (status == NOTMUCH_STATUS_SUCCESS)
2303 _notmuch_message_delete (message);
2304 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2305 _notmuch_message_sync (message);
2307 notmuch_message_destroy (message);
2314 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2315 const char *filename,
2316 notmuch_message_t **message_ret)
2319 const char *prefix = _find_prefix ("file-direntry");
2320 char *direntry, *term;
2321 Xapian::PostingIterator i, end;
2322 notmuch_status_t status;
2324 if (message_ret == NULL)
2325 return NOTMUCH_STATUS_NULL_POINTER;
2327 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2328 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2330 /* return NULL on any failure */
2331 *message_ret = NULL;
2333 local = talloc_new (notmuch);
2336 status = _notmuch_database_filename_to_direntry (
2337 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2338 if (status || !direntry)
2341 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2343 find_doc_ids_for_term (notmuch, term, &i, &end);
2346 notmuch_private_status_t private_status;
2348 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2350 if (*message_ret == NULL)
2351 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2353 } catch (const Xapian::Error &error) {
2354 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2355 error.get_msg().c_str());
2356 notmuch->exception_reported = TRUE;
2357 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2361 talloc_free (local);
2363 if (status && *message_ret) {
2364 notmuch_message_destroy (*message_ret);
2365 *message_ret = NULL;
2370 notmuch_string_list_t *
2371 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2372 Xapian::TermIterator &end,
2375 int prefix_len = strlen (prefix);
2376 notmuch_string_list_t *list;
2378 list = _notmuch_string_list_create (ctx);
2379 if (unlikely (list == NULL))
2382 for (i.skip_to (prefix); i != end; i++) {
2383 /* Terminate loop at first term without desired prefix. */
2384 if (strncmp ((*i).c_str (), prefix, prefix_len))
2387 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2394 notmuch_database_get_all_tags (notmuch_database_t *db)
2396 Xapian::TermIterator i, end;
2397 notmuch_string_list_t *tags;
2400 i = db->xapian_db->allterms_begin();
2401 end = db->xapian_db->allterms_end();
2402 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2403 _find_prefix ("tag"));
2404 _notmuch_string_list_sort (tags);
2405 return _notmuch_tags_create (db, tags);
2406 } catch (const Xapian::Error &error) {
2407 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2408 error.get_msg().c_str());
2409 db->exception_reported = TRUE;