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]))
47 #define NOTMUCH_DATABASE_VERSION 3
49 #define STRINGIFY(s) _SUB_STRINGIFY(s)
50 #define _SUB_STRINGIFY(s) #s
52 #if HAVE_XAPIAN_DB_RETRY_LOCK
53 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
55 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
58 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
60 * We currently have three different types of documents (mail, ghost,
61 * and directory) and also some metadata.
65 * A mail document is associated with a particular email message. It
66 * is stored in one or more files on disk (though only one has its
67 * content indexed) and is uniquely identified by its "id" field
68 * (which is generally the message ID). It is indexed with the
69 * following prefixed terms which the database uses to construct
72 * Single terms of given prefix:
76 * id: Unique ID of mail. This is from the Message-ID header
77 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
78 * If it's present and too long, then we use
79 * "notmuch-sha1-<sha1_sum_of_message_id>".
80 * If this header is not present, we use
81 * "notmuch-sha1-<sha1_sum_of_entire_file>".
83 * thread: The ID of the thread to which the mail belongs
85 * replyto: The ID from the In-Reply-To header of the mail (if any).
87 * Multiple terms of given prefix:
89 * reference: All message IDs from In-Reply-To and References
90 * headers in the message.
92 * tag: Any tags associated with this message by the user.
94 * file-direntry: A colon-separated pair of values
95 * (INTEGER:STRING), where INTEGER is the
96 * document ID of a directory document, and
97 * STRING is the name of a file within that
98 * directory for this mail message.
100 * property: Has a property with key=value
101 * FIXME: if no = is present, should match on any value
103 * A mail document also has four values:
105 * TIMESTAMP: The time_t value corresponding to the message's
108 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
110 * FROM: The value of the "From" header
112 * SUBJECT: The value of the "Subject" header
114 * LAST_MOD: The revision number as of the last tag or
117 * In addition, terms from the content of the message are added with
118 * "from", "to", "attachment", and "subject" prefixes for use by the
119 * user in searching. Similarly, terms from the path of the mail
120 * message are added with "folder" and "path" prefixes. But the
121 * database doesn't really care itself about any of these.
123 * The data portion of a mail document is empty.
125 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
126 * -----------------------------------------------
127 * A ghost mail document is like a mail document, but where we don't
128 * have the message content. These are used to track thread reference
129 * information for messages we haven't received.
131 * A ghost mail document has type: ghost; id and thread fields that
132 * are identical to the mail document fields; and a MESSAGE_ID value.
136 * A directory document is used by a client of the notmuch library to
137 * maintain data necessary to allow for efficient polling of mail
140 * All directory documents contain one term:
142 * directory: The directory path (relative to the database path)
143 * Or the SHA1 sum of the directory path (if the
144 * path itself is too long to fit in a Xapian
147 * And all directory documents for directories other than top-level
148 * directories also contain the following term:
150 * directory-direntry: A colon-separated pair of values
151 * (INTEGER:STRING), where INTEGER is the
152 * document ID of the parent directory
153 * document, and STRING is the name of this
154 * directory within that parent.
156 * All directory documents have a single value:
158 * TIMESTAMP: The mtime of the directory (at last scan)
160 * The data portion of a directory document contains the path of the
161 * directory (relative to the database path).
165 * Xapian allows us to store arbitrary name-value pairs as
166 * "metadata". We currently use the following metadata names with the
169 * version The database schema version, (which is distinct
170 * from both the notmuch package version (see
171 * notmuch --version) and the libnotmuch library
172 * version. The version is stored as an base-10
173 * ASCII integer. The initial database version
174 * was 1, (though a schema existed before that
175 * were no "version" database value existed at
176 * all). Successive versions are allocated as
177 * changes are made to the database (such as by
178 * indexing new fields).
180 * features The set of features supported by this
181 * database. This consists of a set of
182 * '\n'-separated lines, where each is a feature
183 * name, a '\t', and compatibility flags. If the
184 * compatibility flags contain 'w', then the
185 * opener must support this feature to safely
186 * write this database. If the compatibility
187 * flags contain 'r', then the opener must
188 * support this feature to read this database.
189 * Introduced in database version 3.
191 * last_thread_id The last thread ID generated. This is stored
192 * as a 16-byte hexadecimal ASCII representation
193 * of a 64-bit unsigned integer. The first ID
194 * generated is 1 and the value will be
195 * incremented for each thread ID.
197 * C* metadata keys starting with C indicate
198 * configuration data. It can be managed with the
199 * n_database_*config* API. There is a convention
200 * of hierarchical keys separated by '.' (e.g.
201 * query.notmuch stores the value for the named
202 * query 'notmuch'), but it is not enforced by the
208 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
209 * Instead, the database has the following additional database
212 * thread_id_* A pre-allocated thread ID for a particular
213 * message. This is actually an arbitrarily large
214 * family of metadata name. Any particular name is
215 * formed by concatenating "thread_id_" with a message
216 * ID (or the SHA1 sum of a message ID if it is very
217 * long---see description of 'id' in the mail
218 * document). The value stored is a thread ID.
220 * These thread ID metadata values are stored
221 * whenever a message references a parent message
222 * that does not yet exist in the database. A
223 * thread ID will be allocated and stored, and if
224 * the message is later added, the stored thread
225 * ID will be used (and the metadata value will
228 * Even before a message is added, it's
229 * pre-allocated thread ID is useful so that all
230 * descendant messages that reference this common
231 * parent can be recognized as belonging to the
235 /* With these prefix values we follow the conventions published here:
237 * https://xapian.org/docs/omega/termprefixes.html
239 * as much as makes sense. Note that I took some liberty in matching
240 * the reserved prefix values to notmuch concepts, (for example, 'G'
241 * is documented as "newsGroup (or similar entity - e.g. a web forum
242 * name)", for which I think the thread is the closest analogue in
243 * notmuch. This in spite of the fact that we will eventually be
244 * storing mailing-list messages where 'G' for "mailing list name"
245 * might be even a closer analogue. I'm treating the single-character
246 * prefixes preferentially for core notmuch concepts (which will be
247 * nearly universal to all mail messages).
250 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
252 { "reference", "XREFERENCE" },
253 { "replyto", "XREPLYTO" },
254 { "directory", "XDIRECTORY" },
255 { "file-direntry", "XFDIRENTRY" },
256 { "directory-direntry", "XDDIRENTRY" },
259 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
265 { "property", "XPROPERTY" },
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:" },
275 static prefix_t PROBABILISTIC_PREFIX[]= {
278 { "attachment", "XATTACHMENT" },
279 { "mimetype", "XMIMETYPE"},
280 { "subject", "XSUBJECT"},
284 _find_prefix (const char *name)
288 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
289 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
290 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
293 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
294 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
295 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
298 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
299 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
300 return PROBABILISTIC_PREFIX[i].prefix;
303 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
308 static const struct {
309 /* NOTMUCH_FEATURE_* value. */
310 _notmuch_features value;
311 /* Feature name as it appears in the database. This name should
312 * be appropriate for displaying to the user if an older version
313 * of notmuch doesn't support this feature. */
315 /* Compatibility flags when this feature is declared. */
317 } feature_names[] = {
318 { NOTMUCH_FEATURE_FILE_TERMS,
319 "multiple paths per message", "rw" },
320 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
321 "relative directory paths", "rw" },
322 /* Header values are not required for reading a database because a
323 * reader can just refer to the message file. */
324 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
325 "from/subject/message-ID in database", "w" },
326 { NOTMUCH_FEATURE_BOOL_FOLDER,
327 "exact folder:/path: search", "rw" },
328 { NOTMUCH_FEATURE_GHOSTS,
329 "mail documents for missing messages", "w"},
330 /* Knowledge of the index mime-types are not required for reading
331 * a database because a reader will just be unable to query
333 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
334 "indexed MIME types", "w"},
335 { NOTMUCH_FEATURE_LAST_MOD,
336 "modification tracking", "w"},
340 notmuch_status_to_string (notmuch_status_t status)
343 case NOTMUCH_STATUS_SUCCESS:
344 return "No error occurred";
345 case NOTMUCH_STATUS_OUT_OF_MEMORY:
346 return "Out of memory";
347 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
348 return "Attempt to write to a read-only database";
349 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
350 return "A Xapian exception occurred";
351 case NOTMUCH_STATUS_FILE_ERROR:
352 return "Something went wrong trying to read or write a file";
353 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
354 return "File is not an email";
355 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
356 return "Message ID is identical to a message in database";
357 case NOTMUCH_STATUS_NULL_POINTER:
358 return "Erroneous NULL pointer";
359 case NOTMUCH_STATUS_TAG_TOO_LONG:
360 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
361 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
362 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
363 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
364 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
365 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
366 return "Unsupported operation";
367 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
368 return "Operation requires a database upgrade";
369 case NOTMUCH_STATUS_PATH_ERROR:
370 return "Path supplied is illegal for this function";
372 case NOTMUCH_STATUS_LAST_STATUS:
373 return "Unknown error status value";
378 _notmuch_database_log (notmuch_database_t *notmuch,
384 va_start (va_args, format);
386 if (notmuch->status_string)
387 talloc_free (notmuch->status_string);
389 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
394 _notmuch_database_log_append (notmuch_database_t *notmuch,
400 va_start (va_args, format);
402 if (notmuch->status_string)
403 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
405 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
411 find_doc_ids_for_term (notmuch_database_t *notmuch,
413 Xapian::PostingIterator *begin,
414 Xapian::PostingIterator *end)
416 *begin = notmuch->xapian_db->postlist_begin (term);
418 *end = notmuch->xapian_db->postlist_end (term);
422 find_doc_ids (notmuch_database_t *notmuch,
423 const char *prefix_name,
425 Xapian::PostingIterator *begin,
426 Xapian::PostingIterator *end)
430 term = talloc_asprintf (notmuch, "%s%s",
431 _find_prefix (prefix_name), value);
433 find_doc_ids_for_term (notmuch, term, begin, end);
438 notmuch_private_status_t
439 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
440 const char *prefix_name,
442 unsigned int *doc_id)
444 Xapian::PostingIterator i, end;
446 find_doc_ids (notmuch, prefix_name, value, &i, &end);
450 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
455 #if DEBUG_DATABASE_SANITY
459 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
463 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
466 static Xapian::Document
467 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
469 return notmuch->xapian_db->get_document (doc_id);
472 /* Generate a compressed version of 'message_id' of the form:
474 * notmuch-sha1-<sha1_sum_of_message_id>
477 _notmuch_message_id_compressed (void *ctx, const char *message_id)
479 char *sha1, *compressed;
481 sha1 = _notmuch_sha1_of_string (message_id);
483 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
490 notmuch_database_find_message (notmuch_database_t *notmuch,
491 const char *message_id,
492 notmuch_message_t **message_ret)
494 notmuch_private_status_t status;
497 if (message_ret == NULL)
498 return NOTMUCH_STATUS_NULL_POINTER;
500 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
501 message_id = _notmuch_message_id_compressed (notmuch, message_id);
504 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
505 message_id, &doc_id);
507 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
510 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
512 if (*message_ret == NULL)
513 return NOTMUCH_STATUS_OUT_OF_MEMORY;
516 return NOTMUCH_STATUS_SUCCESS;
517 } catch (const Xapian::Error &error) {
518 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
519 error.get_msg().c_str());
520 notmuch->exception_reported = TRUE;
522 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
526 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
527 * a (potentially nested) parenthesized sequence with '\' used to
528 * escape any character (including parentheses).
530 * If the sequence to be skipped continues to the end of the string,
531 * then 'str' will be left pointing at the final terminating '\0'
535 skip_space_and_comments (const char **str)
540 while (*s && (isspace (*s) || *s == '(')) {
541 while (*s && isspace (*s))
546 while (*s && nesting) {
549 } else if (*s == ')') {
551 } else if (*s == '\\') {
563 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
564 * comments, and the '<' and '>' delimiters.
566 * If not NULL, then *next will be made to point to the first character
567 * not parsed, (possibly pointing to the final '\0' terminator.
569 * Returns a newly talloc'ed string belonging to 'ctx'.
571 * Returns NULL if there is any error parsing the message-id. */
573 _parse_message_id (void *ctx, const char *message_id, const char **next)
578 if (message_id == NULL || *message_id == '\0')
583 skip_space_and_comments (&s);
585 /* Skip any unstructured text as well. */
586 while (*s && *s != '<')
597 skip_space_and_comments (&s);
600 while (*end && *end != '>')
609 if (end > s && *end == '>')
614 result = talloc_strndup (ctx, s, end - s + 1);
616 /* Finally, collapse any whitespace that is within the message-id
622 for (r = result, len = strlen (r); *r; r++, len--)
623 if (*r == ' ' || *r == '\t')
624 memmove (r, r+1, len);
630 /* Parse a References header value, putting a (talloc'ed under 'ctx')
631 * copy of each referenced message-id into 'hash'.
633 * We explicitly avoid including any reference identical to
634 * 'message_id' in the result (to avoid mass confusion when a single
635 * message references itself cyclically---and yes, mail messages are
636 * not infrequent in the wild that do this---don't ask me why).
638 * Return the last reference parsed, if it is not equal to message_id.
641 parse_references (void *ctx,
642 const char *message_id,
646 char *ref, *last_ref = NULL;
648 if (refs == NULL || *refs == '\0')
652 ref = _parse_message_id (ctx, refs, &refs);
654 if (ref && strcmp (ref, message_id)) {
655 g_hash_table_insert (hash, ref, NULL);
660 /* The return value of this function is used to add a parent
661 * reference to the database. We should avoid making a message
662 * its own parent, thus the above check.
668 notmuch_database_create (const char *path, notmuch_database_t **database)
670 char *status_string = NULL;
671 notmuch_status_t status;
673 status = notmuch_database_create_verbose (path, database,
677 fputs (status_string, stderr);
678 free (status_string);
685 notmuch_database_create_verbose (const char *path,
686 notmuch_database_t **database,
687 char **status_string)
689 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
690 notmuch_database_t *notmuch = NULL;
691 char *notmuch_path = NULL;
692 char *message = NULL;
697 message = strdup ("Error: Cannot create a database for a NULL path.\n");
698 status = NOTMUCH_STATUS_NULL_POINTER;
702 if (path[0] != '/') {
703 message = strdup ("Error: Database path must be absolute.\n");
704 status = NOTMUCH_STATUS_PATH_ERROR;
708 err = stat (path, &st);
710 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
711 path, strerror (errno)));
712 status = NOTMUCH_STATUS_FILE_ERROR;
716 if (! S_ISDIR (st.st_mode)) {
717 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
718 "Not a directory.\n",
720 status = NOTMUCH_STATUS_FILE_ERROR;
724 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
726 err = mkdir (notmuch_path, 0755);
729 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
730 notmuch_path, strerror (errno)));
731 status = NOTMUCH_STATUS_FILE_ERROR;
735 status = notmuch_database_open_verbose (path,
736 NOTMUCH_DATABASE_MODE_READ_WRITE,
741 /* Upgrade doesn't add these feature to existing databases, but
742 * new databases have them. */
743 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
744 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
746 status = notmuch_database_upgrade (notmuch, NULL, NULL);
748 notmuch_database_close(notmuch);
754 talloc_free (notmuch_path);
758 *status_string = message;
765 talloc_free (notmuch);
770 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
772 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
773 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
774 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
777 return NOTMUCH_STATUS_SUCCESS;
780 /* Allocate a revision number for the next change. */
782 _notmuch_database_new_revision (notmuch_database_t *notmuch)
784 unsigned long new_revision = notmuch->revision + 1;
786 /* If we're in an atomic section, hold off on updating the
787 * committed revision number until we commit the atomic section.
789 if (notmuch->atomic_nesting)
790 notmuch->atomic_dirty = TRUE;
792 notmuch->revision = new_revision;
797 /* Parse a database features string from the given database version.
798 * Returns the feature bit set.
800 * For version < 3, this ignores the features string and returns a
801 * hard-coded set of features.
803 * If there are unrecognized features that are required to open the
804 * database in mode (which should be 'r' or 'w'), return a
805 * comma-separated list of unrecognized but required features in
806 * *incompat_out suitable for presenting to the user. *incompat_out
807 * will be allocated from ctx.
809 static _notmuch_features
810 _parse_features (const void *ctx, const char *features, unsigned int version,
811 char mode, char **incompat_out)
813 _notmuch_features res = static_cast<_notmuch_features>(0);
814 unsigned int namelen, i;
818 /* Prior to database version 3, features were implied by the
821 return NOTMUCH_FEATURES_V0;
822 else if (version == 1)
823 return NOTMUCH_FEATURES_V1;
824 else if (version == 2)
825 return NOTMUCH_FEATURES_V2;
827 /* Parse the features string */
828 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
829 flags = strchr (features, '\t');
830 if (! flags || flags > features + llen)
832 namelen = flags - features;
834 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
835 if (strlen (feature_names[i].name) == namelen &&
836 strncmp (feature_names[i].name, features, namelen) == 0) {
837 res |= feature_names[i].value;
842 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
843 /* Unrecognized feature */
844 const char *have = strchr (flags, mode);
845 if (have && have < features + llen) {
846 /* This feature is required to access this database in
847 * 'mode', but we don't understand it. */
849 *incompat_out = talloc_strdup (ctx, "");
850 *incompat_out = talloc_asprintf_append_buffer (
851 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
861 _print_features (const void *ctx, unsigned int features)
864 char *res = talloc_strdup (ctx, "");
866 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
867 if (features & feature_names[i].value)
868 res = talloc_asprintf_append_buffer (
869 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
875 notmuch_database_open (const char *path,
876 notmuch_database_mode_t mode,
877 notmuch_database_t **database)
879 char *status_string = NULL;
880 notmuch_status_t status;
882 status = notmuch_database_open_verbose (path, mode, database,
886 fputs (status_string, stderr);
887 free (status_string);
894 notmuch_database_open_verbose (const char *path,
895 notmuch_database_mode_t mode,
896 notmuch_database_t **database,
897 char **status_string)
899 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
900 void *local = talloc_new (NULL);
901 notmuch_database_t *notmuch = NULL;
902 char *notmuch_path, *xapian_path, *incompat_features;
903 char *message = NULL;
906 unsigned int i, version;
907 static int initialized = 0;
910 message = strdup ("Error: Cannot open a database for a NULL path.\n");
911 status = NOTMUCH_STATUS_NULL_POINTER;
915 if (path[0] != '/') {
916 message = strdup ("Error: Database path must be absolute.\n");
917 status = NOTMUCH_STATUS_PATH_ERROR;
921 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
922 message = strdup ("Out of memory\n");
923 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
927 err = stat (notmuch_path, &st);
929 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
930 notmuch_path, strerror (errno)));
931 status = NOTMUCH_STATUS_FILE_ERROR;
935 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
936 message = strdup ("Out of memory\n");
937 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
941 /* Initialize the GLib type system and threads */
942 #if !GLIB_CHECK_VERSION(2, 35, 1)
946 /* Initialize gmime */
948 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
952 notmuch = talloc_zero (NULL, notmuch_database_t);
953 notmuch->exception_reported = FALSE;
954 notmuch->status_string = NULL;
955 notmuch->path = talloc_strdup (notmuch, path);
957 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
958 notmuch->path[strlen (notmuch->path) - 1] = '\0';
960 notmuch->mode = mode;
961 notmuch->atomic_nesting = 0;
963 string last_thread_id;
966 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
967 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
970 notmuch->xapian_db = new Xapian::Database (xapian_path);
973 /* Check version. As of database version 3, we represent
974 * changes in terms of features, so assume a version bump
975 * means a dramatically incompatible change. */
976 version = notmuch_database_get_version (notmuch);
977 if (version > NOTMUCH_DATABASE_VERSION) {
978 IGNORE_RESULT (asprintf (&message,
979 "Error: Notmuch database at %s\n"
980 " has a newer database format version (%u) than supported by this\n"
981 " version of notmuch (%u).\n",
982 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
983 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
984 notmuch_database_destroy (notmuch);
986 status = NOTMUCH_STATUS_FILE_ERROR;
990 /* Check features. */
991 incompat_features = NULL;
992 notmuch->features = _parse_features (
993 local, notmuch->xapian_db->get_metadata ("features").c_str (),
994 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
996 if (incompat_features) {
997 IGNORE_RESULT (asprintf (&message,
998 "Error: Notmuch database at %s\n"
999 " requires features (%s)\n"
1000 " not supported by this version of notmuch.\n",
1001 notmuch_path, incompat_features));
1002 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1003 notmuch_database_destroy (notmuch);
1005 status = NOTMUCH_STATUS_FILE_ERROR;
1009 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1010 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1011 if (last_thread_id.empty ()) {
1012 notmuch->last_thread_id = 0;
1017 str = last_thread_id.c_str ();
1018 notmuch->last_thread_id = strtoull (str, &end, 16);
1020 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1023 /* Get current highest revision number. */
1024 last_mod = notmuch->xapian_db->get_value_upper_bound (
1025 NOTMUCH_VALUE_LAST_MOD);
1026 if (last_mod.empty ())
1027 notmuch->revision = 0;
1029 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1030 notmuch->uuid = talloc_strdup (
1031 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1033 notmuch->query_parser = new Xapian::QueryParser;
1034 notmuch->term_gen = new Xapian::TermGenerator;
1035 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1036 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1037 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1038 #if HAVE_XAPIAN_FIELD_PROCESSOR
1039 /* This currently relies on the query parser to pass anything
1040 * with a .. to the range processor */
1041 notmuch->date_field_processor = new DateFieldProcessor();
1042 notmuch->query_parser->add_boolean_prefix("date", notmuch->date_field_processor);
1043 notmuch->query_field_processor = new QueryFieldProcessor (*notmuch->query_parser, notmuch);
1044 notmuch->query_parser->add_boolean_prefix("query", notmuch->query_field_processor);
1046 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1048 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1049 notmuch->query_parser->set_database (*notmuch->xapian_db);
1050 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1051 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1052 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1053 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1054 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1056 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
1057 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
1058 notmuch->query_parser->add_boolean_prefix (prefix->name,
1062 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
1063 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
1064 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
1066 } catch (const Xapian::Error &error) {
1067 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1068 error.get_msg().c_str()));
1069 notmuch_database_destroy (notmuch);
1071 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1075 talloc_free (local);
1079 *status_string = message;
1085 *database = notmuch;
1087 talloc_free (notmuch);
1092 notmuch_database_close (notmuch_database_t *notmuch)
1094 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1096 /* Many Xapian objects (and thus notmuch objects) hold references to
1097 * the database, so merely deleting the database may not suffice to
1098 * close it. Thus, we explicitly close it here. */
1099 if (notmuch->xapian_db != NULL) {
1101 /* If there's an outstanding transaction, it's unclear if
1102 * closing the Xapian database commits everything up to
1103 * that transaction, or may discard committed (but
1104 * unflushed) transactions. To be certain, explicitly
1105 * cancel any outstanding transaction before closing. */
1106 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1107 notmuch->atomic_nesting)
1108 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1109 ->cancel_transaction ();
1111 /* Close the database. This implicitly flushes
1112 * outstanding changes. */
1113 notmuch->xapian_db->close();
1114 } catch (const Xapian::Error &error) {
1115 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1116 if (! notmuch->exception_reported) {
1117 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1118 error.get_msg().c_str());
1123 delete notmuch->term_gen;
1124 notmuch->term_gen = NULL;
1125 delete notmuch->query_parser;
1126 notmuch->query_parser = NULL;
1127 delete notmuch->xapian_db;
1128 notmuch->xapian_db = NULL;
1129 delete notmuch->value_range_processor;
1130 notmuch->value_range_processor = NULL;
1131 delete notmuch->date_range_processor;
1132 notmuch->date_range_processor = NULL;
1133 delete notmuch->last_mod_range_processor;
1134 notmuch->last_mod_range_processor = NULL;
1136 #if HAVE_XAPIAN_FIELD_PROCESSOR
1137 delete notmuch->date_field_processor;
1138 notmuch->date_field_processor = NULL;
1139 delete notmuch->query_field_processor;
1140 notmuch->query_field_processor = NULL;
1146 #if HAVE_XAPIAN_COMPACT
1148 unlink_cb (const char *path,
1149 unused (const struct stat *sb),
1151 unused (struct FTW *ftw))
1153 return remove (path);
1157 rmtree (const char *path)
1159 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1162 class NotmuchCompactor : public Xapian::Compactor
1164 notmuch_compact_status_cb_t status_cb;
1165 void *status_closure;
1168 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1169 status_cb (cb), status_closure (closure) { }
1172 set_status (const std::string &table, const std::string &status)
1176 if (status_cb == NULL)
1179 if (status.length () == 0)
1180 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1182 msg = talloc_asprintf (NULL, " %s", status.c_str());
1188 status_cb (msg, status_closure);
1193 /* Compacts the given database, optionally saving the original database
1194 * in backup_path. Additionally, a callback function can be provided to
1195 * give the user feedback on the progress of the (likely long-lived)
1196 * compaction process.
1198 * The backup path must point to a directory on the same volume as the
1199 * original database. Passing a NULL backup_path will result in the
1200 * uncompacted database being deleted after compaction has finished.
1201 * Note that the database write lock will be held during the
1202 * compaction process to protect data integrity.
1205 notmuch_database_compact (const char *path,
1206 const char *backup_path,
1207 notmuch_compact_status_cb_t status_cb,
1211 char *notmuch_path, *xapian_path, *compact_xapian_path;
1212 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1213 notmuch_database_t *notmuch = NULL;
1214 struct stat statbuf;
1215 notmuch_bool_t keep_backup;
1216 char *message = NULL;
1218 local = talloc_new (NULL);
1220 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1222 ret = notmuch_database_open_verbose (path,
1223 NOTMUCH_DATABASE_MODE_READ_WRITE,
1227 if (status_cb) status_cb (message, closure);
1231 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1232 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1236 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1237 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1241 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1242 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1246 if (backup_path == NULL) {
1247 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1248 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1251 keep_backup = FALSE;
1257 if (stat (backup_path, &statbuf) != -1) {
1258 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1259 ret = NOTMUCH_STATUS_FILE_ERROR;
1262 if (errno != ENOENT) {
1263 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1265 ret = NOTMUCH_STATUS_FILE_ERROR;
1269 /* Unconditionally attempt to remove old work-in-progress database (if
1270 * any). This is "protected" by database lock. If this fails due to write
1271 * errors (etc), the following code will fail and provide error message.
1273 (void) rmtree (compact_xapian_path);
1276 NotmuchCompactor compactor (status_cb, closure);
1278 compactor.set_renumber (false);
1279 compactor.add_source (xapian_path);
1280 compactor.set_destdir (compact_xapian_path);
1281 compactor.compact ();
1282 } catch (const Xapian::Error &error) {
1283 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1284 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1288 if (rename (xapian_path, backup_path)) {
1289 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1290 xapian_path, backup_path, strerror (errno));
1291 ret = NOTMUCH_STATUS_FILE_ERROR;
1295 if (rename (compact_xapian_path, xapian_path)) {
1296 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1297 compact_xapian_path, xapian_path, strerror (errno));
1298 ret = NOTMUCH_STATUS_FILE_ERROR;
1302 if (! keep_backup) {
1303 if (rmtree (backup_path)) {
1304 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1305 backup_path, strerror (errno));
1306 ret = NOTMUCH_STATUS_FILE_ERROR;
1313 notmuch_status_t ret2;
1315 const char *str = notmuch_database_status_string (notmuch);
1316 if (status_cb && str)
1317 status_cb (str, closure);
1319 ret2 = notmuch_database_destroy (notmuch);
1321 /* don't clobber previous error status */
1322 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1326 talloc_free (local);
1332 notmuch_database_compact (unused (const char *path),
1333 unused (const char *backup_path),
1334 unused (notmuch_compact_status_cb_t status_cb),
1335 unused (void *closure))
1337 _notmuch_database_log (notmuch, "notmuch was compiled against a xapian version lacking compaction support.\n");
1338 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1343 notmuch_database_destroy (notmuch_database_t *notmuch)
1345 notmuch_status_t status;
1347 status = notmuch_database_close (notmuch);
1348 talloc_free (notmuch);
1354 notmuch_database_get_path (notmuch_database_t *notmuch)
1356 return notmuch->path;
1360 notmuch_database_get_version (notmuch_database_t *notmuch)
1362 unsigned int version;
1363 string version_string;
1367 version_string = notmuch->xapian_db->get_metadata ("version");
1368 if (version_string.empty ())
1371 str = version_string.c_str ();
1372 if (str == NULL || *str == '\0')
1375 version = strtoul (str, &end, 10);
1377 INTERNAL_ERROR ("Malformed database version: %s", str);
1383 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1385 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1386 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1387 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1390 static volatile sig_atomic_t do_progress_notify = 0;
1393 handle_sigalrm (unused (int signal))
1395 do_progress_notify = 1;
1398 /* Upgrade the current database.
1400 * After opening a database in read-write mode, the client should
1401 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1402 * if so, upgrade with this function before making any modifications.
1404 * The optional progress_notify callback can be used by the caller to
1405 * provide progress indication to the user. If non-NULL it will be
1406 * called periodically with 'count' as the number of messages upgraded
1407 * so far and 'total' the overall number of messages that will be
1411 notmuch_database_upgrade (notmuch_database_t *notmuch,
1412 void (*progress_notify) (void *closure,
1416 void *local = talloc_new (NULL);
1417 Xapian::TermIterator t, t_end;
1418 Xapian::WritableDatabase *db;
1419 struct sigaction action;
1420 struct itimerval timerval;
1421 notmuch_bool_t timer_is_active = FALSE;
1422 enum _notmuch_features target_features, new_features;
1423 notmuch_status_t status;
1424 notmuch_private_status_t private_status;
1425 notmuch_query_t *query = NULL;
1426 unsigned int count = 0, total = 0;
1428 status = _notmuch_database_ensure_writable (notmuch);
1432 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1434 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1435 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1437 if (! notmuch_database_needs_upgrade (notmuch))
1438 return NOTMUCH_STATUS_SUCCESS;
1440 if (progress_notify) {
1441 /* Set up our handler for SIGALRM */
1442 memset (&action, 0, sizeof (struct sigaction));
1443 action.sa_handler = handle_sigalrm;
1444 sigemptyset (&action.sa_mask);
1445 action.sa_flags = SA_RESTART;
1446 sigaction (SIGALRM, &action, NULL);
1448 /* Then start a timer to send SIGALRM once per second. */
1449 timerval.it_interval.tv_sec = 1;
1450 timerval.it_interval.tv_usec = 0;
1451 timerval.it_value.tv_sec = 1;
1452 timerval.it_value.tv_usec = 0;
1453 setitimer (ITIMER_REAL, &timerval, NULL);
1455 timer_is_active = TRUE;
1458 /* Figure out how much total work we need to do. */
1460 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1461 NOTMUCH_FEATURE_LAST_MOD)) {
1462 query = notmuch_query_create (notmuch, "");
1465 status = notmuch_query_count_messages_st (query, &msg_count);
1470 notmuch_query_destroy (query);
1473 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1474 t_end = db->allterms_end ("XTIMESTAMP");
1475 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1478 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1479 /* The ghost message upgrade converts all thread_id_*
1480 * metadata values into ghost message documents. */
1481 t_end = db->metadata_keys_end ("thread_id_");
1482 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1486 /* Perform the upgrade in a transaction. */
1487 db->begin_transaction (true);
1489 /* Set the target features so we write out changes in the desired
1491 notmuch->features = target_features;
1493 /* Perform per-message upgrades. */
1495 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1496 NOTMUCH_FEATURE_LAST_MOD)) {
1497 notmuch_messages_t *messages;
1498 notmuch_message_t *message;
1501 query = notmuch_query_create (notmuch, "");
1503 status = notmuch_query_search_messages_st (query, &messages);
1507 notmuch_messages_valid (messages);
1508 notmuch_messages_move_to_next (messages))
1510 if (do_progress_notify) {
1511 progress_notify (closure, (double) count / total);
1512 do_progress_notify = 0;
1515 message = notmuch_messages_get (messages);
1517 /* Before version 1, each message document had its
1518 * filename in the data field. Copy that into the new
1519 * format by calling notmuch_message_add_filename.
1521 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1522 filename = _notmuch_message_talloc_copy_data (message);
1523 if (filename && *filename != '\0') {
1524 _notmuch_message_add_filename (message, filename);
1525 _notmuch_message_clear_data (message);
1527 talloc_free (filename);
1530 /* Prior to version 2, the "folder:" prefix was
1531 * probabilistic and stemmed. Change it to the current
1532 * boolean prefix. Add "path:" prefixes while at it.
1534 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1535 _notmuch_message_upgrade_folder (message);
1537 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1538 * track modification revisions. Give all messages the
1539 * next available revision; since we just started tracking
1540 * revisions for this database, that will be 1.
1542 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1543 _notmuch_message_upgrade_last_mod (message);
1545 _notmuch_message_sync (message);
1547 notmuch_message_destroy (message);
1552 notmuch_query_destroy (query);
1556 /* Perform per-directory upgrades. */
1558 /* Before version 1 we stored directory timestamps in
1559 * XTIMESTAMP documents instead of the current XDIRECTORY
1560 * documents. So copy those as well. */
1561 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1562 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1564 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1568 Xapian::PostingIterator p, p_end;
1569 std::string term = *t;
1571 p_end = notmuch->xapian_db->postlist_end (term);
1573 for (p = notmuch->xapian_db->postlist_begin (term);
1577 Xapian::Document document;
1579 notmuch_directory_t *directory;
1581 if (do_progress_notify) {
1582 progress_notify (closure, (double) count / total);
1583 do_progress_notify = 0;
1586 document = find_document_for_doc_id (notmuch, *p);
1587 mtime = Xapian::sortable_unserialise (
1588 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1590 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1591 NOTMUCH_FIND_CREATE, &status);
1592 notmuch_directory_set_mtime (directory, mtime);
1593 notmuch_directory_destroy (directory);
1595 db->delete_document (*p);
1602 /* Perform metadata upgrades. */
1604 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1605 * messages were stored as database metadata. Change these to
1608 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1609 notmuch_message_t *message;
1610 std::string message_id, thread_id;
1612 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1613 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1615 if (do_progress_notify) {
1616 progress_notify (closure, (double) count / total);
1617 do_progress_notify = 0;
1620 message_id = (*t).substr (
1621 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1622 thread_id = db->get_metadata (*t);
1624 /* Create ghost message */
1625 message = _notmuch_message_create_for_message_id (
1626 notmuch, message_id.c_str (), &private_status);
1627 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1628 /* Document already exists; ignore the stored thread ID */
1629 } else if (private_status ==
1630 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1631 private_status = _notmuch_message_initialize_ghost (
1632 message, thread_id.c_str ());
1633 if (! private_status)
1634 _notmuch_message_sync (message);
1637 if (private_status) {
1638 _notmuch_database_log (notmuch,
1639 "Upgrade failed while creating ghost messages.\n");
1640 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1644 /* Clear saved metadata thread ID */
1645 db->set_metadata (*t, "");
1651 status = NOTMUCH_STATUS_SUCCESS;
1652 db->set_metadata ("features", _print_features (local, notmuch->features));
1653 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1656 if (status == NOTMUCH_STATUS_SUCCESS)
1657 db->commit_transaction ();
1659 db->cancel_transaction ();
1661 if (timer_is_active) {
1662 /* Now stop the timer. */
1663 timerval.it_interval.tv_sec = 0;
1664 timerval.it_interval.tv_usec = 0;
1665 timerval.it_value.tv_sec = 0;
1666 timerval.it_value.tv_usec = 0;
1667 setitimer (ITIMER_REAL, &timerval, NULL);
1669 /* And disable the signal handler. */
1670 action.sa_handler = SIG_IGN;
1671 sigaction (SIGALRM, &action, NULL);
1675 notmuch_query_destroy (query);
1677 talloc_free (local);
1682 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1684 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1685 notmuch->atomic_nesting > 0)
1688 if (notmuch_database_needs_upgrade(notmuch))
1689 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1692 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1693 } catch (const Xapian::Error &error) {
1694 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1695 error.get_msg().c_str());
1696 notmuch->exception_reported = TRUE;
1697 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1701 notmuch->atomic_nesting++;
1702 return NOTMUCH_STATUS_SUCCESS;
1706 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1708 Xapian::WritableDatabase *db;
1710 if (notmuch->atomic_nesting == 0)
1711 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1713 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1714 notmuch->atomic_nesting > 1)
1717 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1719 db->commit_transaction ();
1721 /* This is a hack for testing. Xapian never flushes on a
1722 * non-flushed commit, even if the flush threshold is 1.
1723 * However, we rely on flushing to test atomicity. */
1724 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1725 if (thresh && atoi (thresh) == 1)
1727 } catch (const Xapian::Error &error) {
1728 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1729 error.get_msg().c_str());
1730 notmuch->exception_reported = TRUE;
1731 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1734 if (notmuch->atomic_dirty) {
1735 ++notmuch->revision;
1736 notmuch->atomic_dirty = FALSE;
1740 notmuch->atomic_nesting--;
1741 return NOTMUCH_STATUS_SUCCESS;
1745 notmuch_database_get_revision (notmuch_database_t *notmuch,
1749 *uuid = notmuch->uuid;
1750 return notmuch->revision;
1753 /* We allow the user to use arbitrarily long paths for directories. But
1754 * we have a term-length limit. So if we exceed that, we'll use the
1755 * SHA-1 of the path for the database term.
1757 * Note: This function may return the original value of 'path'. If it
1758 * does not, then the caller is responsible to free() the returned
1762 _notmuch_database_get_directory_db_path (const char *path)
1764 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1766 if (term_len > NOTMUCH_TERM_MAX)
1767 return _notmuch_sha1_of_string (path);
1772 /* Given a path, split it into two parts: the directory part is all
1773 * components except for the last, and the basename is that last
1774 * component. Getting the return-value for either part is optional
1775 * (the caller can pass NULL).
1777 * The original 'path' can represent either a regular file or a
1778 * directory---the splitting will be carried out in the same way in
1779 * either case. Trailing slashes on 'path' will be ignored, and any
1780 * cases of multiple '/' characters appearing in series will be
1781 * treated as a single '/'.
1783 * Allocation (if any) will have 'ctx' as the talloc owner. But
1784 * pointers will be returned within the original path string whenever
1787 * Note: If 'path' is non-empty and contains no non-trailing slash,
1788 * (that is, consists of a filename with no parent directory), then
1789 * the directory returned will be an empty string. However, if 'path'
1790 * is an empty string, then both directory and basename will be
1794 _notmuch_database_split_path (void *ctx,
1796 const char **directory,
1797 const char **basename)
1801 if (path == NULL || *path == '\0') {
1806 return NOTMUCH_STATUS_SUCCESS;
1809 /* Find the last slash (not counting a trailing slash), if any. */
1811 slash = path + strlen (path) - 1;
1813 /* First, skip trailing slashes. */
1814 while (slash != path && *slash == '/')
1817 /* Then, find a slash. */
1818 while (slash != path && *slash != '/') {
1825 /* Finally, skip multiple slashes. */
1826 while (slash != path && *(slash - 1) == '/')
1829 if (slash == path) {
1831 *directory = talloc_strdup (ctx, "");
1836 *directory = talloc_strndup (ctx, path, slash - path);
1839 return NOTMUCH_STATUS_SUCCESS;
1842 /* Find the document ID of the specified directory.
1844 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1845 * created if one does not exist for 'path'. Otherwise, if the
1846 * directory document does not exist, this sets *directory_id to
1847 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1850 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1852 notmuch_find_flags_t flags,
1853 unsigned int *directory_id)
1855 notmuch_directory_t *directory;
1856 notmuch_status_t status;
1860 return NOTMUCH_STATUS_SUCCESS;
1863 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1864 if (status || !directory) {
1869 *directory_id = _notmuch_directory_get_document_id (directory);
1871 notmuch_directory_destroy (directory);
1873 return NOTMUCH_STATUS_SUCCESS;
1877 _notmuch_database_get_directory_path (void *ctx,
1878 notmuch_database_t *notmuch,
1879 unsigned int doc_id)
1881 Xapian::Document document;
1883 document = find_document_for_doc_id (notmuch, doc_id);
1885 return talloc_strdup (ctx, document.get_data ().c_str ());
1888 /* Given a legal 'filename' for the database, (either relative to
1889 * database path or absolute with initial components identical to
1890 * database path), return a new string (with 'ctx' as the talloc
1891 * owner) suitable for use as a direntry term value.
1893 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1894 * will be created in the database as needed. Otherwise, if the
1895 * necessary directory documents do not exist, this sets
1896 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1899 _notmuch_database_filename_to_direntry (void *ctx,
1900 notmuch_database_t *notmuch,
1901 const char *filename,
1902 notmuch_find_flags_t flags,
1905 const char *relative, *directory, *basename;
1906 Xapian::docid directory_id;
1907 notmuch_status_t status;
1909 relative = _notmuch_database_relative_path (notmuch, filename);
1911 status = _notmuch_database_split_path (ctx, relative,
1912 &directory, &basename);
1916 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1918 if (status || directory_id == (unsigned int)-1) {
1923 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1925 return NOTMUCH_STATUS_SUCCESS;
1928 /* Given a legal 'path' for the database, return the relative path.
1930 * The return value will be a pointer to the original path contents,
1931 * and will be either the original string (if 'path' was relative) or
1932 * a portion of the string (if path was absolute and begins with the
1936 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1939 const char *db_path, *relative;
1940 unsigned int db_path_len;
1942 db_path = notmuch_database_get_path (notmuch);
1943 db_path_len = strlen (db_path);
1947 if (*relative == '/') {
1948 while (*relative == '/' && *(relative+1) == '/')
1951 if (strncmp (relative, db_path, db_path_len) == 0)
1953 relative += db_path_len;
1954 while (*relative == '/')
1963 notmuch_database_get_directory (notmuch_database_t *notmuch,
1965 notmuch_directory_t **directory)
1967 notmuch_status_t status;
1969 if (directory == NULL)
1970 return NOTMUCH_STATUS_NULL_POINTER;
1974 *directory = _notmuch_directory_create (notmuch, path,
1975 NOTMUCH_FIND_LOOKUP, &status);
1976 } catch (const Xapian::Error &error) {
1977 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1978 error.get_msg().c_str());
1979 notmuch->exception_reported = TRUE;
1980 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1985 /* Allocate a document ID that satisfies the following criteria:
1987 * 1. The ID does not exist for any document in the Xapian database
1989 * 2. The ID was not previously returned from this function
1991 * 3. The ID is the smallest integer satisfying (1) and (2)
1993 * This function will trigger an internal error if these constraints
1994 * cannot all be satisfied, (that is, the pool of available document
1995 * IDs has been exhausted).
1998 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2000 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2002 notmuch->last_doc_id++;
2004 if (notmuch->last_doc_id == 0)
2005 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2007 return notmuch->last_doc_id;
2011 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
2013 /* 16 bytes (+ terminator) for hexadecimal representation of
2014 * a 64-bit integer. */
2015 static char thread_id[17];
2016 Xapian::WritableDatabase *db;
2018 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2020 notmuch->last_thread_id++;
2022 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2024 db->set_metadata ("last_thread_id", thread_id);
2030 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2032 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2033 message_id = _notmuch_message_id_compressed (ctx, message_id);
2035 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2039 static notmuch_status_t
2040 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2042 const char *message_id,
2043 const char **thread_id_ret);
2045 /* Find the thread ID to which the message with 'message_id' belongs.
2047 * Note: 'thread_id_ret' must not be NULL!
2048 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2051 * Note: If there is no message in the database with the given
2052 * 'message_id' then a new thread_id will be allocated for this
2053 * message ID and stored in the database metadata so that the
2054 * thread ID can be looked up if the message is added to the database
2057 static notmuch_status_t
2058 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2060 const char *message_id,
2061 const char **thread_id_ret)
2063 notmuch_private_status_t status;
2064 notmuch_message_t *message;
2066 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2067 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2070 /* Look for this message (regular or ghost) */
2071 message = _notmuch_message_create_for_message_id (
2072 notmuch, message_id, &status);
2073 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2074 /* Message exists */
2075 *thread_id_ret = talloc_steal (
2076 ctx, notmuch_message_get_thread_id (message));
2077 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2078 /* Message did not exist. Give it a fresh thread ID and
2079 * populate this message as a ghost message. */
2080 *thread_id_ret = talloc_strdup (
2081 ctx, _notmuch_database_generate_thread_id (notmuch));
2082 if (! *thread_id_ret) {
2083 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2085 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2087 /* Commit the new ghost message */
2088 _notmuch_message_sync (message);
2091 /* Create failed. Fall through. */
2094 notmuch_message_destroy (message);
2096 return COERCE_STATUS (status, "Error creating ghost message");
2099 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2100 static notmuch_status_t
2101 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2103 const char *message_id,
2104 const char **thread_id_ret)
2106 notmuch_status_t status;
2107 notmuch_message_t *message;
2108 string thread_id_string;
2110 Xapian::WritableDatabase *db;
2112 status = notmuch_database_find_message (notmuch, message_id, &message);
2118 *thread_id_ret = talloc_steal (ctx,
2119 notmuch_message_get_thread_id (message));
2121 notmuch_message_destroy (message);
2123 return NOTMUCH_STATUS_SUCCESS;
2126 /* Message has not been seen yet.
2128 * We may have seen a reference to it already, in which case, we
2129 * can return the thread ID stored in the metadata. Otherwise, we
2130 * generate a new thread ID and store it there.
2132 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2133 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2134 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2136 if (thread_id_string.empty()) {
2137 *thread_id_ret = talloc_strdup (ctx,
2138 _notmuch_database_generate_thread_id (notmuch));
2139 db->set_metadata (metadata_key, *thread_id_ret);
2141 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2144 talloc_free (metadata_key);
2146 return NOTMUCH_STATUS_SUCCESS;
2149 static notmuch_status_t
2150 _merge_threads (notmuch_database_t *notmuch,
2151 const char *winner_thread_id,
2152 const char *loser_thread_id)
2154 Xapian::PostingIterator loser, loser_end;
2155 notmuch_message_t *message = NULL;
2156 notmuch_private_status_t private_status;
2157 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2159 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2161 for ( ; loser != loser_end; loser++) {
2162 message = _notmuch_message_create (notmuch, notmuch,
2163 *loser, &private_status);
2164 if (message == NULL) {
2165 ret = COERCE_STATUS (private_status,
2166 "Cannot find document for doc_id from query");
2170 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2171 _notmuch_message_add_term (message, "thread", winner_thread_id);
2172 _notmuch_message_sync (message);
2174 notmuch_message_destroy (message);
2180 notmuch_message_destroy (message);
2186 _my_talloc_free_for_g_hash (void *ptr)
2191 static notmuch_status_t
2192 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2193 notmuch_message_t *message,
2194 notmuch_message_file_t *message_file,
2195 const char **thread_id)
2197 GHashTable *parents = NULL;
2198 const char *refs, *in_reply_to, *in_reply_to_message_id;
2199 const char *last_ref_message_id, *this_message_id;
2200 GList *l, *keys = NULL;
2201 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2203 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2204 _my_talloc_free_for_g_hash, NULL);
2205 this_message_id = notmuch_message_get_message_id (message);
2207 refs = _notmuch_message_file_get_header (message_file, "references");
2208 last_ref_message_id = parse_references (message,
2212 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2213 in_reply_to_message_id = parse_references (message,
2215 parents, in_reply_to);
2217 /* For the parent of this message, use the last message ID of the
2218 * References header, if available. If not, fall back to the
2219 * first message ID in the In-Reply-To header. */
2220 if (last_ref_message_id) {
2221 _notmuch_message_add_term (message, "replyto",
2222 last_ref_message_id);
2223 } else if (in_reply_to_message_id) {
2224 _notmuch_message_add_term (message, "replyto",
2225 in_reply_to_message_id);
2228 keys = g_hash_table_get_keys (parents);
2229 for (l = keys; l; l = l->next) {
2230 char *parent_message_id;
2231 const char *parent_thread_id = NULL;
2233 parent_message_id = (char *) l->data;
2235 _notmuch_message_add_term (message, "reference",
2238 ret = _resolve_message_id_to_thread_id (notmuch,
2245 if (*thread_id == NULL) {
2246 *thread_id = talloc_strdup (message, parent_thread_id);
2247 _notmuch_message_add_term (message, "thread", *thread_id);
2248 } else if (strcmp (*thread_id, parent_thread_id)) {
2249 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2259 g_hash_table_unref (parents);
2264 static notmuch_status_t
2265 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2266 notmuch_message_t *message,
2267 const char **thread_id)
2269 const char *message_id = notmuch_message_get_message_id (message);
2270 Xapian::PostingIterator child, children_end;
2271 notmuch_message_t *child_message = NULL;
2272 const char *child_thread_id;
2273 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2274 notmuch_private_status_t private_status;
2276 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2278 for ( ; child != children_end; child++) {
2280 child_message = _notmuch_message_create (message, notmuch,
2281 *child, &private_status);
2282 if (child_message == NULL) {
2283 ret = COERCE_STATUS (private_status,
2284 "Cannot find document for doc_id from query");
2288 child_thread_id = notmuch_message_get_thread_id (child_message);
2289 if (*thread_id == NULL) {
2290 *thread_id = talloc_strdup (message, child_thread_id);
2291 _notmuch_message_add_term (message, "thread", *thread_id);
2292 } else if (strcmp (*thread_id, child_thread_id)) {
2293 _notmuch_message_remove_term (child_message, "reference",
2295 _notmuch_message_sync (child_message);
2296 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2301 notmuch_message_destroy (child_message);
2302 child_message = NULL;
2307 notmuch_message_destroy (child_message);
2312 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2314 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2315 notmuch_message_t *message)
2317 const char *message_id;
2321 message_id = notmuch_message_get_message_id (message);
2322 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2324 /* Check if we have already seen related messages to this one.
2325 * If we have then use the thread_id that we stored at that time.
2327 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2328 if (stored_id.empty ()) {
2331 Xapian::WritableDatabase *db;
2333 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2335 /* Clear the metadata for this message ID. We don't need it
2337 db->set_metadata (metadata_key, "");
2339 return talloc_strdup (ctx, stored_id.c_str ());
2343 /* Given a blank or ghost 'message' and its corresponding
2344 * 'message_file' link it to existing threads in the database.
2346 * First, if is_ghost, this retrieves the thread ID already stored in
2347 * the message (which will be the case if a message was previously
2348 * added that referenced this one). If the message is blank
2349 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2350 * later in this function). If the database does not support ghost
2351 * messages, this checks for a thread ID stored in database metadata
2352 * for this message ID.
2354 * Second, we look at 'message_file' and its link-relevant headers
2355 * (References and In-Reply-To) for message IDs.
2357 * Finally, we look in the database for existing message that
2358 * reference 'message'.
2360 * In all cases, we assign to the current message the first thread ID
2361 * found. We will also merge any existing, distinct threads where this
2362 * message belongs to both, (which is not uncommon when messages are
2363 * processed out of order).
2365 * Finally, if no thread ID has been found through referenced messages, we
2366 * call _notmuch_message_generate_thread_id to generate a new thread
2367 * ID. This should only happen for new, top-level messages, (no
2368 * References or In-Reply-To header in this message, and no previously
2369 * added message refers to this message).
2371 static notmuch_status_t
2372 _notmuch_database_link_message (notmuch_database_t *notmuch,
2373 notmuch_message_t *message,
2374 notmuch_message_file_t *message_file,
2375 notmuch_bool_t is_ghost)
2377 void *local = talloc_new (NULL);
2378 notmuch_status_t status;
2379 const char *thread_id = NULL;
2381 /* Check if the message already had a thread ID */
2382 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2384 thread_id = notmuch_message_get_thread_id (message);
2386 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2388 _notmuch_message_add_term (message, "thread", thread_id);
2391 status = _notmuch_database_link_message_to_parents (notmuch, message,
2397 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2398 /* In general, it shouldn't be necessary to link children,
2399 * since the earlier indexing of those children will have
2400 * stored a thread ID for the missing parent. However, prior
2401 * to ghost messages, these stored thread IDs were NOT
2402 * rewritten during thread merging (and there was no
2403 * performant way to do so), so if indexed children were
2404 * pulled into a different thread ID by a merge, it was
2405 * necessary to pull them *back* into the stored thread ID of
2406 * the parent. With ghost messages, we just rewrite the
2407 * stored thread IDs during merging, so this workaround isn't
2409 status = _notmuch_database_link_message_to_children (notmuch, message,
2415 /* If not part of any existing thread, generate a new thread ID. */
2416 if (thread_id == NULL) {
2417 thread_id = _notmuch_database_generate_thread_id (notmuch);
2419 _notmuch_message_add_term (message, "thread", thread_id);
2423 talloc_free (local);
2429 notmuch_database_add_message (notmuch_database_t *notmuch,
2430 const char *filename,
2431 notmuch_message_t **message_ret)
2433 notmuch_message_file_t *message_file;
2434 notmuch_message_t *message = NULL;
2435 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2436 notmuch_private_status_t private_status;
2437 notmuch_bool_t is_ghost = false;
2439 const char *date, *header;
2440 const char *from, *to, *subject;
2441 char *message_id = NULL;
2444 *message_ret = NULL;
2446 ret = _notmuch_database_ensure_writable (notmuch);
2450 message_file = _notmuch_message_file_open (notmuch, filename);
2451 if (message_file == NULL)
2452 return NOTMUCH_STATUS_FILE_ERROR;
2454 /* Adding a message may change many documents. Do this all
2456 ret = notmuch_database_begin_atomic (notmuch);
2460 /* Parse message up front to get better error status. */
2461 ret = _notmuch_message_file_parse (message_file);
2466 /* Before we do any real work, (especially before doing a
2467 * potential SHA-1 computation on the entire file's contents),
2468 * let's make sure that what we're looking at looks like an
2469 * actual email message.
2471 from = _notmuch_message_file_get_header (message_file, "from");
2472 subject = _notmuch_message_file_get_header (message_file, "subject");
2473 to = _notmuch_message_file_get_header (message_file, "to");
2475 if ((from == NULL || *from == '\0') &&
2476 (subject == NULL || *subject == '\0') &&
2477 (to == NULL || *to == '\0'))
2479 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2483 /* Now that we're sure it's mail, the first order of business
2484 * is to find a message ID (or else create one ourselves). */
2486 header = _notmuch_message_file_get_header (message_file, "message-id");
2487 if (header && *header != '\0') {
2488 message_id = _parse_message_id (message_file, header, NULL);
2490 /* So the header value isn't RFC-compliant, but it's
2491 * better than no message-id at all. */
2492 if (message_id == NULL)
2493 message_id = talloc_strdup (message_file, header);
2496 if (message_id == NULL ) {
2497 /* No message-id at all, let's generate one by taking a
2498 * hash over the file's contents. */
2499 char *sha1 = _notmuch_sha1_of_file (filename);
2501 /* If that failed too, something is really wrong. Give up. */
2503 ret = NOTMUCH_STATUS_FILE_ERROR;
2507 message_id = talloc_asprintf (message_file,
2508 "notmuch-sha1-%s", sha1);
2512 /* Now that we have a message ID, we get a message object,
2513 * (which may or may not reference an existing document in the
2516 message = _notmuch_message_create_for_message_id (notmuch,
2520 talloc_free (message_id);
2522 if (message == NULL) {
2523 ret = COERCE_STATUS (private_status,
2524 "Unexpected status value from _notmuch_message_create_for_message_id");
2528 _notmuch_message_add_filename (message, filename);
2530 /* Is this a newly created message object or a ghost
2531 * message? We have to be slightly careful: if this is a
2532 * blank message, it's not safe to call
2533 * notmuch_message_get_flag yet. */
2534 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2535 (is_ghost = notmuch_message_get_flag (
2536 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2537 _notmuch_message_add_term (message, "type", "mail");
2539 /* Convert ghost message to a regular message */
2540 _notmuch_message_remove_term (message, "type", "ghost");
2542 ret = _notmuch_database_link_message (notmuch, message,
2543 message_file, is_ghost);
2547 date = _notmuch_message_file_get_header (message_file, "date");
2548 _notmuch_message_set_header_values (message, date, from, subject);
2550 ret = _notmuch_message_index_file (message, message_file);
2554 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2557 _notmuch_message_sync (message);
2558 } catch (const Xapian::Error &error) {
2559 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2560 error.get_msg().c_str());
2561 notmuch->exception_reported = TRUE;
2562 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2568 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2569 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2570 *message_ret = message;
2572 notmuch_message_destroy (message);
2576 _notmuch_message_file_close (message_file);
2578 ret2 = notmuch_database_end_atomic (notmuch);
2579 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2580 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2581 ret2 != NOTMUCH_STATUS_SUCCESS)
2588 notmuch_database_remove_message (notmuch_database_t *notmuch,
2589 const char *filename)
2591 notmuch_status_t status;
2592 notmuch_message_t *message;
2594 status = notmuch_database_find_message_by_filename (notmuch, filename,
2597 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2598 status = _notmuch_message_remove_filename (message, filename);
2599 if (status == NOTMUCH_STATUS_SUCCESS)
2600 _notmuch_message_delete (message);
2601 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2602 _notmuch_message_sync (message);
2604 notmuch_message_destroy (message);
2611 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2612 const char *filename,
2613 notmuch_message_t **message_ret)
2616 const char *prefix = _find_prefix ("file-direntry");
2617 char *direntry, *term;
2618 Xapian::PostingIterator i, end;
2619 notmuch_status_t status;
2621 if (message_ret == NULL)
2622 return NOTMUCH_STATUS_NULL_POINTER;
2624 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2625 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2627 /* return NULL on any failure */
2628 *message_ret = NULL;
2630 local = talloc_new (notmuch);
2633 status = _notmuch_database_filename_to_direntry (
2634 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2635 if (status || !direntry)
2638 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2640 find_doc_ids_for_term (notmuch, term, &i, &end);
2643 notmuch_private_status_t private_status;
2645 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2647 if (*message_ret == NULL)
2648 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2650 } catch (const Xapian::Error &error) {
2651 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2652 error.get_msg().c_str());
2653 notmuch->exception_reported = TRUE;
2654 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2658 talloc_free (local);
2660 if (status && *message_ret) {
2661 notmuch_message_destroy (*message_ret);
2662 *message_ret = NULL;
2667 notmuch_string_list_t *
2668 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2669 Xapian::TermIterator &end,
2672 int prefix_len = strlen (prefix);
2673 notmuch_string_list_t *list;
2675 list = _notmuch_string_list_create (ctx);
2676 if (unlikely (list == NULL))
2679 for (i.skip_to (prefix); i != end; i++) {
2680 /* Terminate loop at first term without desired prefix. */
2681 if (strncmp ((*i).c_str (), prefix, prefix_len))
2684 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2691 notmuch_database_get_all_tags (notmuch_database_t *db)
2693 Xapian::TermIterator i, end;
2694 notmuch_string_list_t *tags;
2697 i = db->xapian_db->allterms_begin();
2698 end = db->xapian_db->allterms_end();
2699 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2700 _find_prefix ("tag"));
2701 _notmuch_string_list_sort (tags);
2702 return _notmuch_tags_create (db, tags);
2703 } catch (const Xapian::Error &error) {
2704 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2705 error.get_msg().c_str());
2706 db->exception_reported = TRUE;
2712 notmuch_database_status_string (const notmuch_database_t *notmuch)
2714 return notmuch->status_string;