1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
24 #include "string-util.h"
33 #include <glib.h> /* g_free, GPtrArray, GHashTable */
34 #include <glib-object.h> /* g_type_init */
36 #include <gmime/gmime.h> /* g_mime_init */
40 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
45 notmuch_field_flag_t flags;
48 #define NOTMUCH_DATABASE_VERSION 3
50 #define STRINGIFY(s) _SUB_STRINGIFY(s)
51 #define _SUB_STRINGIFY(s) #s
53 #if HAVE_XAPIAN_DB_RETRY_LOCK
54 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
56 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
59 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
61 * We currently have three different types of documents (mail, ghost,
62 * and directory) and also some metadata.
66 * A mail document is associated with a particular email message. It
67 * is stored in one or more files on disk (though only one has its
68 * content indexed) and is uniquely identified by its "id" field
69 * (which is generally the message ID). It is indexed with the
70 * following prefixed terms which the database uses to construct
73 * Single terms of given prefix:
77 * id: Unique ID of mail. This is from the Message-ID header
78 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
79 * If it's present and too long, then we use
80 * "notmuch-sha1-<sha1_sum_of_message_id>".
81 * If this header is not present, we use
82 * "notmuch-sha1-<sha1_sum_of_entire_file>".
84 * thread: The ID of the thread to which the mail belongs
86 * replyto: The ID from the In-Reply-To header of the mail (if any).
88 * Multiple terms of given prefix:
90 * reference: All message IDs from In-Reply-To and References
91 * headers in the message.
93 * tag: Any tags associated with this message by the user.
95 * file-direntry: A colon-separated pair of values
96 * (INTEGER:STRING), where INTEGER is the
97 * document ID of a directory document, and
98 * STRING is the name of a file within that
99 * directory for this mail message.
101 * property: Has a property with key=value
102 * FIXME: if no = is present, should match on any value
104 * A mail document also has four values:
106 * TIMESTAMP: The time_t value corresponding to the message's
109 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
111 * FROM: The value of the "From" header
113 * SUBJECT: The value of the "Subject" header
115 * LAST_MOD: The revision number as of the last tag or
118 * In addition, terms from the content of the message are added with
119 * "from", "to", "attachment", and "subject" prefixes for use by the
120 * user in searching. Similarly, terms from the path of the mail
121 * message are added with "folder" and "path" prefixes. But the
122 * database doesn't really care itself about any of these.
124 * The data portion of a mail document is empty.
126 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
127 * -----------------------------------------------
128 * A ghost mail document is like a mail document, but where we don't
129 * have the message content. These are used to track thread reference
130 * information for messages we haven't received.
132 * A ghost mail document has type: ghost; id and thread fields that
133 * are identical to the mail document fields; and a MESSAGE_ID value.
137 * A directory document is used by a client of the notmuch library to
138 * maintain data necessary to allow for efficient polling of mail
141 * All directory documents contain one term:
143 * directory: The directory path (relative to the database path)
144 * Or the SHA1 sum of the directory path (if the
145 * path itself is too long to fit in a Xapian
148 * And all directory documents for directories other than top-level
149 * directories also contain the following term:
151 * directory-direntry: A colon-separated pair of values
152 * (INTEGER:STRING), where INTEGER is the
153 * document ID of the parent directory
154 * document, and STRING is the name of this
155 * directory within that parent.
157 * All directory documents have a single value:
159 * TIMESTAMP: The mtime of the directory (at last scan)
161 * The data portion of a directory document contains the path of the
162 * directory (relative to the database path).
166 * Xapian allows us to store arbitrary name-value pairs as
167 * "metadata". We currently use the following metadata names with the
170 * version The database schema version, (which is distinct
171 * from both the notmuch package version (see
172 * notmuch --version) and the libnotmuch library
173 * version. The version is stored as an base-10
174 * ASCII integer. The initial database version
175 * was 1, (though a schema existed before that
176 * were no "version" database value existed at
177 * all). Successive versions are allocated as
178 * changes are made to the database (such as by
179 * indexing new fields).
181 * features The set of features supported by this
182 * database. This consists of a set of
183 * '\n'-separated lines, where each is a feature
184 * name, a '\t', and compatibility flags. If the
185 * compatibility flags contain 'w', then the
186 * opener must support this feature to safely
187 * write this database. If the compatibility
188 * flags contain 'r', then the opener must
189 * support this feature to read this database.
190 * Introduced in database version 3.
192 * last_thread_id The last thread ID generated. This is stored
193 * as a 16-byte hexadecimal ASCII representation
194 * of a 64-bit unsigned integer. The first ID
195 * generated is 1 and the value will be
196 * incremented for each thread ID.
198 * C* metadata keys starting with C indicate
199 * configuration data. It can be managed with the
200 * n_database_*config* API. There is a convention
201 * of hierarchical keys separated by '.' (e.g.
202 * query.notmuch stores the value for the named
203 * query 'notmuch'), but it is not enforced by the
209 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
210 * Instead, the database has the following additional database
213 * thread_id_* A pre-allocated thread ID for a particular
214 * message. This is actually an arbitrarily large
215 * family of metadata name. Any particular name is
216 * formed by concatenating "thread_id_" with a message
217 * ID (or the SHA1 sum of a message ID if it is very
218 * long---see description of 'id' in the mail
219 * document). The value stored is a thread ID.
221 * These thread ID metadata values are stored
222 * whenever a message references a parent message
223 * that does not yet exist in the database. A
224 * thread ID will be allocated and stored, and if
225 * the message is later added, the stored thread
226 * ID will be used (and the metadata value will
229 * Even before a message is added, it's
230 * pre-allocated thread ID is useful so that all
231 * descendant messages that reference this common
232 * parent can be recognized as belonging to the
236 /* With these prefix values we follow the conventions published here:
238 * https://xapian.org/docs/omega/termprefixes.html
240 * as much as makes sense. Note that I took some liberty in matching
241 * the reserved prefix values to notmuch concepts, (for example, 'G'
242 * is documented as "newsGroup (or similar entity - e.g. a web forum
243 * name)", for which I think the thread is the closest analogue in
244 * notmuch. This in spite of the fact that we will eventually be
245 * storing mailing-list messages where 'G' for "mailing list name"
246 * might be even a closer analogue. I'm treating the single-character
247 * prefixes preferentially for core notmuch concepts (which will be
248 * nearly universal to all mail messages).
252 prefix_t prefix_table[] = {
253 /* name term prefix flags */
254 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
255 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
256 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
257 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
258 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
259 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
260 { "thread", "G", NOTMUCH_FIELD_EXTERNAL },
261 { "tag", "K", NOTMUCH_FIELD_EXTERNAL },
262 { "is", "K", NOTMUCH_FIELD_EXTERNAL },
263 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
264 { "path", "P", NOTMUCH_FIELD_EXTERNAL },
265 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
267 * Unconditionally add ':' to reduce potential ambiguity with
268 * overlapping prefixes and/or terms that start with capital
269 * letters. See Xapian document termprefixes.html for related
272 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL },
273 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
274 NOTMUCH_FIELD_PROBABILISTIC },
275 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
276 NOTMUCH_FIELD_PROBABILISTIC },
277 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
278 NOTMUCH_FIELD_PROBABILISTIC },
279 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
280 NOTMUCH_FIELD_PROBABILISTIC },
281 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
282 NOTMUCH_FIELD_PROBABILISTIC },
286 _find_prefix (const char *name)
290 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
291 if (strcmp (name, prefix_table[i].name) == 0)
292 return prefix_table[i].prefix;
295 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
300 static const struct {
301 /* NOTMUCH_FEATURE_* value. */
302 _notmuch_features value;
303 /* Feature name as it appears in the database. This name should
304 * be appropriate for displaying to the user if an older version
305 * of notmuch doesn't support this feature. */
307 /* Compatibility flags when this feature is declared. */
309 } feature_names[] = {
310 { NOTMUCH_FEATURE_FILE_TERMS,
311 "multiple paths per message", "rw" },
312 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
313 "relative directory paths", "rw" },
314 /* Header values are not required for reading a database because a
315 * reader can just refer to the message file. */
316 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
317 "from/subject/message-ID in database", "w" },
318 { NOTMUCH_FEATURE_BOOL_FOLDER,
319 "exact folder:/path: search", "rw" },
320 { NOTMUCH_FEATURE_GHOSTS,
321 "mail documents for missing messages", "w"},
322 /* Knowledge of the index mime-types are not required for reading
323 * a database because a reader will just be unable to query
325 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
326 "indexed MIME types", "w"},
327 { NOTMUCH_FEATURE_LAST_MOD,
328 "modification tracking", "w"},
332 notmuch_status_to_string (notmuch_status_t status)
335 case NOTMUCH_STATUS_SUCCESS:
336 return "No error occurred";
337 case NOTMUCH_STATUS_OUT_OF_MEMORY:
338 return "Out of memory";
339 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
340 return "Attempt to write to a read-only database";
341 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
342 return "A Xapian exception occurred";
343 case NOTMUCH_STATUS_FILE_ERROR:
344 return "Something went wrong trying to read or write a file";
345 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
346 return "File is not an email";
347 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
348 return "Message ID is identical to a message in database";
349 case NOTMUCH_STATUS_NULL_POINTER:
350 return "Erroneous NULL pointer";
351 case NOTMUCH_STATUS_TAG_TOO_LONG:
352 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
353 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
354 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
355 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
356 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
357 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
358 return "Unsupported operation";
359 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
360 return "Operation requires a database upgrade";
361 case NOTMUCH_STATUS_PATH_ERROR:
362 return "Path supplied is illegal for this function";
364 case NOTMUCH_STATUS_LAST_STATUS:
365 return "Unknown error status value";
370 _notmuch_database_log (notmuch_database_t *notmuch,
376 va_start (va_args, format);
378 if (notmuch->status_string)
379 talloc_free (notmuch->status_string);
381 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
386 _notmuch_database_log_append (notmuch_database_t *notmuch,
392 va_start (va_args, format);
394 if (notmuch->status_string)
395 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
397 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
403 find_doc_ids_for_term (notmuch_database_t *notmuch,
405 Xapian::PostingIterator *begin,
406 Xapian::PostingIterator *end)
408 *begin = notmuch->xapian_db->postlist_begin (term);
410 *end = notmuch->xapian_db->postlist_end (term);
414 find_doc_ids (notmuch_database_t *notmuch,
415 const char *prefix_name,
417 Xapian::PostingIterator *begin,
418 Xapian::PostingIterator *end)
422 term = talloc_asprintf (notmuch, "%s%s",
423 _find_prefix (prefix_name), value);
425 find_doc_ids_for_term (notmuch, term, begin, end);
430 notmuch_private_status_t
431 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
432 const char *prefix_name,
434 unsigned int *doc_id)
436 Xapian::PostingIterator i, end;
438 find_doc_ids (notmuch, prefix_name, value, &i, &end);
442 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
447 #if DEBUG_DATABASE_SANITY
451 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
455 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
458 static Xapian::Document
459 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
461 return notmuch->xapian_db->get_document (doc_id);
464 /* Generate a compressed version of 'message_id' of the form:
466 * notmuch-sha1-<sha1_sum_of_message_id>
469 _notmuch_message_id_compressed (void *ctx, const char *message_id)
471 char *sha1, *compressed;
473 sha1 = _notmuch_sha1_of_string (message_id);
475 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
482 notmuch_database_find_message (notmuch_database_t *notmuch,
483 const char *message_id,
484 notmuch_message_t **message_ret)
486 notmuch_private_status_t status;
489 if (message_ret == NULL)
490 return NOTMUCH_STATUS_NULL_POINTER;
492 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
493 message_id = _notmuch_message_id_compressed (notmuch, message_id);
496 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
497 message_id, &doc_id);
499 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
502 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
504 if (*message_ret == NULL)
505 return NOTMUCH_STATUS_OUT_OF_MEMORY;
508 return NOTMUCH_STATUS_SUCCESS;
509 } catch (const Xapian::Error &error) {
510 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
511 error.get_msg().c_str());
512 notmuch->exception_reported = TRUE;
514 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
518 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
519 * a (potentially nested) parenthesized sequence with '\' used to
520 * escape any character (including parentheses).
522 * If the sequence to be skipped continues to the end of the string,
523 * then 'str' will be left pointing at the final terminating '\0'
527 skip_space_and_comments (const char **str)
532 while (*s && (isspace (*s) || *s == '(')) {
533 while (*s && isspace (*s))
538 while (*s && nesting) {
541 } else if (*s == ')') {
543 } else if (*s == '\\') {
555 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
556 * comments, and the '<' and '>' delimiters.
558 * If not NULL, then *next will be made to point to the first character
559 * not parsed, (possibly pointing to the final '\0' terminator.
561 * Returns a newly talloc'ed string belonging to 'ctx'.
563 * Returns NULL if there is any error parsing the message-id. */
565 _parse_message_id (void *ctx, const char *message_id, const char **next)
570 if (message_id == NULL || *message_id == '\0')
575 skip_space_and_comments (&s);
577 /* Skip any unstructured text as well. */
578 while (*s && *s != '<')
589 skip_space_and_comments (&s);
592 while (*end && *end != '>')
601 if (end > s && *end == '>')
606 result = talloc_strndup (ctx, s, end - s + 1);
608 /* Finally, collapse any whitespace that is within the message-id
614 for (r = result, len = strlen (r); *r; r++, len--)
615 if (*r == ' ' || *r == '\t')
616 memmove (r, r+1, len);
622 /* Parse a References header value, putting a (talloc'ed under 'ctx')
623 * copy of each referenced message-id into 'hash'.
625 * We explicitly avoid including any reference identical to
626 * 'message_id' in the result (to avoid mass confusion when a single
627 * message references itself cyclically---and yes, mail messages are
628 * not infrequent in the wild that do this---don't ask me why).
630 * Return the last reference parsed, if it is not equal to message_id.
633 parse_references (void *ctx,
634 const char *message_id,
638 char *ref, *last_ref = NULL;
640 if (refs == NULL || *refs == '\0')
644 ref = _parse_message_id (ctx, refs, &refs);
646 if (ref && strcmp (ref, message_id)) {
647 g_hash_table_insert (hash, ref, NULL);
652 /* The return value of this function is used to add a parent
653 * reference to the database. We should avoid making a message
654 * its own parent, thus the above check.
660 notmuch_database_create (const char *path, notmuch_database_t **database)
662 char *status_string = NULL;
663 notmuch_status_t status;
665 status = notmuch_database_create_verbose (path, database,
669 fputs (status_string, stderr);
670 free (status_string);
677 notmuch_database_create_verbose (const char *path,
678 notmuch_database_t **database,
679 char **status_string)
681 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
682 notmuch_database_t *notmuch = NULL;
683 char *notmuch_path = NULL;
684 char *message = NULL;
689 message = strdup ("Error: Cannot create a database for a NULL path.\n");
690 status = NOTMUCH_STATUS_NULL_POINTER;
694 if (path[0] != '/') {
695 message = strdup ("Error: Database path must be absolute.\n");
696 status = NOTMUCH_STATUS_PATH_ERROR;
700 err = stat (path, &st);
702 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
703 path, strerror (errno)));
704 status = NOTMUCH_STATUS_FILE_ERROR;
708 if (! S_ISDIR (st.st_mode)) {
709 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
710 "Not a directory.\n",
712 status = NOTMUCH_STATUS_FILE_ERROR;
716 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
718 err = mkdir (notmuch_path, 0755);
721 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
722 notmuch_path, strerror (errno)));
723 status = NOTMUCH_STATUS_FILE_ERROR;
727 status = notmuch_database_open_verbose (path,
728 NOTMUCH_DATABASE_MODE_READ_WRITE,
733 /* Upgrade doesn't add these feature to existing databases, but
734 * new databases have them. */
735 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
736 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
738 status = notmuch_database_upgrade (notmuch, NULL, NULL);
740 notmuch_database_close(notmuch);
746 talloc_free (notmuch_path);
750 *status_string = message;
757 talloc_free (notmuch);
762 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
764 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
765 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
766 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
769 return NOTMUCH_STATUS_SUCCESS;
772 /* Allocate a revision number for the next change. */
774 _notmuch_database_new_revision (notmuch_database_t *notmuch)
776 unsigned long new_revision = notmuch->revision + 1;
778 /* If we're in an atomic section, hold off on updating the
779 * committed revision number until we commit the atomic section.
781 if (notmuch->atomic_nesting)
782 notmuch->atomic_dirty = TRUE;
784 notmuch->revision = new_revision;
789 /* Parse a database features string from the given database version.
790 * Returns the feature bit set.
792 * For version < 3, this ignores the features string and returns a
793 * hard-coded set of features.
795 * If there are unrecognized features that are required to open the
796 * database in mode (which should be 'r' or 'w'), return a
797 * comma-separated list of unrecognized but required features in
798 * *incompat_out suitable for presenting to the user. *incompat_out
799 * will be allocated from ctx.
801 static _notmuch_features
802 _parse_features (const void *ctx, const char *features, unsigned int version,
803 char mode, char **incompat_out)
805 _notmuch_features res = static_cast<_notmuch_features>(0);
806 unsigned int namelen, i;
810 /* Prior to database version 3, features were implied by the
813 return NOTMUCH_FEATURES_V0;
814 else if (version == 1)
815 return NOTMUCH_FEATURES_V1;
816 else if (version == 2)
817 return NOTMUCH_FEATURES_V2;
819 /* Parse the features string */
820 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
821 flags = strchr (features, '\t');
822 if (! flags || flags > features + llen)
824 namelen = flags - features;
826 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
827 if (strlen (feature_names[i].name) == namelen &&
828 strncmp (feature_names[i].name, features, namelen) == 0) {
829 res |= feature_names[i].value;
834 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
835 /* Unrecognized feature */
836 const char *have = strchr (flags, mode);
837 if (have && have < features + llen) {
838 /* This feature is required to access this database in
839 * 'mode', but we don't understand it. */
841 *incompat_out = talloc_strdup (ctx, "");
842 *incompat_out = talloc_asprintf_append_buffer (
843 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
853 _print_features (const void *ctx, unsigned int features)
856 char *res = talloc_strdup (ctx, "");
858 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
859 if (features & feature_names[i].value)
860 res = talloc_asprintf_append_buffer (
861 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
867 notmuch_database_open (const char *path,
868 notmuch_database_mode_t mode,
869 notmuch_database_t **database)
871 char *status_string = NULL;
872 notmuch_status_t status;
874 status = notmuch_database_open_verbose (path, mode, database,
878 fputs (status_string, stderr);
879 free (status_string);
886 notmuch_database_open_verbose (const char *path,
887 notmuch_database_mode_t mode,
888 notmuch_database_t **database,
889 char **status_string)
891 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
892 void *local = talloc_new (NULL);
893 notmuch_database_t *notmuch = NULL;
894 char *notmuch_path, *xapian_path, *incompat_features;
895 char *message = NULL;
898 unsigned int i, version;
899 static int initialized = 0;
902 message = strdup ("Error: Cannot open a database for a NULL path.\n");
903 status = NOTMUCH_STATUS_NULL_POINTER;
907 if (path[0] != '/') {
908 message = strdup ("Error: Database path must be absolute.\n");
909 status = NOTMUCH_STATUS_PATH_ERROR;
913 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
914 message = strdup ("Out of memory\n");
915 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
919 err = stat (notmuch_path, &st);
921 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
922 notmuch_path, strerror (errno)));
923 status = NOTMUCH_STATUS_FILE_ERROR;
927 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
928 message = strdup ("Out of memory\n");
929 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
933 /* Initialize the GLib type system and threads */
934 #if !GLIB_CHECK_VERSION(2, 35, 1)
938 /* Initialize gmime */
940 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
944 notmuch = talloc_zero (NULL, notmuch_database_t);
945 notmuch->exception_reported = FALSE;
946 notmuch->status_string = NULL;
947 notmuch->path = talloc_strdup (notmuch, path);
949 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
950 notmuch->path[strlen (notmuch->path) - 1] = '\0';
952 notmuch->mode = mode;
953 notmuch->atomic_nesting = 0;
955 string last_thread_id;
958 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
959 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
962 notmuch->xapian_db = new Xapian::Database (xapian_path);
965 /* Check version. As of database version 3, we represent
966 * changes in terms of features, so assume a version bump
967 * means a dramatically incompatible change. */
968 version = notmuch_database_get_version (notmuch);
969 if (version > NOTMUCH_DATABASE_VERSION) {
970 IGNORE_RESULT (asprintf (&message,
971 "Error: Notmuch database at %s\n"
972 " has a newer database format version (%u) than supported by this\n"
973 " version of notmuch (%u).\n",
974 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
975 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
976 notmuch_database_destroy (notmuch);
978 status = NOTMUCH_STATUS_FILE_ERROR;
982 /* Check features. */
983 incompat_features = NULL;
984 notmuch->features = _parse_features (
985 local, notmuch->xapian_db->get_metadata ("features").c_str (),
986 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
988 if (incompat_features) {
989 IGNORE_RESULT (asprintf (&message,
990 "Error: Notmuch database at %s\n"
991 " requires features (%s)\n"
992 " not supported by this version of notmuch.\n",
993 notmuch_path, incompat_features));
994 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
995 notmuch_database_destroy (notmuch);
997 status = NOTMUCH_STATUS_FILE_ERROR;
1001 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1002 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1003 if (last_thread_id.empty ()) {
1004 notmuch->last_thread_id = 0;
1009 str = last_thread_id.c_str ();
1010 notmuch->last_thread_id = strtoull (str, &end, 16);
1012 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1015 /* Get current highest revision number. */
1016 last_mod = notmuch->xapian_db->get_value_upper_bound (
1017 NOTMUCH_VALUE_LAST_MOD);
1018 if (last_mod.empty ())
1019 notmuch->revision = 0;
1021 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1022 notmuch->uuid = talloc_strdup (
1023 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1025 notmuch->query_parser = new Xapian::QueryParser;
1026 notmuch->term_gen = new Xapian::TermGenerator;
1027 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1028 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1029 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1030 #if HAVE_XAPIAN_FIELD_PROCESSOR
1031 /* This currently relies on the query parser to pass anything
1032 * with a .. to the range processor */
1033 notmuch->date_field_processor = new DateFieldProcessor();
1034 notmuch->query_parser->add_boolean_prefix("date", notmuch->date_field_processor);
1035 notmuch->query_field_processor = new QueryFieldProcessor (*notmuch->query_parser, notmuch);
1036 notmuch->query_parser->add_boolean_prefix("query", notmuch->query_field_processor);
1038 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1040 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1041 notmuch->query_parser->set_database (*notmuch->xapian_db);
1042 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1043 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1044 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1045 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1046 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1048 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1049 const prefix_t *prefix = &prefix_table[i];
1050 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1051 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC) {
1052 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
1054 notmuch->query_parser->add_boolean_prefix (prefix->name,
1059 } catch (const Xapian::Error &error) {
1060 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1061 error.get_msg().c_str()));
1062 notmuch_database_destroy (notmuch);
1064 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1068 talloc_free (local);
1072 *status_string = message;
1078 *database = notmuch;
1080 talloc_free (notmuch);
1085 notmuch_database_close (notmuch_database_t *notmuch)
1087 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1089 /* Many Xapian objects (and thus notmuch objects) hold references to
1090 * the database, so merely deleting the database may not suffice to
1091 * close it. Thus, we explicitly close it here. */
1092 if (notmuch->xapian_db != NULL) {
1094 /* If there's an outstanding transaction, it's unclear if
1095 * closing the Xapian database commits everything up to
1096 * that transaction, or may discard committed (but
1097 * unflushed) transactions. To be certain, explicitly
1098 * cancel any outstanding transaction before closing. */
1099 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1100 notmuch->atomic_nesting)
1101 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1102 ->cancel_transaction ();
1104 /* Close the database. This implicitly flushes
1105 * outstanding changes. */
1106 notmuch->xapian_db->close();
1107 } catch (const Xapian::Error &error) {
1108 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1109 if (! notmuch->exception_reported) {
1110 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1111 error.get_msg().c_str());
1116 delete notmuch->term_gen;
1117 notmuch->term_gen = NULL;
1118 delete notmuch->query_parser;
1119 notmuch->query_parser = NULL;
1120 delete notmuch->xapian_db;
1121 notmuch->xapian_db = NULL;
1122 delete notmuch->value_range_processor;
1123 notmuch->value_range_processor = NULL;
1124 delete notmuch->date_range_processor;
1125 notmuch->date_range_processor = NULL;
1126 delete notmuch->last_mod_range_processor;
1127 notmuch->last_mod_range_processor = NULL;
1129 #if HAVE_XAPIAN_FIELD_PROCESSOR
1130 delete notmuch->date_field_processor;
1131 notmuch->date_field_processor = NULL;
1132 delete notmuch->query_field_processor;
1133 notmuch->query_field_processor = NULL;
1140 unlink_cb (const char *path,
1141 unused (const struct stat *sb),
1143 unused (struct FTW *ftw))
1145 return remove (path);
1149 rmtree (const char *path)
1151 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1154 class NotmuchCompactor : public Xapian::Compactor
1156 notmuch_compact_status_cb_t status_cb;
1157 void *status_closure;
1160 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1161 status_cb (cb), status_closure (closure) { }
1164 set_status (const std::string &table, const std::string &status)
1168 if (status_cb == NULL)
1171 if (status.length () == 0)
1172 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1174 msg = talloc_asprintf (NULL, " %s", status.c_str());
1180 status_cb (msg, status_closure);
1185 /* Compacts the given database, optionally saving the original database
1186 * in backup_path. Additionally, a callback function can be provided to
1187 * give the user feedback on the progress of the (likely long-lived)
1188 * compaction process.
1190 * The backup path must point to a directory on the same volume as the
1191 * original database. Passing a NULL backup_path will result in the
1192 * uncompacted database being deleted after compaction has finished.
1193 * Note that the database write lock will be held during the
1194 * compaction process to protect data integrity.
1197 notmuch_database_compact (const char *path,
1198 const char *backup_path,
1199 notmuch_compact_status_cb_t status_cb,
1203 char *notmuch_path, *xapian_path, *compact_xapian_path;
1204 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1205 notmuch_database_t *notmuch = NULL;
1206 struct stat statbuf;
1207 notmuch_bool_t keep_backup;
1208 char *message = NULL;
1210 local = talloc_new (NULL);
1212 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1214 ret = notmuch_database_open_verbose (path,
1215 NOTMUCH_DATABASE_MODE_READ_WRITE,
1219 if (status_cb) status_cb (message, closure);
1223 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1224 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1228 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1229 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1233 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1234 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1238 if (backup_path == NULL) {
1239 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1240 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1243 keep_backup = FALSE;
1249 if (stat (backup_path, &statbuf) != -1) {
1250 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1251 ret = NOTMUCH_STATUS_FILE_ERROR;
1254 if (errno != ENOENT) {
1255 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1257 ret = NOTMUCH_STATUS_FILE_ERROR;
1261 /* Unconditionally attempt to remove old work-in-progress database (if
1262 * any). This is "protected" by database lock. If this fails due to write
1263 * errors (etc), the following code will fail and provide error message.
1265 (void) rmtree (compact_xapian_path);
1268 NotmuchCompactor compactor (status_cb, closure);
1270 compactor.set_renumber (false);
1271 compactor.add_source (xapian_path);
1272 compactor.set_destdir (compact_xapian_path);
1273 compactor.compact ();
1274 } catch (const Xapian::Error &error) {
1275 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1276 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1280 if (rename (xapian_path, backup_path)) {
1281 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1282 xapian_path, backup_path, strerror (errno));
1283 ret = NOTMUCH_STATUS_FILE_ERROR;
1287 if (rename (compact_xapian_path, xapian_path)) {
1288 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1289 compact_xapian_path, xapian_path, strerror (errno));
1290 ret = NOTMUCH_STATUS_FILE_ERROR;
1294 if (! keep_backup) {
1295 if (rmtree (backup_path)) {
1296 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1297 backup_path, strerror (errno));
1298 ret = NOTMUCH_STATUS_FILE_ERROR;
1305 notmuch_status_t ret2;
1307 const char *str = notmuch_database_status_string (notmuch);
1308 if (status_cb && str)
1309 status_cb (str, closure);
1311 ret2 = notmuch_database_destroy (notmuch);
1313 /* don't clobber previous error status */
1314 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1318 talloc_free (local);
1324 notmuch_database_destroy (notmuch_database_t *notmuch)
1326 notmuch_status_t status;
1328 status = notmuch_database_close (notmuch);
1329 talloc_free (notmuch);
1335 notmuch_database_get_path (notmuch_database_t *notmuch)
1337 return notmuch->path;
1341 notmuch_database_get_version (notmuch_database_t *notmuch)
1343 unsigned int version;
1344 string version_string;
1348 version_string = notmuch->xapian_db->get_metadata ("version");
1349 if (version_string.empty ())
1352 str = version_string.c_str ();
1353 if (str == NULL || *str == '\0')
1356 version = strtoul (str, &end, 10);
1358 INTERNAL_ERROR ("Malformed database version: %s", str);
1364 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1366 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1367 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1368 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1371 static volatile sig_atomic_t do_progress_notify = 0;
1374 handle_sigalrm (unused (int signal))
1376 do_progress_notify = 1;
1379 /* Upgrade the current database.
1381 * After opening a database in read-write mode, the client should
1382 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1383 * if so, upgrade with this function before making any modifications.
1385 * The optional progress_notify callback can be used by the caller to
1386 * provide progress indication to the user. If non-NULL it will be
1387 * called periodically with 'count' as the number of messages upgraded
1388 * so far and 'total' the overall number of messages that will be
1392 notmuch_database_upgrade (notmuch_database_t *notmuch,
1393 void (*progress_notify) (void *closure,
1397 void *local = talloc_new (NULL);
1398 Xapian::TermIterator t, t_end;
1399 Xapian::WritableDatabase *db;
1400 struct sigaction action;
1401 struct itimerval timerval;
1402 notmuch_bool_t timer_is_active = FALSE;
1403 enum _notmuch_features target_features, new_features;
1404 notmuch_status_t status;
1405 notmuch_private_status_t private_status;
1406 notmuch_query_t *query = NULL;
1407 unsigned int count = 0, total = 0;
1409 status = _notmuch_database_ensure_writable (notmuch);
1413 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1415 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1416 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1418 if (! notmuch_database_needs_upgrade (notmuch))
1419 return NOTMUCH_STATUS_SUCCESS;
1421 if (progress_notify) {
1422 /* Set up our handler for SIGALRM */
1423 memset (&action, 0, sizeof (struct sigaction));
1424 action.sa_handler = handle_sigalrm;
1425 sigemptyset (&action.sa_mask);
1426 action.sa_flags = SA_RESTART;
1427 sigaction (SIGALRM, &action, NULL);
1429 /* Then start a timer to send SIGALRM once per second. */
1430 timerval.it_interval.tv_sec = 1;
1431 timerval.it_interval.tv_usec = 0;
1432 timerval.it_value.tv_sec = 1;
1433 timerval.it_value.tv_usec = 0;
1434 setitimer (ITIMER_REAL, &timerval, NULL);
1436 timer_is_active = TRUE;
1439 /* Figure out how much total work we need to do. */
1441 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1442 NOTMUCH_FEATURE_LAST_MOD)) {
1443 query = notmuch_query_create (notmuch, "");
1446 status = notmuch_query_count_messages_st (query, &msg_count);
1451 notmuch_query_destroy (query);
1454 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1455 t_end = db->allterms_end ("XTIMESTAMP");
1456 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1459 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1460 /* The ghost message upgrade converts all thread_id_*
1461 * metadata values into ghost message documents. */
1462 t_end = db->metadata_keys_end ("thread_id_");
1463 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1467 /* Perform the upgrade in a transaction. */
1468 db->begin_transaction (true);
1470 /* Set the target features so we write out changes in the desired
1472 notmuch->features = target_features;
1474 /* Perform per-message upgrades. */
1476 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1477 NOTMUCH_FEATURE_LAST_MOD)) {
1478 notmuch_messages_t *messages;
1479 notmuch_message_t *message;
1482 query = notmuch_query_create (notmuch, "");
1484 status = notmuch_query_search_messages_st (query, &messages);
1488 notmuch_messages_valid (messages);
1489 notmuch_messages_move_to_next (messages))
1491 if (do_progress_notify) {
1492 progress_notify (closure, (double) count / total);
1493 do_progress_notify = 0;
1496 message = notmuch_messages_get (messages);
1498 /* Before version 1, each message document had its
1499 * filename in the data field. Copy that into the new
1500 * format by calling notmuch_message_add_filename.
1502 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1503 filename = _notmuch_message_talloc_copy_data (message);
1504 if (filename && *filename != '\0') {
1505 _notmuch_message_add_filename (message, filename);
1506 _notmuch_message_clear_data (message);
1508 talloc_free (filename);
1511 /* Prior to version 2, the "folder:" prefix was
1512 * probabilistic and stemmed. Change it to the current
1513 * boolean prefix. Add "path:" prefixes while at it.
1515 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1516 _notmuch_message_upgrade_folder (message);
1518 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1519 * track modification revisions. Give all messages the
1520 * next available revision; since we just started tracking
1521 * revisions for this database, that will be 1.
1523 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1524 _notmuch_message_upgrade_last_mod (message);
1526 _notmuch_message_sync (message);
1528 notmuch_message_destroy (message);
1533 notmuch_query_destroy (query);
1537 /* Perform per-directory upgrades. */
1539 /* Before version 1 we stored directory timestamps in
1540 * XTIMESTAMP documents instead of the current XDIRECTORY
1541 * documents. So copy those as well. */
1542 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1543 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1545 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1549 Xapian::PostingIterator p, p_end;
1550 std::string term = *t;
1552 p_end = notmuch->xapian_db->postlist_end (term);
1554 for (p = notmuch->xapian_db->postlist_begin (term);
1558 Xapian::Document document;
1560 notmuch_directory_t *directory;
1562 if (do_progress_notify) {
1563 progress_notify (closure, (double) count / total);
1564 do_progress_notify = 0;
1567 document = find_document_for_doc_id (notmuch, *p);
1568 mtime = Xapian::sortable_unserialise (
1569 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1571 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1572 NOTMUCH_FIND_CREATE, &status);
1573 notmuch_directory_set_mtime (directory, mtime);
1574 notmuch_directory_destroy (directory);
1576 db->delete_document (*p);
1583 /* Perform metadata upgrades. */
1585 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1586 * messages were stored as database metadata. Change these to
1589 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1590 notmuch_message_t *message;
1591 std::string message_id, thread_id;
1593 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1594 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1596 if (do_progress_notify) {
1597 progress_notify (closure, (double) count / total);
1598 do_progress_notify = 0;
1601 message_id = (*t).substr (
1602 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1603 thread_id = db->get_metadata (*t);
1605 /* Create ghost message */
1606 message = _notmuch_message_create_for_message_id (
1607 notmuch, message_id.c_str (), &private_status);
1608 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1609 /* Document already exists; ignore the stored thread ID */
1610 } else if (private_status ==
1611 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1612 private_status = _notmuch_message_initialize_ghost (
1613 message, thread_id.c_str ());
1614 if (! private_status)
1615 _notmuch_message_sync (message);
1618 if (private_status) {
1619 _notmuch_database_log (notmuch,
1620 "Upgrade failed while creating ghost messages.\n");
1621 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1625 /* Clear saved metadata thread ID */
1626 db->set_metadata (*t, "");
1632 status = NOTMUCH_STATUS_SUCCESS;
1633 db->set_metadata ("features", _print_features (local, notmuch->features));
1634 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1637 if (status == NOTMUCH_STATUS_SUCCESS)
1638 db->commit_transaction ();
1640 db->cancel_transaction ();
1642 if (timer_is_active) {
1643 /* Now stop the timer. */
1644 timerval.it_interval.tv_sec = 0;
1645 timerval.it_interval.tv_usec = 0;
1646 timerval.it_value.tv_sec = 0;
1647 timerval.it_value.tv_usec = 0;
1648 setitimer (ITIMER_REAL, &timerval, NULL);
1650 /* And disable the signal handler. */
1651 action.sa_handler = SIG_IGN;
1652 sigaction (SIGALRM, &action, NULL);
1656 notmuch_query_destroy (query);
1658 talloc_free (local);
1663 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1665 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1666 notmuch->atomic_nesting > 0)
1669 if (notmuch_database_needs_upgrade (notmuch))
1670 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1673 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1674 } catch (const Xapian::Error &error) {
1675 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1676 error.get_msg().c_str());
1677 notmuch->exception_reported = TRUE;
1678 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1682 notmuch->atomic_nesting++;
1683 return NOTMUCH_STATUS_SUCCESS;
1687 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1689 Xapian::WritableDatabase *db;
1691 if (notmuch->atomic_nesting == 0)
1692 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1694 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1695 notmuch->atomic_nesting > 1)
1698 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1700 db->commit_transaction ();
1702 /* This is a hack for testing. Xapian never flushes on a
1703 * non-flushed commit, even if the flush threshold is 1.
1704 * However, we rely on flushing to test atomicity. */
1705 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1706 if (thresh && atoi (thresh) == 1)
1708 } catch (const Xapian::Error &error) {
1709 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1710 error.get_msg().c_str());
1711 notmuch->exception_reported = TRUE;
1712 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1715 if (notmuch->atomic_dirty) {
1716 ++notmuch->revision;
1717 notmuch->atomic_dirty = FALSE;
1721 notmuch->atomic_nesting--;
1722 return NOTMUCH_STATUS_SUCCESS;
1726 notmuch_database_get_revision (notmuch_database_t *notmuch,
1730 *uuid = notmuch->uuid;
1731 return notmuch->revision;
1734 /* We allow the user to use arbitrarily long paths for directories. But
1735 * we have a term-length limit. So if we exceed that, we'll use the
1736 * SHA-1 of the path for the database term.
1738 * Note: This function may return the original value of 'path'. If it
1739 * does not, then the caller is responsible to free() the returned
1743 _notmuch_database_get_directory_db_path (const char *path)
1745 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1747 if (term_len > NOTMUCH_TERM_MAX)
1748 return _notmuch_sha1_of_string (path);
1753 /* Given a path, split it into two parts: the directory part is all
1754 * components except for the last, and the basename is that last
1755 * component. Getting the return-value for either part is optional
1756 * (the caller can pass NULL).
1758 * The original 'path' can represent either a regular file or a
1759 * directory---the splitting will be carried out in the same way in
1760 * either case. Trailing slashes on 'path' will be ignored, and any
1761 * cases of multiple '/' characters appearing in series will be
1762 * treated as a single '/'.
1764 * Allocation (if any) will have 'ctx' as the talloc owner. But
1765 * pointers will be returned within the original path string whenever
1768 * Note: If 'path' is non-empty and contains no non-trailing slash,
1769 * (that is, consists of a filename with no parent directory), then
1770 * the directory returned will be an empty string. However, if 'path'
1771 * is an empty string, then both directory and basename will be
1775 _notmuch_database_split_path (void *ctx,
1777 const char **directory,
1778 const char **basename)
1782 if (path == NULL || *path == '\0') {
1787 return NOTMUCH_STATUS_SUCCESS;
1790 /* Find the last slash (not counting a trailing slash), if any. */
1792 slash = path + strlen (path) - 1;
1794 /* First, skip trailing slashes. */
1795 while (slash != path && *slash == '/')
1798 /* Then, find a slash. */
1799 while (slash != path && *slash != '/') {
1806 /* Finally, skip multiple slashes. */
1807 while (slash != path && *(slash - 1) == '/')
1810 if (slash == path) {
1812 *directory = talloc_strdup (ctx, "");
1817 *directory = talloc_strndup (ctx, path, slash - path);
1820 return NOTMUCH_STATUS_SUCCESS;
1823 /* Find the document ID of the specified directory.
1825 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1826 * created if one does not exist for 'path'. Otherwise, if the
1827 * directory document does not exist, this sets *directory_id to
1828 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1831 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1833 notmuch_find_flags_t flags,
1834 unsigned int *directory_id)
1836 notmuch_directory_t *directory;
1837 notmuch_status_t status;
1841 return NOTMUCH_STATUS_SUCCESS;
1844 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1845 if (status || !directory) {
1850 *directory_id = _notmuch_directory_get_document_id (directory);
1852 notmuch_directory_destroy (directory);
1854 return NOTMUCH_STATUS_SUCCESS;
1858 _notmuch_database_get_directory_path (void *ctx,
1859 notmuch_database_t *notmuch,
1860 unsigned int doc_id)
1862 Xapian::Document document;
1864 document = find_document_for_doc_id (notmuch, doc_id);
1866 return talloc_strdup (ctx, document.get_data ().c_str ());
1869 /* Given a legal 'filename' for the database, (either relative to
1870 * database path or absolute with initial components identical to
1871 * database path), return a new string (with 'ctx' as the talloc
1872 * owner) suitable for use as a direntry term value.
1874 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1875 * will be created in the database as needed. Otherwise, if the
1876 * necessary directory documents do not exist, this sets
1877 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1880 _notmuch_database_filename_to_direntry (void *ctx,
1881 notmuch_database_t *notmuch,
1882 const char *filename,
1883 notmuch_find_flags_t flags,
1886 const char *relative, *directory, *basename;
1887 Xapian::docid directory_id;
1888 notmuch_status_t status;
1890 relative = _notmuch_database_relative_path (notmuch, filename);
1892 status = _notmuch_database_split_path (ctx, relative,
1893 &directory, &basename);
1897 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1899 if (status || directory_id == (unsigned int)-1) {
1904 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1906 return NOTMUCH_STATUS_SUCCESS;
1909 /* Given a legal 'path' for the database, return the relative path.
1911 * The return value will be a pointer to the original path contents,
1912 * and will be either the original string (if 'path' was relative) or
1913 * a portion of the string (if path was absolute and begins with the
1917 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1920 const char *db_path, *relative;
1921 unsigned int db_path_len;
1923 db_path = notmuch_database_get_path (notmuch);
1924 db_path_len = strlen (db_path);
1928 if (*relative == '/') {
1929 while (*relative == '/' && *(relative+1) == '/')
1932 if (strncmp (relative, db_path, db_path_len) == 0)
1934 relative += db_path_len;
1935 while (*relative == '/')
1944 notmuch_database_get_directory (notmuch_database_t *notmuch,
1946 notmuch_directory_t **directory)
1948 notmuch_status_t status;
1950 if (directory == NULL)
1951 return NOTMUCH_STATUS_NULL_POINTER;
1955 *directory = _notmuch_directory_create (notmuch, path,
1956 NOTMUCH_FIND_LOOKUP, &status);
1957 } catch (const Xapian::Error &error) {
1958 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1959 error.get_msg().c_str());
1960 notmuch->exception_reported = TRUE;
1961 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1966 /* Allocate a document ID that satisfies the following criteria:
1968 * 1. The ID does not exist for any document in the Xapian database
1970 * 2. The ID was not previously returned from this function
1972 * 3. The ID is the smallest integer satisfying (1) and (2)
1974 * This function will trigger an internal error if these constraints
1975 * cannot all be satisfied, (that is, the pool of available document
1976 * IDs has been exhausted).
1979 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1981 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1983 notmuch->last_doc_id++;
1985 if (notmuch->last_doc_id == 0)
1986 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1988 return notmuch->last_doc_id;
1992 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1994 /* 16 bytes (+ terminator) for hexadecimal representation of
1995 * a 64-bit integer. */
1996 static char thread_id[17];
1997 Xapian::WritableDatabase *db;
1999 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2001 notmuch->last_thread_id++;
2003 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2005 db->set_metadata ("last_thread_id", thread_id);
2011 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2013 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2014 message_id = _notmuch_message_id_compressed (ctx, message_id);
2016 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2020 static notmuch_status_t
2021 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2023 const char *message_id,
2024 const char **thread_id_ret);
2026 /* Find the thread ID to which the message with 'message_id' belongs.
2028 * Note: 'thread_id_ret' must not be NULL!
2029 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2032 * Note: If there is no message in the database with the given
2033 * 'message_id' then a new thread_id will be allocated for this
2034 * message ID and stored in the database metadata so that the
2035 * thread ID can be looked up if the message is added to the database
2038 static notmuch_status_t
2039 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2041 const char *message_id,
2042 const char **thread_id_ret)
2044 notmuch_private_status_t status;
2045 notmuch_message_t *message;
2047 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2048 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2051 /* Look for this message (regular or ghost) */
2052 message = _notmuch_message_create_for_message_id (
2053 notmuch, message_id, &status);
2054 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2055 /* Message exists */
2056 *thread_id_ret = talloc_steal (
2057 ctx, notmuch_message_get_thread_id (message));
2058 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2059 /* Message did not exist. Give it a fresh thread ID and
2060 * populate this message as a ghost message. */
2061 *thread_id_ret = talloc_strdup (
2062 ctx, _notmuch_database_generate_thread_id (notmuch));
2063 if (! *thread_id_ret) {
2064 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2066 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2068 /* Commit the new ghost message */
2069 _notmuch_message_sync (message);
2072 /* Create failed. Fall through. */
2075 notmuch_message_destroy (message);
2077 return COERCE_STATUS (status, "Error creating ghost message");
2080 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2081 static notmuch_status_t
2082 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2084 const char *message_id,
2085 const char **thread_id_ret)
2087 notmuch_status_t status;
2088 notmuch_message_t *message;
2089 string thread_id_string;
2091 Xapian::WritableDatabase *db;
2093 status = notmuch_database_find_message (notmuch, message_id, &message);
2099 *thread_id_ret = talloc_steal (ctx,
2100 notmuch_message_get_thread_id (message));
2102 notmuch_message_destroy (message);
2104 return NOTMUCH_STATUS_SUCCESS;
2107 /* Message has not been seen yet.
2109 * We may have seen a reference to it already, in which case, we
2110 * can return the thread ID stored in the metadata. Otherwise, we
2111 * generate a new thread ID and store it there.
2113 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2114 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2115 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2117 if (thread_id_string.empty()) {
2118 *thread_id_ret = talloc_strdup (ctx,
2119 _notmuch_database_generate_thread_id (notmuch));
2120 db->set_metadata (metadata_key, *thread_id_ret);
2122 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2125 talloc_free (metadata_key);
2127 return NOTMUCH_STATUS_SUCCESS;
2130 static notmuch_status_t
2131 _merge_threads (notmuch_database_t *notmuch,
2132 const char *winner_thread_id,
2133 const char *loser_thread_id)
2135 Xapian::PostingIterator loser, loser_end;
2136 notmuch_message_t *message = NULL;
2137 notmuch_private_status_t private_status;
2138 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2140 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2142 for ( ; loser != loser_end; loser++) {
2143 message = _notmuch_message_create (notmuch, notmuch,
2144 *loser, &private_status);
2145 if (message == NULL) {
2146 ret = COERCE_STATUS (private_status,
2147 "Cannot find document for doc_id from query");
2151 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2152 _notmuch_message_add_term (message, "thread", winner_thread_id);
2153 _notmuch_message_sync (message);
2155 notmuch_message_destroy (message);
2161 notmuch_message_destroy (message);
2167 _my_talloc_free_for_g_hash (void *ptr)
2172 static notmuch_status_t
2173 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2174 notmuch_message_t *message,
2175 notmuch_message_file_t *message_file,
2176 const char **thread_id)
2178 GHashTable *parents = NULL;
2179 const char *refs, *in_reply_to, *in_reply_to_message_id;
2180 const char *last_ref_message_id, *this_message_id;
2181 GList *l, *keys = NULL;
2182 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2184 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2185 _my_talloc_free_for_g_hash, NULL);
2186 this_message_id = notmuch_message_get_message_id (message);
2188 refs = _notmuch_message_file_get_header (message_file, "references");
2189 last_ref_message_id = parse_references (message,
2193 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2194 in_reply_to_message_id = parse_references (message,
2196 parents, in_reply_to);
2198 /* For the parent of this message, use the last message ID of the
2199 * References header, if available. If not, fall back to the
2200 * first message ID in the In-Reply-To header. */
2201 if (last_ref_message_id) {
2202 _notmuch_message_add_term (message, "replyto",
2203 last_ref_message_id);
2204 } else if (in_reply_to_message_id) {
2205 _notmuch_message_add_term (message, "replyto",
2206 in_reply_to_message_id);
2209 keys = g_hash_table_get_keys (parents);
2210 for (l = keys; l; l = l->next) {
2211 char *parent_message_id;
2212 const char *parent_thread_id = NULL;
2214 parent_message_id = (char *) l->data;
2216 _notmuch_message_add_term (message, "reference",
2219 ret = _resolve_message_id_to_thread_id (notmuch,
2226 if (*thread_id == NULL) {
2227 *thread_id = talloc_strdup (message, parent_thread_id);
2228 _notmuch_message_add_term (message, "thread", *thread_id);
2229 } else if (strcmp (*thread_id, parent_thread_id)) {
2230 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2240 g_hash_table_unref (parents);
2245 static notmuch_status_t
2246 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2247 notmuch_message_t *message,
2248 const char **thread_id)
2250 const char *message_id = notmuch_message_get_message_id (message);
2251 Xapian::PostingIterator child, children_end;
2252 notmuch_message_t *child_message = NULL;
2253 const char *child_thread_id;
2254 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2255 notmuch_private_status_t private_status;
2257 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2259 for ( ; child != children_end; child++) {
2261 child_message = _notmuch_message_create (message, notmuch,
2262 *child, &private_status);
2263 if (child_message == NULL) {
2264 ret = COERCE_STATUS (private_status,
2265 "Cannot find document for doc_id from query");
2269 child_thread_id = notmuch_message_get_thread_id (child_message);
2270 if (*thread_id == NULL) {
2271 *thread_id = talloc_strdup (message, child_thread_id);
2272 _notmuch_message_add_term (message, "thread", *thread_id);
2273 } else if (strcmp (*thread_id, child_thread_id)) {
2274 _notmuch_message_remove_term (child_message, "reference",
2276 _notmuch_message_sync (child_message);
2277 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2282 notmuch_message_destroy (child_message);
2283 child_message = NULL;
2288 notmuch_message_destroy (child_message);
2293 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2295 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2296 notmuch_message_t *message)
2298 const char *message_id;
2302 message_id = notmuch_message_get_message_id (message);
2303 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2305 /* Check if we have already seen related messages to this one.
2306 * If we have then use the thread_id that we stored at that time.
2308 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2309 if (stored_id.empty ()) {
2312 Xapian::WritableDatabase *db;
2314 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2316 /* Clear the metadata for this message ID. We don't need it
2318 db->set_metadata (metadata_key, "");
2320 return talloc_strdup (ctx, stored_id.c_str ());
2324 /* Given a blank or ghost 'message' and its corresponding
2325 * 'message_file' link it to existing threads in the database.
2327 * First, if is_ghost, this retrieves the thread ID already stored in
2328 * the message (which will be the case if a message was previously
2329 * added that referenced this one). If the message is blank
2330 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2331 * later in this function). If the database does not support ghost
2332 * messages, this checks for a thread ID stored in database metadata
2333 * for this message ID.
2335 * Second, we look at 'message_file' and its link-relevant headers
2336 * (References and In-Reply-To) for message IDs.
2338 * Finally, we look in the database for existing message that
2339 * reference 'message'.
2341 * In all cases, we assign to the current message the first thread ID
2342 * found. We will also merge any existing, distinct threads where this
2343 * message belongs to both, (which is not uncommon when messages are
2344 * processed out of order).
2346 * Finally, if no thread ID has been found through referenced messages, we
2347 * call _notmuch_message_generate_thread_id to generate a new thread
2348 * ID. This should only happen for new, top-level messages, (no
2349 * References or In-Reply-To header in this message, and no previously
2350 * added message refers to this message).
2352 static notmuch_status_t
2353 _notmuch_database_link_message (notmuch_database_t *notmuch,
2354 notmuch_message_t *message,
2355 notmuch_message_file_t *message_file,
2356 notmuch_bool_t is_ghost)
2358 void *local = talloc_new (NULL);
2359 notmuch_status_t status;
2360 const char *thread_id = NULL;
2362 /* Check if the message already had a thread ID */
2363 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2365 thread_id = notmuch_message_get_thread_id (message);
2367 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2369 _notmuch_message_add_term (message, "thread", thread_id);
2372 status = _notmuch_database_link_message_to_parents (notmuch, message,
2378 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2379 /* In general, it shouldn't be necessary to link children,
2380 * since the earlier indexing of those children will have
2381 * stored a thread ID for the missing parent. However, prior
2382 * to ghost messages, these stored thread IDs were NOT
2383 * rewritten during thread merging (and there was no
2384 * performant way to do so), so if indexed children were
2385 * pulled into a different thread ID by a merge, it was
2386 * necessary to pull them *back* into the stored thread ID of
2387 * the parent. With ghost messages, we just rewrite the
2388 * stored thread IDs during merging, so this workaround isn't
2390 status = _notmuch_database_link_message_to_children (notmuch, message,
2396 /* If not part of any existing thread, generate a new thread ID. */
2397 if (thread_id == NULL) {
2398 thread_id = _notmuch_database_generate_thread_id (notmuch);
2400 _notmuch_message_add_term (message, "thread", thread_id);
2404 talloc_free (local);
2410 notmuch_database_add_message (notmuch_database_t *notmuch,
2411 const char *filename,
2412 notmuch_message_t **message_ret)
2414 notmuch_message_file_t *message_file;
2415 notmuch_message_t *message = NULL;
2416 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2417 notmuch_private_status_t private_status;
2418 notmuch_bool_t is_ghost = false;
2420 const char *date, *header;
2421 const char *from, *to, *subject;
2422 char *message_id = NULL;
2425 *message_ret = NULL;
2427 ret = _notmuch_database_ensure_writable (notmuch);
2431 message_file = _notmuch_message_file_open (notmuch, filename);
2432 if (message_file == NULL)
2433 return NOTMUCH_STATUS_FILE_ERROR;
2435 /* Adding a message may change many documents. Do this all
2437 ret = notmuch_database_begin_atomic (notmuch);
2441 /* Parse message up front to get better error status. */
2442 ret = _notmuch_message_file_parse (message_file);
2447 /* Before we do any real work, (especially before doing a
2448 * potential SHA-1 computation on the entire file's contents),
2449 * let's make sure that what we're looking at looks like an
2450 * actual email message.
2452 from = _notmuch_message_file_get_header (message_file, "from");
2453 subject = _notmuch_message_file_get_header (message_file, "subject");
2454 to = _notmuch_message_file_get_header (message_file, "to");
2456 if ((from == NULL || *from == '\0') &&
2457 (subject == NULL || *subject == '\0') &&
2458 (to == NULL || *to == '\0'))
2460 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2464 /* Now that we're sure it's mail, the first order of business
2465 * is to find a message ID (or else create one ourselves). */
2467 header = _notmuch_message_file_get_header (message_file, "message-id");
2468 if (header && *header != '\0') {
2469 message_id = _parse_message_id (message_file, header, NULL);
2471 /* So the header value isn't RFC-compliant, but it's
2472 * better than no message-id at all. */
2473 if (message_id == NULL)
2474 message_id = talloc_strdup (message_file, header);
2477 if (message_id == NULL ) {
2478 /* No message-id at all, let's generate one by taking a
2479 * hash over the file's contents. */
2480 char *sha1 = _notmuch_sha1_of_file (filename);
2482 /* If that failed too, something is really wrong. Give up. */
2484 ret = NOTMUCH_STATUS_FILE_ERROR;
2488 message_id = talloc_asprintf (message_file,
2489 "notmuch-sha1-%s", sha1);
2493 /* Now that we have a message ID, we get a message object,
2494 * (which may or may not reference an existing document in the
2497 message = _notmuch_message_create_for_message_id (notmuch,
2501 talloc_free (message_id);
2503 if (message == NULL) {
2504 ret = COERCE_STATUS (private_status,
2505 "Unexpected status value from _notmuch_message_create_for_message_id");
2509 _notmuch_message_add_filename (message, filename);
2511 /* Is this a newly created message object or a ghost
2512 * message? We have to be slightly careful: if this is a
2513 * blank message, it's not safe to call
2514 * notmuch_message_get_flag yet. */
2515 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2516 (is_ghost = notmuch_message_get_flag (
2517 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2518 _notmuch_message_add_term (message, "type", "mail");
2520 /* Convert ghost message to a regular message */
2521 _notmuch_message_remove_term (message, "type", "ghost");
2523 ret = _notmuch_database_link_message (notmuch, message,
2524 message_file, is_ghost);
2528 date = _notmuch_message_file_get_header (message_file, "date");
2529 _notmuch_message_set_header_values (message, date, from, subject);
2531 ret = _notmuch_message_index_file (message, message_file);
2535 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2538 _notmuch_message_sync (message);
2539 } catch (const Xapian::Error &error) {
2540 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2541 error.get_msg().c_str());
2542 notmuch->exception_reported = TRUE;
2543 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2549 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2550 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2551 *message_ret = message;
2553 notmuch_message_destroy (message);
2557 _notmuch_message_file_close (message_file);
2559 ret2 = notmuch_database_end_atomic (notmuch);
2560 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2561 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2562 ret2 != NOTMUCH_STATUS_SUCCESS)
2569 notmuch_database_remove_message (notmuch_database_t *notmuch,
2570 const char *filename)
2572 notmuch_status_t status;
2573 notmuch_message_t *message;
2575 status = notmuch_database_find_message_by_filename (notmuch, filename,
2578 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2579 status = _notmuch_message_remove_filename (message, filename);
2580 if (status == NOTMUCH_STATUS_SUCCESS)
2581 _notmuch_message_delete (message);
2582 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2583 _notmuch_message_sync (message);
2585 notmuch_message_destroy (message);
2592 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2593 const char *filename,
2594 notmuch_message_t **message_ret)
2597 const char *prefix = _find_prefix ("file-direntry");
2598 char *direntry, *term;
2599 Xapian::PostingIterator i, end;
2600 notmuch_status_t status;
2602 if (message_ret == NULL)
2603 return NOTMUCH_STATUS_NULL_POINTER;
2605 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2606 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2608 /* return NULL on any failure */
2609 *message_ret = NULL;
2611 local = talloc_new (notmuch);
2614 status = _notmuch_database_filename_to_direntry (
2615 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2616 if (status || !direntry)
2619 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2621 find_doc_ids_for_term (notmuch, term, &i, &end);
2624 notmuch_private_status_t private_status;
2626 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2628 if (*message_ret == NULL)
2629 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2631 } catch (const Xapian::Error &error) {
2632 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2633 error.get_msg().c_str());
2634 notmuch->exception_reported = TRUE;
2635 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2639 talloc_free (local);
2641 if (status && *message_ret) {
2642 notmuch_message_destroy (*message_ret);
2643 *message_ret = NULL;
2648 notmuch_string_list_t *
2649 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2650 Xapian::TermIterator &end,
2653 int prefix_len = strlen (prefix);
2654 notmuch_string_list_t *list;
2656 list = _notmuch_string_list_create (ctx);
2657 if (unlikely (list == NULL))
2660 for (i.skip_to (prefix); i != end; i++) {
2661 /* Terminate loop at first term without desired prefix. */
2662 if (strncmp ((*i).c_str (), prefix, prefix_len))
2665 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2672 notmuch_database_get_all_tags (notmuch_database_t *db)
2674 Xapian::TermIterator i, end;
2675 notmuch_string_list_t *tags;
2678 i = db->xapian_db->allterms_begin();
2679 end = db->xapian_db->allterms_end();
2680 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2681 _find_prefix ("tag"));
2682 _notmuch_string_list_sort (tags);
2683 return _notmuch_tags_create (db, tags);
2684 } catch (const Xapian::Error &error) {
2685 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2686 error.get_msg().c_str());
2687 db->exception_reported = TRUE;
2693 notmuch_database_status_string (const notmuch_database_t *notmuch)
2695 return notmuch->status_string;