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 * A mail document also has four values:
102 * TIMESTAMP: The time_t value corresponding to the message's
105 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
107 * FROM: The value of the "From" header
109 * SUBJECT: The value of the "Subject" header
111 * LAST_MOD: The revision number as of the last tag or
114 * In addition, terms from the content of the message are added with
115 * "from", "to", "attachment", and "subject" prefixes for use by the
116 * user in searching. Similarly, terms from the path of the mail
117 * message are added with "folder" and "path" prefixes. But the
118 * database doesn't really care itself about any of these.
120 * The data portion of a mail document is empty.
122 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
123 * -----------------------------------------------
124 * A ghost mail document is like a mail document, but where we don't
125 * have the message content. These are used to track thread reference
126 * information for messages we haven't received.
128 * A ghost mail document has type: ghost; id and thread fields that
129 * are identical to the mail document fields; and a MESSAGE_ID value.
133 * A directory document is used by a client of the notmuch library to
134 * maintain data necessary to allow for efficient polling of mail
137 * All directory documents contain one term:
139 * directory: The directory path (relative to the database path)
140 * Or the SHA1 sum of the directory path (if the
141 * path itself is too long to fit in a Xapian
144 * And all directory documents for directories other than top-level
145 * directories also contain the following term:
147 * directory-direntry: A colon-separated pair of values
148 * (INTEGER:STRING), where INTEGER is the
149 * document ID of the parent directory
150 * document, and STRING is the name of this
151 * directory within that parent.
153 * All directory documents have a single value:
155 * TIMESTAMP: The mtime of the directory (at last scan)
157 * The data portion of a directory document contains the path of the
158 * directory (relative to the database path).
162 * Xapian allows us to store arbitrary name-value pairs as
163 * "metadata". We currently use the following metadata names with the
166 * version The database schema version, (which is distinct
167 * from both the notmuch package version (see
168 * notmuch --version) and the libnotmuch library
169 * version. The version is stored as an base-10
170 * ASCII integer. The initial database version
171 * was 1, (though a schema existed before that
172 * were no "version" database value existed at
173 * all). Successive versions are allocated as
174 * changes are made to the database (such as by
175 * indexing new fields).
177 * features The set of features supported by this
178 * database. This consists of a set of
179 * '\n'-separated lines, where each is a feature
180 * name, a '\t', and compatibility flags. If the
181 * compatibility flags contain 'w', then the
182 * opener must support this feature to safely
183 * write this database. If the compatibility
184 * flags contain 'r', then the opener must
185 * support this feature to read this database.
186 * Introduced in database version 3.
188 * last_thread_id The last thread ID generated. This is stored
189 * as a 16-byte hexadecimal ASCII representation
190 * of a 64-bit unsigned integer. The first ID
191 * generated is 1 and the value will be
192 * incremented for each thread ID.
194 * C* metadata keys starting with C indicate
195 * configuration data. It can be managed with the
196 * n_database_*config* API. There is a convention
197 * of hierarchical keys separated by '.' (e.g.
198 * query.notmuch stores the value for the named
199 * query 'notmuch'), but it is not enforced by the
205 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
206 * Instead, the database has the following additional database
209 * thread_id_* A pre-allocated thread ID for a particular
210 * message. This is actually an arbitrarily large
211 * family of metadata name. Any particular name is
212 * formed by concatenating "thread_id_" with a message
213 * ID (or the SHA1 sum of a message ID if it is very
214 * long---see description of 'id' in the mail
215 * document). The value stored is a thread ID.
217 * These thread ID metadata values are stored
218 * whenever a message references a parent message
219 * that does not yet exist in the database. A
220 * thread ID will be allocated and stored, and if
221 * the message is later added, the stored thread
222 * ID will be used (and the metadata value will
225 * Even before a message is added, it's
226 * pre-allocated thread ID is useful so that all
227 * descendant messages that reference this common
228 * parent can be recognized as belonging to the
232 /* With these prefix values we follow the conventions published here:
234 * https://xapian.org/docs/omega/termprefixes.html
236 * as much as makes sense. Note that I took some liberty in matching
237 * the reserved prefix values to notmuch concepts, (for example, 'G'
238 * is documented as "newsGroup (or similar entity - e.g. a web forum
239 * name)", for which I think the thread is the closest analogue in
240 * notmuch. This in spite of the fact that we will eventually be
241 * storing mailing-list messages where 'G' for "mailing list name"
242 * might be even a closer analogue. I'm treating the single-character
243 * prefixes preferentially for core notmuch concepts (which will be
244 * nearly universal to all mail messages).
247 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
249 { "reference", "XREFERENCE" },
250 { "replyto", "XREPLYTO" },
251 { "directory", "XDIRECTORY" },
252 { "file-direntry", "XFDIRENTRY" },
253 { "directory-direntry", "XDDIRENTRY" },
256 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
263 * Without the ":", since this is a multi-letter prefix, Xapian
264 * will add a colon itself if the first letter of the path is
265 * upper-case ASCII. Including the ":" forces there to always be a
266 * colon, which keeps our own logic simpler.
268 { "folder", "XFOLDER:" },
271 static prefix_t PROBABILISTIC_PREFIX[]= {
274 { "attachment", "XATTACHMENT" },
275 { "mimetype", "XMIMETYPE"},
276 { "subject", "XSUBJECT"},
280 _find_prefix (const char *name)
284 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
285 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
286 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
289 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
290 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
291 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
294 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
295 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
296 return PROBABILISTIC_PREFIX[i].prefix;
299 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
304 static const struct {
305 /* NOTMUCH_FEATURE_* value. */
306 _notmuch_features value;
307 /* Feature name as it appears in the database. This name should
308 * be appropriate for displaying to the user if an older version
309 * of notmuch doesn't support this feature. */
311 /* Compatibility flags when this feature is declared. */
313 } feature_names[] = {
314 { NOTMUCH_FEATURE_FILE_TERMS,
315 "multiple paths per message", "rw" },
316 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
317 "relative directory paths", "rw" },
318 /* Header values are not required for reading a database because a
319 * reader can just refer to the message file. */
320 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
321 "from/subject/message-ID in database", "w" },
322 { NOTMUCH_FEATURE_BOOL_FOLDER,
323 "exact folder:/path: search", "rw" },
324 { NOTMUCH_FEATURE_GHOSTS,
325 "mail documents for missing messages", "w"},
326 /* Knowledge of the index mime-types are not required for reading
327 * a database because a reader will just be unable to query
329 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
330 "indexed MIME types", "w"},
331 { NOTMUCH_FEATURE_LAST_MOD,
332 "modification tracking", "w"},
336 notmuch_status_to_string (notmuch_status_t status)
339 case NOTMUCH_STATUS_SUCCESS:
340 return "No error occurred";
341 case NOTMUCH_STATUS_OUT_OF_MEMORY:
342 return "Out of memory";
343 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
344 return "Attempt to write to a read-only database";
345 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
346 return "A Xapian exception occurred";
347 case NOTMUCH_STATUS_FILE_ERROR:
348 return "Something went wrong trying to read or write a file";
349 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
350 return "File is not an email";
351 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
352 return "Message ID is identical to a message in database";
353 case NOTMUCH_STATUS_NULL_POINTER:
354 return "Erroneous NULL pointer";
355 case NOTMUCH_STATUS_TAG_TOO_LONG:
356 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
357 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
358 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
359 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
360 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
361 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
362 return "Unsupported operation";
363 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
364 return "Operation requires a database upgrade";
365 case NOTMUCH_STATUS_PATH_ERROR:
366 return "Path supplied is illegal for this function";
368 case NOTMUCH_STATUS_LAST_STATUS:
369 return "Unknown error status value";
374 _notmuch_database_log (notmuch_database_t *notmuch,
380 va_start (va_args, format);
382 if (notmuch->status_string)
383 talloc_free (notmuch->status_string);
385 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
390 _notmuch_database_log_append (notmuch_database_t *notmuch,
396 va_start (va_args, format);
398 if (notmuch->status_string)
399 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
401 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
407 find_doc_ids_for_term (notmuch_database_t *notmuch,
409 Xapian::PostingIterator *begin,
410 Xapian::PostingIterator *end)
412 *begin = notmuch->xapian_db->postlist_begin (term);
414 *end = notmuch->xapian_db->postlist_end (term);
418 find_doc_ids (notmuch_database_t *notmuch,
419 const char *prefix_name,
421 Xapian::PostingIterator *begin,
422 Xapian::PostingIterator *end)
426 term = talloc_asprintf (notmuch, "%s%s",
427 _find_prefix (prefix_name), value);
429 find_doc_ids_for_term (notmuch, term, begin, end);
434 notmuch_private_status_t
435 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
436 const char *prefix_name,
438 unsigned int *doc_id)
440 Xapian::PostingIterator i, end;
442 find_doc_ids (notmuch, prefix_name, value, &i, &end);
446 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
451 #if DEBUG_DATABASE_SANITY
455 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
459 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
462 static Xapian::Document
463 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
465 return notmuch->xapian_db->get_document (doc_id);
468 /* Generate a compressed version of 'message_id' of the form:
470 * notmuch-sha1-<sha1_sum_of_message_id>
473 _notmuch_message_id_compressed (void *ctx, const char *message_id)
475 char *sha1, *compressed;
477 sha1 = _notmuch_sha1_of_string (message_id);
479 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
486 notmuch_database_find_message (notmuch_database_t *notmuch,
487 const char *message_id,
488 notmuch_message_t **message_ret)
490 notmuch_private_status_t status;
493 if (message_ret == NULL)
494 return NOTMUCH_STATUS_NULL_POINTER;
496 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
497 message_id = _notmuch_message_id_compressed (notmuch, message_id);
500 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
501 message_id, &doc_id);
503 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
506 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
508 if (*message_ret == NULL)
509 return NOTMUCH_STATUS_OUT_OF_MEMORY;
512 return NOTMUCH_STATUS_SUCCESS;
513 } catch (const Xapian::Error &error) {
514 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
515 error.get_msg().c_str());
516 notmuch->exception_reported = TRUE;
518 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
522 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
523 * a (potentially nested) parenthesized sequence with '\' used to
524 * escape any character (including parentheses).
526 * If the sequence to be skipped continues to the end of the string,
527 * then 'str' will be left pointing at the final terminating '\0'
531 skip_space_and_comments (const char **str)
536 while (*s && (isspace (*s) || *s == '(')) {
537 while (*s && isspace (*s))
542 while (*s && nesting) {
545 } else if (*s == ')') {
547 } else if (*s == '\\') {
559 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
560 * comments, and the '<' and '>' delimiters.
562 * If not NULL, then *next will be made to point to the first character
563 * not parsed, (possibly pointing to the final '\0' terminator.
565 * Returns a newly talloc'ed string belonging to 'ctx'.
567 * Returns NULL if there is any error parsing the message-id. */
569 _parse_message_id (void *ctx, const char *message_id, const char **next)
574 if (message_id == NULL || *message_id == '\0')
579 skip_space_and_comments (&s);
581 /* Skip any unstructured text as well. */
582 while (*s && *s != '<')
593 skip_space_and_comments (&s);
596 while (*end && *end != '>')
605 if (end > s && *end == '>')
610 result = talloc_strndup (ctx, s, end - s + 1);
612 /* Finally, collapse any whitespace that is within the message-id
618 for (r = result, len = strlen (r); *r; r++, len--)
619 if (*r == ' ' || *r == '\t')
620 memmove (r, r+1, len);
626 /* Parse a References header value, putting a (talloc'ed under 'ctx')
627 * copy of each referenced message-id into 'hash'.
629 * We explicitly avoid including any reference identical to
630 * 'message_id' in the result (to avoid mass confusion when a single
631 * message references itself cyclically---and yes, mail messages are
632 * not infrequent in the wild that do this---don't ask me why).
634 * Return the last reference parsed, if it is not equal to message_id.
637 parse_references (void *ctx,
638 const char *message_id,
642 char *ref, *last_ref = NULL;
644 if (refs == NULL || *refs == '\0')
648 ref = _parse_message_id (ctx, refs, &refs);
650 if (ref && strcmp (ref, message_id)) {
651 g_hash_table_insert (hash, ref, NULL);
656 /* The return value of this function is used to add a parent
657 * reference to the database. We should avoid making a message
658 * its own parent, thus the above check.
664 notmuch_database_create (const char *path, notmuch_database_t **database)
666 char *status_string = NULL;
667 notmuch_status_t status;
669 status = notmuch_database_create_verbose (path, database,
673 fputs (status_string, stderr);
674 free (status_string);
681 notmuch_database_create_verbose (const char *path,
682 notmuch_database_t **database,
683 char **status_string)
685 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
686 notmuch_database_t *notmuch = NULL;
687 char *notmuch_path = NULL;
688 char *message = NULL;
693 message = strdup ("Error: Cannot create a database for a NULL path.\n");
694 status = NOTMUCH_STATUS_NULL_POINTER;
698 if (path[0] != '/') {
699 message = strdup ("Error: Database path must be absolute.\n");
700 status = NOTMUCH_STATUS_PATH_ERROR;
704 err = stat (path, &st);
706 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
707 path, strerror (errno)));
708 status = NOTMUCH_STATUS_FILE_ERROR;
712 if (! S_ISDIR (st.st_mode)) {
713 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
714 "Not a directory.\n",
716 status = NOTMUCH_STATUS_FILE_ERROR;
720 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
722 err = mkdir (notmuch_path, 0755);
725 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
726 notmuch_path, strerror (errno)));
727 status = NOTMUCH_STATUS_FILE_ERROR;
731 status = notmuch_database_open_verbose (path,
732 NOTMUCH_DATABASE_MODE_READ_WRITE,
737 /* Upgrade doesn't add these feature to existing databases, but
738 * new databases have them. */
739 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
740 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
742 status = notmuch_database_upgrade (notmuch, NULL, NULL);
744 notmuch_database_close(notmuch);
750 talloc_free (notmuch_path);
754 *status_string = message;
761 talloc_free (notmuch);
766 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
768 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
769 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
770 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
773 return NOTMUCH_STATUS_SUCCESS;
776 /* Allocate a revision number for the next change. */
778 _notmuch_database_new_revision (notmuch_database_t *notmuch)
780 unsigned long new_revision = notmuch->revision + 1;
782 /* If we're in an atomic section, hold off on updating the
783 * committed revision number until we commit the atomic section.
785 if (notmuch->atomic_nesting)
786 notmuch->atomic_dirty = TRUE;
788 notmuch->revision = new_revision;
793 /* Parse a database features string from the given database version.
794 * Returns the feature bit set.
796 * For version < 3, this ignores the features string and returns a
797 * hard-coded set of features.
799 * If there are unrecognized features that are required to open the
800 * database in mode (which should be 'r' or 'w'), return a
801 * comma-separated list of unrecognized but required features in
802 * *incompat_out suitable for presenting to the user. *incompat_out
803 * will be allocated from ctx.
805 static _notmuch_features
806 _parse_features (const void *ctx, const char *features, unsigned int version,
807 char mode, char **incompat_out)
809 _notmuch_features res = static_cast<_notmuch_features>(0);
810 unsigned int namelen, i;
814 /* Prior to database version 3, features were implied by the
817 return NOTMUCH_FEATURES_V0;
818 else if (version == 1)
819 return NOTMUCH_FEATURES_V1;
820 else if (version == 2)
821 return NOTMUCH_FEATURES_V2;
823 /* Parse the features string */
824 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
825 flags = strchr (features, '\t');
826 if (! flags || flags > features + llen)
828 namelen = flags - features;
830 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
831 if (strlen (feature_names[i].name) == namelen &&
832 strncmp (feature_names[i].name, features, namelen) == 0) {
833 res |= feature_names[i].value;
838 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
839 /* Unrecognized feature */
840 const char *have = strchr (flags, mode);
841 if (have && have < features + llen) {
842 /* This feature is required to access this database in
843 * 'mode', but we don't understand it. */
845 *incompat_out = talloc_strdup (ctx, "");
846 *incompat_out = talloc_asprintf_append_buffer (
847 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
857 _print_features (const void *ctx, unsigned int features)
860 char *res = talloc_strdup (ctx, "");
862 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
863 if (features & feature_names[i].value)
864 res = talloc_asprintf_append_buffer (
865 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
871 notmuch_database_open (const char *path,
872 notmuch_database_mode_t mode,
873 notmuch_database_t **database)
875 char *status_string = NULL;
876 notmuch_status_t status;
878 status = notmuch_database_open_verbose (path, mode, database,
882 fputs (status_string, stderr);
883 free (status_string);
890 notmuch_database_open_verbose (const char *path,
891 notmuch_database_mode_t mode,
892 notmuch_database_t **database,
893 char **status_string)
895 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
896 void *local = talloc_new (NULL);
897 notmuch_database_t *notmuch = NULL;
898 char *notmuch_path, *xapian_path, *incompat_features;
899 char *message = NULL;
902 unsigned int i, version;
903 static int initialized = 0;
906 message = strdup ("Error: Cannot open a database for a NULL path.\n");
907 status = NOTMUCH_STATUS_NULL_POINTER;
911 if (path[0] != '/') {
912 message = strdup ("Error: Database path must be absolute.\n");
913 status = NOTMUCH_STATUS_PATH_ERROR;
917 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
918 message = strdup ("Out of memory\n");
919 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
923 err = stat (notmuch_path, &st);
925 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
926 notmuch_path, strerror (errno)));
927 status = NOTMUCH_STATUS_FILE_ERROR;
931 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
932 message = strdup ("Out of memory\n");
933 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
937 /* Initialize the GLib type system and threads */
938 #if !GLIB_CHECK_VERSION(2, 35, 1)
942 /* Initialize gmime */
944 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
948 notmuch = talloc_zero (NULL, notmuch_database_t);
949 notmuch->exception_reported = FALSE;
950 notmuch->status_string = NULL;
951 notmuch->path = talloc_strdup (notmuch, path);
953 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
954 notmuch->path[strlen (notmuch->path) - 1] = '\0';
956 notmuch->mode = mode;
957 notmuch->atomic_nesting = 0;
959 string last_thread_id;
962 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
963 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
966 notmuch->xapian_db = new Xapian::Database (xapian_path);
969 /* Check version. As of database version 3, we represent
970 * changes in terms of features, so assume a version bump
971 * means a dramatically incompatible change. */
972 version = notmuch_database_get_version (notmuch);
973 if (version > NOTMUCH_DATABASE_VERSION) {
974 IGNORE_RESULT (asprintf (&message,
975 "Error: Notmuch database at %s\n"
976 " has a newer database format version (%u) than supported by this\n"
977 " version of notmuch (%u).\n",
978 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
979 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
980 notmuch_database_destroy (notmuch);
982 status = NOTMUCH_STATUS_FILE_ERROR;
986 /* Check features. */
987 incompat_features = NULL;
988 notmuch->features = _parse_features (
989 local, notmuch->xapian_db->get_metadata ("features").c_str (),
990 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
992 if (incompat_features) {
993 IGNORE_RESULT (asprintf (&message,
994 "Error: Notmuch database at %s\n"
995 " requires features (%s)\n"
996 " not supported by this version of notmuch.\n",
997 notmuch_path, incompat_features));
998 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
999 notmuch_database_destroy (notmuch);
1001 status = NOTMUCH_STATUS_FILE_ERROR;
1005 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1006 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1007 if (last_thread_id.empty ()) {
1008 notmuch->last_thread_id = 0;
1013 str = last_thread_id.c_str ();
1014 notmuch->last_thread_id = strtoull (str, &end, 16);
1016 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1019 /* Get current highest revision number. */
1020 last_mod = notmuch->xapian_db->get_value_upper_bound (
1021 NOTMUCH_VALUE_LAST_MOD);
1022 if (last_mod.empty ())
1023 notmuch->revision = 0;
1025 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1026 notmuch->uuid = talloc_strdup (
1027 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1029 notmuch->query_parser = new Xapian::QueryParser;
1030 notmuch->term_gen = new Xapian::TermGenerator;
1031 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1032 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1033 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1034 #if HAVE_XAPIAN_FIELD_PROCESSOR
1035 /* This currently relies on the query parser to pass anything
1036 * with a .. to the range processor */
1037 notmuch->date_field_processor = new DateFieldProcessor();
1038 notmuch->query_parser->add_boolean_prefix("date", notmuch->date_field_processor);
1039 notmuch->query_field_processor = new QueryFieldProcessor (*notmuch->query_parser, notmuch);
1040 notmuch->query_parser->add_boolean_prefix("query", notmuch->query_field_processor);
1042 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1044 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1045 notmuch->query_parser->set_database (*notmuch->xapian_db);
1046 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1047 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1048 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1049 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1050 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1052 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
1053 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
1054 notmuch->query_parser->add_boolean_prefix (prefix->name,
1058 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
1059 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
1060 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
1062 } catch (const Xapian::Error &error) {
1063 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1064 error.get_msg().c_str()));
1065 notmuch_database_destroy (notmuch);
1067 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1071 talloc_free (local);
1075 *status_string = message;
1081 *database = notmuch;
1083 talloc_free (notmuch);
1088 notmuch_database_close (notmuch_database_t *notmuch)
1090 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1092 /* Many Xapian objects (and thus notmuch objects) hold references to
1093 * the database, so merely deleting the database may not suffice to
1094 * close it. Thus, we explicitly close it here. */
1095 if (notmuch->xapian_db != NULL) {
1097 /* If there's an outstanding transaction, it's unclear if
1098 * closing the Xapian database commits everything up to
1099 * that transaction, or may discard committed (but
1100 * unflushed) transactions. To be certain, explicitly
1101 * cancel any outstanding transaction before closing. */
1102 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1103 notmuch->atomic_nesting)
1104 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1105 ->cancel_transaction ();
1107 /* Close the database. This implicitly flushes
1108 * outstanding changes. */
1109 notmuch->xapian_db->close();
1110 } catch (const Xapian::Error &error) {
1111 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1112 if (! notmuch->exception_reported) {
1113 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1114 error.get_msg().c_str());
1119 delete notmuch->term_gen;
1120 notmuch->term_gen = NULL;
1121 delete notmuch->query_parser;
1122 notmuch->query_parser = NULL;
1123 delete notmuch->xapian_db;
1124 notmuch->xapian_db = NULL;
1125 delete notmuch->value_range_processor;
1126 notmuch->value_range_processor = NULL;
1127 delete notmuch->date_range_processor;
1128 notmuch->date_range_processor = NULL;
1129 delete notmuch->last_mod_range_processor;
1130 notmuch->last_mod_range_processor = NULL;
1132 #if HAVE_XAPIAN_FIELD_PROCESSOR
1133 delete notmuch->date_field_processor;
1134 notmuch->date_field_processor = NULL;
1135 delete notmuch->query_field_processor;
1136 notmuch->query_field_processor = NULL;
1142 #if HAVE_XAPIAN_COMPACT
1144 unlink_cb (const char *path,
1145 unused (const struct stat *sb),
1147 unused (struct FTW *ftw))
1149 return remove (path);
1153 rmtree (const char *path)
1155 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1158 class NotmuchCompactor : public Xapian::Compactor
1160 notmuch_compact_status_cb_t status_cb;
1161 void *status_closure;
1164 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1165 status_cb (cb), status_closure (closure) { }
1168 set_status (const std::string &table, const std::string &status)
1172 if (status_cb == NULL)
1175 if (status.length () == 0)
1176 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1178 msg = talloc_asprintf (NULL, " %s", status.c_str());
1184 status_cb (msg, status_closure);
1189 /* Compacts the given database, optionally saving the original database
1190 * in backup_path. Additionally, a callback function can be provided to
1191 * give the user feedback on the progress of the (likely long-lived)
1192 * compaction process.
1194 * The backup path must point to a directory on the same volume as the
1195 * original database. Passing a NULL backup_path will result in the
1196 * uncompacted database being deleted after compaction has finished.
1197 * Note that the database write lock will be held during the
1198 * compaction process to protect data integrity.
1201 notmuch_database_compact (const char *path,
1202 const char *backup_path,
1203 notmuch_compact_status_cb_t status_cb,
1207 char *notmuch_path, *xapian_path, *compact_xapian_path;
1208 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1209 notmuch_database_t *notmuch = NULL;
1210 struct stat statbuf;
1211 notmuch_bool_t keep_backup;
1212 char *message = NULL;
1214 local = talloc_new (NULL);
1216 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1218 ret = notmuch_database_open_verbose (path,
1219 NOTMUCH_DATABASE_MODE_READ_WRITE,
1223 if (status_cb) status_cb (message, closure);
1227 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1228 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1232 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1233 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1237 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1238 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1242 if (backup_path == NULL) {
1243 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1244 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1247 keep_backup = FALSE;
1253 if (stat (backup_path, &statbuf) != -1) {
1254 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1255 ret = NOTMUCH_STATUS_FILE_ERROR;
1258 if (errno != ENOENT) {
1259 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1261 ret = NOTMUCH_STATUS_FILE_ERROR;
1265 /* Unconditionally attempt to remove old work-in-progress database (if
1266 * any). This is "protected" by database lock. If this fails due to write
1267 * errors (etc), the following code will fail and provide error message.
1269 (void) rmtree (compact_xapian_path);
1272 NotmuchCompactor compactor (status_cb, closure);
1274 compactor.set_renumber (false);
1275 compactor.add_source (xapian_path);
1276 compactor.set_destdir (compact_xapian_path);
1277 compactor.compact ();
1278 } catch (const Xapian::Error &error) {
1279 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1280 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1284 if (rename (xapian_path, backup_path)) {
1285 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1286 xapian_path, backup_path, strerror (errno));
1287 ret = NOTMUCH_STATUS_FILE_ERROR;
1291 if (rename (compact_xapian_path, xapian_path)) {
1292 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1293 compact_xapian_path, xapian_path, strerror (errno));
1294 ret = NOTMUCH_STATUS_FILE_ERROR;
1298 if (! keep_backup) {
1299 if (rmtree (backup_path)) {
1300 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1301 backup_path, strerror (errno));
1302 ret = NOTMUCH_STATUS_FILE_ERROR;
1309 notmuch_status_t ret2;
1311 const char *str = notmuch_database_status_string (notmuch);
1312 if (status_cb && str)
1313 status_cb (str, closure);
1315 ret2 = notmuch_database_destroy (notmuch);
1317 /* don't clobber previous error status */
1318 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1322 talloc_free (local);
1328 notmuch_database_compact (unused (const char *path),
1329 unused (const char *backup_path),
1330 unused (notmuch_compact_status_cb_t status_cb),
1331 unused (void *closure))
1333 _notmuch_database_log (notmuch, "notmuch was compiled against a xapian version lacking compaction support.\n");
1334 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1339 notmuch_database_destroy (notmuch_database_t *notmuch)
1341 notmuch_status_t status;
1343 status = notmuch_database_close (notmuch);
1344 talloc_free (notmuch);
1350 notmuch_database_get_path (notmuch_database_t *notmuch)
1352 return notmuch->path;
1356 notmuch_database_get_version (notmuch_database_t *notmuch)
1358 unsigned int version;
1359 string version_string;
1363 version_string = notmuch->xapian_db->get_metadata ("version");
1364 if (version_string.empty ())
1367 str = version_string.c_str ();
1368 if (str == NULL || *str == '\0')
1371 version = strtoul (str, &end, 10);
1373 INTERNAL_ERROR ("Malformed database version: %s", str);
1379 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1381 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1382 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1383 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1386 static volatile sig_atomic_t do_progress_notify = 0;
1389 handle_sigalrm (unused (int signal))
1391 do_progress_notify = 1;
1394 /* Upgrade the current database.
1396 * After opening a database in read-write mode, the client should
1397 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1398 * if so, upgrade with this function before making any modifications.
1400 * The optional progress_notify callback can be used by the caller to
1401 * provide progress indication to the user. If non-NULL it will be
1402 * called periodically with 'count' as the number of messages upgraded
1403 * so far and 'total' the overall number of messages that will be
1407 notmuch_database_upgrade (notmuch_database_t *notmuch,
1408 void (*progress_notify) (void *closure,
1412 void *local = talloc_new (NULL);
1413 Xapian::TermIterator t, t_end;
1414 Xapian::WritableDatabase *db;
1415 struct sigaction action;
1416 struct itimerval timerval;
1417 notmuch_bool_t timer_is_active = FALSE;
1418 enum _notmuch_features target_features, new_features;
1419 notmuch_status_t status;
1420 notmuch_private_status_t private_status;
1421 notmuch_query_t *query = NULL;
1422 unsigned int count = 0, total = 0;
1424 status = _notmuch_database_ensure_writable (notmuch);
1428 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1430 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1431 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1433 if (! notmuch_database_needs_upgrade (notmuch))
1434 return NOTMUCH_STATUS_SUCCESS;
1436 if (progress_notify) {
1437 /* Set up our handler for SIGALRM */
1438 memset (&action, 0, sizeof (struct sigaction));
1439 action.sa_handler = handle_sigalrm;
1440 sigemptyset (&action.sa_mask);
1441 action.sa_flags = SA_RESTART;
1442 sigaction (SIGALRM, &action, NULL);
1444 /* Then start a timer to send SIGALRM once per second. */
1445 timerval.it_interval.tv_sec = 1;
1446 timerval.it_interval.tv_usec = 0;
1447 timerval.it_value.tv_sec = 1;
1448 timerval.it_value.tv_usec = 0;
1449 setitimer (ITIMER_REAL, &timerval, NULL);
1451 timer_is_active = TRUE;
1454 /* Figure out how much total work we need to do. */
1456 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1457 NOTMUCH_FEATURE_LAST_MOD)) {
1458 query = notmuch_query_create (notmuch, "");
1461 status = notmuch_query_count_messages_st (query, &msg_count);
1466 notmuch_query_destroy (query);
1469 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1470 t_end = db->allterms_end ("XTIMESTAMP");
1471 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1474 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1475 /* The ghost message upgrade converts all thread_id_*
1476 * metadata values into ghost message documents. */
1477 t_end = db->metadata_keys_end ("thread_id_");
1478 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1482 /* Perform the upgrade in a transaction. */
1483 db->begin_transaction (true);
1485 /* Set the target features so we write out changes in the desired
1487 notmuch->features = target_features;
1489 /* Perform per-message upgrades. */
1491 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1492 NOTMUCH_FEATURE_LAST_MOD)) {
1493 notmuch_messages_t *messages;
1494 notmuch_message_t *message;
1497 query = notmuch_query_create (notmuch, "");
1499 status = notmuch_query_search_messages_st (query, &messages);
1503 notmuch_messages_valid (messages);
1504 notmuch_messages_move_to_next (messages))
1506 if (do_progress_notify) {
1507 progress_notify (closure, (double) count / total);
1508 do_progress_notify = 0;
1511 message = notmuch_messages_get (messages);
1513 /* Before version 1, each message document had its
1514 * filename in the data field. Copy that into the new
1515 * format by calling notmuch_message_add_filename.
1517 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1518 filename = _notmuch_message_talloc_copy_data (message);
1519 if (filename && *filename != '\0') {
1520 _notmuch_message_add_filename (message, filename);
1521 _notmuch_message_clear_data (message);
1523 talloc_free (filename);
1526 /* Prior to version 2, the "folder:" prefix was
1527 * probabilistic and stemmed. Change it to the current
1528 * boolean prefix. Add "path:" prefixes while at it.
1530 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1531 _notmuch_message_upgrade_folder (message);
1533 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1534 * track modification revisions. Give all messages the
1535 * next available revision; since we just started tracking
1536 * revisions for this database, that will be 1.
1538 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1539 _notmuch_message_upgrade_last_mod (message);
1541 _notmuch_message_sync (message);
1543 notmuch_message_destroy (message);
1548 notmuch_query_destroy (query);
1552 /* Perform per-directory upgrades. */
1554 /* Before version 1 we stored directory timestamps in
1555 * XTIMESTAMP documents instead of the current XDIRECTORY
1556 * documents. So copy those as well. */
1557 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1558 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1560 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1564 Xapian::PostingIterator p, p_end;
1565 std::string term = *t;
1567 p_end = notmuch->xapian_db->postlist_end (term);
1569 for (p = notmuch->xapian_db->postlist_begin (term);
1573 Xapian::Document document;
1575 notmuch_directory_t *directory;
1577 if (do_progress_notify) {
1578 progress_notify (closure, (double) count / total);
1579 do_progress_notify = 0;
1582 document = find_document_for_doc_id (notmuch, *p);
1583 mtime = Xapian::sortable_unserialise (
1584 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1586 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1587 NOTMUCH_FIND_CREATE, &status);
1588 notmuch_directory_set_mtime (directory, mtime);
1589 notmuch_directory_destroy (directory);
1591 db->delete_document (*p);
1598 /* Perform metadata upgrades. */
1600 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1601 * messages were stored as database metadata. Change these to
1604 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1605 notmuch_message_t *message;
1606 std::string message_id, thread_id;
1608 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1609 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1611 if (do_progress_notify) {
1612 progress_notify (closure, (double) count / total);
1613 do_progress_notify = 0;
1616 message_id = (*t).substr (
1617 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1618 thread_id = db->get_metadata (*t);
1620 /* Create ghost message */
1621 message = _notmuch_message_create_for_message_id (
1622 notmuch, message_id.c_str (), &private_status);
1623 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1624 /* Document already exists; ignore the stored thread ID */
1625 } else if (private_status ==
1626 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1627 private_status = _notmuch_message_initialize_ghost (
1628 message, thread_id.c_str ());
1629 if (! private_status)
1630 _notmuch_message_sync (message);
1633 if (private_status) {
1634 _notmuch_database_log (notmuch,
1635 "Upgrade failed while creating ghost messages.\n");
1636 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1640 /* Clear saved metadata thread ID */
1641 db->set_metadata (*t, "");
1647 status = NOTMUCH_STATUS_SUCCESS;
1648 db->set_metadata ("features", _print_features (local, notmuch->features));
1649 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1652 if (status == NOTMUCH_STATUS_SUCCESS)
1653 db->commit_transaction ();
1655 db->cancel_transaction ();
1657 if (timer_is_active) {
1658 /* Now stop the timer. */
1659 timerval.it_interval.tv_sec = 0;
1660 timerval.it_interval.tv_usec = 0;
1661 timerval.it_value.tv_sec = 0;
1662 timerval.it_value.tv_usec = 0;
1663 setitimer (ITIMER_REAL, &timerval, NULL);
1665 /* And disable the signal handler. */
1666 action.sa_handler = SIG_IGN;
1667 sigaction (SIGALRM, &action, NULL);
1671 notmuch_query_destroy (query);
1673 talloc_free (local);
1678 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1680 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1681 notmuch->atomic_nesting > 0)
1684 if (notmuch_database_needs_upgrade(notmuch))
1685 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1688 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1689 } catch (const Xapian::Error &error) {
1690 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1691 error.get_msg().c_str());
1692 notmuch->exception_reported = TRUE;
1693 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1697 notmuch->atomic_nesting++;
1698 return NOTMUCH_STATUS_SUCCESS;
1702 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1704 Xapian::WritableDatabase *db;
1706 if (notmuch->atomic_nesting == 0)
1707 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1709 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1710 notmuch->atomic_nesting > 1)
1713 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1715 db->commit_transaction ();
1717 /* This is a hack for testing. Xapian never flushes on a
1718 * non-flushed commit, even if the flush threshold is 1.
1719 * However, we rely on flushing to test atomicity. */
1720 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1721 if (thresh && atoi (thresh) == 1)
1723 } catch (const Xapian::Error &error) {
1724 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1725 error.get_msg().c_str());
1726 notmuch->exception_reported = TRUE;
1727 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1730 if (notmuch->atomic_dirty) {
1731 ++notmuch->revision;
1732 notmuch->atomic_dirty = FALSE;
1736 notmuch->atomic_nesting--;
1737 return NOTMUCH_STATUS_SUCCESS;
1741 notmuch_database_get_revision (notmuch_database_t *notmuch,
1745 *uuid = notmuch->uuid;
1746 return notmuch->revision;
1749 /* We allow the user to use arbitrarily long paths for directories. But
1750 * we have a term-length limit. So if we exceed that, we'll use the
1751 * SHA-1 of the path for the database term.
1753 * Note: This function may return the original value of 'path'. If it
1754 * does not, then the caller is responsible to free() the returned
1758 _notmuch_database_get_directory_db_path (const char *path)
1760 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1762 if (term_len > NOTMUCH_TERM_MAX)
1763 return _notmuch_sha1_of_string (path);
1768 /* Given a path, split it into two parts: the directory part is all
1769 * components except for the last, and the basename is that last
1770 * component. Getting the return-value for either part is optional
1771 * (the caller can pass NULL).
1773 * The original 'path' can represent either a regular file or a
1774 * directory---the splitting will be carried out in the same way in
1775 * either case. Trailing slashes on 'path' will be ignored, and any
1776 * cases of multiple '/' characters appearing in series will be
1777 * treated as a single '/'.
1779 * Allocation (if any) will have 'ctx' as the talloc owner. But
1780 * pointers will be returned within the original path string whenever
1783 * Note: If 'path' is non-empty and contains no non-trailing slash,
1784 * (that is, consists of a filename with no parent directory), then
1785 * the directory returned will be an empty string. However, if 'path'
1786 * is an empty string, then both directory and basename will be
1790 _notmuch_database_split_path (void *ctx,
1792 const char **directory,
1793 const char **basename)
1797 if (path == NULL || *path == '\0') {
1802 return NOTMUCH_STATUS_SUCCESS;
1805 /* Find the last slash (not counting a trailing slash), if any. */
1807 slash = path + strlen (path) - 1;
1809 /* First, skip trailing slashes. */
1810 while (slash != path && *slash == '/')
1813 /* Then, find a slash. */
1814 while (slash != path && *slash != '/') {
1821 /* Finally, skip multiple slashes. */
1822 while (slash != path && *(slash - 1) == '/')
1825 if (slash == path) {
1827 *directory = talloc_strdup (ctx, "");
1832 *directory = talloc_strndup (ctx, path, slash - path);
1835 return NOTMUCH_STATUS_SUCCESS;
1838 /* Find the document ID of the specified directory.
1840 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1841 * created if one does not exist for 'path'. Otherwise, if the
1842 * directory document does not exist, this sets *directory_id to
1843 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1846 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1848 notmuch_find_flags_t flags,
1849 unsigned int *directory_id)
1851 notmuch_directory_t *directory;
1852 notmuch_status_t status;
1856 return NOTMUCH_STATUS_SUCCESS;
1859 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1860 if (status || !directory) {
1865 *directory_id = _notmuch_directory_get_document_id (directory);
1867 notmuch_directory_destroy (directory);
1869 return NOTMUCH_STATUS_SUCCESS;
1873 _notmuch_database_get_directory_path (void *ctx,
1874 notmuch_database_t *notmuch,
1875 unsigned int doc_id)
1877 Xapian::Document document;
1879 document = find_document_for_doc_id (notmuch, doc_id);
1881 return talloc_strdup (ctx, document.get_data ().c_str ());
1884 /* Given a legal 'filename' for the database, (either relative to
1885 * database path or absolute with initial components identical to
1886 * database path), return a new string (with 'ctx' as the talloc
1887 * owner) suitable for use as a direntry term value.
1889 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1890 * will be created in the database as needed. Otherwise, if the
1891 * necessary directory documents do not exist, this sets
1892 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1895 _notmuch_database_filename_to_direntry (void *ctx,
1896 notmuch_database_t *notmuch,
1897 const char *filename,
1898 notmuch_find_flags_t flags,
1901 const char *relative, *directory, *basename;
1902 Xapian::docid directory_id;
1903 notmuch_status_t status;
1905 relative = _notmuch_database_relative_path (notmuch, filename);
1907 status = _notmuch_database_split_path (ctx, relative,
1908 &directory, &basename);
1912 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1914 if (status || directory_id == (unsigned int)-1) {
1919 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1921 return NOTMUCH_STATUS_SUCCESS;
1924 /* Given a legal 'path' for the database, return the relative path.
1926 * The return value will be a pointer to the original path contents,
1927 * and will be either the original string (if 'path' was relative) or
1928 * a portion of the string (if path was absolute and begins with the
1932 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1935 const char *db_path, *relative;
1936 unsigned int db_path_len;
1938 db_path = notmuch_database_get_path (notmuch);
1939 db_path_len = strlen (db_path);
1943 if (*relative == '/') {
1944 while (*relative == '/' && *(relative+1) == '/')
1947 if (strncmp (relative, db_path, db_path_len) == 0)
1949 relative += db_path_len;
1950 while (*relative == '/')
1959 notmuch_database_get_directory (notmuch_database_t *notmuch,
1961 notmuch_directory_t **directory)
1963 notmuch_status_t status;
1965 if (directory == NULL)
1966 return NOTMUCH_STATUS_NULL_POINTER;
1970 *directory = _notmuch_directory_create (notmuch, path,
1971 NOTMUCH_FIND_LOOKUP, &status);
1972 } catch (const Xapian::Error &error) {
1973 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1974 error.get_msg().c_str());
1975 notmuch->exception_reported = TRUE;
1976 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1981 /* Allocate a document ID that satisfies the following criteria:
1983 * 1. The ID does not exist for any document in the Xapian database
1985 * 2. The ID was not previously returned from this function
1987 * 3. The ID is the smallest integer satisfying (1) and (2)
1989 * This function will trigger an internal error if these constraints
1990 * cannot all be satisfied, (that is, the pool of available document
1991 * IDs has been exhausted).
1994 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1996 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1998 notmuch->last_doc_id++;
2000 if (notmuch->last_doc_id == 0)
2001 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2003 return notmuch->last_doc_id;
2007 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
2009 /* 16 bytes (+ terminator) for hexadecimal representation of
2010 * a 64-bit integer. */
2011 static char thread_id[17];
2012 Xapian::WritableDatabase *db;
2014 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2016 notmuch->last_thread_id++;
2018 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2020 db->set_metadata ("last_thread_id", thread_id);
2026 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2028 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2029 message_id = _notmuch_message_id_compressed (ctx, message_id);
2031 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2035 static notmuch_status_t
2036 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2038 const char *message_id,
2039 const char **thread_id_ret);
2041 /* Find the thread ID to which the message with 'message_id' belongs.
2043 * Note: 'thread_id_ret' must not be NULL!
2044 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2047 * Note: If there is no message in the database with the given
2048 * 'message_id' then a new thread_id will be allocated for this
2049 * message ID and stored in the database metadata so that the
2050 * thread ID can be looked up if the message is added to the database
2053 static notmuch_status_t
2054 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2056 const char *message_id,
2057 const char **thread_id_ret)
2059 notmuch_private_status_t status;
2060 notmuch_message_t *message;
2062 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2063 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2066 /* Look for this message (regular or ghost) */
2067 message = _notmuch_message_create_for_message_id (
2068 notmuch, message_id, &status);
2069 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2070 /* Message exists */
2071 *thread_id_ret = talloc_steal (
2072 ctx, notmuch_message_get_thread_id (message));
2073 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2074 /* Message did not exist. Give it a fresh thread ID and
2075 * populate this message as a ghost message. */
2076 *thread_id_ret = talloc_strdup (
2077 ctx, _notmuch_database_generate_thread_id (notmuch));
2078 if (! *thread_id_ret) {
2079 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2081 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2083 /* Commit the new ghost message */
2084 _notmuch_message_sync (message);
2087 /* Create failed. Fall through. */
2090 notmuch_message_destroy (message);
2092 return COERCE_STATUS (status, "Error creating ghost message");
2095 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2096 static notmuch_status_t
2097 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2099 const char *message_id,
2100 const char **thread_id_ret)
2102 notmuch_status_t status;
2103 notmuch_message_t *message;
2104 string thread_id_string;
2106 Xapian::WritableDatabase *db;
2108 status = notmuch_database_find_message (notmuch, message_id, &message);
2114 *thread_id_ret = talloc_steal (ctx,
2115 notmuch_message_get_thread_id (message));
2117 notmuch_message_destroy (message);
2119 return NOTMUCH_STATUS_SUCCESS;
2122 /* Message has not been seen yet.
2124 * We may have seen a reference to it already, in which case, we
2125 * can return the thread ID stored in the metadata. Otherwise, we
2126 * generate a new thread ID and store it there.
2128 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2129 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2130 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2132 if (thread_id_string.empty()) {
2133 *thread_id_ret = talloc_strdup (ctx,
2134 _notmuch_database_generate_thread_id (notmuch));
2135 db->set_metadata (metadata_key, *thread_id_ret);
2137 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2140 talloc_free (metadata_key);
2142 return NOTMUCH_STATUS_SUCCESS;
2145 static notmuch_status_t
2146 _merge_threads (notmuch_database_t *notmuch,
2147 const char *winner_thread_id,
2148 const char *loser_thread_id)
2150 Xapian::PostingIterator loser, loser_end;
2151 notmuch_message_t *message = NULL;
2152 notmuch_private_status_t private_status;
2153 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2155 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2157 for ( ; loser != loser_end; loser++) {
2158 message = _notmuch_message_create (notmuch, notmuch,
2159 *loser, &private_status);
2160 if (message == NULL) {
2161 ret = COERCE_STATUS (private_status,
2162 "Cannot find document for doc_id from query");
2166 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2167 _notmuch_message_add_term (message, "thread", winner_thread_id);
2168 _notmuch_message_sync (message);
2170 notmuch_message_destroy (message);
2176 notmuch_message_destroy (message);
2182 _my_talloc_free_for_g_hash (void *ptr)
2187 static notmuch_status_t
2188 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2189 notmuch_message_t *message,
2190 notmuch_message_file_t *message_file,
2191 const char **thread_id)
2193 GHashTable *parents = NULL;
2194 const char *refs, *in_reply_to, *in_reply_to_message_id;
2195 const char *last_ref_message_id, *this_message_id;
2196 GList *l, *keys = NULL;
2197 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2199 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2200 _my_talloc_free_for_g_hash, NULL);
2201 this_message_id = notmuch_message_get_message_id (message);
2203 refs = _notmuch_message_file_get_header (message_file, "references");
2204 last_ref_message_id = parse_references (message,
2208 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2209 in_reply_to_message_id = parse_references (message,
2211 parents, in_reply_to);
2213 /* For the parent of this message, use the last message ID of the
2214 * References header, if available. If not, fall back to the
2215 * first message ID in the In-Reply-To header. */
2216 if (last_ref_message_id) {
2217 _notmuch_message_add_term (message, "replyto",
2218 last_ref_message_id);
2219 } else if (in_reply_to_message_id) {
2220 _notmuch_message_add_term (message, "replyto",
2221 in_reply_to_message_id);
2224 keys = g_hash_table_get_keys (parents);
2225 for (l = keys; l; l = l->next) {
2226 char *parent_message_id;
2227 const char *parent_thread_id = NULL;
2229 parent_message_id = (char *) l->data;
2231 _notmuch_message_add_term (message, "reference",
2234 ret = _resolve_message_id_to_thread_id (notmuch,
2241 if (*thread_id == NULL) {
2242 *thread_id = talloc_strdup (message, parent_thread_id);
2243 _notmuch_message_add_term (message, "thread", *thread_id);
2244 } else if (strcmp (*thread_id, parent_thread_id)) {
2245 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2255 g_hash_table_unref (parents);
2260 static notmuch_status_t
2261 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2262 notmuch_message_t *message,
2263 const char **thread_id)
2265 const char *message_id = notmuch_message_get_message_id (message);
2266 Xapian::PostingIterator child, children_end;
2267 notmuch_message_t *child_message = NULL;
2268 const char *child_thread_id;
2269 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2270 notmuch_private_status_t private_status;
2272 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2274 for ( ; child != children_end; child++) {
2276 child_message = _notmuch_message_create (message, notmuch,
2277 *child, &private_status);
2278 if (child_message == NULL) {
2279 ret = COERCE_STATUS (private_status,
2280 "Cannot find document for doc_id from query");
2284 child_thread_id = notmuch_message_get_thread_id (child_message);
2285 if (*thread_id == NULL) {
2286 *thread_id = talloc_strdup (message, child_thread_id);
2287 _notmuch_message_add_term (message, "thread", *thread_id);
2288 } else if (strcmp (*thread_id, child_thread_id)) {
2289 _notmuch_message_remove_term (child_message, "reference",
2291 _notmuch_message_sync (child_message);
2292 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2297 notmuch_message_destroy (child_message);
2298 child_message = NULL;
2303 notmuch_message_destroy (child_message);
2308 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2310 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2311 notmuch_message_t *message)
2313 const char *message_id;
2317 message_id = notmuch_message_get_message_id (message);
2318 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2320 /* Check if we have already seen related messages to this one.
2321 * If we have then use the thread_id that we stored at that time.
2323 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2324 if (stored_id.empty ()) {
2327 Xapian::WritableDatabase *db;
2329 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2331 /* Clear the metadata for this message ID. We don't need it
2333 db->set_metadata (metadata_key, "");
2335 return talloc_strdup (ctx, stored_id.c_str ());
2339 /* Given a blank or ghost 'message' and its corresponding
2340 * 'message_file' link it to existing threads in the database.
2342 * First, if is_ghost, this retrieves the thread ID already stored in
2343 * the message (which will be the case if a message was previously
2344 * added that referenced this one). If the message is blank
2345 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2346 * later in this function). If the database does not support ghost
2347 * messages, this checks for a thread ID stored in database metadata
2348 * for this message ID.
2350 * Second, we look at 'message_file' and its link-relevant headers
2351 * (References and In-Reply-To) for message IDs.
2353 * Finally, we look in the database for existing message that
2354 * reference 'message'.
2356 * In all cases, we assign to the current message the first thread ID
2357 * found. We will also merge any existing, distinct threads where this
2358 * message belongs to both, (which is not uncommon when messages are
2359 * processed out of order).
2361 * Finally, if no thread ID has been found through referenced messages, we
2362 * call _notmuch_message_generate_thread_id to generate a new thread
2363 * ID. This should only happen for new, top-level messages, (no
2364 * References or In-Reply-To header in this message, and no previously
2365 * added message refers to this message).
2367 static notmuch_status_t
2368 _notmuch_database_link_message (notmuch_database_t *notmuch,
2369 notmuch_message_t *message,
2370 notmuch_message_file_t *message_file,
2371 notmuch_bool_t is_ghost)
2373 void *local = talloc_new (NULL);
2374 notmuch_status_t status;
2375 const char *thread_id = NULL;
2377 /* Check if the message already had a thread ID */
2378 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2380 thread_id = notmuch_message_get_thread_id (message);
2382 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2384 _notmuch_message_add_term (message, "thread", thread_id);
2387 status = _notmuch_database_link_message_to_parents (notmuch, message,
2393 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2394 /* In general, it shouldn't be necessary to link children,
2395 * since the earlier indexing of those children will have
2396 * stored a thread ID for the missing parent. However, prior
2397 * to ghost messages, these stored thread IDs were NOT
2398 * rewritten during thread merging (and there was no
2399 * performant way to do so), so if indexed children were
2400 * pulled into a different thread ID by a merge, it was
2401 * necessary to pull them *back* into the stored thread ID of
2402 * the parent. With ghost messages, we just rewrite the
2403 * stored thread IDs during merging, so this workaround isn't
2405 status = _notmuch_database_link_message_to_children (notmuch, message,
2411 /* If not part of any existing thread, generate a new thread ID. */
2412 if (thread_id == NULL) {
2413 thread_id = _notmuch_database_generate_thread_id (notmuch);
2415 _notmuch_message_add_term (message, "thread", thread_id);
2419 talloc_free (local);
2425 notmuch_database_add_message (notmuch_database_t *notmuch,
2426 const char *filename,
2427 notmuch_message_t **message_ret)
2429 notmuch_message_file_t *message_file;
2430 notmuch_message_t *message = NULL;
2431 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2432 notmuch_private_status_t private_status;
2433 notmuch_bool_t is_ghost = false;
2435 const char *date, *header;
2436 const char *from, *to, *subject;
2437 char *message_id = NULL;
2440 *message_ret = NULL;
2442 ret = _notmuch_database_ensure_writable (notmuch);
2446 message_file = _notmuch_message_file_open (notmuch, filename);
2447 if (message_file == NULL)
2448 return NOTMUCH_STATUS_FILE_ERROR;
2450 /* Adding a message may change many documents. Do this all
2452 ret = notmuch_database_begin_atomic (notmuch);
2456 /* Parse message up front to get better error status. */
2457 ret = _notmuch_message_file_parse (message_file);
2462 /* Before we do any real work, (especially before doing a
2463 * potential SHA-1 computation on the entire file's contents),
2464 * let's make sure that what we're looking at looks like an
2465 * actual email message.
2467 from = _notmuch_message_file_get_header (message_file, "from");
2468 subject = _notmuch_message_file_get_header (message_file, "subject");
2469 to = _notmuch_message_file_get_header (message_file, "to");
2471 if ((from == NULL || *from == '\0') &&
2472 (subject == NULL || *subject == '\0') &&
2473 (to == NULL || *to == '\0'))
2475 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2479 /* Now that we're sure it's mail, the first order of business
2480 * is to find a message ID (or else create one ourselves). */
2482 header = _notmuch_message_file_get_header (message_file, "message-id");
2483 if (header && *header != '\0') {
2484 message_id = _parse_message_id (message_file, header, NULL);
2486 /* So the header value isn't RFC-compliant, but it's
2487 * better than no message-id at all. */
2488 if (message_id == NULL)
2489 message_id = talloc_strdup (message_file, header);
2492 if (message_id == NULL ) {
2493 /* No message-id at all, let's generate one by taking a
2494 * hash over the file's contents. */
2495 char *sha1 = _notmuch_sha1_of_file (filename);
2497 /* If that failed too, something is really wrong. Give up. */
2499 ret = NOTMUCH_STATUS_FILE_ERROR;
2503 message_id = talloc_asprintf (message_file,
2504 "notmuch-sha1-%s", sha1);
2508 /* Now that we have a message ID, we get a message object,
2509 * (which may or may not reference an existing document in the
2512 message = _notmuch_message_create_for_message_id (notmuch,
2516 talloc_free (message_id);
2518 if (message == NULL) {
2519 ret = COERCE_STATUS (private_status,
2520 "Unexpected status value from _notmuch_message_create_for_message_id");
2524 _notmuch_message_add_filename (message, filename);
2526 /* Is this a newly created message object or a ghost
2527 * message? We have to be slightly careful: if this is a
2528 * blank message, it's not safe to call
2529 * notmuch_message_get_flag yet. */
2530 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2531 (is_ghost = notmuch_message_get_flag (
2532 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2533 _notmuch_message_add_term (message, "type", "mail");
2535 /* Convert ghost message to a regular message */
2536 _notmuch_message_remove_term (message, "type", "ghost");
2538 ret = _notmuch_database_link_message (notmuch, message,
2539 message_file, is_ghost);
2543 date = _notmuch_message_file_get_header (message_file, "date");
2544 _notmuch_message_set_header_values (message, date, from, subject);
2546 ret = _notmuch_message_index_file (message, message_file);
2550 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2553 _notmuch_message_sync (message);
2554 } catch (const Xapian::Error &error) {
2555 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2556 error.get_msg().c_str());
2557 notmuch->exception_reported = TRUE;
2558 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2564 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2565 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2566 *message_ret = message;
2568 notmuch_message_destroy (message);
2572 _notmuch_message_file_close (message_file);
2574 ret2 = notmuch_database_end_atomic (notmuch);
2575 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2576 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2577 ret2 != NOTMUCH_STATUS_SUCCESS)
2584 notmuch_database_remove_message (notmuch_database_t *notmuch,
2585 const char *filename)
2587 notmuch_status_t status;
2588 notmuch_message_t *message;
2590 status = notmuch_database_find_message_by_filename (notmuch, filename,
2593 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2594 status = _notmuch_message_remove_filename (message, filename);
2595 if (status == NOTMUCH_STATUS_SUCCESS)
2596 _notmuch_message_delete (message);
2597 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2598 _notmuch_message_sync (message);
2600 notmuch_message_destroy (message);
2607 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2608 const char *filename,
2609 notmuch_message_t **message_ret)
2612 const char *prefix = _find_prefix ("file-direntry");
2613 char *direntry, *term;
2614 Xapian::PostingIterator i, end;
2615 notmuch_status_t status;
2617 if (message_ret == NULL)
2618 return NOTMUCH_STATUS_NULL_POINTER;
2620 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2621 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2623 /* return NULL on any failure */
2624 *message_ret = NULL;
2626 local = talloc_new (notmuch);
2629 status = _notmuch_database_filename_to_direntry (
2630 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2631 if (status || !direntry)
2634 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2636 find_doc_ids_for_term (notmuch, term, &i, &end);
2639 notmuch_private_status_t private_status;
2641 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2643 if (*message_ret == NULL)
2644 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2646 } catch (const Xapian::Error &error) {
2647 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2648 error.get_msg().c_str());
2649 notmuch->exception_reported = TRUE;
2650 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2654 talloc_free (local);
2656 if (status && *message_ret) {
2657 notmuch_message_destroy (*message_ret);
2658 *message_ret = NULL;
2663 notmuch_string_list_t *
2664 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2665 Xapian::TermIterator &end,
2668 int prefix_len = strlen (prefix);
2669 notmuch_string_list_t *list;
2671 list = _notmuch_string_list_create (ctx);
2672 if (unlikely (list == NULL))
2675 for (i.skip_to (prefix); i != end; i++) {
2676 /* Terminate loop at first term without desired prefix. */
2677 if (strncmp ((*i).c_str (), prefix, prefix_len))
2680 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2687 notmuch_database_get_all_tags (notmuch_database_t *db)
2689 Xapian::TermIterator i, end;
2690 notmuch_string_list_t *tags;
2693 i = db->xapian_db->allterms_begin();
2694 end = db->xapian_db->allterms_end();
2695 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2696 _find_prefix ("tag"));
2697 _notmuch_string_list_sort (tags);
2698 return _notmuch_tags_create (db, tags);
2699 } catch (const Xapian::Error &error) {
2700 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2701 error.get_msg().c_str());
2702 db->exception_reported = TRUE;
2708 notmuch_database_status_string (const notmuch_database_t *notmuch)
2710 return notmuch->status_string;