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 "regexp-fields.h"
25 #include "string-util.h"
34 #include <glib.h> /* g_free, GPtrArray, GHashTable */
35 #include <glib-object.h> /* g_type_init */
37 #include <gmime/gmime.h> /* g_mime_init */
41 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
46 notmuch_field_flag_t flags;
49 #define NOTMUCH_DATABASE_VERSION 3
51 #define STRINGIFY(s) _SUB_STRINGIFY(s)
52 #define _SUB_STRINGIFY(s) #s
54 #if HAVE_XAPIAN_DB_RETRY_LOCK
55 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
57 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
60 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
62 * We currently have three different types of documents (mail, ghost,
63 * and directory) and also some metadata.
67 * A mail document is associated with a particular email message. It
68 * is stored in one or more files on disk (though only one has its
69 * content indexed) and is uniquely identified by its "id" field
70 * (which is generally the message ID). It is indexed with the
71 * following prefixed terms which the database uses to construct
74 * Single terms of given prefix:
78 * id: Unique ID of mail. This is from the Message-ID header
79 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
80 * If it's present and too long, then we use
81 * "notmuch-sha1-<sha1_sum_of_message_id>".
82 * If this header is not present, we use
83 * "notmuch-sha1-<sha1_sum_of_entire_file>".
85 * thread: The ID of the thread to which the mail belongs
87 * replyto: The ID from the In-Reply-To header of the mail (if any).
89 * Multiple terms of given prefix:
91 * reference: All message IDs from In-Reply-To and References
92 * headers in the message.
94 * tag: Any tags associated with this message by the user.
96 * file-direntry: A colon-separated pair of values
97 * (INTEGER:STRING), where INTEGER is the
98 * document ID of a directory document, and
99 * STRING is the name of a file within that
100 * directory for this mail message.
102 * property: Has a property with key=value
103 * FIXME: if no = is present, should match on any value
105 * A mail document also has four values:
107 * TIMESTAMP: The time_t value corresponding to the message's
110 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
112 * FROM: The value of the "From" header
114 * SUBJECT: The value of the "Subject" header
116 * LAST_MOD: The revision number as of the last tag or
119 * In addition, terms from the content of the message are added with
120 * "from", "to", "attachment", and "subject" prefixes for use by the
121 * user in searching. Similarly, terms from the path of the mail
122 * message are added with "folder" and "path" prefixes. But the
123 * database doesn't really care itself about any of these.
125 * The data portion of a mail document is empty.
127 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
128 * -----------------------------------------------
129 * A ghost mail document is like a mail document, but where we don't
130 * have the message content. These are used to track thread reference
131 * information for messages we haven't received.
133 * A ghost mail document has type: ghost; id and thread fields that
134 * are identical to the mail document fields; and a MESSAGE_ID value.
138 * A directory document is used by a client of the notmuch library to
139 * maintain data necessary to allow for efficient polling of mail
142 * All directory documents contain one term:
144 * directory: The directory path (relative to the database path)
145 * Or the SHA1 sum of the directory path (if the
146 * path itself is too long to fit in a Xapian
149 * And all directory documents for directories other than top-level
150 * directories also contain the following term:
152 * directory-direntry: A colon-separated pair of values
153 * (INTEGER:STRING), where INTEGER is the
154 * document ID of the parent directory
155 * document, and STRING is the name of this
156 * directory within that parent.
158 * All directory documents have a single value:
160 * TIMESTAMP: The mtime of the directory (at last scan)
162 * The data portion of a directory document contains the path of the
163 * directory (relative to the database path).
167 * Xapian allows us to store arbitrary name-value pairs as
168 * "metadata". We currently use the following metadata names with the
171 * version The database schema version, (which is distinct
172 * from both the notmuch package version (see
173 * notmuch --version) and the libnotmuch library
174 * version. The version is stored as an base-10
175 * ASCII integer. The initial database version
176 * was 1, (though a schema existed before that
177 * were no "version" database value existed at
178 * all). Successive versions are allocated as
179 * changes are made to the database (such as by
180 * indexing new fields).
182 * features The set of features supported by this
183 * database. This consists of a set of
184 * '\n'-separated lines, where each is a feature
185 * name, a '\t', and compatibility flags. If the
186 * compatibility flags contain 'w', then the
187 * opener must support this feature to safely
188 * write this database. If the compatibility
189 * flags contain 'r', then the opener must
190 * support this feature to read this database.
191 * Introduced in database version 3.
193 * last_thread_id The last thread ID generated. This is stored
194 * as a 16-byte hexadecimal ASCII representation
195 * of a 64-bit unsigned integer. The first ID
196 * generated is 1 and the value will be
197 * incremented for each thread ID.
199 * C* metadata keys starting with C indicate
200 * configuration data. It can be managed with the
201 * n_database_*config* API. There is a convention
202 * of hierarchical keys separated by '.' (e.g.
203 * query.notmuch stores the value for the named
204 * query 'notmuch'), but it is not enforced by the
210 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
211 * Instead, the database has the following additional database
214 * thread_id_* A pre-allocated thread ID for a particular
215 * message. This is actually an arbitrarily large
216 * family of metadata name. Any particular name is
217 * formed by concatenating "thread_id_" with a message
218 * ID (or the SHA1 sum of a message ID if it is very
219 * long---see description of 'id' in the mail
220 * document). The value stored is a thread ID.
222 * These thread ID metadata values are stored
223 * whenever a message references a parent message
224 * that does not yet exist in the database. A
225 * thread ID will be allocated and stored, and if
226 * the message is later added, the stored thread
227 * ID will be used (and the metadata value will
230 * Even before a message is added, it's
231 * pre-allocated thread ID is useful so that all
232 * descendant messages that reference this common
233 * parent can be recognized as belonging to the
237 /* With these prefix values we follow the conventions published here:
239 * https://xapian.org/docs/omega/termprefixes.html
241 * as much as makes sense. Note that I took some liberty in matching
242 * the reserved prefix values to notmuch concepts, (for example, 'G'
243 * is documented as "newsGroup (or similar entity - e.g. a web forum
244 * name)", for which I think the thread is the closest analogue in
245 * notmuch. This in spite of the fact that we will eventually be
246 * storing mailing-list messages where 'G' for "mailing list name"
247 * might be even a closer analogue. I'm treating the single-character
248 * prefixes preferentially for core notmuch concepts (which will be
249 * nearly universal to all mail messages).
253 prefix_t prefix_table[] = {
254 /* name term prefix flags */
255 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
256 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
257 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
258 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
259 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
260 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
261 { "thread", "G", NOTMUCH_FIELD_EXTERNAL },
262 { "tag", "K", NOTMUCH_FIELD_EXTERNAL },
263 { "is", "K", NOTMUCH_FIELD_EXTERNAL },
264 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
265 { "path", "P", NOTMUCH_FIELD_EXTERNAL },
266 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
268 * Unconditionally add ':' to reduce potential ambiguity with
269 * overlapping prefixes and/or terms that start with capital
270 * letters. See Xapian document termprefixes.html for related
273 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL },
274 #if HAVE_XAPIAN_FIELD_PROCESSOR
275 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
276 NOTMUCH_FIELD_PROCESSOR },
277 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
278 NOTMUCH_FIELD_PROCESSOR },
280 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
281 NOTMUCH_FIELD_PROBABILISTIC |
282 NOTMUCH_FIELD_PROCESSOR },
283 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
284 NOTMUCH_FIELD_PROBABILISTIC },
285 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
286 NOTMUCH_FIELD_PROBABILISTIC },
287 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
288 NOTMUCH_FIELD_PROBABILISTIC },
289 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
290 NOTMUCH_FIELD_PROBABILISTIC |
291 NOTMUCH_FIELD_PROCESSOR},
295 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
297 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
298 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
300 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
303 #if HAVE_XAPIAN_FIELD_PROCESSOR
305 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
307 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
308 Xapian::FieldProcessor *fp;
310 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
311 fp = (new DateFieldProcessor())->release ();
312 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
313 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
315 fp = (new RegexpFieldProcessor (prefix->name, *notmuch->query_parser, notmuch))->release ();
317 /* we treat all field-processor fields as boolean in order to get the raw input */
318 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
320 _setup_query_field_default (prefix, notmuch);
325 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
327 _setup_query_field_default (prefix, notmuch);
332 _find_prefix (const char *name)
336 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
337 if (strcmp (name, prefix_table[i].name) == 0)
338 return prefix_table[i].prefix;
341 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
346 static const struct {
347 /* NOTMUCH_FEATURE_* value. */
348 _notmuch_features value;
349 /* Feature name as it appears in the database. This name should
350 * be appropriate for displaying to the user if an older version
351 * of notmuch doesn't support this feature. */
353 /* Compatibility flags when this feature is declared. */
355 } feature_names[] = {
356 { NOTMUCH_FEATURE_FILE_TERMS,
357 "multiple paths per message", "rw" },
358 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
359 "relative directory paths", "rw" },
360 /* Header values are not required for reading a database because a
361 * reader can just refer to the message file. */
362 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
363 "from/subject/message-ID in database", "w" },
364 { NOTMUCH_FEATURE_BOOL_FOLDER,
365 "exact folder:/path: search", "rw" },
366 { NOTMUCH_FEATURE_GHOSTS,
367 "mail documents for missing messages", "w"},
368 /* Knowledge of the index mime-types are not required for reading
369 * a database because a reader will just be unable to query
371 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
372 "indexed MIME types", "w"},
373 { NOTMUCH_FEATURE_LAST_MOD,
374 "modification tracking", "w"},
378 notmuch_status_to_string (notmuch_status_t status)
381 case NOTMUCH_STATUS_SUCCESS:
382 return "No error occurred";
383 case NOTMUCH_STATUS_OUT_OF_MEMORY:
384 return "Out of memory";
385 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
386 return "Attempt to write to a read-only database";
387 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
388 return "A Xapian exception occurred";
389 case NOTMUCH_STATUS_FILE_ERROR:
390 return "Something went wrong trying to read or write a file";
391 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
392 return "File is not an email";
393 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
394 return "Message ID is identical to a message in database";
395 case NOTMUCH_STATUS_NULL_POINTER:
396 return "Erroneous NULL pointer";
397 case NOTMUCH_STATUS_TAG_TOO_LONG:
398 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
399 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
400 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
401 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
402 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
403 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
404 return "Unsupported operation";
405 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
406 return "Operation requires a database upgrade";
407 case NOTMUCH_STATUS_PATH_ERROR:
408 return "Path supplied is illegal for this function";
410 case NOTMUCH_STATUS_LAST_STATUS:
411 return "Unknown error status value";
416 _notmuch_database_log (notmuch_database_t *notmuch,
422 va_start (va_args, format);
424 if (notmuch->status_string)
425 talloc_free (notmuch->status_string);
427 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
432 _notmuch_database_log_append (notmuch_database_t *notmuch,
438 va_start (va_args, format);
440 if (notmuch->status_string)
441 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
443 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
449 find_doc_ids_for_term (notmuch_database_t *notmuch,
451 Xapian::PostingIterator *begin,
452 Xapian::PostingIterator *end)
454 *begin = notmuch->xapian_db->postlist_begin (term);
456 *end = notmuch->xapian_db->postlist_end (term);
460 find_doc_ids (notmuch_database_t *notmuch,
461 const char *prefix_name,
463 Xapian::PostingIterator *begin,
464 Xapian::PostingIterator *end)
468 term = talloc_asprintf (notmuch, "%s%s",
469 _find_prefix (prefix_name), value);
471 find_doc_ids_for_term (notmuch, term, begin, end);
476 notmuch_private_status_t
477 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
478 const char *prefix_name,
480 unsigned int *doc_id)
482 Xapian::PostingIterator i, end;
484 find_doc_ids (notmuch, prefix_name, value, &i, &end);
488 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
493 #if DEBUG_DATABASE_SANITY
497 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
501 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
504 static Xapian::Document
505 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
507 return notmuch->xapian_db->get_document (doc_id);
510 /* Generate a compressed version of 'message_id' of the form:
512 * notmuch-sha1-<sha1_sum_of_message_id>
515 _notmuch_message_id_compressed (void *ctx, const char *message_id)
517 char *sha1, *compressed;
519 sha1 = _notmuch_sha1_of_string (message_id);
521 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
528 notmuch_database_find_message (notmuch_database_t *notmuch,
529 const char *message_id,
530 notmuch_message_t **message_ret)
532 notmuch_private_status_t status;
535 if (message_ret == NULL)
536 return NOTMUCH_STATUS_NULL_POINTER;
538 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
539 message_id = _notmuch_message_id_compressed (notmuch, message_id);
542 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
543 message_id, &doc_id);
545 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
548 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
550 if (*message_ret == NULL)
551 return NOTMUCH_STATUS_OUT_OF_MEMORY;
554 return NOTMUCH_STATUS_SUCCESS;
555 } catch (const Xapian::Error &error) {
556 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
557 error.get_msg().c_str());
558 notmuch->exception_reported = TRUE;
560 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
564 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
565 * a (potentially nested) parenthesized sequence with '\' used to
566 * escape any character (including parentheses).
568 * If the sequence to be skipped continues to the end of the string,
569 * then 'str' will be left pointing at the final terminating '\0'
573 skip_space_and_comments (const char **str)
578 while (*s && (isspace (*s) || *s == '(')) {
579 while (*s && isspace (*s))
584 while (*s && nesting) {
587 } else if (*s == ')') {
589 } else if (*s == '\\') {
601 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
602 * comments, and the '<' and '>' delimiters.
604 * If not NULL, then *next will be made to point to the first character
605 * not parsed, (possibly pointing to the final '\0' terminator.
607 * Returns a newly talloc'ed string belonging to 'ctx'.
609 * Returns NULL if there is any error parsing the message-id. */
611 _parse_message_id (void *ctx, const char *message_id, const char **next)
616 if (message_id == NULL || *message_id == '\0')
621 skip_space_and_comments (&s);
623 /* Skip any unstructured text as well. */
624 while (*s && *s != '<')
635 skip_space_and_comments (&s);
638 while (*end && *end != '>')
647 if (end > s && *end == '>')
652 result = talloc_strndup (ctx, s, end - s + 1);
654 /* Finally, collapse any whitespace that is within the message-id
660 for (r = result, len = strlen (r); *r; r++, len--)
661 if (*r == ' ' || *r == '\t')
662 memmove (r, r+1, len);
668 /* Parse a References header value, putting a (talloc'ed under 'ctx')
669 * copy of each referenced message-id into 'hash'.
671 * We explicitly avoid including any reference identical to
672 * 'message_id' in the result (to avoid mass confusion when a single
673 * message references itself cyclically---and yes, mail messages are
674 * not infrequent in the wild that do this---don't ask me why).
676 * Return the last reference parsed, if it is not equal to message_id.
679 parse_references (void *ctx,
680 const char *message_id,
684 char *ref, *last_ref = NULL;
686 if (refs == NULL || *refs == '\0')
690 ref = _parse_message_id (ctx, refs, &refs);
692 if (ref && strcmp (ref, message_id)) {
693 g_hash_table_add (hash, ref);
698 /* The return value of this function is used to add a parent
699 * reference to the database. We should avoid making a message
700 * its own parent, thus the above check.
702 return talloc_strdup(ctx, last_ref);
706 notmuch_database_create (const char *path, notmuch_database_t **database)
708 char *status_string = NULL;
709 notmuch_status_t status;
711 status = notmuch_database_create_verbose (path, database,
715 fputs (status_string, stderr);
716 free (status_string);
723 notmuch_database_create_verbose (const char *path,
724 notmuch_database_t **database,
725 char **status_string)
727 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
728 notmuch_database_t *notmuch = NULL;
729 char *notmuch_path = NULL;
730 char *message = NULL;
735 message = strdup ("Error: Cannot create a database for a NULL path.\n");
736 status = NOTMUCH_STATUS_NULL_POINTER;
740 if (path[0] != '/') {
741 message = strdup ("Error: Database path must be absolute.\n");
742 status = NOTMUCH_STATUS_PATH_ERROR;
746 err = stat (path, &st);
748 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
749 path, strerror (errno)));
750 status = NOTMUCH_STATUS_FILE_ERROR;
754 if (! S_ISDIR (st.st_mode)) {
755 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
756 "Not a directory.\n",
758 status = NOTMUCH_STATUS_FILE_ERROR;
762 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
764 err = mkdir (notmuch_path, 0755);
767 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
768 notmuch_path, strerror (errno)));
769 status = NOTMUCH_STATUS_FILE_ERROR;
773 status = notmuch_database_open_verbose (path,
774 NOTMUCH_DATABASE_MODE_READ_WRITE,
779 /* Upgrade doesn't add these feature to existing databases, but
780 * new databases have them. */
781 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
782 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
784 status = notmuch_database_upgrade (notmuch, NULL, NULL);
786 notmuch_database_close(notmuch);
792 talloc_free (notmuch_path);
796 *status_string = message;
803 talloc_free (notmuch);
808 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
810 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
811 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
812 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
815 return NOTMUCH_STATUS_SUCCESS;
818 /* Allocate a revision number for the next change. */
820 _notmuch_database_new_revision (notmuch_database_t *notmuch)
822 unsigned long new_revision = notmuch->revision + 1;
824 /* If we're in an atomic section, hold off on updating the
825 * committed revision number until we commit the atomic section.
827 if (notmuch->atomic_nesting)
828 notmuch->atomic_dirty = TRUE;
830 notmuch->revision = new_revision;
835 /* Parse a database features string from the given database version.
836 * Returns the feature bit set.
838 * For version < 3, this ignores the features string and returns a
839 * hard-coded set of features.
841 * If there are unrecognized features that are required to open the
842 * database in mode (which should be 'r' or 'w'), return a
843 * comma-separated list of unrecognized but required features in
844 * *incompat_out suitable for presenting to the user. *incompat_out
845 * will be allocated from ctx.
847 static _notmuch_features
848 _parse_features (const void *ctx, const char *features, unsigned int version,
849 char mode, char **incompat_out)
851 _notmuch_features res = static_cast<_notmuch_features>(0);
852 unsigned int namelen, i;
856 /* Prior to database version 3, features were implied by the
859 return NOTMUCH_FEATURES_V0;
860 else if (version == 1)
861 return NOTMUCH_FEATURES_V1;
862 else if (version == 2)
863 return NOTMUCH_FEATURES_V2;
865 /* Parse the features string */
866 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
867 flags = strchr (features, '\t');
868 if (! flags || flags > features + llen)
870 namelen = flags - features;
872 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
873 if (strlen (feature_names[i].name) == namelen &&
874 strncmp (feature_names[i].name, features, namelen) == 0) {
875 res |= feature_names[i].value;
880 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
881 /* Unrecognized feature */
882 const char *have = strchr (flags, mode);
883 if (have && have < features + llen) {
884 /* This feature is required to access this database in
885 * 'mode', but we don't understand it. */
887 *incompat_out = talloc_strdup (ctx, "");
888 *incompat_out = talloc_asprintf_append_buffer (
889 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
899 _print_features (const void *ctx, unsigned int features)
902 char *res = talloc_strdup (ctx, "");
904 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
905 if (features & feature_names[i].value)
906 res = talloc_asprintf_append_buffer (
907 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
913 notmuch_database_open (const char *path,
914 notmuch_database_mode_t mode,
915 notmuch_database_t **database)
917 char *status_string = NULL;
918 notmuch_status_t status;
920 status = notmuch_database_open_verbose (path, mode, database,
924 fputs (status_string, stderr);
925 free (status_string);
932 notmuch_database_open_verbose (const char *path,
933 notmuch_database_mode_t mode,
934 notmuch_database_t **database,
935 char **status_string)
937 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
938 void *local = talloc_new (NULL);
939 notmuch_database_t *notmuch = NULL;
940 char *notmuch_path, *xapian_path, *incompat_features;
941 char *message = NULL;
944 unsigned int i, version;
945 static int initialized = 0;
948 message = strdup ("Error: Cannot open a database for a NULL path.\n");
949 status = NOTMUCH_STATUS_NULL_POINTER;
953 if (path[0] != '/') {
954 message = strdup ("Error: Database path must be absolute.\n");
955 status = NOTMUCH_STATUS_PATH_ERROR;
959 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
960 message = strdup ("Out of memory\n");
961 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
965 err = stat (notmuch_path, &st);
967 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
968 notmuch_path, strerror (errno)));
969 status = NOTMUCH_STATUS_FILE_ERROR;
973 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
974 message = strdup ("Out of memory\n");
975 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
979 /* Initialize the GLib type system and threads */
980 #if !GLIB_CHECK_VERSION(2, 35, 1)
984 /* Initialize gmime */
986 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
990 notmuch = talloc_zero (NULL, notmuch_database_t);
991 notmuch->exception_reported = FALSE;
992 notmuch->status_string = NULL;
993 notmuch->path = talloc_strdup (notmuch, path);
995 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
996 notmuch->path[strlen (notmuch->path) - 1] = '\0';
998 notmuch->mode = mode;
999 notmuch->atomic_nesting = 0;
1002 string last_thread_id;
1005 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
1006 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
1009 notmuch->xapian_db = new Xapian::Database (xapian_path);
1012 /* Check version. As of database version 3, we represent
1013 * changes in terms of features, so assume a version bump
1014 * means a dramatically incompatible change. */
1015 version = notmuch_database_get_version (notmuch);
1016 if (version > NOTMUCH_DATABASE_VERSION) {
1017 IGNORE_RESULT (asprintf (&message,
1018 "Error: Notmuch database at %s\n"
1019 " has a newer database format version (%u) than supported by this\n"
1020 " version of notmuch (%u).\n",
1021 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
1022 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1023 notmuch_database_destroy (notmuch);
1025 status = NOTMUCH_STATUS_FILE_ERROR;
1029 /* Check features. */
1030 incompat_features = NULL;
1031 notmuch->features = _parse_features (
1032 local, notmuch->xapian_db->get_metadata ("features").c_str (),
1033 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1034 &incompat_features);
1035 if (incompat_features) {
1036 IGNORE_RESULT (asprintf (&message,
1037 "Error: Notmuch database at %s\n"
1038 " requires features (%s)\n"
1039 " not supported by this version of notmuch.\n",
1040 notmuch_path, incompat_features));
1041 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1042 notmuch_database_destroy (notmuch);
1044 status = NOTMUCH_STATUS_FILE_ERROR;
1048 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1049 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1050 if (last_thread_id.empty ()) {
1051 notmuch->last_thread_id = 0;
1056 str = last_thread_id.c_str ();
1057 notmuch->last_thread_id = strtoull (str, &end, 16);
1059 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1062 /* Get current highest revision number. */
1063 last_mod = notmuch->xapian_db->get_value_upper_bound (
1064 NOTMUCH_VALUE_LAST_MOD);
1065 if (last_mod.empty ())
1066 notmuch->revision = 0;
1068 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1069 notmuch->uuid = talloc_strdup (
1070 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1072 notmuch->query_parser = new Xapian::QueryParser;
1073 notmuch->term_gen = new Xapian::TermGenerator;
1074 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1075 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1076 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1077 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1079 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1080 notmuch->query_parser->set_database (*notmuch->xapian_db);
1081 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1082 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1083 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1084 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1085 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1087 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1088 const prefix_t *prefix = &prefix_table[i];
1089 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1090 _setup_query_field (prefix, notmuch);
1093 } catch (const Xapian::Error &error) {
1094 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1095 error.get_msg().c_str()));
1096 notmuch_database_destroy (notmuch);
1098 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1102 talloc_free (local);
1106 *status_string = message;
1112 *database = notmuch;
1114 talloc_free (notmuch);
1119 notmuch_database_close (notmuch_database_t *notmuch)
1121 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1123 /* Many Xapian objects (and thus notmuch objects) hold references to
1124 * the database, so merely deleting the database may not suffice to
1125 * close it. Thus, we explicitly close it here. */
1126 if (notmuch->xapian_db != NULL) {
1128 /* If there's an outstanding transaction, it's unclear if
1129 * closing the Xapian database commits everything up to
1130 * that transaction, or may discard committed (but
1131 * unflushed) transactions. To be certain, explicitly
1132 * cancel any outstanding transaction before closing. */
1133 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1134 notmuch->atomic_nesting)
1135 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1136 ->cancel_transaction ();
1138 /* Close the database. This implicitly flushes
1139 * outstanding changes. */
1140 notmuch->xapian_db->close();
1141 } catch (const Xapian::Error &error) {
1142 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1143 if (! notmuch->exception_reported) {
1144 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1145 error.get_msg().c_str());
1150 delete notmuch->term_gen;
1151 notmuch->term_gen = NULL;
1152 delete notmuch->query_parser;
1153 notmuch->query_parser = NULL;
1154 delete notmuch->xapian_db;
1155 notmuch->xapian_db = NULL;
1156 delete notmuch->value_range_processor;
1157 notmuch->value_range_processor = NULL;
1158 delete notmuch->date_range_processor;
1159 notmuch->date_range_processor = NULL;
1160 delete notmuch->last_mod_range_processor;
1161 notmuch->last_mod_range_processor = NULL;
1167 _notmuch_database_reopen (notmuch_database_t *notmuch)
1169 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1170 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1173 notmuch->xapian_db->reopen ();
1174 } catch (const Xapian::Error &error) {
1175 if (! notmuch->exception_reported) {
1176 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1177 error.get_msg ().c_str ());
1178 notmuch->exception_reported = TRUE;
1180 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1185 return NOTMUCH_STATUS_SUCCESS;
1189 unlink_cb (const char *path,
1190 unused (const struct stat *sb),
1192 unused (struct FTW *ftw))
1194 return remove (path);
1198 rmtree (const char *path)
1200 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1203 class NotmuchCompactor : public Xapian::Compactor
1205 notmuch_compact_status_cb_t status_cb;
1206 void *status_closure;
1209 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1210 status_cb (cb), status_closure (closure) { }
1213 set_status (const std::string &table, const std::string &status)
1217 if (status_cb == NULL)
1220 if (status.length () == 0)
1221 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1223 msg = talloc_asprintf (NULL, " %s", status.c_str());
1229 status_cb (msg, status_closure);
1234 /* Compacts the given database, optionally saving the original database
1235 * in backup_path. Additionally, a callback function can be provided to
1236 * give the user feedback on the progress of the (likely long-lived)
1237 * compaction process.
1239 * The backup path must point to a directory on the same volume as the
1240 * original database. Passing a NULL backup_path will result in the
1241 * uncompacted database being deleted after compaction has finished.
1242 * Note that the database write lock will be held during the
1243 * compaction process to protect data integrity.
1246 notmuch_database_compact (const char *path,
1247 const char *backup_path,
1248 notmuch_compact_status_cb_t status_cb,
1252 char *notmuch_path, *xapian_path, *compact_xapian_path;
1253 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1254 notmuch_database_t *notmuch = NULL;
1255 struct stat statbuf;
1256 notmuch_bool_t keep_backup;
1257 char *message = NULL;
1259 local = talloc_new (NULL);
1261 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1263 ret = notmuch_database_open_verbose (path,
1264 NOTMUCH_DATABASE_MODE_READ_WRITE,
1268 if (status_cb) status_cb (message, closure);
1272 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1273 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1277 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1278 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1282 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1283 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1287 if (backup_path == NULL) {
1288 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1289 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1292 keep_backup = FALSE;
1298 if (stat (backup_path, &statbuf) != -1) {
1299 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1300 ret = NOTMUCH_STATUS_FILE_ERROR;
1303 if (errno != ENOENT) {
1304 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1306 ret = NOTMUCH_STATUS_FILE_ERROR;
1310 /* Unconditionally attempt to remove old work-in-progress database (if
1311 * any). This is "protected" by database lock. If this fails due to write
1312 * errors (etc), the following code will fail and provide error message.
1314 (void) rmtree (compact_xapian_path);
1317 NotmuchCompactor compactor (status_cb, closure);
1319 compactor.set_renumber (false);
1320 compactor.add_source (xapian_path);
1321 compactor.set_destdir (compact_xapian_path);
1322 compactor.compact ();
1323 } catch (const Xapian::Error &error) {
1324 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1325 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1329 if (rename (xapian_path, backup_path)) {
1330 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1331 xapian_path, backup_path, strerror (errno));
1332 ret = NOTMUCH_STATUS_FILE_ERROR;
1336 if (rename (compact_xapian_path, xapian_path)) {
1337 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1338 compact_xapian_path, xapian_path, strerror (errno));
1339 ret = NOTMUCH_STATUS_FILE_ERROR;
1343 if (! keep_backup) {
1344 if (rmtree (backup_path)) {
1345 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1346 backup_path, strerror (errno));
1347 ret = NOTMUCH_STATUS_FILE_ERROR;
1354 notmuch_status_t ret2;
1356 const char *str = notmuch_database_status_string (notmuch);
1357 if (status_cb && str)
1358 status_cb (str, closure);
1360 ret2 = notmuch_database_destroy (notmuch);
1362 /* don't clobber previous error status */
1363 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1367 talloc_free (local);
1373 notmuch_database_destroy (notmuch_database_t *notmuch)
1375 notmuch_status_t status;
1377 status = notmuch_database_close (notmuch);
1378 talloc_free (notmuch);
1384 notmuch_database_get_path (notmuch_database_t *notmuch)
1386 return notmuch->path;
1390 notmuch_database_get_version (notmuch_database_t *notmuch)
1392 unsigned int version;
1393 string version_string;
1397 version_string = notmuch->xapian_db->get_metadata ("version");
1398 if (version_string.empty ())
1401 str = version_string.c_str ();
1402 if (str == NULL || *str == '\0')
1405 version = strtoul (str, &end, 10);
1407 INTERNAL_ERROR ("Malformed database version: %s", str);
1413 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1415 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1416 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1417 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1420 static volatile sig_atomic_t do_progress_notify = 0;
1423 handle_sigalrm (unused (int signal))
1425 do_progress_notify = 1;
1428 /* Upgrade the current database.
1430 * After opening a database in read-write mode, the client should
1431 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1432 * if so, upgrade with this function before making any modifications.
1434 * The optional progress_notify callback can be used by the caller to
1435 * provide progress indication to the user. If non-NULL it will be
1436 * called periodically with 'count' as the number of messages upgraded
1437 * so far and 'total' the overall number of messages that will be
1441 notmuch_database_upgrade (notmuch_database_t *notmuch,
1442 void (*progress_notify) (void *closure,
1446 void *local = talloc_new (NULL);
1447 Xapian::TermIterator t, t_end;
1448 Xapian::WritableDatabase *db;
1449 struct sigaction action;
1450 struct itimerval timerval;
1451 notmuch_bool_t timer_is_active = FALSE;
1452 enum _notmuch_features target_features, new_features;
1453 notmuch_status_t status;
1454 notmuch_private_status_t private_status;
1455 notmuch_query_t *query = NULL;
1456 unsigned int count = 0, total = 0;
1458 status = _notmuch_database_ensure_writable (notmuch);
1462 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1464 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1465 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1467 if (! notmuch_database_needs_upgrade (notmuch))
1468 return NOTMUCH_STATUS_SUCCESS;
1470 if (progress_notify) {
1471 /* Set up our handler for SIGALRM */
1472 memset (&action, 0, sizeof (struct sigaction));
1473 action.sa_handler = handle_sigalrm;
1474 sigemptyset (&action.sa_mask);
1475 action.sa_flags = SA_RESTART;
1476 sigaction (SIGALRM, &action, NULL);
1478 /* Then start a timer to send SIGALRM once per second. */
1479 timerval.it_interval.tv_sec = 1;
1480 timerval.it_interval.tv_usec = 0;
1481 timerval.it_value.tv_sec = 1;
1482 timerval.it_value.tv_usec = 0;
1483 setitimer (ITIMER_REAL, &timerval, NULL);
1485 timer_is_active = TRUE;
1488 /* Figure out how much total work we need to do. */
1490 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1491 NOTMUCH_FEATURE_LAST_MOD)) {
1492 query = notmuch_query_create (notmuch, "");
1495 status = notmuch_query_count_messages_st (query, &msg_count);
1500 notmuch_query_destroy (query);
1503 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1504 t_end = db->allterms_end ("XTIMESTAMP");
1505 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1508 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1509 /* The ghost message upgrade converts all thread_id_*
1510 * metadata values into ghost message documents. */
1511 t_end = db->metadata_keys_end ("thread_id_");
1512 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1516 /* Perform the upgrade in a transaction. */
1517 db->begin_transaction (true);
1519 /* Set the target features so we write out changes in the desired
1521 notmuch->features = target_features;
1523 /* Perform per-message upgrades. */
1525 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1526 NOTMUCH_FEATURE_LAST_MOD)) {
1527 notmuch_messages_t *messages;
1528 notmuch_message_t *message;
1531 query = notmuch_query_create (notmuch, "");
1533 status = notmuch_query_search_messages_st (query, &messages);
1537 notmuch_messages_valid (messages);
1538 notmuch_messages_move_to_next (messages))
1540 if (do_progress_notify) {
1541 progress_notify (closure, (double) count / total);
1542 do_progress_notify = 0;
1545 message = notmuch_messages_get (messages);
1547 /* Before version 1, each message document had its
1548 * filename in the data field. Copy that into the new
1549 * format by calling notmuch_message_add_filename.
1551 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1552 filename = _notmuch_message_talloc_copy_data (message);
1553 if (filename && *filename != '\0') {
1554 _notmuch_message_add_filename (message, filename);
1555 _notmuch_message_clear_data (message);
1557 talloc_free (filename);
1560 /* Prior to version 2, the "folder:" prefix was
1561 * probabilistic and stemmed. Change it to the current
1562 * boolean prefix. Add "path:" prefixes while at it.
1564 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1565 _notmuch_message_upgrade_folder (message);
1567 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1568 * track modification revisions. Give all messages the
1569 * next available revision; since we just started tracking
1570 * revisions for this database, that will be 1.
1572 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1573 _notmuch_message_upgrade_last_mod (message);
1575 _notmuch_message_sync (message);
1577 notmuch_message_destroy (message);
1582 notmuch_query_destroy (query);
1586 /* Perform per-directory upgrades. */
1588 /* Before version 1 we stored directory timestamps in
1589 * XTIMESTAMP documents instead of the current XDIRECTORY
1590 * documents. So copy those as well. */
1591 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1592 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1594 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1598 Xapian::PostingIterator p, p_end;
1599 std::string term = *t;
1601 p_end = notmuch->xapian_db->postlist_end (term);
1603 for (p = notmuch->xapian_db->postlist_begin (term);
1607 Xapian::Document document;
1609 notmuch_directory_t *directory;
1611 if (do_progress_notify) {
1612 progress_notify (closure, (double) count / total);
1613 do_progress_notify = 0;
1616 document = find_document_for_doc_id (notmuch, *p);
1617 mtime = Xapian::sortable_unserialise (
1618 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1620 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1621 NOTMUCH_FIND_CREATE, &status);
1622 notmuch_directory_set_mtime (directory, mtime);
1623 notmuch_directory_destroy (directory);
1625 db->delete_document (*p);
1632 /* Perform metadata upgrades. */
1634 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1635 * messages were stored as database metadata. Change these to
1638 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1639 notmuch_message_t *message;
1640 std::string message_id, thread_id;
1642 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1643 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1645 if (do_progress_notify) {
1646 progress_notify (closure, (double) count / total);
1647 do_progress_notify = 0;
1650 message_id = (*t).substr (
1651 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1652 thread_id = db->get_metadata (*t);
1654 /* Create ghost message */
1655 message = _notmuch_message_create_for_message_id (
1656 notmuch, message_id.c_str (), &private_status);
1657 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1658 /* Document already exists; ignore the stored thread ID */
1659 } else if (private_status ==
1660 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1661 private_status = _notmuch_message_initialize_ghost (
1662 message, thread_id.c_str ());
1663 if (! private_status)
1664 _notmuch_message_sync (message);
1667 if (private_status) {
1668 _notmuch_database_log (notmuch,
1669 "Upgrade failed while creating ghost messages.\n");
1670 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1674 /* Clear saved metadata thread ID */
1675 db->set_metadata (*t, "");
1681 status = NOTMUCH_STATUS_SUCCESS;
1682 db->set_metadata ("features", _print_features (local, notmuch->features));
1683 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1686 if (status == NOTMUCH_STATUS_SUCCESS)
1687 db->commit_transaction ();
1689 db->cancel_transaction ();
1691 if (timer_is_active) {
1692 /* Now stop the timer. */
1693 timerval.it_interval.tv_sec = 0;
1694 timerval.it_interval.tv_usec = 0;
1695 timerval.it_value.tv_sec = 0;
1696 timerval.it_value.tv_usec = 0;
1697 setitimer (ITIMER_REAL, &timerval, NULL);
1699 /* And disable the signal handler. */
1700 action.sa_handler = SIG_IGN;
1701 sigaction (SIGALRM, &action, NULL);
1705 notmuch_query_destroy (query);
1707 talloc_free (local);
1712 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1714 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1715 notmuch->atomic_nesting > 0)
1718 if (notmuch_database_needs_upgrade (notmuch))
1719 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1722 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1723 } catch (const Xapian::Error &error) {
1724 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1725 error.get_msg().c_str());
1726 notmuch->exception_reported = TRUE;
1727 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1731 notmuch->atomic_nesting++;
1732 return NOTMUCH_STATUS_SUCCESS;
1736 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1738 Xapian::WritableDatabase *db;
1740 if (notmuch->atomic_nesting == 0)
1741 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1743 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1744 notmuch->atomic_nesting > 1)
1747 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1749 db->commit_transaction ();
1751 /* This is a hack for testing. Xapian never flushes on a
1752 * non-flushed commit, even if the flush threshold is 1.
1753 * However, we rely on flushing to test atomicity. */
1754 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1755 if (thresh && atoi (thresh) == 1)
1757 } catch (const Xapian::Error &error) {
1758 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1759 error.get_msg().c_str());
1760 notmuch->exception_reported = TRUE;
1761 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1764 if (notmuch->atomic_dirty) {
1765 ++notmuch->revision;
1766 notmuch->atomic_dirty = FALSE;
1770 notmuch->atomic_nesting--;
1771 return NOTMUCH_STATUS_SUCCESS;
1775 notmuch_database_get_revision (notmuch_database_t *notmuch,
1779 *uuid = notmuch->uuid;
1780 return notmuch->revision;
1783 /* We allow the user to use arbitrarily long paths for directories. But
1784 * we have a term-length limit. So if we exceed that, we'll use the
1785 * SHA-1 of the path for the database term.
1787 * Note: This function may return the original value of 'path'. If it
1788 * does not, then the caller is responsible to free() the returned
1792 _notmuch_database_get_directory_db_path (const char *path)
1794 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1796 if (term_len > NOTMUCH_TERM_MAX)
1797 return _notmuch_sha1_of_string (path);
1802 /* Given a path, split it into two parts: the directory part is all
1803 * components except for the last, and the basename is that last
1804 * component. Getting the return-value for either part is optional
1805 * (the caller can pass NULL).
1807 * The original 'path' can represent either a regular file or a
1808 * directory---the splitting will be carried out in the same way in
1809 * either case. Trailing slashes on 'path' will be ignored, and any
1810 * cases of multiple '/' characters appearing in series will be
1811 * treated as a single '/'.
1813 * Allocation (if any) will have 'ctx' as the talloc owner. But
1814 * pointers will be returned within the original path string whenever
1817 * Note: If 'path' is non-empty and contains no non-trailing slash,
1818 * (that is, consists of a filename with no parent directory), then
1819 * the directory returned will be an empty string. However, if 'path'
1820 * is an empty string, then both directory and basename will be
1824 _notmuch_database_split_path (void *ctx,
1826 const char **directory,
1827 const char **basename)
1831 if (path == NULL || *path == '\0') {
1836 return NOTMUCH_STATUS_SUCCESS;
1839 /* Find the last slash (not counting a trailing slash), if any. */
1841 slash = path + strlen (path) - 1;
1843 /* First, skip trailing slashes. */
1844 while (slash != path && *slash == '/')
1847 /* Then, find a slash. */
1848 while (slash != path && *slash != '/') {
1855 /* Finally, skip multiple slashes. */
1856 while (slash != path && *(slash - 1) == '/')
1859 if (slash == path) {
1861 *directory = talloc_strdup (ctx, "");
1866 *directory = talloc_strndup (ctx, path, slash - path);
1869 return NOTMUCH_STATUS_SUCCESS;
1872 /* Find the document ID of the specified directory.
1874 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1875 * created if one does not exist for 'path'. Otherwise, if the
1876 * directory document does not exist, this sets *directory_id to
1877 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1880 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1882 notmuch_find_flags_t flags,
1883 unsigned int *directory_id)
1885 notmuch_directory_t *directory;
1886 notmuch_status_t status;
1890 return NOTMUCH_STATUS_SUCCESS;
1893 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1894 if (status || !directory) {
1899 *directory_id = _notmuch_directory_get_document_id (directory);
1901 notmuch_directory_destroy (directory);
1903 return NOTMUCH_STATUS_SUCCESS;
1907 _notmuch_database_get_directory_path (void *ctx,
1908 notmuch_database_t *notmuch,
1909 unsigned int doc_id)
1911 Xapian::Document document;
1913 document = find_document_for_doc_id (notmuch, doc_id);
1915 return talloc_strdup (ctx, document.get_data ().c_str ());
1918 /* Given a legal 'filename' for the database, (either relative to
1919 * database path or absolute with initial components identical to
1920 * database path), return a new string (with 'ctx' as the talloc
1921 * owner) suitable for use as a direntry term value.
1923 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1924 * will be created in the database as needed. Otherwise, if the
1925 * necessary directory documents do not exist, this sets
1926 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1929 _notmuch_database_filename_to_direntry (void *ctx,
1930 notmuch_database_t *notmuch,
1931 const char *filename,
1932 notmuch_find_flags_t flags,
1935 const char *relative, *directory, *basename;
1936 Xapian::docid directory_id;
1937 notmuch_status_t status;
1939 relative = _notmuch_database_relative_path (notmuch, filename);
1941 status = _notmuch_database_split_path (ctx, relative,
1942 &directory, &basename);
1946 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1948 if (status || directory_id == (unsigned int)-1) {
1953 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1955 return NOTMUCH_STATUS_SUCCESS;
1958 /* Given a legal 'path' for the database, return the relative path.
1960 * The return value will be a pointer to the original path contents,
1961 * and will be either the original string (if 'path' was relative) or
1962 * a portion of the string (if path was absolute and begins with the
1966 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1969 const char *db_path, *relative;
1970 unsigned int db_path_len;
1972 db_path = notmuch_database_get_path (notmuch);
1973 db_path_len = strlen (db_path);
1977 if (*relative == '/') {
1978 while (*relative == '/' && *(relative+1) == '/')
1981 if (strncmp (relative, db_path, db_path_len) == 0)
1983 relative += db_path_len;
1984 while (*relative == '/')
1993 notmuch_database_get_directory (notmuch_database_t *notmuch,
1995 notmuch_directory_t **directory)
1997 notmuch_status_t status;
1999 if (directory == NULL)
2000 return NOTMUCH_STATUS_NULL_POINTER;
2004 *directory = _notmuch_directory_create (notmuch, path,
2005 NOTMUCH_FIND_LOOKUP, &status);
2006 } catch (const Xapian::Error &error) {
2007 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
2008 error.get_msg().c_str());
2009 notmuch->exception_reported = TRUE;
2010 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2015 /* Allocate a document ID that satisfies the following criteria:
2017 * 1. The ID does not exist for any document in the Xapian database
2019 * 2. The ID was not previously returned from this function
2021 * 3. The ID is the smallest integer satisfying (1) and (2)
2023 * This function will trigger an internal error if these constraints
2024 * cannot all be satisfied, (that is, the pool of available document
2025 * IDs has been exhausted).
2028 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2030 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2032 notmuch->last_doc_id++;
2034 if (notmuch->last_doc_id == 0)
2035 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2037 return notmuch->last_doc_id;
2041 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
2043 /* 16 bytes (+ terminator) for hexadecimal representation of
2044 * a 64-bit integer. */
2045 static char thread_id[17];
2046 Xapian::WritableDatabase *db;
2048 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2050 notmuch->last_thread_id++;
2052 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2054 db->set_metadata ("last_thread_id", thread_id);
2060 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2062 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2063 message_id = _notmuch_message_id_compressed (ctx, message_id);
2065 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2069 static notmuch_status_t
2070 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2072 const char *message_id,
2073 const char **thread_id_ret);
2075 /* Find the thread ID to which the message with 'message_id' belongs.
2077 * Note: 'thread_id_ret' must not be NULL!
2078 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2081 * Note: If there is no message in the database with the given
2082 * 'message_id' then a new thread_id will be allocated for this
2083 * message ID and stored in the database metadata so that the
2084 * thread ID can be looked up if the message is added to the database
2087 static notmuch_status_t
2088 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2090 const char *message_id,
2091 const char **thread_id_ret)
2093 notmuch_private_status_t status;
2094 notmuch_message_t *message;
2096 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2097 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2100 /* Look for this message (regular or ghost) */
2101 message = _notmuch_message_create_for_message_id (
2102 notmuch, message_id, &status);
2103 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2104 /* Message exists */
2105 *thread_id_ret = talloc_steal (
2106 ctx, notmuch_message_get_thread_id (message));
2107 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2108 /* Message did not exist. Give it a fresh thread ID and
2109 * populate this message as a ghost message. */
2110 *thread_id_ret = talloc_strdup (
2111 ctx, _notmuch_database_generate_thread_id (notmuch));
2112 if (! *thread_id_ret) {
2113 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2115 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2117 /* Commit the new ghost message */
2118 _notmuch_message_sync (message);
2121 /* Create failed. Fall through. */
2124 notmuch_message_destroy (message);
2126 return COERCE_STATUS (status, "Error creating ghost message");
2129 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2130 static notmuch_status_t
2131 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2133 const char *message_id,
2134 const char **thread_id_ret)
2136 notmuch_status_t status;
2137 notmuch_message_t *message;
2138 string thread_id_string;
2140 Xapian::WritableDatabase *db;
2142 status = notmuch_database_find_message (notmuch, message_id, &message);
2148 *thread_id_ret = talloc_steal (ctx,
2149 notmuch_message_get_thread_id (message));
2151 notmuch_message_destroy (message);
2153 return NOTMUCH_STATUS_SUCCESS;
2156 /* Message has not been seen yet.
2158 * We may have seen a reference to it already, in which case, we
2159 * can return the thread ID stored in the metadata. Otherwise, we
2160 * generate a new thread ID and store it there.
2162 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2163 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2164 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2166 if (thread_id_string.empty()) {
2167 *thread_id_ret = talloc_strdup (ctx,
2168 _notmuch_database_generate_thread_id (notmuch));
2169 db->set_metadata (metadata_key, *thread_id_ret);
2171 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2174 talloc_free (metadata_key);
2176 return NOTMUCH_STATUS_SUCCESS;
2179 static notmuch_status_t
2180 _merge_threads (notmuch_database_t *notmuch,
2181 const char *winner_thread_id,
2182 const char *loser_thread_id)
2184 Xapian::PostingIterator loser, loser_end;
2185 notmuch_message_t *message = NULL;
2186 notmuch_private_status_t private_status;
2187 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2189 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2191 for ( ; loser != loser_end; loser++) {
2192 message = _notmuch_message_create (notmuch, notmuch,
2193 *loser, &private_status);
2194 if (message == NULL) {
2195 ret = COERCE_STATUS (private_status,
2196 "Cannot find document for doc_id from query");
2200 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2201 _notmuch_message_add_term (message, "thread", winner_thread_id);
2202 _notmuch_message_sync (message);
2204 notmuch_message_destroy (message);
2210 notmuch_message_destroy (message);
2216 _my_talloc_free_for_g_hash (void *ptr)
2221 static notmuch_status_t
2222 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2223 notmuch_message_t *message,
2224 notmuch_message_file_t *message_file,
2225 const char **thread_id)
2227 GHashTable *parents = NULL;
2228 const char *refs, *in_reply_to, *in_reply_to_message_id;
2229 const char *last_ref_message_id, *this_message_id;
2230 GList *l, *keys = NULL;
2231 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2233 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2234 _my_talloc_free_for_g_hash, NULL);
2235 this_message_id = notmuch_message_get_message_id (message);
2237 refs = _notmuch_message_file_get_header (message_file, "references");
2238 last_ref_message_id = parse_references (message,
2242 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2243 in_reply_to_message_id = parse_references (message,
2245 parents, in_reply_to);
2247 /* For the parent of this message, use the last message ID of the
2248 * References header, if available. If not, fall back to the
2249 * first message ID in the In-Reply-To header. */
2250 if (last_ref_message_id) {
2251 _notmuch_message_add_term (message, "replyto",
2252 last_ref_message_id);
2253 } else if (in_reply_to_message_id) {
2254 _notmuch_message_add_term (message, "replyto",
2255 in_reply_to_message_id);
2258 keys = g_hash_table_get_keys (parents);
2259 for (l = keys; l; l = l->next) {
2260 char *parent_message_id;
2261 const char *parent_thread_id = NULL;
2263 parent_message_id = (char *) l->data;
2265 _notmuch_message_add_term (message, "reference",
2268 ret = _resolve_message_id_to_thread_id (notmuch,
2275 if (*thread_id == NULL) {
2276 *thread_id = talloc_strdup (message, parent_thread_id);
2277 _notmuch_message_add_term (message, "thread", *thread_id);
2278 } else if (strcmp (*thread_id, parent_thread_id)) {
2279 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2289 g_hash_table_unref (parents);
2294 static notmuch_status_t
2295 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2296 notmuch_message_t *message,
2297 const char **thread_id)
2299 const char *message_id = notmuch_message_get_message_id (message);
2300 Xapian::PostingIterator child, children_end;
2301 notmuch_message_t *child_message = NULL;
2302 const char *child_thread_id;
2303 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2304 notmuch_private_status_t private_status;
2306 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2308 for ( ; child != children_end; child++) {
2310 child_message = _notmuch_message_create (message, notmuch,
2311 *child, &private_status);
2312 if (child_message == NULL) {
2313 ret = COERCE_STATUS (private_status,
2314 "Cannot find document for doc_id from query");
2318 child_thread_id = notmuch_message_get_thread_id (child_message);
2319 if (*thread_id == NULL) {
2320 *thread_id = talloc_strdup (message, child_thread_id);
2321 _notmuch_message_add_term (message, "thread", *thread_id);
2322 } else if (strcmp (*thread_id, child_thread_id)) {
2323 _notmuch_message_remove_term (child_message, "reference",
2325 _notmuch_message_sync (child_message);
2326 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2331 notmuch_message_destroy (child_message);
2332 child_message = NULL;
2337 notmuch_message_destroy (child_message);
2342 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2344 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2345 notmuch_message_t *message)
2347 const char *message_id;
2351 message_id = notmuch_message_get_message_id (message);
2352 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2354 /* Check if we have already seen related messages to this one.
2355 * If we have then use the thread_id that we stored at that time.
2357 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2358 if (stored_id.empty ()) {
2361 Xapian::WritableDatabase *db;
2363 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2365 /* Clear the metadata for this message ID. We don't need it
2367 db->set_metadata (metadata_key, "");
2369 return talloc_strdup (ctx, stored_id.c_str ());
2373 /* Given a blank or ghost 'message' and its corresponding
2374 * 'message_file' link it to existing threads in the database.
2376 * First, if is_ghost, this retrieves the thread ID already stored in
2377 * the message (which will be the case if a message was previously
2378 * added that referenced this one). If the message is blank
2379 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2380 * later in this function). If the database does not support ghost
2381 * messages, this checks for a thread ID stored in database metadata
2382 * for this message ID.
2384 * Second, we look at 'message_file' and its link-relevant headers
2385 * (References and In-Reply-To) for message IDs.
2387 * Finally, we look in the database for existing message that
2388 * reference 'message'.
2390 * In all cases, we assign to the current message the first thread ID
2391 * found. We will also merge any existing, distinct threads where this
2392 * message belongs to both, (which is not uncommon when messages are
2393 * processed out of order).
2395 * Finally, if no thread ID has been found through referenced messages, we
2396 * call _notmuch_message_generate_thread_id to generate a new thread
2397 * ID. This should only happen for new, top-level messages, (no
2398 * References or In-Reply-To header in this message, and no previously
2399 * added message refers to this message).
2401 static notmuch_status_t
2402 _notmuch_database_link_message (notmuch_database_t *notmuch,
2403 notmuch_message_t *message,
2404 notmuch_message_file_t *message_file,
2405 notmuch_bool_t is_ghost)
2407 void *local = talloc_new (NULL);
2408 notmuch_status_t status;
2409 const char *thread_id = NULL;
2411 /* Check if the message already had a thread ID */
2412 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2414 thread_id = notmuch_message_get_thread_id (message);
2416 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2418 _notmuch_message_add_term (message, "thread", thread_id);
2421 status = _notmuch_database_link_message_to_parents (notmuch, message,
2427 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2428 /* In general, it shouldn't be necessary to link children,
2429 * since the earlier indexing of those children will have
2430 * stored a thread ID for the missing parent. However, prior
2431 * to ghost messages, these stored thread IDs were NOT
2432 * rewritten during thread merging (and there was no
2433 * performant way to do so), so if indexed children were
2434 * pulled into a different thread ID by a merge, it was
2435 * necessary to pull them *back* into the stored thread ID of
2436 * the parent. With ghost messages, we just rewrite the
2437 * stored thread IDs during merging, so this workaround isn't
2439 status = _notmuch_database_link_message_to_children (notmuch, message,
2445 /* If not part of any existing thread, generate a new thread ID. */
2446 if (thread_id == NULL) {
2447 thread_id = _notmuch_database_generate_thread_id (notmuch);
2449 _notmuch_message_add_term (message, "thread", thread_id);
2453 talloc_free (local);
2459 notmuch_database_add_message (notmuch_database_t *notmuch,
2460 const char *filename,
2461 notmuch_message_t **message_ret)
2463 notmuch_message_file_t *message_file;
2464 notmuch_message_t *message = NULL;
2465 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2466 notmuch_private_status_t private_status;
2467 notmuch_bool_t is_ghost = false;
2469 const char *date, *header;
2470 const char *from, *to, *subject;
2471 char *message_id = NULL;
2474 *message_ret = NULL;
2476 ret = _notmuch_database_ensure_writable (notmuch);
2480 message_file = _notmuch_message_file_open (notmuch, filename);
2481 if (message_file == NULL)
2482 return NOTMUCH_STATUS_FILE_ERROR;
2484 /* Adding a message may change many documents. Do this all
2486 ret = notmuch_database_begin_atomic (notmuch);
2490 /* Parse message up front to get better error status. */
2491 ret = _notmuch_message_file_parse (message_file);
2496 /* Before we do any real work, (especially before doing a
2497 * potential SHA-1 computation on the entire file's contents),
2498 * let's make sure that what we're looking at looks like an
2499 * actual email message.
2501 from = _notmuch_message_file_get_header (message_file, "from");
2502 subject = _notmuch_message_file_get_header (message_file, "subject");
2503 to = _notmuch_message_file_get_header (message_file, "to");
2505 if ((from == NULL || *from == '\0') &&
2506 (subject == NULL || *subject == '\0') &&
2507 (to == NULL || *to == '\0'))
2509 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2513 /* Now that we're sure it's mail, the first order of business
2514 * is to find a message ID (or else create one ourselves). */
2516 header = _notmuch_message_file_get_header (message_file, "message-id");
2517 if (header && *header != '\0') {
2518 message_id = _parse_message_id (message_file, header, NULL);
2520 /* So the header value isn't RFC-compliant, but it's
2521 * better than no message-id at all. */
2522 if (message_id == NULL)
2523 message_id = talloc_strdup (message_file, header);
2526 if (message_id == NULL ) {
2527 /* No message-id at all, let's generate one by taking a
2528 * hash over the file's contents. */
2529 char *sha1 = _notmuch_sha1_of_file (filename);
2531 /* If that failed too, something is really wrong. Give up. */
2533 ret = NOTMUCH_STATUS_FILE_ERROR;
2537 message_id = talloc_asprintf (message_file,
2538 "notmuch-sha1-%s", sha1);
2542 /* Now that we have a message ID, we get a message object,
2543 * (which may or may not reference an existing document in the
2546 message = _notmuch_message_create_for_message_id (notmuch,
2550 talloc_free (message_id);
2552 if (message == NULL) {
2553 ret = COERCE_STATUS (private_status,
2554 "Unexpected status value from _notmuch_message_create_for_message_id");
2558 _notmuch_message_add_filename (message, filename);
2560 /* Is this a newly created message object or a ghost
2561 * message? We have to be slightly careful: if this is a
2562 * blank message, it's not safe to call
2563 * notmuch_message_get_flag yet. */
2564 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2565 (is_ghost = notmuch_message_get_flag (
2566 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2567 _notmuch_message_add_term (message, "type", "mail");
2569 /* Convert ghost message to a regular message */
2570 _notmuch_message_remove_term (message, "type", "ghost");
2572 ret = _notmuch_database_link_message (notmuch, message,
2573 message_file, is_ghost);
2577 date = _notmuch_message_file_get_header (message_file, "date");
2578 _notmuch_message_set_header_values (message, date, from, subject);
2580 ret = _notmuch_message_index_file (message, message_file);
2584 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2587 _notmuch_message_sync (message);
2588 } catch (const Xapian::Error &error) {
2589 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2590 error.get_msg().c_str());
2591 notmuch->exception_reported = TRUE;
2592 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2598 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2599 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2600 *message_ret = message;
2602 notmuch_message_destroy (message);
2606 _notmuch_message_file_close (message_file);
2608 ret2 = notmuch_database_end_atomic (notmuch);
2609 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2610 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2611 ret2 != NOTMUCH_STATUS_SUCCESS)
2618 notmuch_database_remove_message (notmuch_database_t *notmuch,
2619 const char *filename)
2621 notmuch_status_t status;
2622 notmuch_message_t *message;
2624 status = notmuch_database_find_message_by_filename (notmuch, filename,
2627 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2628 status = _notmuch_message_remove_filename (message, filename);
2629 if (status == NOTMUCH_STATUS_SUCCESS)
2630 _notmuch_message_delete (message);
2631 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2632 _notmuch_message_sync (message);
2634 notmuch_message_destroy (message);
2641 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2642 const char *filename,
2643 notmuch_message_t **message_ret)
2646 const char *prefix = _find_prefix ("file-direntry");
2647 char *direntry, *term;
2648 Xapian::PostingIterator i, end;
2649 notmuch_status_t status;
2651 if (message_ret == NULL)
2652 return NOTMUCH_STATUS_NULL_POINTER;
2654 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2655 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2657 /* return NULL on any failure */
2658 *message_ret = NULL;
2660 local = talloc_new (notmuch);
2663 status = _notmuch_database_filename_to_direntry (
2664 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2665 if (status || !direntry)
2668 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2670 find_doc_ids_for_term (notmuch, term, &i, &end);
2673 notmuch_private_status_t private_status;
2675 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2677 if (*message_ret == NULL)
2678 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2680 } catch (const Xapian::Error &error) {
2681 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2682 error.get_msg().c_str());
2683 notmuch->exception_reported = TRUE;
2684 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2688 talloc_free (local);
2690 if (status && *message_ret) {
2691 notmuch_message_destroy (*message_ret);
2692 *message_ret = NULL;
2697 notmuch_string_list_t *
2698 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2699 Xapian::TermIterator &end,
2702 int prefix_len = strlen (prefix);
2703 notmuch_string_list_t *list;
2705 list = _notmuch_string_list_create (ctx);
2706 if (unlikely (list == NULL))
2709 for (i.skip_to (prefix); i != end; i++) {
2710 /* Terminate loop at first term without desired prefix. */
2711 if (strncmp ((*i).c_str (), prefix, prefix_len))
2714 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2721 notmuch_database_get_all_tags (notmuch_database_t *db)
2723 Xapian::TermIterator i, end;
2724 notmuch_string_list_t *tags;
2727 i = db->xapian_db->allterms_begin();
2728 end = db->xapian_db->allterms_end();
2729 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2730 _find_prefix ("tag"));
2731 _notmuch_string_list_sort (tags);
2732 return _notmuch_tags_create (db, tags);
2733 } catch (const Xapian::Error &error) {
2734 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2735 error.get_msg().c_str());
2736 db->exception_reported = TRUE;
2742 notmuch_database_status_string (const notmuch_database_t *notmuch)
2744 return notmuch->status_string;