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 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
266 NOTMUCH_FIELD_PROCESSOR },
267 { "path", "P", NOTMUCH_FIELD_EXTERNAL },
268 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
270 * Unconditionally add ':' to reduce potential ambiguity with
271 * overlapping prefixes and/or terms that start with capital
272 * letters. See Xapian document termprefixes.html for related
275 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL },
276 #if HAVE_XAPIAN_FIELD_PROCESSOR
277 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
278 NOTMUCH_FIELD_PROCESSOR },
279 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
280 NOTMUCH_FIELD_PROCESSOR },
282 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
283 NOTMUCH_FIELD_PROBABILISTIC |
284 NOTMUCH_FIELD_PROCESSOR },
285 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
286 NOTMUCH_FIELD_PROBABILISTIC },
287 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
288 NOTMUCH_FIELD_PROBABILISTIC },
289 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
290 NOTMUCH_FIELD_PROBABILISTIC },
291 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
292 NOTMUCH_FIELD_PROBABILISTIC |
293 NOTMUCH_FIELD_PROCESSOR},
297 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
299 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
300 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
302 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
305 #if HAVE_XAPIAN_FIELD_PROCESSOR
307 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
309 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
310 Xapian::FieldProcessor *fp;
312 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
313 fp = (new DateFieldProcessor())->release ();
314 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
315 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
317 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
318 *notmuch->query_parser, notmuch))->release ();
320 /* we treat all field-processor fields as boolean in order to get the raw input */
321 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
323 _setup_query_field_default (prefix, notmuch);
328 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
330 _setup_query_field_default (prefix, notmuch);
335 _find_prefix (const char *name)
339 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
340 if (strcmp (name, prefix_table[i].name) == 0)
341 return prefix_table[i].prefix;
344 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
349 static const struct {
350 /* NOTMUCH_FEATURE_* value. */
351 _notmuch_features value;
352 /* Feature name as it appears in the database. This name should
353 * be appropriate for displaying to the user if an older version
354 * of notmuch doesn't support this feature. */
356 /* Compatibility flags when this feature is declared. */
358 } feature_names[] = {
359 { NOTMUCH_FEATURE_FILE_TERMS,
360 "multiple paths per message", "rw" },
361 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
362 "relative directory paths", "rw" },
363 /* Header values are not required for reading a database because a
364 * reader can just refer to the message file. */
365 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
366 "from/subject/message-ID in database", "w" },
367 { NOTMUCH_FEATURE_BOOL_FOLDER,
368 "exact folder:/path: search", "rw" },
369 { NOTMUCH_FEATURE_GHOSTS,
370 "mail documents for missing messages", "w"},
371 /* Knowledge of the index mime-types are not required for reading
372 * a database because a reader will just be unable to query
374 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
375 "indexed MIME types", "w"},
376 { NOTMUCH_FEATURE_LAST_MOD,
377 "modification tracking", "w"},
381 notmuch_status_to_string (notmuch_status_t status)
384 case NOTMUCH_STATUS_SUCCESS:
385 return "No error occurred";
386 case NOTMUCH_STATUS_OUT_OF_MEMORY:
387 return "Out of memory";
388 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
389 return "Attempt to write to a read-only database";
390 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
391 return "A Xapian exception occurred";
392 case NOTMUCH_STATUS_FILE_ERROR:
393 return "Something went wrong trying to read or write a file";
394 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
395 return "File is not an email";
396 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
397 return "Message ID is identical to a message in database";
398 case NOTMUCH_STATUS_NULL_POINTER:
399 return "Erroneous NULL pointer";
400 case NOTMUCH_STATUS_TAG_TOO_LONG:
401 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
402 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
403 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
404 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
405 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
406 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
407 return "Unsupported operation";
408 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
409 return "Operation requires a database upgrade";
410 case NOTMUCH_STATUS_PATH_ERROR:
411 return "Path supplied is illegal for this function";
413 case NOTMUCH_STATUS_LAST_STATUS:
414 return "Unknown error status value";
419 _notmuch_database_log (notmuch_database_t *notmuch,
425 va_start (va_args, format);
427 if (notmuch->status_string)
428 talloc_free (notmuch->status_string);
430 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
435 _notmuch_database_log_append (notmuch_database_t *notmuch,
441 va_start (va_args, format);
443 if (notmuch->status_string)
444 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
446 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
452 find_doc_ids_for_term (notmuch_database_t *notmuch,
454 Xapian::PostingIterator *begin,
455 Xapian::PostingIterator *end)
457 *begin = notmuch->xapian_db->postlist_begin (term);
459 *end = notmuch->xapian_db->postlist_end (term);
463 find_doc_ids (notmuch_database_t *notmuch,
464 const char *prefix_name,
466 Xapian::PostingIterator *begin,
467 Xapian::PostingIterator *end)
471 term = talloc_asprintf (notmuch, "%s%s",
472 _find_prefix (prefix_name), value);
474 find_doc_ids_for_term (notmuch, term, begin, end);
479 notmuch_private_status_t
480 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
481 const char *prefix_name,
483 unsigned int *doc_id)
485 Xapian::PostingIterator i, end;
487 find_doc_ids (notmuch, prefix_name, value, &i, &end);
491 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
496 #if DEBUG_DATABASE_SANITY
500 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
504 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
507 static Xapian::Document
508 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
510 return notmuch->xapian_db->get_document (doc_id);
513 /* Generate a compressed version of 'message_id' of the form:
515 * notmuch-sha1-<sha1_sum_of_message_id>
518 _notmuch_message_id_compressed (void *ctx, const char *message_id)
520 char *sha1, *compressed;
522 sha1 = _notmuch_sha1_of_string (message_id);
524 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
531 notmuch_database_find_message (notmuch_database_t *notmuch,
532 const char *message_id,
533 notmuch_message_t **message_ret)
535 notmuch_private_status_t status;
538 if (message_ret == NULL)
539 return NOTMUCH_STATUS_NULL_POINTER;
541 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
542 message_id = _notmuch_message_id_compressed (notmuch, message_id);
545 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
546 message_id, &doc_id);
548 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
551 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
553 if (*message_ret == NULL)
554 return NOTMUCH_STATUS_OUT_OF_MEMORY;
557 return NOTMUCH_STATUS_SUCCESS;
558 } catch (const Xapian::Error &error) {
559 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
560 error.get_msg().c_str());
561 notmuch->exception_reported = TRUE;
563 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
567 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
568 * a (potentially nested) parenthesized sequence with '\' used to
569 * escape any character (including parentheses).
571 * If the sequence to be skipped continues to the end of the string,
572 * then 'str' will be left pointing at the final terminating '\0'
576 skip_space_and_comments (const char **str)
581 while (*s && (isspace (*s) || *s == '(')) {
582 while (*s && isspace (*s))
587 while (*s && nesting) {
590 } else if (*s == ')') {
592 } else if (*s == '\\') {
604 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
605 * comments, and the '<' and '>' delimiters.
607 * If not NULL, then *next will be made to point to the first character
608 * not parsed, (possibly pointing to the final '\0' terminator.
610 * Returns a newly talloc'ed string belonging to 'ctx'.
612 * Returns NULL if there is any error parsing the message-id. */
614 _parse_message_id (void *ctx, const char *message_id, const char **next)
619 if (message_id == NULL || *message_id == '\0')
624 skip_space_and_comments (&s);
626 /* Skip any unstructured text as well. */
627 while (*s && *s != '<')
638 skip_space_and_comments (&s);
641 while (*end && *end != '>')
650 if (end > s && *end == '>')
655 result = talloc_strndup (ctx, s, end - s + 1);
657 /* Finally, collapse any whitespace that is within the message-id
663 for (r = result, len = strlen (r); *r; r++, len--)
664 if (*r == ' ' || *r == '\t')
665 memmove (r, r+1, len);
671 /* Parse a References header value, putting a (talloc'ed under 'ctx')
672 * copy of each referenced message-id into 'hash'.
674 * We explicitly avoid including any reference identical to
675 * 'message_id' in the result (to avoid mass confusion when a single
676 * message references itself cyclically---and yes, mail messages are
677 * not infrequent in the wild that do this---don't ask me why).
679 * Return the last reference parsed, if it is not equal to message_id.
682 parse_references (void *ctx,
683 const char *message_id,
687 char *ref, *last_ref = NULL;
689 if (refs == NULL || *refs == '\0')
693 ref = _parse_message_id (ctx, refs, &refs);
695 if (ref && strcmp (ref, message_id)) {
696 g_hash_table_add (hash, ref);
701 /* The return value of this function is used to add a parent
702 * reference to the database. We should avoid making a message
703 * its own parent, thus the above check.
705 return talloc_strdup(ctx, last_ref);
709 notmuch_database_create (const char *path, notmuch_database_t **database)
711 char *status_string = NULL;
712 notmuch_status_t status;
714 status = notmuch_database_create_verbose (path, database,
718 fputs (status_string, stderr);
719 free (status_string);
726 notmuch_database_create_verbose (const char *path,
727 notmuch_database_t **database,
728 char **status_string)
730 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
731 notmuch_database_t *notmuch = NULL;
732 char *notmuch_path = NULL;
733 char *message = NULL;
738 message = strdup ("Error: Cannot create a database for a NULL path.\n");
739 status = NOTMUCH_STATUS_NULL_POINTER;
743 if (path[0] != '/') {
744 message = strdup ("Error: Database path must be absolute.\n");
745 status = NOTMUCH_STATUS_PATH_ERROR;
749 err = stat (path, &st);
751 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
752 path, strerror (errno)));
753 status = NOTMUCH_STATUS_FILE_ERROR;
757 if (! S_ISDIR (st.st_mode)) {
758 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
759 "Not a directory.\n",
761 status = NOTMUCH_STATUS_FILE_ERROR;
765 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
767 err = mkdir (notmuch_path, 0755);
770 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
771 notmuch_path, strerror (errno)));
772 status = NOTMUCH_STATUS_FILE_ERROR;
776 status = notmuch_database_open_verbose (path,
777 NOTMUCH_DATABASE_MODE_READ_WRITE,
782 /* Upgrade doesn't add these feature to existing databases, but
783 * new databases have them. */
784 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
785 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
787 status = notmuch_database_upgrade (notmuch, NULL, NULL);
789 notmuch_database_close(notmuch);
795 talloc_free (notmuch_path);
799 *status_string = message;
806 talloc_free (notmuch);
811 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
813 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
814 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
815 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
818 return NOTMUCH_STATUS_SUCCESS;
821 /* Allocate a revision number for the next change. */
823 _notmuch_database_new_revision (notmuch_database_t *notmuch)
825 unsigned long new_revision = notmuch->revision + 1;
827 /* If we're in an atomic section, hold off on updating the
828 * committed revision number until we commit the atomic section.
830 if (notmuch->atomic_nesting)
831 notmuch->atomic_dirty = TRUE;
833 notmuch->revision = new_revision;
838 /* Parse a database features string from the given database version.
839 * Returns the feature bit set.
841 * For version < 3, this ignores the features string and returns a
842 * hard-coded set of features.
844 * If there are unrecognized features that are required to open the
845 * database in mode (which should be 'r' or 'w'), return a
846 * comma-separated list of unrecognized but required features in
847 * *incompat_out suitable for presenting to the user. *incompat_out
848 * will be allocated from ctx.
850 static _notmuch_features
851 _parse_features (const void *ctx, const char *features, unsigned int version,
852 char mode, char **incompat_out)
854 _notmuch_features res = static_cast<_notmuch_features>(0);
855 unsigned int namelen, i;
859 /* Prior to database version 3, features were implied by the
862 return NOTMUCH_FEATURES_V0;
863 else if (version == 1)
864 return NOTMUCH_FEATURES_V1;
865 else if (version == 2)
866 return NOTMUCH_FEATURES_V2;
868 /* Parse the features string */
869 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
870 flags = strchr (features, '\t');
871 if (! flags || flags > features + llen)
873 namelen = flags - features;
875 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
876 if (strlen (feature_names[i].name) == namelen &&
877 strncmp (feature_names[i].name, features, namelen) == 0) {
878 res |= feature_names[i].value;
883 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
884 /* Unrecognized feature */
885 const char *have = strchr (flags, mode);
886 if (have && have < features + llen) {
887 /* This feature is required to access this database in
888 * 'mode', but we don't understand it. */
890 *incompat_out = talloc_strdup (ctx, "");
891 *incompat_out = talloc_asprintf_append_buffer (
892 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
902 _print_features (const void *ctx, unsigned int features)
905 char *res = talloc_strdup (ctx, "");
907 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
908 if (features & feature_names[i].value)
909 res = talloc_asprintf_append_buffer (
910 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
916 notmuch_database_open (const char *path,
917 notmuch_database_mode_t mode,
918 notmuch_database_t **database)
920 char *status_string = NULL;
921 notmuch_status_t status;
923 status = notmuch_database_open_verbose (path, mode, database,
927 fputs (status_string, stderr);
928 free (status_string);
935 notmuch_database_open_verbose (const char *path,
936 notmuch_database_mode_t mode,
937 notmuch_database_t **database,
938 char **status_string)
940 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
941 void *local = talloc_new (NULL);
942 notmuch_database_t *notmuch = NULL;
943 char *notmuch_path, *xapian_path, *incompat_features;
944 char *message = NULL;
947 unsigned int i, version;
948 static int initialized = 0;
951 message = strdup ("Error: Cannot open a database for a NULL path.\n");
952 status = NOTMUCH_STATUS_NULL_POINTER;
956 if (path[0] != '/') {
957 message = strdup ("Error: Database path must be absolute.\n");
958 status = NOTMUCH_STATUS_PATH_ERROR;
962 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
963 message = strdup ("Out of memory\n");
964 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
968 err = stat (notmuch_path, &st);
970 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
971 notmuch_path, strerror (errno)));
972 status = NOTMUCH_STATUS_FILE_ERROR;
976 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
977 message = strdup ("Out of memory\n");
978 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
982 /* Initialize the GLib type system and threads */
983 #if !GLIB_CHECK_VERSION(2, 35, 1)
987 /* Initialize gmime */
989 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
993 notmuch = talloc_zero (NULL, notmuch_database_t);
994 notmuch->exception_reported = FALSE;
995 notmuch->status_string = NULL;
996 notmuch->path = talloc_strdup (notmuch, path);
998 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
999 notmuch->path[strlen (notmuch->path) - 1] = '\0';
1001 notmuch->mode = mode;
1002 notmuch->atomic_nesting = 0;
1005 string last_thread_id;
1008 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
1009 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
1012 notmuch->xapian_db = new Xapian::Database (xapian_path);
1015 /* Check version. As of database version 3, we represent
1016 * changes in terms of features, so assume a version bump
1017 * means a dramatically incompatible change. */
1018 version = notmuch_database_get_version (notmuch);
1019 if (version > NOTMUCH_DATABASE_VERSION) {
1020 IGNORE_RESULT (asprintf (&message,
1021 "Error: Notmuch database at %s\n"
1022 " has a newer database format version (%u) than supported by this\n"
1023 " version of notmuch (%u).\n",
1024 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
1025 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1026 notmuch_database_destroy (notmuch);
1028 status = NOTMUCH_STATUS_FILE_ERROR;
1032 /* Check features. */
1033 incompat_features = NULL;
1034 notmuch->features = _parse_features (
1035 local, notmuch->xapian_db->get_metadata ("features").c_str (),
1036 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1037 &incompat_features);
1038 if (incompat_features) {
1039 IGNORE_RESULT (asprintf (&message,
1040 "Error: Notmuch database at %s\n"
1041 " requires features (%s)\n"
1042 " not supported by this version of notmuch.\n",
1043 notmuch_path, incompat_features));
1044 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1045 notmuch_database_destroy (notmuch);
1047 status = NOTMUCH_STATUS_FILE_ERROR;
1051 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1052 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1053 if (last_thread_id.empty ()) {
1054 notmuch->last_thread_id = 0;
1059 str = last_thread_id.c_str ();
1060 notmuch->last_thread_id = strtoull (str, &end, 16);
1062 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1065 /* Get current highest revision number. */
1066 last_mod = notmuch->xapian_db->get_value_upper_bound (
1067 NOTMUCH_VALUE_LAST_MOD);
1068 if (last_mod.empty ())
1069 notmuch->revision = 0;
1071 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1072 notmuch->uuid = talloc_strdup (
1073 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1075 notmuch->query_parser = new Xapian::QueryParser;
1076 notmuch->term_gen = new Xapian::TermGenerator;
1077 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1078 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1079 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1080 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1082 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1083 notmuch->query_parser->set_database (*notmuch->xapian_db);
1084 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1085 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1086 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1087 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1088 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1090 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1091 const prefix_t *prefix = &prefix_table[i];
1092 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1093 _setup_query_field (prefix, notmuch);
1096 } catch (const Xapian::Error &error) {
1097 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1098 error.get_msg().c_str()));
1099 notmuch_database_destroy (notmuch);
1101 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1105 talloc_free (local);
1109 *status_string = message;
1115 *database = notmuch;
1117 talloc_free (notmuch);
1122 notmuch_database_close (notmuch_database_t *notmuch)
1124 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1126 /* Many Xapian objects (and thus notmuch objects) hold references to
1127 * the database, so merely deleting the database may not suffice to
1128 * close it. Thus, we explicitly close it here. */
1129 if (notmuch->xapian_db != NULL) {
1131 /* If there's an outstanding transaction, it's unclear if
1132 * closing the Xapian database commits everything up to
1133 * that transaction, or may discard committed (but
1134 * unflushed) transactions. To be certain, explicitly
1135 * cancel any outstanding transaction before closing. */
1136 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1137 notmuch->atomic_nesting)
1138 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1139 ->cancel_transaction ();
1141 /* Close the database. This implicitly flushes
1142 * outstanding changes. */
1143 notmuch->xapian_db->close();
1144 } catch (const Xapian::Error &error) {
1145 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1146 if (! notmuch->exception_reported) {
1147 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1148 error.get_msg().c_str());
1153 delete notmuch->term_gen;
1154 notmuch->term_gen = NULL;
1155 delete notmuch->query_parser;
1156 notmuch->query_parser = NULL;
1157 delete notmuch->xapian_db;
1158 notmuch->xapian_db = NULL;
1159 delete notmuch->value_range_processor;
1160 notmuch->value_range_processor = NULL;
1161 delete notmuch->date_range_processor;
1162 notmuch->date_range_processor = NULL;
1163 delete notmuch->last_mod_range_processor;
1164 notmuch->last_mod_range_processor = NULL;
1170 _notmuch_database_reopen (notmuch_database_t *notmuch)
1172 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1173 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1176 notmuch->xapian_db->reopen ();
1177 } catch (const Xapian::Error &error) {
1178 if (! notmuch->exception_reported) {
1179 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1180 error.get_msg ().c_str ());
1181 notmuch->exception_reported = TRUE;
1183 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1188 return NOTMUCH_STATUS_SUCCESS;
1192 unlink_cb (const char *path,
1193 unused (const struct stat *sb),
1195 unused (struct FTW *ftw))
1197 return remove (path);
1201 rmtree (const char *path)
1203 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1206 class NotmuchCompactor : public Xapian::Compactor
1208 notmuch_compact_status_cb_t status_cb;
1209 void *status_closure;
1212 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1213 status_cb (cb), status_closure (closure) { }
1216 set_status (const std::string &table, const std::string &status)
1220 if (status_cb == NULL)
1223 if (status.length () == 0)
1224 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1226 msg = talloc_asprintf (NULL, " %s", status.c_str());
1232 status_cb (msg, status_closure);
1237 /* Compacts the given database, optionally saving the original database
1238 * in backup_path. Additionally, a callback function can be provided to
1239 * give the user feedback on the progress of the (likely long-lived)
1240 * compaction process.
1242 * The backup path must point to a directory on the same volume as the
1243 * original database. Passing a NULL backup_path will result in the
1244 * uncompacted database being deleted after compaction has finished.
1245 * Note that the database write lock will be held during the
1246 * compaction process to protect data integrity.
1249 notmuch_database_compact (const char *path,
1250 const char *backup_path,
1251 notmuch_compact_status_cb_t status_cb,
1255 char *notmuch_path, *xapian_path, *compact_xapian_path;
1256 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1257 notmuch_database_t *notmuch = NULL;
1258 struct stat statbuf;
1259 notmuch_bool_t keep_backup;
1260 char *message = NULL;
1262 local = talloc_new (NULL);
1264 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1266 ret = notmuch_database_open_verbose (path,
1267 NOTMUCH_DATABASE_MODE_READ_WRITE,
1271 if (status_cb) status_cb (message, closure);
1275 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1276 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1280 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1281 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1285 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1286 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1290 if (backup_path == NULL) {
1291 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1292 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1295 keep_backup = FALSE;
1301 if (stat (backup_path, &statbuf) != -1) {
1302 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1303 ret = NOTMUCH_STATUS_FILE_ERROR;
1306 if (errno != ENOENT) {
1307 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1309 ret = NOTMUCH_STATUS_FILE_ERROR;
1313 /* Unconditionally attempt to remove old work-in-progress database (if
1314 * any). This is "protected" by database lock. If this fails due to write
1315 * errors (etc), the following code will fail and provide error message.
1317 (void) rmtree (compact_xapian_path);
1320 NotmuchCompactor compactor (status_cb, closure);
1322 compactor.set_renumber (false);
1323 compactor.add_source (xapian_path);
1324 compactor.set_destdir (compact_xapian_path);
1325 compactor.compact ();
1326 } catch (const Xapian::Error &error) {
1327 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1328 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1332 if (rename (xapian_path, backup_path)) {
1333 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1334 xapian_path, backup_path, strerror (errno));
1335 ret = NOTMUCH_STATUS_FILE_ERROR;
1339 if (rename (compact_xapian_path, xapian_path)) {
1340 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1341 compact_xapian_path, xapian_path, strerror (errno));
1342 ret = NOTMUCH_STATUS_FILE_ERROR;
1346 if (! keep_backup) {
1347 if (rmtree (backup_path)) {
1348 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1349 backup_path, strerror (errno));
1350 ret = NOTMUCH_STATUS_FILE_ERROR;
1357 notmuch_status_t ret2;
1359 const char *str = notmuch_database_status_string (notmuch);
1360 if (status_cb && str)
1361 status_cb (str, closure);
1363 ret2 = notmuch_database_destroy (notmuch);
1365 /* don't clobber previous error status */
1366 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1370 talloc_free (local);
1376 notmuch_database_destroy (notmuch_database_t *notmuch)
1378 notmuch_status_t status;
1380 status = notmuch_database_close (notmuch);
1381 talloc_free (notmuch);
1387 notmuch_database_get_path (notmuch_database_t *notmuch)
1389 return notmuch->path;
1393 notmuch_database_get_version (notmuch_database_t *notmuch)
1395 unsigned int version;
1396 string version_string;
1400 version_string = notmuch->xapian_db->get_metadata ("version");
1401 if (version_string.empty ())
1404 str = version_string.c_str ();
1405 if (str == NULL || *str == '\0')
1408 version = strtoul (str, &end, 10);
1410 INTERNAL_ERROR ("Malformed database version: %s", str);
1416 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1418 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1419 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1420 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1423 static volatile sig_atomic_t do_progress_notify = 0;
1426 handle_sigalrm (unused (int signal))
1428 do_progress_notify = 1;
1431 /* Upgrade the current database.
1433 * After opening a database in read-write mode, the client should
1434 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1435 * if so, upgrade with this function before making any modifications.
1437 * The optional progress_notify callback can be used by the caller to
1438 * provide progress indication to the user. If non-NULL it will be
1439 * called periodically with 'count' as the number of messages upgraded
1440 * so far and 'total' the overall number of messages that will be
1444 notmuch_database_upgrade (notmuch_database_t *notmuch,
1445 void (*progress_notify) (void *closure,
1449 void *local = talloc_new (NULL);
1450 Xapian::TermIterator t, t_end;
1451 Xapian::WritableDatabase *db;
1452 struct sigaction action;
1453 struct itimerval timerval;
1454 notmuch_bool_t timer_is_active = FALSE;
1455 enum _notmuch_features target_features, new_features;
1456 notmuch_status_t status;
1457 notmuch_private_status_t private_status;
1458 notmuch_query_t *query = NULL;
1459 unsigned int count = 0, total = 0;
1461 status = _notmuch_database_ensure_writable (notmuch);
1465 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1467 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1468 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1470 if (! notmuch_database_needs_upgrade (notmuch))
1471 return NOTMUCH_STATUS_SUCCESS;
1473 if (progress_notify) {
1474 /* Set up our handler for SIGALRM */
1475 memset (&action, 0, sizeof (struct sigaction));
1476 action.sa_handler = handle_sigalrm;
1477 sigemptyset (&action.sa_mask);
1478 action.sa_flags = SA_RESTART;
1479 sigaction (SIGALRM, &action, NULL);
1481 /* Then start a timer to send SIGALRM once per second. */
1482 timerval.it_interval.tv_sec = 1;
1483 timerval.it_interval.tv_usec = 0;
1484 timerval.it_value.tv_sec = 1;
1485 timerval.it_value.tv_usec = 0;
1486 setitimer (ITIMER_REAL, &timerval, NULL);
1488 timer_is_active = TRUE;
1491 /* Figure out how much total work we need to do. */
1493 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1494 NOTMUCH_FEATURE_LAST_MOD)) {
1495 query = notmuch_query_create (notmuch, "");
1498 status = notmuch_query_count_messages (query, &msg_count);
1503 notmuch_query_destroy (query);
1506 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1507 t_end = db->allterms_end ("XTIMESTAMP");
1508 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1511 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1512 /* The ghost message upgrade converts all thread_id_*
1513 * metadata values into ghost message documents. */
1514 t_end = db->metadata_keys_end ("thread_id_");
1515 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1519 /* Perform the upgrade in a transaction. */
1520 db->begin_transaction (true);
1522 /* Set the target features so we write out changes in the desired
1524 notmuch->features = target_features;
1526 /* Perform per-message upgrades. */
1528 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1529 NOTMUCH_FEATURE_LAST_MOD)) {
1530 notmuch_messages_t *messages;
1531 notmuch_message_t *message;
1534 query = notmuch_query_create (notmuch, "");
1536 status = notmuch_query_search_messages (query, &messages);
1540 notmuch_messages_valid (messages);
1541 notmuch_messages_move_to_next (messages))
1543 if (do_progress_notify) {
1544 progress_notify (closure, (double) count / total);
1545 do_progress_notify = 0;
1548 message = notmuch_messages_get (messages);
1550 /* Before version 1, each message document had its
1551 * filename in the data field. Copy that into the new
1552 * format by calling notmuch_message_add_filename.
1554 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1555 filename = _notmuch_message_talloc_copy_data (message);
1556 if (filename && *filename != '\0') {
1557 _notmuch_message_add_filename (message, filename);
1558 _notmuch_message_clear_data (message);
1560 talloc_free (filename);
1563 /* Prior to version 2, the "folder:" prefix was
1564 * probabilistic and stemmed. Change it to the current
1565 * boolean prefix. Add "path:" prefixes while at it.
1567 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1568 _notmuch_message_upgrade_folder (message);
1570 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1571 * track modification revisions. Give all messages the
1572 * next available revision; since we just started tracking
1573 * revisions for this database, that will be 1.
1575 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1576 _notmuch_message_upgrade_last_mod (message);
1578 _notmuch_message_sync (message);
1580 notmuch_message_destroy (message);
1585 notmuch_query_destroy (query);
1589 /* Perform per-directory upgrades. */
1591 /* Before version 1 we stored directory timestamps in
1592 * XTIMESTAMP documents instead of the current XDIRECTORY
1593 * documents. So copy those as well. */
1594 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1595 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1597 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1601 Xapian::PostingIterator p, p_end;
1602 std::string term = *t;
1604 p_end = notmuch->xapian_db->postlist_end (term);
1606 for (p = notmuch->xapian_db->postlist_begin (term);
1610 Xapian::Document document;
1612 notmuch_directory_t *directory;
1614 if (do_progress_notify) {
1615 progress_notify (closure, (double) count / total);
1616 do_progress_notify = 0;
1619 document = find_document_for_doc_id (notmuch, *p);
1620 mtime = Xapian::sortable_unserialise (
1621 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1623 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1624 NOTMUCH_FIND_CREATE, &status);
1625 notmuch_directory_set_mtime (directory, mtime);
1626 notmuch_directory_destroy (directory);
1628 db->delete_document (*p);
1635 /* Perform metadata upgrades. */
1637 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1638 * messages were stored as database metadata. Change these to
1641 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1642 notmuch_message_t *message;
1643 std::string message_id, thread_id;
1645 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1646 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1648 if (do_progress_notify) {
1649 progress_notify (closure, (double) count / total);
1650 do_progress_notify = 0;
1653 message_id = (*t).substr (
1654 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1655 thread_id = db->get_metadata (*t);
1657 /* Create ghost message */
1658 message = _notmuch_message_create_for_message_id (
1659 notmuch, message_id.c_str (), &private_status);
1660 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1661 /* Document already exists; ignore the stored thread ID */
1662 } else if (private_status ==
1663 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1664 private_status = _notmuch_message_initialize_ghost (
1665 message, thread_id.c_str ());
1666 if (! private_status)
1667 _notmuch_message_sync (message);
1670 if (private_status) {
1671 _notmuch_database_log (notmuch,
1672 "Upgrade failed while creating ghost messages.\n");
1673 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1677 /* Clear saved metadata thread ID */
1678 db->set_metadata (*t, "");
1684 status = NOTMUCH_STATUS_SUCCESS;
1685 db->set_metadata ("features", _print_features (local, notmuch->features));
1686 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1689 if (status == NOTMUCH_STATUS_SUCCESS)
1690 db->commit_transaction ();
1692 db->cancel_transaction ();
1694 if (timer_is_active) {
1695 /* Now stop the timer. */
1696 timerval.it_interval.tv_sec = 0;
1697 timerval.it_interval.tv_usec = 0;
1698 timerval.it_value.tv_sec = 0;
1699 timerval.it_value.tv_usec = 0;
1700 setitimer (ITIMER_REAL, &timerval, NULL);
1702 /* And disable the signal handler. */
1703 action.sa_handler = SIG_IGN;
1704 sigaction (SIGALRM, &action, NULL);
1708 notmuch_query_destroy (query);
1710 talloc_free (local);
1715 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1717 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1718 notmuch->atomic_nesting > 0)
1721 if (notmuch_database_needs_upgrade (notmuch))
1722 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1725 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1726 } catch (const Xapian::Error &error) {
1727 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1728 error.get_msg().c_str());
1729 notmuch->exception_reported = TRUE;
1730 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1734 notmuch->atomic_nesting++;
1735 return NOTMUCH_STATUS_SUCCESS;
1739 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1741 Xapian::WritableDatabase *db;
1743 if (notmuch->atomic_nesting == 0)
1744 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1746 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1747 notmuch->atomic_nesting > 1)
1750 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1752 db->commit_transaction ();
1754 /* This is a hack for testing. Xapian never flushes on a
1755 * non-flushed commit, even if the flush threshold is 1.
1756 * However, we rely on flushing to test atomicity. */
1757 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1758 if (thresh && atoi (thresh) == 1)
1760 } catch (const Xapian::Error &error) {
1761 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1762 error.get_msg().c_str());
1763 notmuch->exception_reported = TRUE;
1764 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1767 if (notmuch->atomic_dirty) {
1768 ++notmuch->revision;
1769 notmuch->atomic_dirty = FALSE;
1773 notmuch->atomic_nesting--;
1774 return NOTMUCH_STATUS_SUCCESS;
1778 notmuch_database_get_revision (notmuch_database_t *notmuch,
1782 *uuid = notmuch->uuid;
1783 return notmuch->revision;
1786 /* We allow the user to use arbitrarily long paths for directories. But
1787 * we have a term-length limit. So if we exceed that, we'll use the
1788 * SHA-1 of the path for the database term.
1790 * Note: This function may return the original value of 'path'. If it
1791 * does not, then the caller is responsible to free() the returned
1795 _notmuch_database_get_directory_db_path (const char *path)
1797 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1799 if (term_len > NOTMUCH_TERM_MAX)
1800 return _notmuch_sha1_of_string (path);
1805 /* Given a path, split it into two parts: the directory part is all
1806 * components except for the last, and the basename is that last
1807 * component. Getting the return-value for either part is optional
1808 * (the caller can pass NULL).
1810 * The original 'path' can represent either a regular file or a
1811 * directory---the splitting will be carried out in the same way in
1812 * either case. Trailing slashes on 'path' will be ignored, and any
1813 * cases of multiple '/' characters appearing in series will be
1814 * treated as a single '/'.
1816 * Allocation (if any) will have 'ctx' as the talloc owner. But
1817 * pointers will be returned within the original path string whenever
1820 * Note: If 'path' is non-empty and contains no non-trailing slash,
1821 * (that is, consists of a filename with no parent directory), then
1822 * the directory returned will be an empty string. However, if 'path'
1823 * is an empty string, then both directory and basename will be
1827 _notmuch_database_split_path (void *ctx,
1829 const char **directory,
1830 const char **basename)
1834 if (path == NULL || *path == '\0') {
1839 return NOTMUCH_STATUS_SUCCESS;
1842 /* Find the last slash (not counting a trailing slash), if any. */
1844 slash = path + strlen (path) - 1;
1846 /* First, skip trailing slashes. */
1847 while (slash != path && *slash == '/')
1850 /* Then, find a slash. */
1851 while (slash != path && *slash != '/') {
1858 /* Finally, skip multiple slashes. */
1859 while (slash != path && *(slash - 1) == '/')
1862 if (slash == path) {
1864 *directory = talloc_strdup (ctx, "");
1869 *directory = talloc_strndup (ctx, path, slash - path);
1872 return NOTMUCH_STATUS_SUCCESS;
1875 /* Find the document ID of the specified directory.
1877 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1878 * created if one does not exist for 'path'. Otherwise, if the
1879 * directory document does not exist, this sets *directory_id to
1880 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1883 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1885 notmuch_find_flags_t flags,
1886 unsigned int *directory_id)
1888 notmuch_directory_t *directory;
1889 notmuch_status_t status;
1893 return NOTMUCH_STATUS_SUCCESS;
1896 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1897 if (status || !directory) {
1902 *directory_id = _notmuch_directory_get_document_id (directory);
1904 notmuch_directory_destroy (directory);
1906 return NOTMUCH_STATUS_SUCCESS;
1910 _notmuch_database_get_directory_path (void *ctx,
1911 notmuch_database_t *notmuch,
1912 unsigned int doc_id)
1914 Xapian::Document document;
1916 document = find_document_for_doc_id (notmuch, doc_id);
1918 return talloc_strdup (ctx, document.get_data ().c_str ());
1921 /* Given a legal 'filename' for the database, (either relative to
1922 * database path or absolute with initial components identical to
1923 * database path), return a new string (with 'ctx' as the talloc
1924 * owner) suitable for use as a direntry term value.
1926 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1927 * will be created in the database as needed. Otherwise, if the
1928 * necessary directory documents do not exist, this sets
1929 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1932 _notmuch_database_filename_to_direntry (void *ctx,
1933 notmuch_database_t *notmuch,
1934 const char *filename,
1935 notmuch_find_flags_t flags,
1938 const char *relative, *directory, *basename;
1939 Xapian::docid directory_id;
1940 notmuch_status_t status;
1942 relative = _notmuch_database_relative_path (notmuch, filename);
1944 status = _notmuch_database_split_path (ctx, relative,
1945 &directory, &basename);
1949 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1951 if (status || directory_id == (unsigned int)-1) {
1956 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1958 return NOTMUCH_STATUS_SUCCESS;
1961 /* Given a legal 'path' for the database, return the relative path.
1963 * The return value will be a pointer to the original path contents,
1964 * and will be either the original string (if 'path' was relative) or
1965 * a portion of the string (if path was absolute and begins with the
1969 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1972 const char *db_path, *relative;
1973 unsigned int db_path_len;
1975 db_path = notmuch_database_get_path (notmuch);
1976 db_path_len = strlen (db_path);
1980 if (*relative == '/') {
1981 while (*relative == '/' && *(relative+1) == '/')
1984 if (strncmp (relative, db_path, db_path_len) == 0)
1986 relative += db_path_len;
1987 while (*relative == '/')
1996 notmuch_database_get_directory (notmuch_database_t *notmuch,
1998 notmuch_directory_t **directory)
2000 notmuch_status_t status;
2002 if (directory == NULL)
2003 return NOTMUCH_STATUS_NULL_POINTER;
2007 *directory = _notmuch_directory_create (notmuch, path,
2008 NOTMUCH_FIND_LOOKUP, &status);
2009 } catch (const Xapian::Error &error) {
2010 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
2011 error.get_msg().c_str());
2012 notmuch->exception_reported = TRUE;
2013 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2018 /* Allocate a document ID that satisfies the following criteria:
2020 * 1. The ID does not exist for any document in the Xapian database
2022 * 2. The ID was not previously returned from this function
2024 * 3. The ID is the smallest integer satisfying (1) and (2)
2026 * This function will trigger an internal error if these constraints
2027 * cannot all be satisfied, (that is, the pool of available document
2028 * IDs has been exhausted).
2031 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2033 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2035 notmuch->last_doc_id++;
2037 if (notmuch->last_doc_id == 0)
2038 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2040 return notmuch->last_doc_id;
2044 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
2046 /* 16 bytes (+ terminator) for hexadecimal representation of
2047 * a 64-bit integer. */
2048 static char thread_id[17];
2049 Xapian::WritableDatabase *db;
2051 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2053 notmuch->last_thread_id++;
2055 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2057 db->set_metadata ("last_thread_id", thread_id);
2063 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2065 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2066 message_id = _notmuch_message_id_compressed (ctx, message_id);
2068 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2072 static notmuch_status_t
2073 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2075 const char *message_id,
2076 const char **thread_id_ret);
2078 /* Find the thread ID to which the message with 'message_id' belongs.
2080 * Note: 'thread_id_ret' must not be NULL!
2081 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2084 * Note: If there is no message in the database with the given
2085 * 'message_id' then a new thread_id will be allocated for this
2086 * message ID and stored in the database metadata so that the
2087 * thread ID can be looked up if the message is added to the database
2090 static notmuch_status_t
2091 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2093 const char *message_id,
2094 const char **thread_id_ret)
2096 notmuch_private_status_t status;
2097 notmuch_message_t *message;
2099 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2100 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2103 /* Look for this message (regular or ghost) */
2104 message = _notmuch_message_create_for_message_id (
2105 notmuch, message_id, &status);
2106 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2107 /* Message exists */
2108 *thread_id_ret = talloc_steal (
2109 ctx, notmuch_message_get_thread_id (message));
2110 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2111 /* Message did not exist. Give it a fresh thread ID and
2112 * populate this message as a ghost message. */
2113 *thread_id_ret = talloc_strdup (
2114 ctx, _notmuch_database_generate_thread_id (notmuch));
2115 if (! *thread_id_ret) {
2116 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2118 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2120 /* Commit the new ghost message */
2121 _notmuch_message_sync (message);
2124 /* Create failed. Fall through. */
2127 notmuch_message_destroy (message);
2129 return COERCE_STATUS (status, "Error creating ghost message");
2132 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2133 static notmuch_status_t
2134 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2136 const char *message_id,
2137 const char **thread_id_ret)
2139 notmuch_status_t status;
2140 notmuch_message_t *message;
2141 string thread_id_string;
2143 Xapian::WritableDatabase *db;
2145 status = notmuch_database_find_message (notmuch, message_id, &message);
2151 *thread_id_ret = talloc_steal (ctx,
2152 notmuch_message_get_thread_id (message));
2154 notmuch_message_destroy (message);
2156 return NOTMUCH_STATUS_SUCCESS;
2159 /* Message has not been seen yet.
2161 * We may have seen a reference to it already, in which case, we
2162 * can return the thread ID stored in the metadata. Otherwise, we
2163 * generate a new thread ID and store it there.
2165 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2166 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2167 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2169 if (thread_id_string.empty()) {
2170 *thread_id_ret = talloc_strdup (ctx,
2171 _notmuch_database_generate_thread_id (notmuch));
2172 db->set_metadata (metadata_key, *thread_id_ret);
2174 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2177 talloc_free (metadata_key);
2179 return NOTMUCH_STATUS_SUCCESS;
2182 static notmuch_status_t
2183 _merge_threads (notmuch_database_t *notmuch,
2184 const char *winner_thread_id,
2185 const char *loser_thread_id)
2187 Xapian::PostingIterator loser, loser_end;
2188 notmuch_message_t *message = NULL;
2189 notmuch_private_status_t private_status;
2190 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2192 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2194 for ( ; loser != loser_end; loser++) {
2195 message = _notmuch_message_create (notmuch, notmuch,
2196 *loser, &private_status);
2197 if (message == NULL) {
2198 ret = COERCE_STATUS (private_status,
2199 "Cannot find document for doc_id from query");
2203 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2204 _notmuch_message_add_term (message, "thread", winner_thread_id);
2205 _notmuch_message_sync (message);
2207 notmuch_message_destroy (message);
2213 notmuch_message_destroy (message);
2219 _my_talloc_free_for_g_hash (void *ptr)
2224 static notmuch_status_t
2225 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2226 notmuch_message_t *message,
2227 notmuch_message_file_t *message_file,
2228 const char **thread_id)
2230 GHashTable *parents = NULL;
2231 const char *refs, *in_reply_to, *in_reply_to_message_id;
2232 const char *last_ref_message_id, *this_message_id;
2233 GList *l, *keys = NULL;
2234 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2236 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2237 _my_talloc_free_for_g_hash, NULL);
2238 this_message_id = notmuch_message_get_message_id (message);
2240 refs = _notmuch_message_file_get_header (message_file, "references");
2241 last_ref_message_id = parse_references (message,
2245 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2246 in_reply_to_message_id = parse_references (message,
2248 parents, in_reply_to);
2250 /* For the parent of this message, use the last message ID of the
2251 * References header, if available. If not, fall back to the
2252 * first message ID in the In-Reply-To header. */
2253 if (last_ref_message_id) {
2254 _notmuch_message_add_term (message, "replyto",
2255 last_ref_message_id);
2256 } else if (in_reply_to_message_id) {
2257 _notmuch_message_add_term (message, "replyto",
2258 in_reply_to_message_id);
2261 keys = g_hash_table_get_keys (parents);
2262 for (l = keys; l; l = l->next) {
2263 char *parent_message_id;
2264 const char *parent_thread_id = NULL;
2266 parent_message_id = (char *) l->data;
2268 _notmuch_message_add_term (message, "reference",
2271 ret = _resolve_message_id_to_thread_id (notmuch,
2278 if (*thread_id == NULL) {
2279 *thread_id = talloc_strdup (message, parent_thread_id);
2280 _notmuch_message_add_term (message, "thread", *thread_id);
2281 } else if (strcmp (*thread_id, parent_thread_id)) {
2282 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2292 g_hash_table_unref (parents);
2297 static notmuch_status_t
2298 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2299 notmuch_message_t *message,
2300 const char **thread_id)
2302 const char *message_id = notmuch_message_get_message_id (message);
2303 Xapian::PostingIterator child, children_end;
2304 notmuch_message_t *child_message = NULL;
2305 const char *child_thread_id;
2306 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2307 notmuch_private_status_t private_status;
2309 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2311 for ( ; child != children_end; child++) {
2313 child_message = _notmuch_message_create (message, notmuch,
2314 *child, &private_status);
2315 if (child_message == NULL) {
2316 ret = COERCE_STATUS (private_status,
2317 "Cannot find document for doc_id from query");
2321 child_thread_id = notmuch_message_get_thread_id (child_message);
2322 if (*thread_id == NULL) {
2323 *thread_id = talloc_strdup (message, child_thread_id);
2324 _notmuch_message_add_term (message, "thread", *thread_id);
2325 } else if (strcmp (*thread_id, child_thread_id)) {
2326 _notmuch_message_remove_term (child_message, "reference",
2328 _notmuch_message_sync (child_message);
2329 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2334 notmuch_message_destroy (child_message);
2335 child_message = NULL;
2340 notmuch_message_destroy (child_message);
2345 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2347 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2348 notmuch_message_t *message)
2350 const char *message_id;
2354 message_id = notmuch_message_get_message_id (message);
2355 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2357 /* Check if we have already seen related messages to this one.
2358 * If we have then use the thread_id that we stored at that time.
2360 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2361 if (stored_id.empty ()) {
2364 Xapian::WritableDatabase *db;
2366 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2368 /* Clear the metadata for this message ID. We don't need it
2370 db->set_metadata (metadata_key, "");
2372 return talloc_strdup (ctx, stored_id.c_str ());
2376 /* Given a blank or ghost 'message' and its corresponding
2377 * 'message_file' link it to existing threads in the database.
2379 * First, if is_ghost, this retrieves the thread ID already stored in
2380 * the message (which will be the case if a message was previously
2381 * added that referenced this one). If the message is blank
2382 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2383 * later in this function). If the database does not support ghost
2384 * messages, this checks for a thread ID stored in database metadata
2385 * for this message ID.
2387 * Second, we look at 'message_file' and its link-relevant headers
2388 * (References and In-Reply-To) for message IDs.
2390 * Finally, we look in the database for existing message that
2391 * reference 'message'.
2393 * In all cases, we assign to the current message the first thread ID
2394 * found. We will also merge any existing, distinct threads where this
2395 * message belongs to both, (which is not uncommon when messages are
2396 * processed out of order).
2398 * Finally, if no thread ID has been found through referenced messages, we
2399 * call _notmuch_message_generate_thread_id to generate a new thread
2400 * ID. This should only happen for new, top-level messages, (no
2401 * References or In-Reply-To header in this message, and no previously
2402 * added message refers to this message).
2404 static notmuch_status_t
2405 _notmuch_database_link_message (notmuch_database_t *notmuch,
2406 notmuch_message_t *message,
2407 notmuch_message_file_t *message_file,
2408 notmuch_bool_t is_ghost)
2410 void *local = talloc_new (NULL);
2411 notmuch_status_t status;
2412 const char *thread_id = NULL;
2414 /* Check if the message already had a thread ID */
2415 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2417 thread_id = notmuch_message_get_thread_id (message);
2419 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2421 _notmuch_message_add_term (message, "thread", thread_id);
2424 status = _notmuch_database_link_message_to_parents (notmuch, message,
2430 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2431 /* In general, it shouldn't be necessary to link children,
2432 * since the earlier indexing of those children will have
2433 * stored a thread ID for the missing parent. However, prior
2434 * to ghost messages, these stored thread IDs were NOT
2435 * rewritten during thread merging (and there was no
2436 * performant way to do so), so if indexed children were
2437 * pulled into a different thread ID by a merge, it was
2438 * necessary to pull them *back* into the stored thread ID of
2439 * the parent. With ghost messages, we just rewrite the
2440 * stored thread IDs during merging, so this workaround isn't
2442 status = _notmuch_database_link_message_to_children (notmuch, message,
2448 /* If not part of any existing thread, generate a new thread ID. */
2449 if (thread_id == NULL) {
2450 thread_id = _notmuch_database_generate_thread_id (notmuch);
2452 _notmuch_message_add_term (message, "thread", thread_id);
2456 talloc_free (local);
2462 notmuch_database_add_message (notmuch_database_t *notmuch,
2463 const char *filename,
2464 notmuch_message_t **message_ret)
2466 notmuch_message_file_t *message_file;
2467 notmuch_message_t *message = NULL;
2468 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2469 notmuch_private_status_t private_status;
2470 notmuch_bool_t is_ghost = false;
2472 const char *date, *header;
2473 const char *from, *to, *subject;
2474 char *message_id = NULL;
2477 *message_ret = NULL;
2479 ret = _notmuch_database_ensure_writable (notmuch);
2483 message_file = _notmuch_message_file_open (notmuch, filename);
2484 if (message_file == NULL)
2485 return NOTMUCH_STATUS_FILE_ERROR;
2487 /* Adding a message may change many documents. Do this all
2489 ret = notmuch_database_begin_atomic (notmuch);
2493 /* Parse message up front to get better error status. */
2494 ret = _notmuch_message_file_parse (message_file);
2498 /* Before we do any real work, (especially before doing a
2499 * potential SHA-1 computation on the entire file's contents),
2500 * let's make sure that what we're looking at looks like an
2501 * actual email message.
2503 from = _notmuch_message_file_get_header (message_file, "from");
2504 subject = _notmuch_message_file_get_header (message_file, "subject");
2505 to = _notmuch_message_file_get_header (message_file, "to");
2507 if ((from == NULL || *from == '\0') &&
2508 (subject == NULL || *subject == '\0') &&
2509 (to == NULL || *to == '\0')) {
2510 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2514 /* Now that we're sure it's mail, the first order of business
2515 * is to find a message ID (or else create one ourselves).
2517 header = _notmuch_message_file_get_header (message_file, "message-id");
2518 if (header && *header != '\0') {
2519 message_id = _parse_message_id (message_file, header, NULL);
2521 /* So the header value isn't RFC-compliant, but it's
2522 * better than no message-id at all.
2524 if (message_id == NULL)
2525 message_id = talloc_strdup (message_file, header);
2528 if (message_id == NULL ) {
2529 /* No message-id at all, let's generate one by taking a
2530 * hash over the file's contents.
2532 char *sha1 = _notmuch_sha1_of_file (filename);
2534 /* If that failed too, something is really wrong. Give up. */
2536 ret = NOTMUCH_STATUS_FILE_ERROR;
2540 message_id = talloc_asprintf (message_file, "notmuch-sha1-%s", sha1);
2545 /* Now that we have a message ID, we get a message object,
2546 * (which may or may not reference an existing document in the
2549 message = _notmuch_message_create_for_message_id (notmuch,
2553 talloc_free (message_id);
2555 if (message == NULL) {
2556 ret = COERCE_STATUS (private_status,
2557 "Unexpected status value from _notmuch_message_create_for_message_id");
2561 _notmuch_message_add_filename (message, filename);
2563 /* Is this a newly created message object or a ghost
2564 * message? We have to be slightly careful: if this is a
2565 * blank message, it's not safe to call
2566 * notmuch_message_get_flag yet. */
2567 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2568 (is_ghost = notmuch_message_get_flag (
2569 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2570 _notmuch_message_add_term (message, "type", "mail");
2572 /* Convert ghost message to a regular message */
2573 _notmuch_message_remove_term (message, "type", "ghost");
2575 ret = _notmuch_database_link_message (notmuch, message,
2576 message_file, is_ghost);
2580 date = _notmuch_message_file_get_header (message_file, "date");
2581 _notmuch_message_set_header_values (message, date, from, subject);
2583 ret = _notmuch_message_index_file (message, message_file);
2587 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2590 _notmuch_message_sync (message);
2591 } catch (const Xapian::Error &error) {
2592 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2593 error.get_msg().c_str());
2594 notmuch->exception_reported = TRUE;
2595 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2601 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2602 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2603 *message_ret = message;
2605 notmuch_message_destroy (message);
2609 _notmuch_message_file_close (message_file);
2611 ret2 = notmuch_database_end_atomic (notmuch);
2612 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2613 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2614 ret2 != NOTMUCH_STATUS_SUCCESS)
2621 notmuch_database_remove_message (notmuch_database_t *notmuch,
2622 const char *filename)
2624 notmuch_status_t status;
2625 notmuch_message_t *message;
2627 status = notmuch_database_find_message_by_filename (notmuch, filename,
2630 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2631 status = _notmuch_message_remove_filename (message, filename);
2632 if (status == NOTMUCH_STATUS_SUCCESS)
2633 _notmuch_message_delete (message);
2634 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2635 _notmuch_message_sync (message);
2637 notmuch_message_destroy (message);
2644 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2645 const char *filename,
2646 notmuch_message_t **message_ret)
2649 const char *prefix = _find_prefix ("file-direntry");
2650 char *direntry, *term;
2651 Xapian::PostingIterator i, end;
2652 notmuch_status_t status;
2654 if (message_ret == NULL)
2655 return NOTMUCH_STATUS_NULL_POINTER;
2657 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2658 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2660 /* return NULL on any failure */
2661 *message_ret = NULL;
2663 local = talloc_new (notmuch);
2666 status = _notmuch_database_filename_to_direntry (
2667 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2668 if (status || !direntry)
2671 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2673 find_doc_ids_for_term (notmuch, term, &i, &end);
2676 notmuch_private_status_t private_status;
2678 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2680 if (*message_ret == NULL)
2681 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2683 } catch (const Xapian::Error &error) {
2684 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2685 error.get_msg().c_str());
2686 notmuch->exception_reported = TRUE;
2687 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2691 talloc_free (local);
2693 if (status && *message_ret) {
2694 notmuch_message_destroy (*message_ret);
2695 *message_ret = NULL;
2700 notmuch_string_list_t *
2701 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2702 Xapian::TermIterator &end,
2705 int prefix_len = strlen (prefix);
2706 notmuch_string_list_t *list;
2708 list = _notmuch_string_list_create (ctx);
2709 if (unlikely (list == NULL))
2712 for (i.skip_to (prefix); i != end; i++) {
2713 /* Terminate loop at first term without desired prefix. */
2714 if (strncmp ((*i).c_str (), prefix, prefix_len))
2717 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2724 notmuch_database_get_all_tags (notmuch_database_t *db)
2726 Xapian::TermIterator i, end;
2727 notmuch_string_list_t *tags;
2730 i = db->xapian_db->allterms_begin();
2731 end = db->xapian_db->allterms_end();
2732 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2733 _find_prefix ("tag"));
2734 _notmuch_string_list_sort (tags);
2735 return _notmuch_tags_create (db, tags);
2736 } catch (const Xapian::Error &error) {
2737 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2738 error.get_msg().c_str());
2739 db->exception_reported = TRUE;
2745 notmuch_database_status_string (const notmuch_database_t *notmuch)
2747 return notmuch->status_string;