1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
24 #include "regexp-fields.h"
25 #include "string-util.h"
34 #include <glib.h> /* g_free, GPtrArray, GHashTable */
35 #include <glib-object.h> /* g_type_init */
37 #include <gmime/gmime.h> /* g_mime_init */
41 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
46 notmuch_field_flag_t flags;
49 #define NOTMUCH_DATABASE_VERSION 3
51 #define STRINGIFY(s) _SUB_STRINGIFY(s)
52 #define _SUB_STRINGIFY(s) #s
54 #if HAVE_XAPIAN_DB_RETRY_LOCK
55 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
57 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
60 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
62 * We currently have three different types of documents (mail, ghost,
63 * and directory) and also some metadata.
67 * A mail document is associated with a particular email message. It
68 * is stored in one or more files on disk (though only one has its
69 * content indexed) and is uniquely identified by its "id" field
70 * (which is generally the message ID). It is indexed with the
71 * following prefixed terms which the database uses to construct
74 * Single terms of given prefix:
78 * id: Unique ID of mail. This is from the Message-ID header
79 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
80 * If it's present and too long, then we use
81 * "notmuch-sha1-<sha1_sum_of_message_id>".
82 * If this header is not present, we use
83 * "notmuch-sha1-<sha1_sum_of_entire_file>".
85 * thread: The ID of the thread to which the mail belongs
87 * replyto: The ID from the In-Reply-To header of the mail (if any).
89 * Multiple terms of given prefix:
91 * reference: All message IDs from In-Reply-To and References
92 * headers in the message.
94 * tag: Any tags associated with this message by the user.
96 * file-direntry: A colon-separated pair of values
97 * (INTEGER:STRING), where INTEGER is the
98 * document ID of a directory document, and
99 * STRING is the name of a file within that
100 * directory for this mail message.
102 * property: Has a property with key=value
103 * FIXME: if no = is present, should match on any value
105 * A mail document also has four values:
107 * TIMESTAMP: The time_t value corresponding to the message's
110 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
112 * FROM: The value of the "From" header
114 * SUBJECT: The value of the "Subject" header
116 * LAST_MOD: The revision number as of the last tag or
119 * In addition, terms from the content of the message are added with
120 * "from", "to", "attachment", and "subject" prefixes for use by the
121 * user in searching. Similarly, terms from the path of the mail
122 * message are added with "folder" and "path" prefixes. But the
123 * database doesn't really care itself about any of these.
125 * The data portion of a mail document is empty.
127 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
128 * -----------------------------------------------
129 * A ghost mail document is like a mail document, but where we don't
130 * have the message content. These are used to track thread reference
131 * information for messages we haven't received.
133 * A ghost mail document has type: ghost; id and thread fields that
134 * are identical to the mail document fields; and a MESSAGE_ID value.
138 * A directory document is used by a client of the notmuch library to
139 * maintain data necessary to allow for efficient polling of mail
142 * All directory documents contain one term:
144 * directory: The directory path (relative to the database path)
145 * Or the SHA1 sum of the directory path (if the
146 * path itself is too long to fit in a Xapian
149 * And all directory documents for directories other than top-level
150 * directories also contain the following term:
152 * directory-direntry: A colon-separated pair of values
153 * (INTEGER:STRING), where INTEGER is the
154 * document ID of the parent directory
155 * document, and STRING is the name of this
156 * directory within that parent.
158 * All directory documents have a single value:
160 * TIMESTAMP: The mtime of the directory (at last scan)
162 * The data portion of a directory document contains the path of the
163 * directory (relative to the database path).
167 * Xapian allows us to store arbitrary name-value pairs as
168 * "metadata". We currently use the following metadata names with the
171 * version The database schema version, (which is distinct
172 * from both the notmuch package version (see
173 * notmuch --version) and the libnotmuch library
174 * version. The version is stored as an base-10
175 * ASCII integer. The initial database version
176 * was 1, (though a schema existed before that
177 * were no "version" database value existed at
178 * all). Successive versions are allocated as
179 * changes are made to the database (such as by
180 * indexing new fields).
182 * features The set of features supported by this
183 * database. This consists of a set of
184 * '\n'-separated lines, where each is a feature
185 * name, a '\t', and compatibility flags. If the
186 * compatibility flags contain 'w', then the
187 * opener must support this feature to safely
188 * write this database. If the compatibility
189 * flags contain 'r', then the opener must
190 * support this feature to read this database.
191 * Introduced in database version 3.
193 * last_thread_id The last thread ID generated. This is stored
194 * as a 16-byte hexadecimal ASCII representation
195 * of a 64-bit unsigned integer. The first ID
196 * generated is 1 and the value will be
197 * incremented for each thread ID.
199 * C* metadata keys starting with C indicate
200 * configuration data. It can be managed with the
201 * n_database_*config* API. There is a convention
202 * of hierarchical keys separated by '.' (e.g.
203 * query.notmuch stores the value for the named
204 * query 'notmuch'), but it is not enforced by the
210 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
211 * Instead, the database has the following additional database
214 * thread_id_* A pre-allocated thread ID for a particular
215 * message. This is actually an arbitrarily large
216 * family of metadata name. Any particular name is
217 * formed by concatenating "thread_id_" with a message
218 * ID (or the SHA1 sum of a message ID if it is very
219 * long---see description of 'id' in the mail
220 * document). The value stored is a thread ID.
222 * These thread ID metadata values are stored
223 * whenever a message references a parent message
224 * that does not yet exist in the database. A
225 * thread ID will be allocated and stored, and if
226 * the message is later added, the stored thread
227 * ID will be used (and the metadata value will
230 * Even before a message is added, it's
231 * pre-allocated thread ID is useful so that all
232 * descendant messages that reference this common
233 * parent can be recognized as belonging to the
237 /* With these prefix values we follow the conventions published here:
239 * https://xapian.org/docs/omega/termprefixes.html
241 * as much as makes sense. Note that I took some liberty in matching
242 * the reserved prefix values to notmuch concepts, (for example, 'G'
243 * is documented as "newsGroup (or similar entity - e.g. a web forum
244 * name)", for which I think the thread is the closest analogue in
245 * notmuch. This in spite of the fact that we will eventually be
246 * storing mailing-list messages where 'G' for "mailing list name"
247 * might be even a closer analogue. I'm treating the single-character
248 * prefixes preferentially for core notmuch concepts (which will be
249 * nearly universal to all mail messages).
253 prefix_t prefix_table[] = {
254 /* name term prefix flags */
255 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
256 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
257 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
258 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
259 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
260 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
261 { "thread", "G", NOTMUCH_FIELD_EXTERNAL },
262 { "tag", "K", NOTMUCH_FIELD_EXTERNAL },
263 { "is", "K", NOTMUCH_FIELD_EXTERNAL },
264 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
265 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL },
266 { "path", "P", NOTMUCH_FIELD_EXTERNAL },
267 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
269 * Unconditionally add ':' to reduce potential ambiguity with
270 * overlapping prefixes and/or terms that start with capital
271 * letters. See Xapian document termprefixes.html for related
274 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL },
275 #if HAVE_XAPIAN_FIELD_PROCESSOR
276 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
277 NOTMUCH_FIELD_PROCESSOR },
278 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
279 NOTMUCH_FIELD_PROCESSOR },
281 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
282 NOTMUCH_FIELD_PROBABILISTIC |
283 NOTMUCH_FIELD_PROCESSOR },
284 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
285 NOTMUCH_FIELD_PROBABILISTIC },
286 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
287 NOTMUCH_FIELD_PROBABILISTIC },
288 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
289 NOTMUCH_FIELD_PROBABILISTIC },
290 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
291 NOTMUCH_FIELD_PROBABILISTIC |
292 NOTMUCH_FIELD_PROCESSOR},
296 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
298 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
299 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
301 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
304 #if HAVE_XAPIAN_FIELD_PROCESSOR
306 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
308 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
309 Xapian::FieldProcessor *fp;
311 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
312 fp = (new DateFieldProcessor())->release ();
313 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
314 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
316 fp = (new RegexpFieldProcessor (prefix->name, *notmuch->query_parser, notmuch))->release ();
318 /* we treat all field-processor fields as boolean in order to get the raw input */
319 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
321 _setup_query_field_default (prefix, notmuch);
326 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
328 _setup_query_field_default (prefix, notmuch);
333 _find_prefix (const char *name)
337 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
338 if (strcmp (name, prefix_table[i].name) == 0)
339 return prefix_table[i].prefix;
342 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
347 static const struct {
348 /* NOTMUCH_FEATURE_* value. */
349 _notmuch_features value;
350 /* Feature name as it appears in the database. This name should
351 * be appropriate for displaying to the user if an older version
352 * of notmuch doesn't support this feature. */
354 /* Compatibility flags when this feature is declared. */
356 } feature_names[] = {
357 { NOTMUCH_FEATURE_FILE_TERMS,
358 "multiple paths per message", "rw" },
359 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
360 "relative directory paths", "rw" },
361 /* Header values are not required for reading a database because a
362 * reader can just refer to the message file. */
363 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
364 "from/subject/message-ID in database", "w" },
365 { NOTMUCH_FEATURE_BOOL_FOLDER,
366 "exact folder:/path: search", "rw" },
367 { NOTMUCH_FEATURE_GHOSTS,
368 "mail documents for missing messages", "w"},
369 /* Knowledge of the index mime-types are not required for reading
370 * a database because a reader will just be unable to query
372 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
373 "indexed MIME types", "w"},
374 { NOTMUCH_FEATURE_LAST_MOD,
375 "modification tracking", "w"},
379 notmuch_status_to_string (notmuch_status_t status)
382 case NOTMUCH_STATUS_SUCCESS:
383 return "No error occurred";
384 case NOTMUCH_STATUS_OUT_OF_MEMORY:
385 return "Out of memory";
386 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
387 return "Attempt to write to a read-only database";
388 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
389 return "A Xapian exception occurred";
390 case NOTMUCH_STATUS_FILE_ERROR:
391 return "Something went wrong trying to read or write a file";
392 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
393 return "File is not an email";
394 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
395 return "Message ID is identical to a message in database";
396 case NOTMUCH_STATUS_NULL_POINTER:
397 return "Erroneous NULL pointer";
398 case NOTMUCH_STATUS_TAG_TOO_LONG:
399 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
400 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
401 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
402 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
403 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
404 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
405 return "Unsupported operation";
406 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
407 return "Operation requires a database upgrade";
408 case NOTMUCH_STATUS_PATH_ERROR:
409 return "Path supplied is illegal for this function";
411 case NOTMUCH_STATUS_LAST_STATUS:
412 return "Unknown error status value";
417 _notmuch_database_log (notmuch_database_t *notmuch,
423 va_start (va_args, format);
425 if (notmuch->status_string)
426 talloc_free (notmuch->status_string);
428 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
433 _notmuch_database_log_append (notmuch_database_t *notmuch,
439 va_start (va_args, format);
441 if (notmuch->status_string)
442 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
444 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
450 find_doc_ids_for_term (notmuch_database_t *notmuch,
452 Xapian::PostingIterator *begin,
453 Xapian::PostingIterator *end)
455 *begin = notmuch->xapian_db->postlist_begin (term);
457 *end = notmuch->xapian_db->postlist_end (term);
461 find_doc_ids (notmuch_database_t *notmuch,
462 const char *prefix_name,
464 Xapian::PostingIterator *begin,
465 Xapian::PostingIterator *end)
469 term = talloc_asprintf (notmuch, "%s%s",
470 _find_prefix (prefix_name), value);
472 find_doc_ids_for_term (notmuch, term, begin, end);
477 notmuch_private_status_t
478 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
479 const char *prefix_name,
481 unsigned int *doc_id)
483 Xapian::PostingIterator i, end;
485 find_doc_ids (notmuch, prefix_name, value, &i, &end);
489 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
494 #if DEBUG_DATABASE_SANITY
498 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
502 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
505 static Xapian::Document
506 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
508 return notmuch->xapian_db->get_document (doc_id);
511 /* Generate a compressed version of 'message_id' of the form:
513 * notmuch-sha1-<sha1_sum_of_message_id>
516 _notmuch_message_id_compressed (void *ctx, const char *message_id)
518 char *sha1, *compressed;
520 sha1 = _notmuch_sha1_of_string (message_id);
522 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
529 notmuch_database_find_message (notmuch_database_t *notmuch,
530 const char *message_id,
531 notmuch_message_t **message_ret)
533 notmuch_private_status_t status;
536 if (message_ret == NULL)
537 return NOTMUCH_STATUS_NULL_POINTER;
539 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
540 message_id = _notmuch_message_id_compressed (notmuch, message_id);
543 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
544 message_id, &doc_id);
546 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
549 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
551 if (*message_ret == NULL)
552 return NOTMUCH_STATUS_OUT_OF_MEMORY;
555 return NOTMUCH_STATUS_SUCCESS;
556 } catch (const Xapian::Error &error) {
557 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
558 error.get_msg().c_str());
559 notmuch->exception_reported = TRUE;
561 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
565 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
566 * a (potentially nested) parenthesized sequence with '\' used to
567 * escape any character (including parentheses).
569 * If the sequence to be skipped continues to the end of the string,
570 * then 'str' will be left pointing at the final terminating '\0'
574 skip_space_and_comments (const char **str)
579 while (*s && (isspace (*s) || *s == '(')) {
580 while (*s && isspace (*s))
585 while (*s && nesting) {
588 } else if (*s == ')') {
590 } else if (*s == '\\') {
602 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
603 * comments, and the '<' and '>' delimiters.
605 * If not NULL, then *next will be made to point to the first character
606 * not parsed, (possibly pointing to the final '\0' terminator.
608 * Returns a newly talloc'ed string belonging to 'ctx'.
610 * Returns NULL if there is any error parsing the message-id. */
612 _parse_message_id (void *ctx, const char *message_id, const char **next)
617 if (message_id == NULL || *message_id == '\0')
622 skip_space_and_comments (&s);
624 /* Skip any unstructured text as well. */
625 while (*s && *s != '<')
636 skip_space_and_comments (&s);
639 while (*end && *end != '>')
648 if (end > s && *end == '>')
653 result = talloc_strndup (ctx, s, end - s + 1);
655 /* Finally, collapse any whitespace that is within the message-id
661 for (r = result, len = strlen (r); *r; r++, len--)
662 if (*r == ' ' || *r == '\t')
663 memmove (r, r+1, len);
669 /* Parse a References header value, putting a (talloc'ed under 'ctx')
670 * copy of each referenced message-id into 'hash'.
672 * We explicitly avoid including any reference identical to
673 * 'message_id' in the result (to avoid mass confusion when a single
674 * message references itself cyclically---and yes, mail messages are
675 * not infrequent in the wild that do this---don't ask me why).
677 * Return the last reference parsed, if it is not equal to message_id.
680 parse_references (void *ctx,
681 const char *message_id,
685 char *ref, *last_ref = NULL;
687 if (refs == NULL || *refs == '\0')
691 ref = _parse_message_id (ctx, refs, &refs);
693 if (ref && strcmp (ref, message_id)) {
694 g_hash_table_add (hash, ref);
699 /* The return value of this function is used to add a parent
700 * reference to the database. We should avoid making a message
701 * its own parent, thus the above check.
703 return talloc_strdup(ctx, last_ref);
707 notmuch_database_create (const char *path, notmuch_database_t **database)
709 char *status_string = NULL;
710 notmuch_status_t status;
712 status = notmuch_database_create_verbose (path, database,
716 fputs (status_string, stderr);
717 free (status_string);
724 notmuch_database_create_verbose (const char *path,
725 notmuch_database_t **database,
726 char **status_string)
728 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
729 notmuch_database_t *notmuch = NULL;
730 char *notmuch_path = NULL;
731 char *message = NULL;
736 message = strdup ("Error: Cannot create a database for a NULL path.\n");
737 status = NOTMUCH_STATUS_NULL_POINTER;
741 if (path[0] != '/') {
742 message = strdup ("Error: Database path must be absolute.\n");
743 status = NOTMUCH_STATUS_PATH_ERROR;
747 err = stat (path, &st);
749 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
750 path, strerror (errno)));
751 status = NOTMUCH_STATUS_FILE_ERROR;
755 if (! S_ISDIR (st.st_mode)) {
756 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
757 "Not a directory.\n",
759 status = NOTMUCH_STATUS_FILE_ERROR;
763 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
765 err = mkdir (notmuch_path, 0755);
768 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
769 notmuch_path, strerror (errno)));
770 status = NOTMUCH_STATUS_FILE_ERROR;
774 status = notmuch_database_open_verbose (path,
775 NOTMUCH_DATABASE_MODE_READ_WRITE,
780 /* Upgrade doesn't add these feature to existing databases, but
781 * new databases have them. */
782 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
783 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
785 status = notmuch_database_upgrade (notmuch, NULL, NULL);
787 notmuch_database_close(notmuch);
793 talloc_free (notmuch_path);
797 *status_string = message;
804 talloc_free (notmuch);
809 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
811 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
812 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
813 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
816 return NOTMUCH_STATUS_SUCCESS;
819 /* Allocate a revision number for the next change. */
821 _notmuch_database_new_revision (notmuch_database_t *notmuch)
823 unsigned long new_revision = notmuch->revision + 1;
825 /* If we're in an atomic section, hold off on updating the
826 * committed revision number until we commit the atomic section.
828 if (notmuch->atomic_nesting)
829 notmuch->atomic_dirty = TRUE;
831 notmuch->revision = new_revision;
836 /* Parse a database features string from the given database version.
837 * Returns the feature bit set.
839 * For version < 3, this ignores the features string and returns a
840 * hard-coded set of features.
842 * If there are unrecognized features that are required to open the
843 * database in mode (which should be 'r' or 'w'), return a
844 * comma-separated list of unrecognized but required features in
845 * *incompat_out suitable for presenting to the user. *incompat_out
846 * will be allocated from ctx.
848 static _notmuch_features
849 _parse_features (const void *ctx, const char *features, unsigned int version,
850 char mode, char **incompat_out)
852 _notmuch_features res = static_cast<_notmuch_features>(0);
853 unsigned int namelen, i;
857 /* Prior to database version 3, features were implied by the
860 return NOTMUCH_FEATURES_V0;
861 else if (version == 1)
862 return NOTMUCH_FEATURES_V1;
863 else if (version == 2)
864 return NOTMUCH_FEATURES_V2;
866 /* Parse the features string */
867 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
868 flags = strchr (features, '\t');
869 if (! flags || flags > features + llen)
871 namelen = flags - features;
873 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
874 if (strlen (feature_names[i].name) == namelen &&
875 strncmp (feature_names[i].name, features, namelen) == 0) {
876 res |= feature_names[i].value;
881 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
882 /* Unrecognized feature */
883 const char *have = strchr (flags, mode);
884 if (have && have < features + llen) {
885 /* This feature is required to access this database in
886 * 'mode', but we don't understand it. */
888 *incompat_out = talloc_strdup (ctx, "");
889 *incompat_out = talloc_asprintf_append_buffer (
890 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
900 _print_features (const void *ctx, unsigned int features)
903 char *res = talloc_strdup (ctx, "");
905 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
906 if (features & feature_names[i].value)
907 res = talloc_asprintf_append_buffer (
908 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
914 notmuch_database_open (const char *path,
915 notmuch_database_mode_t mode,
916 notmuch_database_t **database)
918 char *status_string = NULL;
919 notmuch_status_t status;
921 status = notmuch_database_open_verbose (path, mode, database,
925 fputs (status_string, stderr);
926 free (status_string);
933 notmuch_database_open_verbose (const char *path,
934 notmuch_database_mode_t mode,
935 notmuch_database_t **database,
936 char **status_string)
938 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
939 void *local = talloc_new (NULL);
940 notmuch_database_t *notmuch = NULL;
941 char *notmuch_path, *xapian_path, *incompat_features;
942 char *message = NULL;
945 unsigned int i, version;
946 static int initialized = 0;
949 message = strdup ("Error: Cannot open a database for a NULL path.\n");
950 status = NOTMUCH_STATUS_NULL_POINTER;
954 if (path[0] != '/') {
955 message = strdup ("Error: Database path must be absolute.\n");
956 status = NOTMUCH_STATUS_PATH_ERROR;
960 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
961 message = strdup ("Out of memory\n");
962 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
966 err = stat (notmuch_path, &st);
968 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
969 notmuch_path, strerror (errno)));
970 status = NOTMUCH_STATUS_FILE_ERROR;
974 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
975 message = strdup ("Out of memory\n");
976 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
980 /* Initialize the GLib type system and threads */
981 #if !GLIB_CHECK_VERSION(2, 35, 1)
985 /* Initialize gmime */
987 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
991 notmuch = talloc_zero (NULL, notmuch_database_t);
992 notmuch->exception_reported = FALSE;
993 notmuch->status_string = NULL;
994 notmuch->path = talloc_strdup (notmuch, path);
996 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
997 notmuch->path[strlen (notmuch->path) - 1] = '\0';
999 notmuch->mode = mode;
1000 notmuch->atomic_nesting = 0;
1003 string last_thread_id;
1006 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
1007 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
1010 notmuch->xapian_db = new Xapian::Database (xapian_path);
1013 /* Check version. As of database version 3, we represent
1014 * changes in terms of features, so assume a version bump
1015 * means a dramatically incompatible change. */
1016 version = notmuch_database_get_version (notmuch);
1017 if (version > NOTMUCH_DATABASE_VERSION) {
1018 IGNORE_RESULT (asprintf (&message,
1019 "Error: Notmuch database at %s\n"
1020 " has a newer database format version (%u) than supported by this\n"
1021 " version of notmuch (%u).\n",
1022 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
1023 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1024 notmuch_database_destroy (notmuch);
1026 status = NOTMUCH_STATUS_FILE_ERROR;
1030 /* Check features. */
1031 incompat_features = NULL;
1032 notmuch->features = _parse_features (
1033 local, notmuch->xapian_db->get_metadata ("features").c_str (),
1034 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1035 &incompat_features);
1036 if (incompat_features) {
1037 IGNORE_RESULT (asprintf (&message,
1038 "Error: Notmuch database at %s\n"
1039 " requires features (%s)\n"
1040 " not supported by this version of notmuch.\n",
1041 notmuch_path, incompat_features));
1042 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1043 notmuch_database_destroy (notmuch);
1045 status = NOTMUCH_STATUS_FILE_ERROR;
1049 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1050 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1051 if (last_thread_id.empty ()) {
1052 notmuch->last_thread_id = 0;
1057 str = last_thread_id.c_str ();
1058 notmuch->last_thread_id = strtoull (str, &end, 16);
1060 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1063 /* Get current highest revision number. */
1064 last_mod = notmuch->xapian_db->get_value_upper_bound (
1065 NOTMUCH_VALUE_LAST_MOD);
1066 if (last_mod.empty ())
1067 notmuch->revision = 0;
1069 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1070 notmuch->uuid = talloc_strdup (
1071 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1073 notmuch->query_parser = new Xapian::QueryParser;
1074 notmuch->term_gen = new Xapian::TermGenerator;
1075 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1076 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1077 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1078 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1080 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1081 notmuch->query_parser->set_database (*notmuch->xapian_db);
1082 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1083 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1084 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1085 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1086 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1088 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1089 const prefix_t *prefix = &prefix_table[i];
1090 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1091 _setup_query_field (prefix, notmuch);
1094 } catch (const Xapian::Error &error) {
1095 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1096 error.get_msg().c_str()));
1097 notmuch_database_destroy (notmuch);
1099 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1103 talloc_free (local);
1107 *status_string = message;
1113 *database = notmuch;
1115 talloc_free (notmuch);
1120 notmuch_database_close (notmuch_database_t *notmuch)
1122 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1124 /* Many Xapian objects (and thus notmuch objects) hold references to
1125 * the database, so merely deleting the database may not suffice to
1126 * close it. Thus, we explicitly close it here. */
1127 if (notmuch->xapian_db != NULL) {
1129 /* If there's an outstanding transaction, it's unclear if
1130 * closing the Xapian database commits everything up to
1131 * that transaction, or may discard committed (but
1132 * unflushed) transactions. To be certain, explicitly
1133 * cancel any outstanding transaction before closing. */
1134 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1135 notmuch->atomic_nesting)
1136 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1137 ->cancel_transaction ();
1139 /* Close the database. This implicitly flushes
1140 * outstanding changes. */
1141 notmuch->xapian_db->close();
1142 } catch (const Xapian::Error &error) {
1143 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1144 if (! notmuch->exception_reported) {
1145 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1146 error.get_msg().c_str());
1151 delete notmuch->term_gen;
1152 notmuch->term_gen = NULL;
1153 delete notmuch->query_parser;
1154 notmuch->query_parser = NULL;
1155 delete notmuch->xapian_db;
1156 notmuch->xapian_db = NULL;
1157 delete notmuch->value_range_processor;
1158 notmuch->value_range_processor = NULL;
1159 delete notmuch->date_range_processor;
1160 notmuch->date_range_processor = NULL;
1161 delete notmuch->last_mod_range_processor;
1162 notmuch->last_mod_range_processor = NULL;
1168 _notmuch_database_reopen (notmuch_database_t *notmuch)
1170 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1171 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1174 notmuch->xapian_db->reopen ();
1175 } catch (const Xapian::Error &error) {
1176 if (! notmuch->exception_reported) {
1177 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1178 error.get_msg ().c_str ());
1179 notmuch->exception_reported = TRUE;
1181 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1186 return NOTMUCH_STATUS_SUCCESS;
1190 unlink_cb (const char *path,
1191 unused (const struct stat *sb),
1193 unused (struct FTW *ftw))
1195 return remove (path);
1199 rmtree (const char *path)
1201 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1204 class NotmuchCompactor : public Xapian::Compactor
1206 notmuch_compact_status_cb_t status_cb;
1207 void *status_closure;
1210 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1211 status_cb (cb), status_closure (closure) { }
1214 set_status (const std::string &table, const std::string &status)
1218 if (status_cb == NULL)
1221 if (status.length () == 0)
1222 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1224 msg = talloc_asprintf (NULL, " %s", status.c_str());
1230 status_cb (msg, status_closure);
1235 /* Compacts the given database, optionally saving the original database
1236 * in backup_path. Additionally, a callback function can be provided to
1237 * give the user feedback on the progress of the (likely long-lived)
1238 * compaction process.
1240 * The backup path must point to a directory on the same volume as the
1241 * original database. Passing a NULL backup_path will result in the
1242 * uncompacted database being deleted after compaction has finished.
1243 * Note that the database write lock will be held during the
1244 * compaction process to protect data integrity.
1247 notmuch_database_compact (const char *path,
1248 const char *backup_path,
1249 notmuch_compact_status_cb_t status_cb,
1253 char *notmuch_path, *xapian_path, *compact_xapian_path;
1254 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1255 notmuch_database_t *notmuch = NULL;
1256 struct stat statbuf;
1257 notmuch_bool_t keep_backup;
1258 char *message = NULL;
1260 local = talloc_new (NULL);
1262 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1264 ret = notmuch_database_open_verbose (path,
1265 NOTMUCH_DATABASE_MODE_READ_WRITE,
1269 if (status_cb) status_cb (message, closure);
1273 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1274 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1278 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1279 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1283 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1284 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1288 if (backup_path == NULL) {
1289 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1290 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1293 keep_backup = FALSE;
1299 if (stat (backup_path, &statbuf) != -1) {
1300 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1301 ret = NOTMUCH_STATUS_FILE_ERROR;
1304 if (errno != ENOENT) {
1305 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1307 ret = NOTMUCH_STATUS_FILE_ERROR;
1311 /* Unconditionally attempt to remove old work-in-progress database (if
1312 * any). This is "protected" by database lock. If this fails due to write
1313 * errors (etc), the following code will fail and provide error message.
1315 (void) rmtree (compact_xapian_path);
1318 NotmuchCompactor compactor (status_cb, closure);
1320 compactor.set_renumber (false);
1321 compactor.add_source (xapian_path);
1322 compactor.set_destdir (compact_xapian_path);
1323 compactor.compact ();
1324 } catch (const Xapian::Error &error) {
1325 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1326 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1330 if (rename (xapian_path, backup_path)) {
1331 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1332 xapian_path, backup_path, strerror (errno));
1333 ret = NOTMUCH_STATUS_FILE_ERROR;
1337 if (rename (compact_xapian_path, xapian_path)) {
1338 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1339 compact_xapian_path, xapian_path, strerror (errno));
1340 ret = NOTMUCH_STATUS_FILE_ERROR;
1344 if (! keep_backup) {
1345 if (rmtree (backup_path)) {
1346 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1347 backup_path, strerror (errno));
1348 ret = NOTMUCH_STATUS_FILE_ERROR;
1355 notmuch_status_t ret2;
1357 const char *str = notmuch_database_status_string (notmuch);
1358 if (status_cb && str)
1359 status_cb (str, closure);
1361 ret2 = notmuch_database_destroy (notmuch);
1363 /* don't clobber previous error status */
1364 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1368 talloc_free (local);
1374 notmuch_database_destroy (notmuch_database_t *notmuch)
1376 notmuch_status_t status;
1378 status = notmuch_database_close (notmuch);
1379 talloc_free (notmuch);
1385 notmuch_database_get_path (notmuch_database_t *notmuch)
1387 return notmuch->path;
1391 notmuch_database_get_version (notmuch_database_t *notmuch)
1393 unsigned int version;
1394 string version_string;
1398 version_string = notmuch->xapian_db->get_metadata ("version");
1399 if (version_string.empty ())
1402 str = version_string.c_str ();
1403 if (str == NULL || *str == '\0')
1406 version = strtoul (str, &end, 10);
1408 INTERNAL_ERROR ("Malformed database version: %s", str);
1414 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1416 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1417 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1418 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1421 static volatile sig_atomic_t do_progress_notify = 0;
1424 handle_sigalrm (unused (int signal))
1426 do_progress_notify = 1;
1429 /* Upgrade the current database.
1431 * After opening a database in read-write mode, the client should
1432 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1433 * if so, upgrade with this function before making any modifications.
1435 * The optional progress_notify callback can be used by the caller to
1436 * provide progress indication to the user. If non-NULL it will be
1437 * called periodically with 'count' as the number of messages upgraded
1438 * so far and 'total' the overall number of messages that will be
1442 notmuch_database_upgrade (notmuch_database_t *notmuch,
1443 void (*progress_notify) (void *closure,
1447 void *local = talloc_new (NULL);
1448 Xapian::TermIterator t, t_end;
1449 Xapian::WritableDatabase *db;
1450 struct sigaction action;
1451 struct itimerval timerval;
1452 notmuch_bool_t timer_is_active = FALSE;
1453 enum _notmuch_features target_features, new_features;
1454 notmuch_status_t status;
1455 notmuch_private_status_t private_status;
1456 notmuch_query_t *query = NULL;
1457 unsigned int count = 0, total = 0;
1459 status = _notmuch_database_ensure_writable (notmuch);
1463 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1465 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1466 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1468 if (! notmuch_database_needs_upgrade (notmuch))
1469 return NOTMUCH_STATUS_SUCCESS;
1471 if (progress_notify) {
1472 /* Set up our handler for SIGALRM */
1473 memset (&action, 0, sizeof (struct sigaction));
1474 action.sa_handler = handle_sigalrm;
1475 sigemptyset (&action.sa_mask);
1476 action.sa_flags = SA_RESTART;
1477 sigaction (SIGALRM, &action, NULL);
1479 /* Then start a timer to send SIGALRM once per second. */
1480 timerval.it_interval.tv_sec = 1;
1481 timerval.it_interval.tv_usec = 0;
1482 timerval.it_value.tv_sec = 1;
1483 timerval.it_value.tv_usec = 0;
1484 setitimer (ITIMER_REAL, &timerval, NULL);
1486 timer_is_active = TRUE;
1489 /* Figure out how much total work we need to do. */
1491 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1492 NOTMUCH_FEATURE_LAST_MOD)) {
1493 query = notmuch_query_create (notmuch, "");
1496 status = notmuch_query_count_messages (query, &msg_count);
1501 notmuch_query_destroy (query);
1504 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1505 t_end = db->allterms_end ("XTIMESTAMP");
1506 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1509 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1510 /* The ghost message upgrade converts all thread_id_*
1511 * metadata values into ghost message documents. */
1512 t_end = db->metadata_keys_end ("thread_id_");
1513 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1517 /* Perform the upgrade in a transaction. */
1518 db->begin_transaction (true);
1520 /* Set the target features so we write out changes in the desired
1522 notmuch->features = target_features;
1524 /* Perform per-message upgrades. */
1526 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1527 NOTMUCH_FEATURE_LAST_MOD)) {
1528 notmuch_messages_t *messages;
1529 notmuch_message_t *message;
1532 query = notmuch_query_create (notmuch, "");
1534 status = notmuch_query_search_messages (query, &messages);
1538 notmuch_messages_valid (messages);
1539 notmuch_messages_move_to_next (messages))
1541 if (do_progress_notify) {
1542 progress_notify (closure, (double) count / total);
1543 do_progress_notify = 0;
1546 message = notmuch_messages_get (messages);
1548 /* Before version 1, each message document had its
1549 * filename in the data field. Copy that into the new
1550 * format by calling notmuch_message_add_filename.
1552 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1553 filename = _notmuch_message_talloc_copy_data (message);
1554 if (filename && *filename != '\0') {
1555 _notmuch_message_add_filename (message, filename);
1556 _notmuch_message_clear_data (message);
1558 talloc_free (filename);
1561 /* Prior to version 2, the "folder:" prefix was
1562 * probabilistic and stemmed. Change it to the current
1563 * boolean prefix. Add "path:" prefixes while at it.
1565 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1566 _notmuch_message_upgrade_folder (message);
1568 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1569 * track modification revisions. Give all messages the
1570 * next available revision; since we just started tracking
1571 * revisions for this database, that will be 1.
1573 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1574 _notmuch_message_upgrade_last_mod (message);
1576 _notmuch_message_sync (message);
1578 notmuch_message_destroy (message);
1583 notmuch_query_destroy (query);
1587 /* Perform per-directory upgrades. */
1589 /* Before version 1 we stored directory timestamps in
1590 * XTIMESTAMP documents instead of the current XDIRECTORY
1591 * documents. So copy those as well. */
1592 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1593 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1595 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1599 Xapian::PostingIterator p, p_end;
1600 std::string term = *t;
1602 p_end = notmuch->xapian_db->postlist_end (term);
1604 for (p = notmuch->xapian_db->postlist_begin (term);
1608 Xapian::Document document;
1610 notmuch_directory_t *directory;
1612 if (do_progress_notify) {
1613 progress_notify (closure, (double) count / total);
1614 do_progress_notify = 0;
1617 document = find_document_for_doc_id (notmuch, *p);
1618 mtime = Xapian::sortable_unserialise (
1619 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1621 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1622 NOTMUCH_FIND_CREATE, &status);
1623 notmuch_directory_set_mtime (directory, mtime);
1624 notmuch_directory_destroy (directory);
1626 db->delete_document (*p);
1633 /* Perform metadata upgrades. */
1635 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1636 * messages were stored as database metadata. Change these to
1639 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1640 notmuch_message_t *message;
1641 std::string message_id, thread_id;
1643 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1644 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1646 if (do_progress_notify) {
1647 progress_notify (closure, (double) count / total);
1648 do_progress_notify = 0;
1651 message_id = (*t).substr (
1652 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1653 thread_id = db->get_metadata (*t);
1655 /* Create ghost message */
1656 message = _notmuch_message_create_for_message_id (
1657 notmuch, message_id.c_str (), &private_status);
1658 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1659 /* Document already exists; ignore the stored thread ID */
1660 } else if (private_status ==
1661 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1662 private_status = _notmuch_message_initialize_ghost (
1663 message, thread_id.c_str ());
1664 if (! private_status)
1665 _notmuch_message_sync (message);
1668 if (private_status) {
1669 _notmuch_database_log (notmuch,
1670 "Upgrade failed while creating ghost messages.\n");
1671 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1675 /* Clear saved metadata thread ID */
1676 db->set_metadata (*t, "");
1682 status = NOTMUCH_STATUS_SUCCESS;
1683 db->set_metadata ("features", _print_features (local, notmuch->features));
1684 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1687 if (status == NOTMUCH_STATUS_SUCCESS)
1688 db->commit_transaction ();
1690 db->cancel_transaction ();
1692 if (timer_is_active) {
1693 /* Now stop the timer. */
1694 timerval.it_interval.tv_sec = 0;
1695 timerval.it_interval.tv_usec = 0;
1696 timerval.it_value.tv_sec = 0;
1697 timerval.it_value.tv_usec = 0;
1698 setitimer (ITIMER_REAL, &timerval, NULL);
1700 /* And disable the signal handler. */
1701 action.sa_handler = SIG_IGN;
1702 sigaction (SIGALRM, &action, NULL);
1706 notmuch_query_destroy (query);
1708 talloc_free (local);
1713 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1715 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1716 notmuch->atomic_nesting > 0)
1719 if (notmuch_database_needs_upgrade (notmuch))
1720 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1723 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1724 } catch (const Xapian::Error &error) {
1725 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1726 error.get_msg().c_str());
1727 notmuch->exception_reported = TRUE;
1728 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1732 notmuch->atomic_nesting++;
1733 return NOTMUCH_STATUS_SUCCESS;
1737 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1739 Xapian::WritableDatabase *db;
1741 if (notmuch->atomic_nesting == 0)
1742 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1744 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1745 notmuch->atomic_nesting > 1)
1748 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1750 db->commit_transaction ();
1752 /* This is a hack for testing. Xapian never flushes on a
1753 * non-flushed commit, even if the flush threshold is 1.
1754 * However, we rely on flushing to test atomicity. */
1755 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1756 if (thresh && atoi (thresh) == 1)
1758 } catch (const Xapian::Error &error) {
1759 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1760 error.get_msg().c_str());
1761 notmuch->exception_reported = TRUE;
1762 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1765 if (notmuch->atomic_dirty) {
1766 ++notmuch->revision;
1767 notmuch->atomic_dirty = FALSE;
1771 notmuch->atomic_nesting--;
1772 return NOTMUCH_STATUS_SUCCESS;
1776 notmuch_database_get_revision (notmuch_database_t *notmuch,
1780 *uuid = notmuch->uuid;
1781 return notmuch->revision;
1784 /* We allow the user to use arbitrarily long paths for directories. But
1785 * we have a term-length limit. So if we exceed that, we'll use the
1786 * SHA-1 of the path for the database term.
1788 * Note: This function may return the original value of 'path'. If it
1789 * does not, then the caller is responsible to free() the returned
1793 _notmuch_database_get_directory_db_path (const char *path)
1795 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1797 if (term_len > NOTMUCH_TERM_MAX)
1798 return _notmuch_sha1_of_string (path);
1803 /* Given a path, split it into two parts: the directory part is all
1804 * components except for the last, and the basename is that last
1805 * component. Getting the return-value for either part is optional
1806 * (the caller can pass NULL).
1808 * The original 'path' can represent either a regular file or a
1809 * directory---the splitting will be carried out in the same way in
1810 * either case. Trailing slashes on 'path' will be ignored, and any
1811 * cases of multiple '/' characters appearing in series will be
1812 * treated as a single '/'.
1814 * Allocation (if any) will have 'ctx' as the talloc owner. But
1815 * pointers will be returned within the original path string whenever
1818 * Note: If 'path' is non-empty and contains no non-trailing slash,
1819 * (that is, consists of a filename with no parent directory), then
1820 * the directory returned will be an empty string. However, if 'path'
1821 * is an empty string, then both directory and basename will be
1825 _notmuch_database_split_path (void *ctx,
1827 const char **directory,
1828 const char **basename)
1832 if (path == NULL || *path == '\0') {
1837 return NOTMUCH_STATUS_SUCCESS;
1840 /* Find the last slash (not counting a trailing slash), if any. */
1842 slash = path + strlen (path) - 1;
1844 /* First, skip trailing slashes. */
1845 while (slash != path && *slash == '/')
1848 /* Then, find a slash. */
1849 while (slash != path && *slash != '/') {
1856 /* Finally, skip multiple slashes. */
1857 while (slash != path && *(slash - 1) == '/')
1860 if (slash == path) {
1862 *directory = talloc_strdup (ctx, "");
1867 *directory = talloc_strndup (ctx, path, slash - path);
1870 return NOTMUCH_STATUS_SUCCESS;
1873 /* Find the document ID of the specified directory.
1875 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1876 * created if one does not exist for 'path'. Otherwise, if the
1877 * directory document does not exist, this sets *directory_id to
1878 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1881 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1883 notmuch_find_flags_t flags,
1884 unsigned int *directory_id)
1886 notmuch_directory_t *directory;
1887 notmuch_status_t status;
1891 return NOTMUCH_STATUS_SUCCESS;
1894 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1895 if (status || !directory) {
1900 *directory_id = _notmuch_directory_get_document_id (directory);
1902 notmuch_directory_destroy (directory);
1904 return NOTMUCH_STATUS_SUCCESS;
1908 _notmuch_database_get_directory_path (void *ctx,
1909 notmuch_database_t *notmuch,
1910 unsigned int doc_id)
1912 Xapian::Document document;
1914 document = find_document_for_doc_id (notmuch, doc_id);
1916 return talloc_strdup (ctx, document.get_data ().c_str ());
1919 /* Given a legal 'filename' for the database, (either relative to
1920 * database path or absolute with initial components identical to
1921 * database path), return a new string (with 'ctx' as the talloc
1922 * owner) suitable for use as a direntry term value.
1924 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1925 * will be created in the database as needed. Otherwise, if the
1926 * necessary directory documents do not exist, this sets
1927 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1930 _notmuch_database_filename_to_direntry (void *ctx,
1931 notmuch_database_t *notmuch,
1932 const char *filename,
1933 notmuch_find_flags_t flags,
1936 const char *relative, *directory, *basename;
1937 Xapian::docid directory_id;
1938 notmuch_status_t status;
1940 relative = _notmuch_database_relative_path (notmuch, filename);
1942 status = _notmuch_database_split_path (ctx, relative,
1943 &directory, &basename);
1947 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1949 if (status || directory_id == (unsigned int)-1) {
1954 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1956 return NOTMUCH_STATUS_SUCCESS;
1959 /* Given a legal 'path' for the database, return the relative path.
1961 * The return value will be a pointer to the original path contents,
1962 * and will be either the original string (if 'path' was relative) or
1963 * a portion of the string (if path was absolute and begins with the
1967 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1970 const char *db_path, *relative;
1971 unsigned int db_path_len;
1973 db_path = notmuch_database_get_path (notmuch);
1974 db_path_len = strlen (db_path);
1978 if (*relative == '/') {
1979 while (*relative == '/' && *(relative+1) == '/')
1982 if (strncmp (relative, db_path, db_path_len) == 0)
1984 relative += db_path_len;
1985 while (*relative == '/')
1994 notmuch_database_get_directory (notmuch_database_t *notmuch,
1996 notmuch_directory_t **directory)
1998 notmuch_status_t status;
2000 if (directory == NULL)
2001 return NOTMUCH_STATUS_NULL_POINTER;
2005 *directory = _notmuch_directory_create (notmuch, path,
2006 NOTMUCH_FIND_LOOKUP, &status);
2007 } catch (const Xapian::Error &error) {
2008 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
2009 error.get_msg().c_str());
2010 notmuch->exception_reported = TRUE;
2011 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2016 /* Allocate a document ID that satisfies the following criteria:
2018 * 1. The ID does not exist for any document in the Xapian database
2020 * 2. The ID was not previously returned from this function
2022 * 3. The ID is the smallest integer satisfying (1) and (2)
2024 * This function will trigger an internal error if these constraints
2025 * cannot all be satisfied, (that is, the pool of available document
2026 * IDs has been exhausted).
2029 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2031 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2033 notmuch->last_doc_id++;
2035 if (notmuch->last_doc_id == 0)
2036 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2038 return notmuch->last_doc_id;
2042 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
2044 /* 16 bytes (+ terminator) for hexadecimal representation of
2045 * a 64-bit integer. */
2046 static char thread_id[17];
2047 Xapian::WritableDatabase *db;
2049 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2051 notmuch->last_thread_id++;
2053 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2055 db->set_metadata ("last_thread_id", thread_id);
2061 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2063 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2064 message_id = _notmuch_message_id_compressed (ctx, message_id);
2066 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2070 static notmuch_status_t
2071 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2073 const char *message_id,
2074 const char **thread_id_ret);
2076 /* Find the thread ID to which the message with 'message_id' belongs.
2078 * Note: 'thread_id_ret' must not be NULL!
2079 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2082 * Note: If there is no message in the database with the given
2083 * 'message_id' then a new thread_id will be allocated for this
2084 * message ID and stored in the database metadata so that the
2085 * thread ID can be looked up if the message is added to the database
2088 static notmuch_status_t
2089 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2091 const char *message_id,
2092 const char **thread_id_ret)
2094 notmuch_private_status_t status;
2095 notmuch_message_t *message;
2097 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2098 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2101 /* Look for this message (regular or ghost) */
2102 message = _notmuch_message_create_for_message_id (
2103 notmuch, message_id, &status);
2104 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2105 /* Message exists */
2106 *thread_id_ret = talloc_steal (
2107 ctx, notmuch_message_get_thread_id (message));
2108 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2109 /* Message did not exist. Give it a fresh thread ID and
2110 * populate this message as a ghost message. */
2111 *thread_id_ret = talloc_strdup (
2112 ctx, _notmuch_database_generate_thread_id (notmuch));
2113 if (! *thread_id_ret) {
2114 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2116 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2118 /* Commit the new ghost message */
2119 _notmuch_message_sync (message);
2122 /* Create failed. Fall through. */
2125 notmuch_message_destroy (message);
2127 return COERCE_STATUS (status, "Error creating ghost message");
2130 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2131 static notmuch_status_t
2132 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2134 const char *message_id,
2135 const char **thread_id_ret)
2137 notmuch_status_t status;
2138 notmuch_message_t *message;
2139 string thread_id_string;
2141 Xapian::WritableDatabase *db;
2143 status = notmuch_database_find_message (notmuch, message_id, &message);
2149 *thread_id_ret = talloc_steal (ctx,
2150 notmuch_message_get_thread_id (message));
2152 notmuch_message_destroy (message);
2154 return NOTMUCH_STATUS_SUCCESS;
2157 /* Message has not been seen yet.
2159 * We may have seen a reference to it already, in which case, we
2160 * can return the thread ID stored in the metadata. Otherwise, we
2161 * generate a new thread ID and store it there.
2163 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2164 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2165 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2167 if (thread_id_string.empty()) {
2168 *thread_id_ret = talloc_strdup (ctx,
2169 _notmuch_database_generate_thread_id (notmuch));
2170 db->set_metadata (metadata_key, *thread_id_ret);
2172 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2175 talloc_free (metadata_key);
2177 return NOTMUCH_STATUS_SUCCESS;
2180 static notmuch_status_t
2181 _merge_threads (notmuch_database_t *notmuch,
2182 const char *winner_thread_id,
2183 const char *loser_thread_id)
2185 Xapian::PostingIterator loser, loser_end;
2186 notmuch_message_t *message = NULL;
2187 notmuch_private_status_t private_status;
2188 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2190 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2192 for ( ; loser != loser_end; loser++) {
2193 message = _notmuch_message_create (notmuch, notmuch,
2194 *loser, &private_status);
2195 if (message == NULL) {
2196 ret = COERCE_STATUS (private_status,
2197 "Cannot find document for doc_id from query");
2201 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2202 _notmuch_message_add_term (message, "thread", winner_thread_id);
2203 _notmuch_message_sync (message);
2205 notmuch_message_destroy (message);
2211 notmuch_message_destroy (message);
2217 _my_talloc_free_for_g_hash (void *ptr)
2222 static notmuch_status_t
2223 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2224 notmuch_message_t *message,
2225 notmuch_message_file_t *message_file,
2226 const char **thread_id)
2228 GHashTable *parents = NULL;
2229 const char *refs, *in_reply_to, *in_reply_to_message_id;
2230 const char *last_ref_message_id, *this_message_id;
2231 GList *l, *keys = NULL;
2232 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2234 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2235 _my_talloc_free_for_g_hash, NULL);
2236 this_message_id = notmuch_message_get_message_id (message);
2238 refs = _notmuch_message_file_get_header (message_file, "references");
2239 last_ref_message_id = parse_references (message,
2243 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2244 in_reply_to_message_id = parse_references (message,
2246 parents, in_reply_to);
2248 /* For the parent of this message, use the last message ID of the
2249 * References header, if available. If not, fall back to the
2250 * first message ID in the In-Reply-To header. */
2251 if (last_ref_message_id) {
2252 _notmuch_message_add_term (message, "replyto",
2253 last_ref_message_id);
2254 } else if (in_reply_to_message_id) {
2255 _notmuch_message_add_term (message, "replyto",
2256 in_reply_to_message_id);
2259 keys = g_hash_table_get_keys (parents);
2260 for (l = keys; l; l = l->next) {
2261 char *parent_message_id;
2262 const char *parent_thread_id = NULL;
2264 parent_message_id = (char *) l->data;
2266 _notmuch_message_add_term (message, "reference",
2269 ret = _resolve_message_id_to_thread_id (notmuch,
2276 if (*thread_id == NULL) {
2277 *thread_id = talloc_strdup (message, parent_thread_id);
2278 _notmuch_message_add_term (message, "thread", *thread_id);
2279 } else if (strcmp (*thread_id, parent_thread_id)) {
2280 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2290 g_hash_table_unref (parents);
2295 static notmuch_status_t
2296 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2297 notmuch_message_t *message,
2298 const char **thread_id)
2300 const char *message_id = notmuch_message_get_message_id (message);
2301 Xapian::PostingIterator child, children_end;
2302 notmuch_message_t *child_message = NULL;
2303 const char *child_thread_id;
2304 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2305 notmuch_private_status_t private_status;
2307 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2309 for ( ; child != children_end; child++) {
2311 child_message = _notmuch_message_create (message, notmuch,
2312 *child, &private_status);
2313 if (child_message == NULL) {
2314 ret = COERCE_STATUS (private_status,
2315 "Cannot find document for doc_id from query");
2319 child_thread_id = notmuch_message_get_thread_id (child_message);
2320 if (*thread_id == NULL) {
2321 *thread_id = talloc_strdup (message, child_thread_id);
2322 _notmuch_message_add_term (message, "thread", *thread_id);
2323 } else if (strcmp (*thread_id, child_thread_id)) {
2324 _notmuch_message_remove_term (child_message, "reference",
2326 _notmuch_message_sync (child_message);
2327 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2332 notmuch_message_destroy (child_message);
2333 child_message = NULL;
2338 notmuch_message_destroy (child_message);
2343 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2345 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2346 notmuch_message_t *message)
2348 const char *message_id;
2352 message_id = notmuch_message_get_message_id (message);
2353 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2355 /* Check if we have already seen related messages to this one.
2356 * If we have then use the thread_id that we stored at that time.
2358 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2359 if (stored_id.empty ()) {
2362 Xapian::WritableDatabase *db;
2364 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2366 /* Clear the metadata for this message ID. We don't need it
2368 db->set_metadata (metadata_key, "");
2370 return talloc_strdup (ctx, stored_id.c_str ());
2374 /* Given a blank or ghost 'message' and its corresponding
2375 * 'message_file' link it to existing threads in the database.
2377 * First, if is_ghost, this retrieves the thread ID already stored in
2378 * the message (which will be the case if a message was previously
2379 * added that referenced this one). If the message is blank
2380 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2381 * later in this function). If the database does not support ghost
2382 * messages, this checks for a thread ID stored in database metadata
2383 * for this message ID.
2385 * Second, we look at 'message_file' and its link-relevant headers
2386 * (References and In-Reply-To) for message IDs.
2388 * Finally, we look in the database for existing message that
2389 * reference 'message'.
2391 * In all cases, we assign to the current message the first thread ID
2392 * found. We will also merge any existing, distinct threads where this
2393 * message belongs to both, (which is not uncommon when messages are
2394 * processed out of order).
2396 * Finally, if no thread ID has been found through referenced messages, we
2397 * call _notmuch_message_generate_thread_id to generate a new thread
2398 * ID. This should only happen for new, top-level messages, (no
2399 * References or In-Reply-To header in this message, and no previously
2400 * added message refers to this message).
2402 static notmuch_status_t
2403 _notmuch_database_link_message (notmuch_database_t *notmuch,
2404 notmuch_message_t *message,
2405 notmuch_message_file_t *message_file,
2406 notmuch_bool_t is_ghost)
2408 void *local = talloc_new (NULL);
2409 notmuch_status_t status;
2410 const char *thread_id = NULL;
2412 /* Check if the message already had a thread ID */
2413 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2415 thread_id = notmuch_message_get_thread_id (message);
2417 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2419 _notmuch_message_add_term (message, "thread", thread_id);
2422 status = _notmuch_database_link_message_to_parents (notmuch, message,
2428 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2429 /* In general, it shouldn't be necessary to link children,
2430 * since the earlier indexing of those children will have
2431 * stored a thread ID for the missing parent. However, prior
2432 * to ghost messages, these stored thread IDs were NOT
2433 * rewritten during thread merging (and there was no
2434 * performant way to do so), so if indexed children were
2435 * pulled into a different thread ID by a merge, it was
2436 * necessary to pull them *back* into the stored thread ID of
2437 * the parent. With ghost messages, we just rewrite the
2438 * stored thread IDs during merging, so this workaround isn't
2440 status = _notmuch_database_link_message_to_children (notmuch, message,
2446 /* If not part of any existing thread, generate a new thread ID. */
2447 if (thread_id == NULL) {
2448 thread_id = _notmuch_database_generate_thread_id (notmuch);
2450 _notmuch_message_add_term (message, "thread", thread_id);
2454 talloc_free (local);
2460 notmuch_database_add_message (notmuch_database_t *notmuch,
2461 const char *filename,
2462 notmuch_message_t **message_ret)
2464 notmuch_message_file_t *message_file;
2465 notmuch_message_t *message = NULL;
2466 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2467 notmuch_private_status_t private_status;
2468 notmuch_bool_t is_ghost = false;
2470 const char *date, *header;
2471 const char *from, *to, *subject;
2472 char *message_id = NULL;
2475 *message_ret = NULL;
2477 ret = _notmuch_database_ensure_writable (notmuch);
2481 message_file = _notmuch_message_file_open (notmuch, filename);
2482 if (message_file == NULL)
2483 return NOTMUCH_STATUS_FILE_ERROR;
2485 /* Adding a message may change many documents. Do this all
2487 ret = notmuch_database_begin_atomic (notmuch);
2491 /* Parse message up front to get better error status. */
2492 ret = _notmuch_message_file_parse (message_file);
2496 /* Before we do any real work, (especially before doing a
2497 * potential SHA-1 computation on the entire file's contents),
2498 * let's make sure that what we're looking at looks like an
2499 * actual email message.
2501 from = _notmuch_message_file_get_header (message_file, "from");
2502 subject = _notmuch_message_file_get_header (message_file, "subject");
2503 to = _notmuch_message_file_get_header (message_file, "to");
2505 if ((from == NULL || *from == '\0') &&
2506 (subject == NULL || *subject == '\0') &&
2507 (to == NULL || *to == '\0')) {
2508 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2512 /* Now that we're sure it's mail, the first order of business
2513 * is to find a message ID (or else create one ourselves).
2515 header = _notmuch_message_file_get_header (message_file, "message-id");
2516 if (header && *header != '\0') {
2517 message_id = _parse_message_id (message_file, header, NULL);
2519 /* So the header value isn't RFC-compliant, but it's
2520 * better than no message-id at all.
2522 if (message_id == NULL)
2523 message_id = talloc_strdup (message_file, header);
2526 if (message_id == NULL ) {
2527 /* No message-id at all, let's generate one by taking a
2528 * hash over the file's contents.
2530 char *sha1 = _notmuch_sha1_of_file (filename);
2532 /* If that failed too, something is really wrong. Give up. */
2534 ret = NOTMUCH_STATUS_FILE_ERROR;
2538 message_id = talloc_asprintf (message_file, "notmuch-sha1-%s", sha1);
2543 /* Now that we have a message ID, we get a message object,
2544 * (which may or may not reference an existing document in the
2547 message = _notmuch_message_create_for_message_id (notmuch,
2551 talloc_free (message_id);
2553 if (message == NULL) {
2554 ret = COERCE_STATUS (private_status,
2555 "Unexpected status value from _notmuch_message_create_for_message_id");
2559 _notmuch_message_add_filename (message, filename);
2561 /* Is this a newly created message object or a ghost
2562 * message? We have to be slightly careful: if this is a
2563 * blank message, it's not safe to call
2564 * notmuch_message_get_flag yet. */
2565 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2566 (is_ghost = notmuch_message_get_flag (
2567 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2568 _notmuch_message_add_term (message, "type", "mail");
2570 /* Convert ghost message to a regular message */
2571 _notmuch_message_remove_term (message, "type", "ghost");
2573 ret = _notmuch_database_link_message (notmuch, message,
2574 message_file, is_ghost);
2578 date = _notmuch_message_file_get_header (message_file, "date");
2579 _notmuch_message_set_header_values (message, date, from, subject);
2581 ret = _notmuch_message_index_file (message, message_file);
2585 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2588 _notmuch_message_sync (message);
2589 } catch (const Xapian::Error &error) {
2590 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2591 error.get_msg().c_str());
2592 notmuch->exception_reported = TRUE;
2593 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2599 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2600 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2601 *message_ret = message;
2603 notmuch_message_destroy (message);
2607 _notmuch_message_file_close (message_file);
2609 ret2 = notmuch_database_end_atomic (notmuch);
2610 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2611 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2612 ret2 != NOTMUCH_STATUS_SUCCESS)
2619 notmuch_database_remove_message (notmuch_database_t *notmuch,
2620 const char *filename)
2622 notmuch_status_t status;
2623 notmuch_message_t *message;
2625 status = notmuch_database_find_message_by_filename (notmuch, filename,
2628 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2629 status = _notmuch_message_remove_filename (message, filename);
2630 if (status == NOTMUCH_STATUS_SUCCESS)
2631 _notmuch_message_delete (message);
2632 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2633 _notmuch_message_sync (message);
2635 notmuch_message_destroy (message);
2642 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2643 const char *filename,
2644 notmuch_message_t **message_ret)
2647 const char *prefix = _find_prefix ("file-direntry");
2648 char *direntry, *term;
2649 Xapian::PostingIterator i, end;
2650 notmuch_status_t status;
2652 if (message_ret == NULL)
2653 return NOTMUCH_STATUS_NULL_POINTER;
2655 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2656 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2658 /* return NULL on any failure */
2659 *message_ret = NULL;
2661 local = talloc_new (notmuch);
2664 status = _notmuch_database_filename_to_direntry (
2665 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2666 if (status || !direntry)
2669 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2671 find_doc_ids_for_term (notmuch, term, &i, &end);
2674 notmuch_private_status_t private_status;
2676 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2678 if (*message_ret == NULL)
2679 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2681 } catch (const Xapian::Error &error) {
2682 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2683 error.get_msg().c_str());
2684 notmuch->exception_reported = TRUE;
2685 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2689 talloc_free (local);
2691 if (status && *message_ret) {
2692 notmuch_message_destroy (*message_ret);
2693 *message_ret = NULL;
2698 notmuch_string_list_t *
2699 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2700 Xapian::TermIterator &end,
2703 int prefix_len = strlen (prefix);
2704 notmuch_string_list_t *list;
2706 list = _notmuch_string_list_create (ctx);
2707 if (unlikely (list == NULL))
2710 for (i.skip_to (prefix); i != end; i++) {
2711 /* Terminate loop at first term without desired prefix. */
2712 if (strncmp ((*i).c_str (), prefix, prefix_len))
2715 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2722 notmuch_database_get_all_tags (notmuch_database_t *db)
2724 Xapian::TermIterator i, end;
2725 notmuch_string_list_t *tags;
2728 i = db->xapian_db->allterms_begin();
2729 end = db->xapian_db->allterms_end();
2730 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2731 _find_prefix ("tag"));
2732 _notmuch_string_list_sort (tags);
2733 return _notmuch_tags_create (db, tags);
2734 } catch (const Xapian::Error &error) {
2735 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2736 error.get_msg().c_str());
2737 db->exception_reported = TRUE;
2743 notmuch_database_status_string (const notmuch_database_t *notmuch)
2745 return notmuch->status_string;