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 https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
24 #include "string-util.h"
33 #include <glib.h> /* g_free, GPtrArray, GHashTable */
34 #include <glib-object.h> /* g_type_init */
36 #include <gmime/gmime.h> /* g_mime_init */
40 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
45 notmuch_field_flag_t flags;
48 #define NOTMUCH_DATABASE_VERSION 3
50 #define STRINGIFY(s) _SUB_STRINGIFY(s)
51 #define _SUB_STRINGIFY(s) #s
53 #if HAVE_XAPIAN_DB_RETRY_LOCK
54 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
56 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
59 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
61 * We currently have three different types of documents (mail, ghost,
62 * and directory) and also some metadata.
66 * A mail document is associated with a particular email message. It
67 * is stored in one or more files on disk (though only one has its
68 * content indexed) and is uniquely identified by its "id" field
69 * (which is generally the message ID). It is indexed with the
70 * following prefixed terms which the database uses to construct
73 * Single terms of given prefix:
77 * id: Unique ID of mail. This is from the Message-ID header
78 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
79 * If it's present and too long, then we use
80 * "notmuch-sha1-<sha1_sum_of_message_id>".
81 * If this header is not present, we use
82 * "notmuch-sha1-<sha1_sum_of_entire_file>".
84 * thread: The ID of the thread to which the mail belongs
86 * replyto: The ID from the In-Reply-To header of the mail (if any).
88 * Multiple terms of given prefix:
90 * reference: All message IDs from In-Reply-To and References
91 * headers in the message.
93 * tag: Any tags associated with this message by the user.
95 * file-direntry: A colon-separated pair of values
96 * (INTEGER:STRING), where INTEGER is the
97 * document ID of a directory document, and
98 * STRING is the name of a file within that
99 * directory for this mail message.
101 * property: Has a property with key=value
102 * FIXME: if no = is present, should match on any value
104 * A mail document also has four values:
106 * TIMESTAMP: The time_t value corresponding to the message's
109 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
111 * FROM: The value of the "From" header
113 * SUBJECT: The value of the "Subject" header
115 * LAST_MOD: The revision number as of the last tag or
118 * In addition, terms from the content of the message are added with
119 * "from", "to", "attachment", and "subject" prefixes for use by the
120 * user in searching. Similarly, terms from the path of the mail
121 * message are added with "folder" and "path" prefixes. But the
122 * database doesn't really care itself about any of these.
124 * The data portion of a mail document is empty.
126 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
127 * -----------------------------------------------
128 * A ghost mail document is like a mail document, but where we don't
129 * have the message content. These are used to track thread reference
130 * information for messages we haven't received.
132 * A ghost mail document has type: ghost; id and thread fields that
133 * are identical to the mail document fields; and a MESSAGE_ID value.
137 * A directory document is used by a client of the notmuch library to
138 * maintain data necessary to allow for efficient polling of mail
141 * All directory documents contain one term:
143 * directory: The directory path (relative to the database path)
144 * Or the SHA1 sum of the directory path (if the
145 * path itself is too long to fit in a Xapian
148 * And all directory documents for directories other than top-level
149 * directories also contain the following term:
151 * directory-direntry: A colon-separated pair of values
152 * (INTEGER:STRING), where INTEGER is the
153 * document ID of the parent directory
154 * document, and STRING is the name of this
155 * directory within that parent.
157 * All directory documents have a single value:
159 * TIMESTAMP: The mtime of the directory (at last scan)
161 * The data portion of a directory document contains the path of the
162 * directory (relative to the database path).
166 * Xapian allows us to store arbitrary name-value pairs as
167 * "metadata". We currently use the following metadata names with the
170 * version The database schema version, (which is distinct
171 * from both the notmuch package version (see
172 * notmuch --version) and the libnotmuch library
173 * version. The version is stored as an base-10
174 * ASCII integer. The initial database version
175 * was 1, (though a schema existed before that
176 * were no "version" database value existed at
177 * all). Successive versions are allocated as
178 * changes are made to the database (such as by
179 * indexing new fields).
181 * features The set of features supported by this
182 * database. This consists of a set of
183 * '\n'-separated lines, where each is a feature
184 * name, a '\t', and compatibility flags. If the
185 * compatibility flags contain 'w', then the
186 * opener must support this feature to safely
187 * write this database. If the compatibility
188 * flags contain 'r', then the opener must
189 * support this feature to read this database.
190 * Introduced in database version 3.
192 * last_thread_id The last thread ID generated. This is stored
193 * as a 16-byte hexadecimal ASCII representation
194 * of a 64-bit unsigned integer. The first ID
195 * generated is 1 and the value will be
196 * incremented for each thread ID.
198 * C* metadata keys starting with C indicate
199 * configuration data. It can be managed with the
200 * n_database_*config* API. There is a convention
201 * of hierarchical keys separated by '.' (e.g.
202 * query.notmuch stores the value for the named
203 * query 'notmuch'), but it is not enforced by the
209 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
210 * Instead, the database has the following additional database
213 * thread_id_* A pre-allocated thread ID for a particular
214 * message. This is actually an arbitrarily large
215 * family of metadata name. Any particular name is
216 * formed by concatenating "thread_id_" with a message
217 * ID (or the SHA1 sum of a message ID if it is very
218 * long---see description of 'id' in the mail
219 * document). The value stored is a thread ID.
221 * These thread ID metadata values are stored
222 * whenever a message references a parent message
223 * that does not yet exist in the database. A
224 * thread ID will be allocated and stored, and if
225 * the message is later added, the stored thread
226 * ID will be used (and the metadata value will
229 * Even before a message is added, it's
230 * pre-allocated thread ID is useful so that all
231 * descendant messages that reference this common
232 * parent can be recognized as belonging to the
236 /* With these prefix values we follow the conventions published here:
238 * https://xapian.org/docs/omega/termprefixes.html
240 * as much as makes sense. Note that I took some liberty in matching
241 * the reserved prefix values to notmuch concepts, (for example, 'G'
242 * is documented as "newsGroup (or similar entity - e.g. a web forum
243 * name)", for which I think the thread is the closest analogue in
244 * notmuch. This in spite of the fact that we will eventually be
245 * storing mailing-list messages where 'G' for "mailing list name"
246 * might be even a closer analogue. I'm treating the single-character
247 * prefixes preferentially for core notmuch concepts (which will be
248 * nearly universal to all mail messages).
252 prefix_t prefix_table[] = {
253 /* name term prefix flags */
254 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
255 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
256 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
257 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
258 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
259 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
260 { "thread", "G", NOTMUCH_FIELD_EXTERNAL },
261 { "tag", "K", NOTMUCH_FIELD_EXTERNAL },
262 { "is", "K", NOTMUCH_FIELD_EXTERNAL },
263 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
264 { "path", "P", NOTMUCH_FIELD_EXTERNAL },
265 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
267 * Unconditionally add ':' to reduce potential ambiguity with
268 * overlapping prefixes and/or terms that start with capital
269 * letters. See Xapian document termprefixes.html for related
272 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL },
273 #if HAVE_XAPIAN_FIELD_PROCESSOR
274 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
275 NOTMUCH_FIELD_PROCESSOR },
276 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
277 NOTMUCH_FIELD_PROCESSOR },
279 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
280 NOTMUCH_FIELD_PROBABILISTIC },
281 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
282 NOTMUCH_FIELD_PROBABILISTIC },
283 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
284 NOTMUCH_FIELD_PROBABILISTIC },
285 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
286 NOTMUCH_FIELD_PROBABILISTIC },
287 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
288 NOTMUCH_FIELD_PROBABILISTIC },
292 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
294 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
295 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
297 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
300 #if HAVE_XAPIAN_FIELD_PROCESSOR
302 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
304 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
305 Xapian::FieldProcessor *fp;
307 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
308 fp = (new DateFieldProcessor())->release ();
309 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
310 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
312 INTERNAL_ERROR("unsupported field processor prefix: %s\n", prefix->name);
314 /* we treat all field-processor fields as boolean in order to get the raw input */
315 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
317 _setup_query_field_default (prefix, notmuch);
322 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
324 _setup_query_field_default (prefix, notmuch);
329 _find_prefix (const char *name)
333 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
334 if (strcmp (name, prefix_table[i].name) == 0)
335 return prefix_table[i].prefix;
338 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
343 static const struct {
344 /* NOTMUCH_FEATURE_* value. */
345 _notmuch_features value;
346 /* Feature name as it appears in the database. This name should
347 * be appropriate for displaying to the user if an older version
348 * of notmuch doesn't support this feature. */
350 /* Compatibility flags when this feature is declared. */
352 } feature_names[] = {
353 { NOTMUCH_FEATURE_FILE_TERMS,
354 "multiple paths per message", "rw" },
355 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
356 "relative directory paths", "rw" },
357 /* Header values are not required for reading a database because a
358 * reader can just refer to the message file. */
359 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
360 "from/subject/message-ID in database", "w" },
361 { NOTMUCH_FEATURE_BOOL_FOLDER,
362 "exact folder:/path: search", "rw" },
363 { NOTMUCH_FEATURE_GHOSTS,
364 "mail documents for missing messages", "w"},
365 /* Knowledge of the index mime-types are not required for reading
366 * a database because a reader will just be unable to query
368 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
369 "indexed MIME types", "w"},
370 { NOTMUCH_FEATURE_LAST_MOD,
371 "modification tracking", "w"},
375 notmuch_status_to_string (notmuch_status_t status)
378 case NOTMUCH_STATUS_SUCCESS:
379 return "No error occurred";
380 case NOTMUCH_STATUS_OUT_OF_MEMORY:
381 return "Out of memory";
382 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
383 return "Attempt to write to a read-only database";
384 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
385 return "A Xapian exception occurred";
386 case NOTMUCH_STATUS_FILE_ERROR:
387 return "Something went wrong trying to read or write a file";
388 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
389 return "File is not an email";
390 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
391 return "Message ID is identical to a message in database";
392 case NOTMUCH_STATUS_NULL_POINTER:
393 return "Erroneous NULL pointer";
394 case NOTMUCH_STATUS_TAG_TOO_LONG:
395 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
396 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
397 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
398 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
399 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
400 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
401 return "Unsupported operation";
402 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
403 return "Operation requires a database upgrade";
404 case NOTMUCH_STATUS_PATH_ERROR:
405 return "Path supplied is illegal for this function";
407 case NOTMUCH_STATUS_LAST_STATUS:
408 return "Unknown error status value";
413 _notmuch_database_log (notmuch_database_t *notmuch,
419 va_start (va_args, format);
421 if (notmuch->status_string)
422 talloc_free (notmuch->status_string);
424 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
429 _notmuch_database_log_append (notmuch_database_t *notmuch,
435 va_start (va_args, format);
437 if (notmuch->status_string)
438 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
440 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
446 find_doc_ids_for_term (notmuch_database_t *notmuch,
448 Xapian::PostingIterator *begin,
449 Xapian::PostingIterator *end)
451 *begin = notmuch->xapian_db->postlist_begin (term);
453 *end = notmuch->xapian_db->postlist_end (term);
457 find_doc_ids (notmuch_database_t *notmuch,
458 const char *prefix_name,
460 Xapian::PostingIterator *begin,
461 Xapian::PostingIterator *end)
465 term = talloc_asprintf (notmuch, "%s%s",
466 _find_prefix (prefix_name), value);
468 find_doc_ids_for_term (notmuch, term, begin, end);
473 notmuch_private_status_t
474 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
475 const char *prefix_name,
477 unsigned int *doc_id)
479 Xapian::PostingIterator i, end;
481 find_doc_ids (notmuch, prefix_name, value, &i, &end);
485 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
490 #if DEBUG_DATABASE_SANITY
494 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
498 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
501 static Xapian::Document
502 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
504 return notmuch->xapian_db->get_document (doc_id);
507 /* Generate a compressed version of 'message_id' of the form:
509 * notmuch-sha1-<sha1_sum_of_message_id>
512 _notmuch_message_id_compressed (void *ctx, const char *message_id)
514 char *sha1, *compressed;
516 sha1 = _notmuch_sha1_of_string (message_id);
518 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
525 notmuch_database_find_message (notmuch_database_t *notmuch,
526 const char *message_id,
527 notmuch_message_t **message_ret)
529 notmuch_private_status_t status;
532 if (message_ret == NULL)
533 return NOTMUCH_STATUS_NULL_POINTER;
535 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
536 message_id = _notmuch_message_id_compressed (notmuch, message_id);
539 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
540 message_id, &doc_id);
542 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
545 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
547 if (*message_ret == NULL)
548 return NOTMUCH_STATUS_OUT_OF_MEMORY;
551 return NOTMUCH_STATUS_SUCCESS;
552 } catch (const Xapian::Error &error) {
553 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
554 error.get_msg().c_str());
555 notmuch->exception_reported = TRUE;
557 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
561 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
562 * a (potentially nested) parenthesized sequence with '\' used to
563 * escape any character (including parentheses).
565 * If the sequence to be skipped continues to the end of the string,
566 * then 'str' will be left pointing at the final terminating '\0'
570 skip_space_and_comments (const char **str)
575 while (*s && (isspace (*s) || *s == '(')) {
576 while (*s && isspace (*s))
581 while (*s && nesting) {
584 } else if (*s == ')') {
586 } else if (*s == '\\') {
598 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
599 * comments, and the '<' and '>' delimiters.
601 * If not NULL, then *next will be made to point to the first character
602 * not parsed, (possibly pointing to the final '\0' terminator.
604 * Returns a newly talloc'ed string belonging to 'ctx'.
606 * Returns NULL if there is any error parsing the message-id. */
608 _parse_message_id (void *ctx, const char *message_id, const char **next)
613 if (message_id == NULL || *message_id == '\0')
618 skip_space_and_comments (&s);
620 /* Skip any unstructured text as well. */
621 while (*s && *s != '<')
632 skip_space_and_comments (&s);
635 while (*end && *end != '>')
644 if (end > s && *end == '>')
649 result = talloc_strndup (ctx, s, end - s + 1);
651 /* Finally, collapse any whitespace that is within the message-id
657 for (r = result, len = strlen (r); *r; r++, len--)
658 if (*r == ' ' || *r == '\t')
659 memmove (r, r+1, len);
665 /* Parse a References header value, putting a (talloc'ed under 'ctx')
666 * copy of each referenced message-id into 'hash'.
668 * We explicitly avoid including any reference identical to
669 * 'message_id' in the result (to avoid mass confusion when a single
670 * message references itself cyclically---and yes, mail messages are
671 * not infrequent in the wild that do this---don't ask me why).
673 * Return the last reference parsed, if it is not equal to message_id.
676 parse_references (void *ctx,
677 const char *message_id,
681 char *ref, *last_ref = NULL;
683 if (refs == NULL || *refs == '\0')
687 ref = _parse_message_id (ctx, refs, &refs);
689 if (ref && strcmp (ref, message_id)) {
690 g_hash_table_add (hash, ref);
695 /* The return value of this function is used to add a parent
696 * reference to the database. We should avoid making a message
697 * its own parent, thus the above check.
699 return talloc_strdup(ctx, last_ref);
703 notmuch_database_create (const char *path, notmuch_database_t **database)
705 char *status_string = NULL;
706 notmuch_status_t status;
708 status = notmuch_database_create_verbose (path, database,
712 fputs (status_string, stderr);
713 free (status_string);
720 notmuch_database_create_verbose (const char *path,
721 notmuch_database_t **database,
722 char **status_string)
724 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
725 notmuch_database_t *notmuch = NULL;
726 char *notmuch_path = NULL;
727 char *message = NULL;
732 message = strdup ("Error: Cannot create a database for a NULL path.\n");
733 status = NOTMUCH_STATUS_NULL_POINTER;
737 if (path[0] != '/') {
738 message = strdup ("Error: Database path must be absolute.\n");
739 status = NOTMUCH_STATUS_PATH_ERROR;
743 err = stat (path, &st);
745 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
746 path, strerror (errno)));
747 status = NOTMUCH_STATUS_FILE_ERROR;
751 if (! S_ISDIR (st.st_mode)) {
752 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
753 "Not a directory.\n",
755 status = NOTMUCH_STATUS_FILE_ERROR;
759 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
761 err = mkdir (notmuch_path, 0755);
764 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
765 notmuch_path, strerror (errno)));
766 status = NOTMUCH_STATUS_FILE_ERROR;
770 status = notmuch_database_open_verbose (path,
771 NOTMUCH_DATABASE_MODE_READ_WRITE,
776 /* Upgrade doesn't add these feature to existing databases, but
777 * new databases have them. */
778 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
779 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
781 status = notmuch_database_upgrade (notmuch, NULL, NULL);
783 notmuch_database_close(notmuch);
789 talloc_free (notmuch_path);
793 *status_string = message;
800 talloc_free (notmuch);
805 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
807 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
808 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
809 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
812 return NOTMUCH_STATUS_SUCCESS;
815 /* Allocate a revision number for the next change. */
817 _notmuch_database_new_revision (notmuch_database_t *notmuch)
819 unsigned long new_revision = notmuch->revision + 1;
821 /* If we're in an atomic section, hold off on updating the
822 * committed revision number until we commit the atomic section.
824 if (notmuch->atomic_nesting)
825 notmuch->atomic_dirty = TRUE;
827 notmuch->revision = new_revision;
832 /* Parse a database features string from the given database version.
833 * Returns the feature bit set.
835 * For version < 3, this ignores the features string and returns a
836 * hard-coded set of features.
838 * If there are unrecognized features that are required to open the
839 * database in mode (which should be 'r' or 'w'), return a
840 * comma-separated list of unrecognized but required features in
841 * *incompat_out suitable for presenting to the user. *incompat_out
842 * will be allocated from ctx.
844 static _notmuch_features
845 _parse_features (const void *ctx, const char *features, unsigned int version,
846 char mode, char **incompat_out)
848 _notmuch_features res = static_cast<_notmuch_features>(0);
849 unsigned int namelen, i;
853 /* Prior to database version 3, features were implied by the
856 return NOTMUCH_FEATURES_V0;
857 else if (version == 1)
858 return NOTMUCH_FEATURES_V1;
859 else if (version == 2)
860 return NOTMUCH_FEATURES_V2;
862 /* Parse the features string */
863 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
864 flags = strchr (features, '\t');
865 if (! flags || flags > features + llen)
867 namelen = flags - features;
869 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
870 if (strlen (feature_names[i].name) == namelen &&
871 strncmp (feature_names[i].name, features, namelen) == 0) {
872 res |= feature_names[i].value;
877 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
878 /* Unrecognized feature */
879 const char *have = strchr (flags, mode);
880 if (have && have < features + llen) {
881 /* This feature is required to access this database in
882 * 'mode', but we don't understand it. */
884 *incompat_out = talloc_strdup (ctx, "");
885 *incompat_out = talloc_asprintf_append_buffer (
886 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
896 _print_features (const void *ctx, unsigned int features)
899 char *res = talloc_strdup (ctx, "");
901 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
902 if (features & feature_names[i].value)
903 res = talloc_asprintf_append_buffer (
904 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
910 notmuch_database_open (const char *path,
911 notmuch_database_mode_t mode,
912 notmuch_database_t **database)
914 char *status_string = NULL;
915 notmuch_status_t status;
917 status = notmuch_database_open_verbose (path, mode, database,
921 fputs (status_string, stderr);
922 free (status_string);
929 notmuch_database_open_verbose (const char *path,
930 notmuch_database_mode_t mode,
931 notmuch_database_t **database,
932 char **status_string)
934 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
935 void *local = talloc_new (NULL);
936 notmuch_database_t *notmuch = NULL;
937 char *notmuch_path, *xapian_path, *incompat_features;
938 char *message = NULL;
941 unsigned int i, version;
942 static int initialized = 0;
945 message = strdup ("Error: Cannot open a database for a NULL path.\n");
946 status = NOTMUCH_STATUS_NULL_POINTER;
950 if (path[0] != '/') {
951 message = strdup ("Error: Database path must be absolute.\n");
952 status = NOTMUCH_STATUS_PATH_ERROR;
956 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
957 message = strdup ("Out of memory\n");
958 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
962 err = stat (notmuch_path, &st);
964 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
965 notmuch_path, strerror (errno)));
966 status = NOTMUCH_STATUS_FILE_ERROR;
970 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
971 message = strdup ("Out of memory\n");
972 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
976 /* Initialize the GLib type system and threads */
977 #if !GLIB_CHECK_VERSION(2, 35, 1)
981 /* Initialize gmime */
983 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
987 notmuch = talloc_zero (NULL, notmuch_database_t);
988 notmuch->exception_reported = FALSE;
989 notmuch->status_string = NULL;
990 notmuch->path = talloc_strdup (notmuch, path);
992 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
993 notmuch->path[strlen (notmuch->path) - 1] = '\0';
995 notmuch->mode = mode;
996 notmuch->atomic_nesting = 0;
999 string last_thread_id;
1002 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
1003 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
1006 notmuch->xapian_db = new Xapian::Database (xapian_path);
1009 /* Check version. As of database version 3, we represent
1010 * changes in terms of features, so assume a version bump
1011 * means a dramatically incompatible change. */
1012 version = notmuch_database_get_version (notmuch);
1013 if (version > NOTMUCH_DATABASE_VERSION) {
1014 IGNORE_RESULT (asprintf (&message,
1015 "Error: Notmuch database at %s\n"
1016 " has a newer database format version (%u) than supported by this\n"
1017 " version of notmuch (%u).\n",
1018 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
1019 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1020 notmuch_database_destroy (notmuch);
1022 status = NOTMUCH_STATUS_FILE_ERROR;
1026 /* Check features. */
1027 incompat_features = NULL;
1028 notmuch->features = _parse_features (
1029 local, notmuch->xapian_db->get_metadata ("features").c_str (),
1030 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1031 &incompat_features);
1032 if (incompat_features) {
1033 IGNORE_RESULT (asprintf (&message,
1034 "Error: Notmuch database at %s\n"
1035 " requires features (%s)\n"
1036 " not supported by this version of notmuch.\n",
1037 notmuch_path, incompat_features));
1038 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1039 notmuch_database_destroy (notmuch);
1041 status = NOTMUCH_STATUS_FILE_ERROR;
1045 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1046 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1047 if (last_thread_id.empty ()) {
1048 notmuch->last_thread_id = 0;
1053 str = last_thread_id.c_str ();
1054 notmuch->last_thread_id = strtoull (str, &end, 16);
1056 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1059 /* Get current highest revision number. */
1060 last_mod = notmuch->xapian_db->get_value_upper_bound (
1061 NOTMUCH_VALUE_LAST_MOD);
1062 if (last_mod.empty ())
1063 notmuch->revision = 0;
1065 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1066 notmuch->uuid = talloc_strdup (
1067 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1069 notmuch->query_parser = new Xapian::QueryParser;
1070 notmuch->term_gen = new Xapian::TermGenerator;
1071 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1072 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1073 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1074 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1076 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1077 notmuch->query_parser->set_database (*notmuch->xapian_db);
1078 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1079 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1080 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1081 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1082 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1084 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1085 const prefix_t *prefix = &prefix_table[i];
1086 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1087 _setup_query_field (prefix, notmuch);
1090 } catch (const Xapian::Error &error) {
1091 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1092 error.get_msg().c_str()));
1093 notmuch_database_destroy (notmuch);
1095 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1099 talloc_free (local);
1103 *status_string = message;
1109 *database = notmuch;
1111 talloc_free (notmuch);
1116 notmuch_database_close (notmuch_database_t *notmuch)
1118 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1120 /* Many Xapian objects (and thus notmuch objects) hold references to
1121 * the database, so merely deleting the database may not suffice to
1122 * close it. Thus, we explicitly close it here. */
1123 if (notmuch->xapian_db != NULL) {
1125 /* If there's an outstanding transaction, it's unclear if
1126 * closing the Xapian database commits everything up to
1127 * that transaction, or may discard committed (but
1128 * unflushed) transactions. To be certain, explicitly
1129 * cancel any outstanding transaction before closing. */
1130 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1131 notmuch->atomic_nesting)
1132 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1133 ->cancel_transaction ();
1135 /* Close the database. This implicitly flushes
1136 * outstanding changes. */
1137 notmuch->xapian_db->close();
1138 } catch (const Xapian::Error &error) {
1139 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1140 if (! notmuch->exception_reported) {
1141 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1142 error.get_msg().c_str());
1147 delete notmuch->term_gen;
1148 notmuch->term_gen = NULL;
1149 delete notmuch->query_parser;
1150 notmuch->query_parser = NULL;
1151 delete notmuch->xapian_db;
1152 notmuch->xapian_db = NULL;
1153 delete notmuch->value_range_processor;
1154 notmuch->value_range_processor = NULL;
1155 delete notmuch->date_range_processor;
1156 notmuch->date_range_processor = NULL;
1157 delete notmuch->last_mod_range_processor;
1158 notmuch->last_mod_range_processor = NULL;
1164 _notmuch_database_reopen (notmuch_database_t *notmuch)
1166 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1167 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1170 notmuch->xapian_db->reopen ();
1171 } catch (const Xapian::Error &error) {
1172 if (! notmuch->exception_reported) {
1173 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1174 error.get_msg ().c_str ());
1175 notmuch->exception_reported = TRUE;
1177 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1182 return NOTMUCH_STATUS_SUCCESS;
1186 unlink_cb (const char *path,
1187 unused (const struct stat *sb),
1189 unused (struct FTW *ftw))
1191 return remove (path);
1195 rmtree (const char *path)
1197 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1200 class NotmuchCompactor : public Xapian::Compactor
1202 notmuch_compact_status_cb_t status_cb;
1203 void *status_closure;
1206 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1207 status_cb (cb), status_closure (closure) { }
1210 set_status (const std::string &table, const std::string &status)
1214 if (status_cb == NULL)
1217 if (status.length () == 0)
1218 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1220 msg = talloc_asprintf (NULL, " %s", status.c_str());
1226 status_cb (msg, status_closure);
1231 /* Compacts the given database, optionally saving the original database
1232 * in backup_path. Additionally, a callback function can be provided to
1233 * give the user feedback on the progress of the (likely long-lived)
1234 * compaction process.
1236 * The backup path must point to a directory on the same volume as the
1237 * original database. Passing a NULL backup_path will result in the
1238 * uncompacted database being deleted after compaction has finished.
1239 * Note that the database write lock will be held during the
1240 * compaction process to protect data integrity.
1243 notmuch_database_compact (const char *path,
1244 const char *backup_path,
1245 notmuch_compact_status_cb_t status_cb,
1249 char *notmuch_path, *xapian_path, *compact_xapian_path;
1250 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1251 notmuch_database_t *notmuch = NULL;
1252 struct stat statbuf;
1253 notmuch_bool_t keep_backup;
1254 char *message = NULL;
1256 local = talloc_new (NULL);
1258 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1260 ret = notmuch_database_open_verbose (path,
1261 NOTMUCH_DATABASE_MODE_READ_WRITE,
1265 if (status_cb) status_cb (message, closure);
1269 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1270 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1274 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1275 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1279 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1280 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1284 if (backup_path == NULL) {
1285 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1286 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1289 keep_backup = FALSE;
1295 if (stat (backup_path, &statbuf) != -1) {
1296 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1297 ret = NOTMUCH_STATUS_FILE_ERROR;
1300 if (errno != ENOENT) {
1301 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1303 ret = NOTMUCH_STATUS_FILE_ERROR;
1307 /* Unconditionally attempt to remove old work-in-progress database (if
1308 * any). This is "protected" by database lock. If this fails due to write
1309 * errors (etc), the following code will fail and provide error message.
1311 (void) rmtree (compact_xapian_path);
1314 NotmuchCompactor compactor (status_cb, closure);
1316 compactor.set_renumber (false);
1317 compactor.add_source (xapian_path);
1318 compactor.set_destdir (compact_xapian_path);
1319 compactor.compact ();
1320 } catch (const Xapian::Error &error) {
1321 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1322 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1326 if (rename (xapian_path, backup_path)) {
1327 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1328 xapian_path, backup_path, strerror (errno));
1329 ret = NOTMUCH_STATUS_FILE_ERROR;
1333 if (rename (compact_xapian_path, xapian_path)) {
1334 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1335 compact_xapian_path, xapian_path, strerror (errno));
1336 ret = NOTMUCH_STATUS_FILE_ERROR;
1340 if (! keep_backup) {
1341 if (rmtree (backup_path)) {
1342 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1343 backup_path, strerror (errno));
1344 ret = NOTMUCH_STATUS_FILE_ERROR;
1351 notmuch_status_t ret2;
1353 const char *str = notmuch_database_status_string (notmuch);
1354 if (status_cb && str)
1355 status_cb (str, closure);
1357 ret2 = notmuch_database_destroy (notmuch);
1359 /* don't clobber previous error status */
1360 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1364 talloc_free (local);
1370 notmuch_database_destroy (notmuch_database_t *notmuch)
1372 notmuch_status_t status;
1374 status = notmuch_database_close (notmuch);
1375 talloc_free (notmuch);
1381 notmuch_database_get_path (notmuch_database_t *notmuch)
1383 return notmuch->path;
1387 notmuch_database_get_version (notmuch_database_t *notmuch)
1389 unsigned int version;
1390 string version_string;
1394 version_string = notmuch->xapian_db->get_metadata ("version");
1395 if (version_string.empty ())
1398 str = version_string.c_str ();
1399 if (str == NULL || *str == '\0')
1402 version = strtoul (str, &end, 10);
1404 INTERNAL_ERROR ("Malformed database version: %s", str);
1410 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1412 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1413 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1414 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1417 static volatile sig_atomic_t do_progress_notify = 0;
1420 handle_sigalrm (unused (int signal))
1422 do_progress_notify = 1;
1425 /* Upgrade the current database.
1427 * After opening a database in read-write mode, the client should
1428 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1429 * if so, upgrade with this function before making any modifications.
1431 * The optional progress_notify callback can be used by the caller to
1432 * provide progress indication to the user. If non-NULL it will be
1433 * called periodically with 'count' as the number of messages upgraded
1434 * so far and 'total' the overall number of messages that will be
1438 notmuch_database_upgrade (notmuch_database_t *notmuch,
1439 void (*progress_notify) (void *closure,
1443 void *local = talloc_new (NULL);
1444 Xapian::TermIterator t, t_end;
1445 Xapian::WritableDatabase *db;
1446 struct sigaction action;
1447 struct itimerval timerval;
1448 notmuch_bool_t timer_is_active = FALSE;
1449 enum _notmuch_features target_features, new_features;
1450 notmuch_status_t status;
1451 notmuch_private_status_t private_status;
1452 notmuch_query_t *query = NULL;
1453 unsigned int count = 0, total = 0;
1455 status = _notmuch_database_ensure_writable (notmuch);
1459 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1461 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1462 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1464 if (! notmuch_database_needs_upgrade (notmuch))
1465 return NOTMUCH_STATUS_SUCCESS;
1467 if (progress_notify) {
1468 /* Set up our handler for SIGALRM */
1469 memset (&action, 0, sizeof (struct sigaction));
1470 action.sa_handler = handle_sigalrm;
1471 sigemptyset (&action.sa_mask);
1472 action.sa_flags = SA_RESTART;
1473 sigaction (SIGALRM, &action, NULL);
1475 /* Then start a timer to send SIGALRM once per second. */
1476 timerval.it_interval.tv_sec = 1;
1477 timerval.it_interval.tv_usec = 0;
1478 timerval.it_value.tv_sec = 1;
1479 timerval.it_value.tv_usec = 0;
1480 setitimer (ITIMER_REAL, &timerval, NULL);
1482 timer_is_active = TRUE;
1485 /* Figure out how much total work we need to do. */
1487 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1488 NOTMUCH_FEATURE_LAST_MOD)) {
1489 query = notmuch_query_create (notmuch, "");
1492 status = notmuch_query_count_messages_st (query, &msg_count);
1497 notmuch_query_destroy (query);
1500 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1501 t_end = db->allterms_end ("XTIMESTAMP");
1502 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1505 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1506 /* The ghost message upgrade converts all thread_id_*
1507 * metadata values into ghost message documents. */
1508 t_end = db->metadata_keys_end ("thread_id_");
1509 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1513 /* Perform the upgrade in a transaction. */
1514 db->begin_transaction (true);
1516 /* Set the target features so we write out changes in the desired
1518 notmuch->features = target_features;
1520 /* Perform per-message upgrades. */
1522 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1523 NOTMUCH_FEATURE_LAST_MOD)) {
1524 notmuch_messages_t *messages;
1525 notmuch_message_t *message;
1528 query = notmuch_query_create (notmuch, "");
1530 status = notmuch_query_search_messages_st (query, &messages);
1534 notmuch_messages_valid (messages);
1535 notmuch_messages_move_to_next (messages))
1537 if (do_progress_notify) {
1538 progress_notify (closure, (double) count / total);
1539 do_progress_notify = 0;
1542 message = notmuch_messages_get (messages);
1544 /* Before version 1, each message document had its
1545 * filename in the data field. Copy that into the new
1546 * format by calling notmuch_message_add_filename.
1548 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1549 filename = _notmuch_message_talloc_copy_data (message);
1550 if (filename && *filename != '\0') {
1551 _notmuch_message_add_filename (message, filename);
1552 _notmuch_message_clear_data (message);
1554 talloc_free (filename);
1557 /* Prior to version 2, the "folder:" prefix was
1558 * probabilistic and stemmed. Change it to the current
1559 * boolean prefix. Add "path:" prefixes while at it.
1561 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1562 _notmuch_message_upgrade_folder (message);
1564 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1565 * track modification revisions. Give all messages the
1566 * next available revision; since we just started tracking
1567 * revisions for this database, that will be 1.
1569 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1570 _notmuch_message_upgrade_last_mod (message);
1572 _notmuch_message_sync (message);
1574 notmuch_message_destroy (message);
1579 notmuch_query_destroy (query);
1583 /* Perform per-directory upgrades. */
1585 /* Before version 1 we stored directory timestamps in
1586 * XTIMESTAMP documents instead of the current XDIRECTORY
1587 * documents. So copy those as well. */
1588 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1589 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1591 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1595 Xapian::PostingIterator p, p_end;
1596 std::string term = *t;
1598 p_end = notmuch->xapian_db->postlist_end (term);
1600 for (p = notmuch->xapian_db->postlist_begin (term);
1604 Xapian::Document document;
1606 notmuch_directory_t *directory;
1608 if (do_progress_notify) {
1609 progress_notify (closure, (double) count / total);
1610 do_progress_notify = 0;
1613 document = find_document_for_doc_id (notmuch, *p);
1614 mtime = Xapian::sortable_unserialise (
1615 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1617 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1618 NOTMUCH_FIND_CREATE, &status);
1619 notmuch_directory_set_mtime (directory, mtime);
1620 notmuch_directory_destroy (directory);
1622 db->delete_document (*p);
1629 /* Perform metadata upgrades. */
1631 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1632 * messages were stored as database metadata. Change these to
1635 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1636 notmuch_message_t *message;
1637 std::string message_id, thread_id;
1639 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1640 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1642 if (do_progress_notify) {
1643 progress_notify (closure, (double) count / total);
1644 do_progress_notify = 0;
1647 message_id = (*t).substr (
1648 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1649 thread_id = db->get_metadata (*t);
1651 /* Create ghost message */
1652 message = _notmuch_message_create_for_message_id (
1653 notmuch, message_id.c_str (), &private_status);
1654 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1655 /* Document already exists; ignore the stored thread ID */
1656 } else if (private_status ==
1657 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1658 private_status = _notmuch_message_initialize_ghost (
1659 message, thread_id.c_str ());
1660 if (! private_status)
1661 _notmuch_message_sync (message);
1664 if (private_status) {
1665 _notmuch_database_log (notmuch,
1666 "Upgrade failed while creating ghost messages.\n");
1667 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1671 /* Clear saved metadata thread ID */
1672 db->set_metadata (*t, "");
1678 status = NOTMUCH_STATUS_SUCCESS;
1679 db->set_metadata ("features", _print_features (local, notmuch->features));
1680 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1683 if (status == NOTMUCH_STATUS_SUCCESS)
1684 db->commit_transaction ();
1686 db->cancel_transaction ();
1688 if (timer_is_active) {
1689 /* Now stop the timer. */
1690 timerval.it_interval.tv_sec = 0;
1691 timerval.it_interval.tv_usec = 0;
1692 timerval.it_value.tv_sec = 0;
1693 timerval.it_value.tv_usec = 0;
1694 setitimer (ITIMER_REAL, &timerval, NULL);
1696 /* And disable the signal handler. */
1697 action.sa_handler = SIG_IGN;
1698 sigaction (SIGALRM, &action, NULL);
1702 notmuch_query_destroy (query);
1704 talloc_free (local);
1709 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1711 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1712 notmuch->atomic_nesting > 0)
1715 if (notmuch_database_needs_upgrade (notmuch))
1716 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1719 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1720 } catch (const Xapian::Error &error) {
1721 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1722 error.get_msg().c_str());
1723 notmuch->exception_reported = TRUE;
1724 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1728 notmuch->atomic_nesting++;
1729 return NOTMUCH_STATUS_SUCCESS;
1733 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1735 Xapian::WritableDatabase *db;
1737 if (notmuch->atomic_nesting == 0)
1738 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1740 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1741 notmuch->atomic_nesting > 1)
1744 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1746 db->commit_transaction ();
1748 /* This is a hack for testing. Xapian never flushes on a
1749 * non-flushed commit, even if the flush threshold is 1.
1750 * However, we rely on flushing to test atomicity. */
1751 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1752 if (thresh && atoi (thresh) == 1)
1754 } catch (const Xapian::Error &error) {
1755 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1756 error.get_msg().c_str());
1757 notmuch->exception_reported = TRUE;
1758 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1761 if (notmuch->atomic_dirty) {
1762 ++notmuch->revision;
1763 notmuch->atomic_dirty = FALSE;
1767 notmuch->atomic_nesting--;
1768 return NOTMUCH_STATUS_SUCCESS;
1772 notmuch_database_get_revision (notmuch_database_t *notmuch,
1776 *uuid = notmuch->uuid;
1777 return notmuch->revision;
1780 /* We allow the user to use arbitrarily long paths for directories. But
1781 * we have a term-length limit. So if we exceed that, we'll use the
1782 * SHA-1 of the path for the database term.
1784 * Note: This function may return the original value of 'path'. If it
1785 * does not, then the caller is responsible to free() the returned
1789 _notmuch_database_get_directory_db_path (const char *path)
1791 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1793 if (term_len > NOTMUCH_TERM_MAX)
1794 return _notmuch_sha1_of_string (path);
1799 /* Given a path, split it into two parts: the directory part is all
1800 * components except for the last, and the basename is that last
1801 * component. Getting the return-value for either part is optional
1802 * (the caller can pass NULL).
1804 * The original 'path' can represent either a regular file or a
1805 * directory---the splitting will be carried out in the same way in
1806 * either case. Trailing slashes on 'path' will be ignored, and any
1807 * cases of multiple '/' characters appearing in series will be
1808 * treated as a single '/'.
1810 * Allocation (if any) will have 'ctx' as the talloc owner. But
1811 * pointers will be returned within the original path string whenever
1814 * Note: If 'path' is non-empty and contains no non-trailing slash,
1815 * (that is, consists of a filename with no parent directory), then
1816 * the directory returned will be an empty string. However, if 'path'
1817 * is an empty string, then both directory and basename will be
1821 _notmuch_database_split_path (void *ctx,
1823 const char **directory,
1824 const char **basename)
1828 if (path == NULL || *path == '\0') {
1833 return NOTMUCH_STATUS_SUCCESS;
1836 /* Find the last slash (not counting a trailing slash), if any. */
1838 slash = path + strlen (path) - 1;
1840 /* First, skip trailing slashes. */
1841 while (slash != path && *slash == '/')
1844 /* Then, find a slash. */
1845 while (slash != path && *slash != '/') {
1852 /* Finally, skip multiple slashes. */
1853 while (slash != path && *(slash - 1) == '/')
1856 if (slash == path) {
1858 *directory = talloc_strdup (ctx, "");
1863 *directory = talloc_strndup (ctx, path, slash - path);
1866 return NOTMUCH_STATUS_SUCCESS;
1869 /* Find the document ID of the specified directory.
1871 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1872 * created if one does not exist for 'path'. Otherwise, if the
1873 * directory document does not exist, this sets *directory_id to
1874 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1877 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1879 notmuch_find_flags_t flags,
1880 unsigned int *directory_id)
1882 notmuch_directory_t *directory;
1883 notmuch_status_t status;
1887 return NOTMUCH_STATUS_SUCCESS;
1890 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1891 if (status || !directory) {
1896 *directory_id = _notmuch_directory_get_document_id (directory);
1898 notmuch_directory_destroy (directory);
1900 return NOTMUCH_STATUS_SUCCESS;
1904 _notmuch_database_get_directory_path (void *ctx,
1905 notmuch_database_t *notmuch,
1906 unsigned int doc_id)
1908 Xapian::Document document;
1910 document = find_document_for_doc_id (notmuch, doc_id);
1912 return talloc_strdup (ctx, document.get_data ().c_str ());
1915 /* Given a legal 'filename' for the database, (either relative to
1916 * database path or absolute with initial components identical to
1917 * database path), return a new string (with 'ctx' as the talloc
1918 * owner) suitable for use as a direntry term value.
1920 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1921 * will be created in the database as needed. Otherwise, if the
1922 * necessary directory documents do not exist, this sets
1923 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1926 _notmuch_database_filename_to_direntry (void *ctx,
1927 notmuch_database_t *notmuch,
1928 const char *filename,
1929 notmuch_find_flags_t flags,
1932 const char *relative, *directory, *basename;
1933 Xapian::docid directory_id;
1934 notmuch_status_t status;
1936 relative = _notmuch_database_relative_path (notmuch, filename);
1938 status = _notmuch_database_split_path (ctx, relative,
1939 &directory, &basename);
1943 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1945 if (status || directory_id == (unsigned int)-1) {
1950 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1952 return NOTMUCH_STATUS_SUCCESS;
1955 /* Given a legal 'path' for the database, return the relative path.
1957 * The return value will be a pointer to the original path contents,
1958 * and will be either the original string (if 'path' was relative) or
1959 * a portion of the string (if path was absolute and begins with the
1963 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1966 const char *db_path, *relative;
1967 unsigned int db_path_len;
1969 db_path = notmuch_database_get_path (notmuch);
1970 db_path_len = strlen (db_path);
1974 if (*relative == '/') {
1975 while (*relative == '/' && *(relative+1) == '/')
1978 if (strncmp (relative, db_path, db_path_len) == 0)
1980 relative += db_path_len;
1981 while (*relative == '/')
1990 notmuch_database_get_directory (notmuch_database_t *notmuch,
1992 notmuch_directory_t **directory)
1994 notmuch_status_t status;
1996 if (directory == NULL)
1997 return NOTMUCH_STATUS_NULL_POINTER;
2001 *directory = _notmuch_directory_create (notmuch, path,
2002 NOTMUCH_FIND_LOOKUP, &status);
2003 } catch (const Xapian::Error &error) {
2004 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
2005 error.get_msg().c_str());
2006 notmuch->exception_reported = TRUE;
2007 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2012 /* Allocate a document ID that satisfies the following criteria:
2014 * 1. The ID does not exist for any document in the Xapian database
2016 * 2. The ID was not previously returned from this function
2018 * 3. The ID is the smallest integer satisfying (1) and (2)
2020 * This function will trigger an internal error if these constraints
2021 * cannot all be satisfied, (that is, the pool of available document
2022 * IDs has been exhausted).
2025 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2027 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2029 notmuch->last_doc_id++;
2031 if (notmuch->last_doc_id == 0)
2032 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2034 return notmuch->last_doc_id;
2038 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
2040 /* 16 bytes (+ terminator) for hexadecimal representation of
2041 * a 64-bit integer. */
2042 static char thread_id[17];
2043 Xapian::WritableDatabase *db;
2045 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2047 notmuch->last_thread_id++;
2049 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2051 db->set_metadata ("last_thread_id", thread_id);
2057 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2059 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2060 message_id = _notmuch_message_id_compressed (ctx, message_id);
2062 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2066 static notmuch_status_t
2067 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2069 const char *message_id,
2070 const char **thread_id_ret);
2072 /* Find the thread ID to which the message with 'message_id' belongs.
2074 * Note: 'thread_id_ret' must not be NULL!
2075 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2078 * Note: If there is no message in the database with the given
2079 * 'message_id' then a new thread_id will be allocated for this
2080 * message ID and stored in the database metadata so that the
2081 * thread ID can be looked up if the message is added to the database
2084 static notmuch_status_t
2085 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2087 const char *message_id,
2088 const char **thread_id_ret)
2090 notmuch_private_status_t status;
2091 notmuch_message_t *message;
2093 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2094 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2097 /* Look for this message (regular or ghost) */
2098 message = _notmuch_message_create_for_message_id (
2099 notmuch, message_id, &status);
2100 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2101 /* Message exists */
2102 *thread_id_ret = talloc_steal (
2103 ctx, notmuch_message_get_thread_id (message));
2104 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2105 /* Message did not exist. Give it a fresh thread ID and
2106 * populate this message as a ghost message. */
2107 *thread_id_ret = talloc_strdup (
2108 ctx, _notmuch_database_generate_thread_id (notmuch));
2109 if (! *thread_id_ret) {
2110 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2112 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2114 /* Commit the new ghost message */
2115 _notmuch_message_sync (message);
2118 /* Create failed. Fall through. */
2121 notmuch_message_destroy (message);
2123 return COERCE_STATUS (status, "Error creating ghost message");
2126 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2127 static notmuch_status_t
2128 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2130 const char *message_id,
2131 const char **thread_id_ret)
2133 notmuch_status_t status;
2134 notmuch_message_t *message;
2135 string thread_id_string;
2137 Xapian::WritableDatabase *db;
2139 status = notmuch_database_find_message (notmuch, message_id, &message);
2145 *thread_id_ret = talloc_steal (ctx,
2146 notmuch_message_get_thread_id (message));
2148 notmuch_message_destroy (message);
2150 return NOTMUCH_STATUS_SUCCESS;
2153 /* Message has not been seen yet.
2155 * We may have seen a reference to it already, in which case, we
2156 * can return the thread ID stored in the metadata. Otherwise, we
2157 * generate a new thread ID and store it there.
2159 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2160 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2161 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2163 if (thread_id_string.empty()) {
2164 *thread_id_ret = talloc_strdup (ctx,
2165 _notmuch_database_generate_thread_id (notmuch));
2166 db->set_metadata (metadata_key, *thread_id_ret);
2168 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2171 talloc_free (metadata_key);
2173 return NOTMUCH_STATUS_SUCCESS;
2176 static notmuch_status_t
2177 _merge_threads (notmuch_database_t *notmuch,
2178 const char *winner_thread_id,
2179 const char *loser_thread_id)
2181 Xapian::PostingIterator loser, loser_end;
2182 notmuch_message_t *message = NULL;
2183 notmuch_private_status_t private_status;
2184 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2186 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2188 for ( ; loser != loser_end; loser++) {
2189 message = _notmuch_message_create (notmuch, notmuch,
2190 *loser, &private_status);
2191 if (message == NULL) {
2192 ret = COERCE_STATUS (private_status,
2193 "Cannot find document for doc_id from query");
2197 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2198 _notmuch_message_add_term (message, "thread", winner_thread_id);
2199 _notmuch_message_sync (message);
2201 notmuch_message_destroy (message);
2207 notmuch_message_destroy (message);
2213 _my_talloc_free_for_g_hash (void *ptr)
2218 static notmuch_status_t
2219 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2220 notmuch_message_t *message,
2221 notmuch_message_file_t *message_file,
2222 const char **thread_id)
2224 GHashTable *parents = NULL;
2225 const char *refs, *in_reply_to, *in_reply_to_message_id;
2226 const char *last_ref_message_id, *this_message_id;
2227 GList *l, *keys = NULL;
2228 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2230 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2231 _my_talloc_free_for_g_hash, NULL);
2232 this_message_id = notmuch_message_get_message_id (message);
2234 refs = _notmuch_message_file_get_header (message_file, "references");
2235 last_ref_message_id = parse_references (message,
2239 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2240 in_reply_to_message_id = parse_references (message,
2242 parents, in_reply_to);
2244 /* For the parent of this message, use the last message ID of the
2245 * References header, if available. If not, fall back to the
2246 * first message ID in the In-Reply-To header. */
2247 if (last_ref_message_id) {
2248 _notmuch_message_add_term (message, "replyto",
2249 last_ref_message_id);
2250 } else if (in_reply_to_message_id) {
2251 _notmuch_message_add_term (message, "replyto",
2252 in_reply_to_message_id);
2255 keys = g_hash_table_get_keys (parents);
2256 for (l = keys; l; l = l->next) {
2257 char *parent_message_id;
2258 const char *parent_thread_id = NULL;
2260 parent_message_id = (char *) l->data;
2262 _notmuch_message_add_term (message, "reference",
2265 ret = _resolve_message_id_to_thread_id (notmuch,
2272 if (*thread_id == NULL) {
2273 *thread_id = talloc_strdup (message, parent_thread_id);
2274 _notmuch_message_add_term (message, "thread", *thread_id);
2275 } else if (strcmp (*thread_id, parent_thread_id)) {
2276 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2286 g_hash_table_unref (parents);
2291 static notmuch_status_t
2292 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2293 notmuch_message_t *message,
2294 const char **thread_id)
2296 const char *message_id = notmuch_message_get_message_id (message);
2297 Xapian::PostingIterator child, children_end;
2298 notmuch_message_t *child_message = NULL;
2299 const char *child_thread_id;
2300 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2301 notmuch_private_status_t private_status;
2303 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2305 for ( ; child != children_end; child++) {
2307 child_message = _notmuch_message_create (message, notmuch,
2308 *child, &private_status);
2309 if (child_message == NULL) {
2310 ret = COERCE_STATUS (private_status,
2311 "Cannot find document for doc_id from query");
2315 child_thread_id = notmuch_message_get_thread_id (child_message);
2316 if (*thread_id == NULL) {
2317 *thread_id = talloc_strdup (message, child_thread_id);
2318 _notmuch_message_add_term (message, "thread", *thread_id);
2319 } else if (strcmp (*thread_id, child_thread_id)) {
2320 _notmuch_message_remove_term (child_message, "reference",
2322 _notmuch_message_sync (child_message);
2323 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2328 notmuch_message_destroy (child_message);
2329 child_message = NULL;
2334 notmuch_message_destroy (child_message);
2339 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2341 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2342 notmuch_message_t *message)
2344 const char *message_id;
2348 message_id = notmuch_message_get_message_id (message);
2349 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2351 /* Check if we have already seen related messages to this one.
2352 * If we have then use the thread_id that we stored at that time.
2354 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2355 if (stored_id.empty ()) {
2358 Xapian::WritableDatabase *db;
2360 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2362 /* Clear the metadata for this message ID. We don't need it
2364 db->set_metadata (metadata_key, "");
2366 return talloc_strdup (ctx, stored_id.c_str ());
2370 /* Given a blank or ghost 'message' and its corresponding
2371 * 'message_file' link it to existing threads in the database.
2373 * First, if is_ghost, this retrieves the thread ID already stored in
2374 * the message (which will be the case if a message was previously
2375 * added that referenced this one). If the message is blank
2376 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2377 * later in this function). If the database does not support ghost
2378 * messages, this checks for a thread ID stored in database metadata
2379 * for this message ID.
2381 * Second, we look at 'message_file' and its link-relevant headers
2382 * (References and In-Reply-To) for message IDs.
2384 * Finally, we look in the database for existing message that
2385 * reference 'message'.
2387 * In all cases, we assign to the current message the first thread ID
2388 * found. We will also merge any existing, distinct threads where this
2389 * message belongs to both, (which is not uncommon when messages are
2390 * processed out of order).
2392 * Finally, if no thread ID has been found through referenced messages, we
2393 * call _notmuch_message_generate_thread_id to generate a new thread
2394 * ID. This should only happen for new, top-level messages, (no
2395 * References or In-Reply-To header in this message, and no previously
2396 * added message refers to this message).
2398 static notmuch_status_t
2399 _notmuch_database_link_message (notmuch_database_t *notmuch,
2400 notmuch_message_t *message,
2401 notmuch_message_file_t *message_file,
2402 notmuch_bool_t is_ghost)
2404 void *local = talloc_new (NULL);
2405 notmuch_status_t status;
2406 const char *thread_id = NULL;
2408 /* Check if the message already had a thread ID */
2409 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2411 thread_id = notmuch_message_get_thread_id (message);
2413 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2415 _notmuch_message_add_term (message, "thread", thread_id);
2418 status = _notmuch_database_link_message_to_parents (notmuch, message,
2424 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2425 /* In general, it shouldn't be necessary to link children,
2426 * since the earlier indexing of those children will have
2427 * stored a thread ID for the missing parent. However, prior
2428 * to ghost messages, these stored thread IDs were NOT
2429 * rewritten during thread merging (and there was no
2430 * performant way to do so), so if indexed children were
2431 * pulled into a different thread ID by a merge, it was
2432 * necessary to pull them *back* into the stored thread ID of
2433 * the parent. With ghost messages, we just rewrite the
2434 * stored thread IDs during merging, so this workaround isn't
2436 status = _notmuch_database_link_message_to_children (notmuch, message,
2442 /* If not part of any existing thread, generate a new thread ID. */
2443 if (thread_id == NULL) {
2444 thread_id = _notmuch_database_generate_thread_id (notmuch);
2446 _notmuch_message_add_term (message, "thread", thread_id);
2450 talloc_free (local);
2456 notmuch_database_add_message (notmuch_database_t *notmuch,
2457 const char *filename,
2458 notmuch_message_t **message_ret)
2460 notmuch_message_file_t *message_file;
2461 notmuch_message_t *message = NULL;
2462 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2463 notmuch_private_status_t private_status;
2464 notmuch_bool_t is_ghost = false;
2466 const char *date, *header;
2467 const char *from, *to, *subject;
2468 char *message_id = NULL;
2471 *message_ret = NULL;
2473 ret = _notmuch_database_ensure_writable (notmuch);
2477 message_file = _notmuch_message_file_open (notmuch, filename);
2478 if (message_file == NULL)
2479 return NOTMUCH_STATUS_FILE_ERROR;
2481 /* Adding a message may change many documents. Do this all
2483 ret = notmuch_database_begin_atomic (notmuch);
2487 /* Parse message up front to get better error status. */
2488 ret = _notmuch_message_file_parse (message_file);
2493 /* Before we do any real work, (especially before doing a
2494 * potential SHA-1 computation on the entire file's contents),
2495 * let's make sure that what we're looking at looks like an
2496 * actual email message.
2498 from = _notmuch_message_file_get_header (message_file, "from");
2499 subject = _notmuch_message_file_get_header (message_file, "subject");
2500 to = _notmuch_message_file_get_header (message_file, "to");
2502 if ((from == NULL || *from == '\0') &&
2503 (subject == NULL || *subject == '\0') &&
2504 (to == NULL || *to == '\0'))
2506 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2510 /* Now that we're sure it's mail, the first order of business
2511 * is to find a message ID (or else create one ourselves). */
2513 header = _notmuch_message_file_get_header (message_file, "message-id");
2514 if (header && *header != '\0') {
2515 message_id = _parse_message_id (message_file, header, NULL);
2517 /* So the header value isn't RFC-compliant, but it's
2518 * better than no message-id at all. */
2519 if (message_id == NULL)
2520 message_id = talloc_strdup (message_file, header);
2523 if (message_id == NULL ) {
2524 /* No message-id at all, let's generate one by taking a
2525 * hash over the file's contents. */
2526 char *sha1 = _notmuch_sha1_of_file (filename);
2528 /* If that failed too, something is really wrong. Give up. */
2530 ret = NOTMUCH_STATUS_FILE_ERROR;
2534 message_id = talloc_asprintf (message_file,
2535 "notmuch-sha1-%s", sha1);
2539 /* Now that we have a message ID, we get a message object,
2540 * (which may or may not reference an existing document in the
2543 message = _notmuch_message_create_for_message_id (notmuch,
2547 talloc_free (message_id);
2549 if (message == NULL) {
2550 ret = COERCE_STATUS (private_status,
2551 "Unexpected status value from _notmuch_message_create_for_message_id");
2555 _notmuch_message_add_filename (message, filename);
2557 /* Is this a newly created message object or a ghost
2558 * message? We have to be slightly careful: if this is a
2559 * blank message, it's not safe to call
2560 * notmuch_message_get_flag yet. */
2561 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2562 (is_ghost = notmuch_message_get_flag (
2563 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2564 _notmuch_message_add_term (message, "type", "mail");
2566 /* Convert ghost message to a regular message */
2567 _notmuch_message_remove_term (message, "type", "ghost");
2569 ret = _notmuch_database_link_message (notmuch, message,
2570 message_file, is_ghost);
2574 date = _notmuch_message_file_get_header (message_file, "date");
2575 _notmuch_message_set_header_values (message, date, from, subject);
2577 ret = _notmuch_message_index_file (message, message_file);
2581 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2584 _notmuch_message_sync (message);
2585 } catch (const Xapian::Error &error) {
2586 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2587 error.get_msg().c_str());
2588 notmuch->exception_reported = TRUE;
2589 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2595 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2596 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2597 *message_ret = message;
2599 notmuch_message_destroy (message);
2603 _notmuch_message_file_close (message_file);
2605 ret2 = notmuch_database_end_atomic (notmuch);
2606 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2607 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2608 ret2 != NOTMUCH_STATUS_SUCCESS)
2615 notmuch_database_remove_message (notmuch_database_t *notmuch,
2616 const char *filename)
2618 notmuch_status_t status;
2619 notmuch_message_t *message;
2621 status = notmuch_database_find_message_by_filename (notmuch, filename,
2624 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2625 status = _notmuch_message_remove_filename (message, filename);
2626 if (status == NOTMUCH_STATUS_SUCCESS)
2627 _notmuch_message_delete (message);
2628 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2629 _notmuch_message_sync (message);
2631 notmuch_message_destroy (message);
2638 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2639 const char *filename,
2640 notmuch_message_t **message_ret)
2643 const char *prefix = _find_prefix ("file-direntry");
2644 char *direntry, *term;
2645 Xapian::PostingIterator i, end;
2646 notmuch_status_t status;
2648 if (message_ret == NULL)
2649 return NOTMUCH_STATUS_NULL_POINTER;
2651 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2652 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2654 /* return NULL on any failure */
2655 *message_ret = NULL;
2657 local = talloc_new (notmuch);
2660 status = _notmuch_database_filename_to_direntry (
2661 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2662 if (status || !direntry)
2665 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2667 find_doc_ids_for_term (notmuch, term, &i, &end);
2670 notmuch_private_status_t private_status;
2672 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2674 if (*message_ret == NULL)
2675 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2677 } catch (const Xapian::Error &error) {
2678 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2679 error.get_msg().c_str());
2680 notmuch->exception_reported = TRUE;
2681 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2685 talloc_free (local);
2687 if (status && *message_ret) {
2688 notmuch_message_destroy (*message_ret);
2689 *message_ret = NULL;
2694 notmuch_string_list_t *
2695 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2696 Xapian::TermIterator &end,
2699 int prefix_len = strlen (prefix);
2700 notmuch_string_list_t *list;
2702 list = _notmuch_string_list_create (ctx);
2703 if (unlikely (list == NULL))
2706 for (i.skip_to (prefix); i != end; i++) {
2707 /* Terminate loop at first term without desired prefix. */
2708 if (strncmp ((*i).c_str (), prefix, prefix_len))
2711 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2718 notmuch_database_get_all_tags (notmuch_database_t *db)
2720 Xapian::TermIterator i, end;
2721 notmuch_string_list_t *tags;
2724 i = db->xapian_db->allterms_begin();
2725 end = db->xapian_db->allterms_end();
2726 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2727 _find_prefix ("tag"));
2728 _notmuch_string_list_sort (tags);
2729 return _notmuch_tags_create (db, tags);
2730 } catch (const Xapian::Error &error) {
2731 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2732 error.get_msg().c_str());
2733 db->exception_reported = TRUE;
2739 notmuch_database_status_string (const notmuch_database_t *notmuch)
2741 return notmuch->status_string;