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 NOTMUCH_FIELD_PROCESSOR },
264 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
265 NOTMUCH_FIELD_PROCESSOR },
266 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
267 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
268 NOTMUCH_FIELD_PROCESSOR },
269 { "path", "P", NOTMUCH_FIELD_EXTERNAL|
270 NOTMUCH_FIELD_PROCESSOR },
271 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
273 * Unconditionally add ':' to reduce potential ambiguity with
274 * overlapping prefixes and/or terms that start with capital
275 * letters. See Xapian document termprefixes.html for related
278 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
279 NOTMUCH_FIELD_PROCESSOR },
280 #if HAVE_XAPIAN_FIELD_PROCESSOR
281 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
282 NOTMUCH_FIELD_PROCESSOR },
283 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
284 NOTMUCH_FIELD_PROCESSOR },
286 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
287 NOTMUCH_FIELD_PROBABILISTIC |
288 NOTMUCH_FIELD_PROCESSOR },
289 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
290 NOTMUCH_FIELD_PROBABILISTIC },
291 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
292 NOTMUCH_FIELD_PROBABILISTIC },
293 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
294 NOTMUCH_FIELD_PROBABILISTIC },
295 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
296 NOTMUCH_FIELD_PROBABILISTIC |
297 NOTMUCH_FIELD_PROCESSOR},
301 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
303 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
304 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
306 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
309 #if HAVE_XAPIAN_FIELD_PROCESSOR
311 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
313 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
314 Xapian::FieldProcessor *fp;
316 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
317 fp = (new DateFieldProcessor())->release ();
318 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
319 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
321 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
322 *notmuch->query_parser, notmuch))->release ();
324 /* we treat all field-processor fields as boolean in order to get the raw input */
325 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
327 _setup_query_field_default (prefix, notmuch);
332 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
334 _setup_query_field_default (prefix, notmuch);
339 _find_prefix (const char *name)
343 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
344 if (strcmp (name, prefix_table[i].name) == 0)
345 return prefix_table[i].prefix;
348 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
353 static const struct {
354 /* NOTMUCH_FEATURE_* value. */
355 _notmuch_features value;
356 /* Feature name as it appears in the database. This name should
357 * be appropriate for displaying to the user if an older version
358 * of notmuch doesn't support this feature. */
360 /* Compatibility flags when this feature is declared. */
362 } feature_names[] = {
363 { NOTMUCH_FEATURE_FILE_TERMS,
364 "multiple paths per message", "rw" },
365 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
366 "relative directory paths", "rw" },
367 /* Header values are not required for reading a database because a
368 * reader can just refer to the message file. */
369 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
370 "from/subject/message-ID in database", "w" },
371 { NOTMUCH_FEATURE_BOOL_FOLDER,
372 "exact folder:/path: search", "rw" },
373 { NOTMUCH_FEATURE_GHOSTS,
374 "mail documents for missing messages", "w"},
375 /* Knowledge of the index mime-types are not required for reading
376 * a database because a reader will just be unable to query
378 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
379 "indexed MIME types", "w"},
380 { NOTMUCH_FEATURE_LAST_MOD,
381 "modification tracking", "w"},
385 notmuch_status_to_string (notmuch_status_t status)
388 case NOTMUCH_STATUS_SUCCESS:
389 return "No error occurred";
390 case NOTMUCH_STATUS_OUT_OF_MEMORY:
391 return "Out of memory";
392 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
393 return "Attempt to write to a read-only database";
394 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
395 return "A Xapian exception occurred";
396 case NOTMUCH_STATUS_FILE_ERROR:
397 return "Something went wrong trying to read or write a file";
398 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
399 return "File is not an email";
400 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
401 return "Message ID is identical to a message in database";
402 case NOTMUCH_STATUS_NULL_POINTER:
403 return "Erroneous NULL pointer";
404 case NOTMUCH_STATUS_TAG_TOO_LONG:
405 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
406 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
407 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
408 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
409 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
410 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
411 return "Unsupported operation";
412 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
413 return "Operation requires a database upgrade";
414 case NOTMUCH_STATUS_PATH_ERROR:
415 return "Path supplied is illegal for this function";
417 case NOTMUCH_STATUS_LAST_STATUS:
418 return "Unknown error status value";
423 _notmuch_database_log (notmuch_database_t *notmuch,
429 va_start (va_args, format);
431 if (notmuch->status_string)
432 talloc_free (notmuch->status_string);
434 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
439 _notmuch_database_log_append (notmuch_database_t *notmuch,
445 va_start (va_args, format);
447 if (notmuch->status_string)
448 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
450 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
456 find_doc_ids_for_term (notmuch_database_t *notmuch,
458 Xapian::PostingIterator *begin,
459 Xapian::PostingIterator *end)
461 *begin = notmuch->xapian_db->postlist_begin (term);
463 *end = notmuch->xapian_db->postlist_end (term);
467 find_doc_ids (notmuch_database_t *notmuch,
468 const char *prefix_name,
470 Xapian::PostingIterator *begin,
471 Xapian::PostingIterator *end)
475 term = talloc_asprintf (notmuch, "%s%s",
476 _find_prefix (prefix_name), value);
478 find_doc_ids_for_term (notmuch, term, begin, end);
483 notmuch_private_status_t
484 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
485 const char *prefix_name,
487 unsigned int *doc_id)
489 Xapian::PostingIterator i, end;
491 find_doc_ids (notmuch, prefix_name, value, &i, &end);
495 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
500 #if DEBUG_DATABASE_SANITY
504 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
508 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
511 static Xapian::Document
512 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
514 return notmuch->xapian_db->get_document (doc_id);
517 /* Generate a compressed version of 'message_id' of the form:
519 * notmuch-sha1-<sha1_sum_of_message_id>
522 _notmuch_message_id_compressed (void *ctx, const char *message_id)
524 char *sha1, *compressed;
526 sha1 = _notmuch_sha1_of_string (message_id);
528 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
535 notmuch_database_find_message (notmuch_database_t *notmuch,
536 const char *message_id,
537 notmuch_message_t **message_ret)
539 notmuch_private_status_t status;
542 if (message_ret == NULL)
543 return NOTMUCH_STATUS_NULL_POINTER;
545 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
546 message_id = _notmuch_message_id_compressed (notmuch, message_id);
549 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
550 message_id, &doc_id);
552 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
555 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
557 if (*message_ret == NULL)
558 return NOTMUCH_STATUS_OUT_OF_MEMORY;
561 return NOTMUCH_STATUS_SUCCESS;
562 } catch (const Xapian::Error &error) {
563 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
564 error.get_msg().c_str());
565 notmuch->exception_reported = TRUE;
567 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
571 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
572 * a (potentially nested) parenthesized sequence with '\' used to
573 * escape any character (including parentheses).
575 * If the sequence to be skipped continues to the end of the string,
576 * then 'str' will be left pointing at the final terminating '\0'
580 skip_space_and_comments (const char **str)
585 while (*s && (isspace (*s) || *s == '(')) {
586 while (*s && isspace (*s))
591 while (*s && nesting) {
594 } else if (*s == ')') {
596 } else if (*s == '\\') {
608 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
609 * comments, and the '<' and '>' delimiters.
611 * If not NULL, then *next will be made to point to the first character
612 * not parsed, (possibly pointing to the final '\0' terminator.
614 * Returns a newly talloc'ed string belonging to 'ctx'.
616 * Returns NULL if there is any error parsing the message-id. */
618 _parse_message_id (void *ctx, const char *message_id, const char **next)
623 if (message_id == NULL || *message_id == '\0')
628 skip_space_and_comments (&s);
630 /* Skip any unstructured text as well. */
631 while (*s && *s != '<')
642 skip_space_and_comments (&s);
645 while (*end && *end != '>')
654 if (end > s && *end == '>')
659 result = talloc_strndup (ctx, s, end - s + 1);
661 /* Finally, collapse any whitespace that is within the message-id
667 for (r = result, len = strlen (r); *r; r++, len--)
668 if (*r == ' ' || *r == '\t')
669 memmove (r, r+1, len);
675 /* Parse a References header value, putting a (talloc'ed under 'ctx')
676 * copy of each referenced message-id into 'hash'.
678 * We explicitly avoid including any reference identical to
679 * 'message_id' in the result (to avoid mass confusion when a single
680 * message references itself cyclically---and yes, mail messages are
681 * not infrequent in the wild that do this---don't ask me why).
683 * Return the last reference parsed, if it is not equal to message_id.
686 parse_references (void *ctx,
687 const char *message_id,
691 char *ref, *last_ref = NULL;
693 if (refs == NULL || *refs == '\0')
697 ref = _parse_message_id (ctx, refs, &refs);
699 if (ref && strcmp (ref, message_id)) {
700 g_hash_table_add (hash, ref);
705 /* The return value of this function is used to add a parent
706 * reference to the database. We should avoid making a message
707 * its own parent, thus the above check.
709 return talloc_strdup(ctx, last_ref);
713 notmuch_database_create (const char *path, notmuch_database_t **database)
715 char *status_string = NULL;
716 notmuch_status_t status;
718 status = notmuch_database_create_verbose (path, database,
722 fputs (status_string, stderr);
723 free (status_string);
730 notmuch_database_create_verbose (const char *path,
731 notmuch_database_t **database,
732 char **status_string)
734 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
735 notmuch_database_t *notmuch = NULL;
736 char *notmuch_path = NULL;
737 char *message = NULL;
742 message = strdup ("Error: Cannot create a database for a NULL path.\n");
743 status = NOTMUCH_STATUS_NULL_POINTER;
747 if (path[0] != '/') {
748 message = strdup ("Error: Database path must be absolute.\n");
749 status = NOTMUCH_STATUS_PATH_ERROR;
753 err = stat (path, &st);
755 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
756 path, strerror (errno)));
757 status = NOTMUCH_STATUS_FILE_ERROR;
761 if (! S_ISDIR (st.st_mode)) {
762 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
763 "Not a directory.\n",
765 status = NOTMUCH_STATUS_FILE_ERROR;
769 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
771 err = mkdir (notmuch_path, 0755);
774 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
775 notmuch_path, strerror (errno)));
776 status = NOTMUCH_STATUS_FILE_ERROR;
780 status = notmuch_database_open_verbose (path,
781 NOTMUCH_DATABASE_MODE_READ_WRITE,
786 /* Upgrade doesn't add these feature to existing databases, but
787 * new databases have them. */
788 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
789 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
791 status = notmuch_database_upgrade (notmuch, NULL, NULL);
793 notmuch_database_close(notmuch);
799 talloc_free (notmuch_path);
803 *status_string = message;
810 talloc_free (notmuch);
815 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
817 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
818 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
819 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
822 return NOTMUCH_STATUS_SUCCESS;
825 /* Allocate a revision number for the next change. */
827 _notmuch_database_new_revision (notmuch_database_t *notmuch)
829 unsigned long new_revision = notmuch->revision + 1;
831 /* If we're in an atomic section, hold off on updating the
832 * committed revision number until we commit the atomic section.
834 if (notmuch->atomic_nesting)
835 notmuch->atomic_dirty = TRUE;
837 notmuch->revision = new_revision;
842 /* Parse a database features string from the given database version.
843 * Returns the feature bit set.
845 * For version < 3, this ignores the features string and returns a
846 * hard-coded set of features.
848 * If there are unrecognized features that are required to open the
849 * database in mode (which should be 'r' or 'w'), return a
850 * comma-separated list of unrecognized but required features in
851 * *incompat_out suitable for presenting to the user. *incompat_out
852 * will be allocated from ctx.
854 static _notmuch_features
855 _parse_features (const void *ctx, const char *features, unsigned int version,
856 char mode, char **incompat_out)
858 _notmuch_features res = static_cast<_notmuch_features>(0);
859 unsigned int namelen, i;
863 /* Prior to database version 3, features were implied by the
866 return NOTMUCH_FEATURES_V0;
867 else if (version == 1)
868 return NOTMUCH_FEATURES_V1;
869 else if (version == 2)
870 return NOTMUCH_FEATURES_V2;
872 /* Parse the features string */
873 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
874 flags = strchr (features, '\t');
875 if (! flags || flags > features + llen)
877 namelen = flags - features;
879 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
880 if (strlen (feature_names[i].name) == namelen &&
881 strncmp (feature_names[i].name, features, namelen) == 0) {
882 res |= feature_names[i].value;
887 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
888 /* Unrecognized feature */
889 const char *have = strchr (flags, mode);
890 if (have && have < features + llen) {
891 /* This feature is required to access this database in
892 * 'mode', but we don't understand it. */
894 *incompat_out = talloc_strdup (ctx, "");
895 *incompat_out = talloc_asprintf_append_buffer (
896 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
906 _print_features (const void *ctx, unsigned int features)
909 char *res = talloc_strdup (ctx, "");
911 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
912 if (features & feature_names[i].value)
913 res = talloc_asprintf_append_buffer (
914 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
920 notmuch_database_open (const char *path,
921 notmuch_database_mode_t mode,
922 notmuch_database_t **database)
924 char *status_string = NULL;
925 notmuch_status_t status;
927 status = notmuch_database_open_verbose (path, mode, database,
931 fputs (status_string, stderr);
932 free (status_string);
939 notmuch_database_open_verbose (const char *path,
940 notmuch_database_mode_t mode,
941 notmuch_database_t **database,
942 char **status_string)
944 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
945 void *local = talloc_new (NULL);
946 notmuch_database_t *notmuch = NULL;
947 char *notmuch_path, *xapian_path, *incompat_features;
948 char *message = NULL;
951 unsigned int i, version;
952 static int initialized = 0;
955 message = strdup ("Error: Cannot open a database for a NULL path.\n");
956 status = NOTMUCH_STATUS_NULL_POINTER;
960 if (path[0] != '/') {
961 message = strdup ("Error: Database path must be absolute.\n");
962 status = NOTMUCH_STATUS_PATH_ERROR;
966 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
967 message = strdup ("Out of memory\n");
968 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
972 err = stat (notmuch_path, &st);
974 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
975 notmuch_path, strerror (errno)));
976 status = NOTMUCH_STATUS_FILE_ERROR;
980 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
981 message = strdup ("Out of memory\n");
982 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
986 /* Initialize the GLib type system and threads */
987 #if !GLIB_CHECK_VERSION(2, 35, 1)
991 /* Initialize gmime */
993 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
997 notmuch = talloc_zero (NULL, notmuch_database_t);
998 notmuch->exception_reported = FALSE;
999 notmuch->status_string = NULL;
1000 notmuch->path = talloc_strdup (notmuch, path);
1002 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
1003 notmuch->path[strlen (notmuch->path) - 1] = '\0';
1005 notmuch->mode = mode;
1006 notmuch->atomic_nesting = 0;
1009 string last_thread_id;
1012 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
1013 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
1016 notmuch->xapian_db = new Xapian::Database (xapian_path);
1019 /* Check version. As of database version 3, we represent
1020 * changes in terms of features, so assume a version bump
1021 * means a dramatically incompatible change. */
1022 version = notmuch_database_get_version (notmuch);
1023 if (version > NOTMUCH_DATABASE_VERSION) {
1024 IGNORE_RESULT (asprintf (&message,
1025 "Error: Notmuch database at %s\n"
1026 " has a newer database format version (%u) than supported by this\n"
1027 " version of notmuch (%u).\n",
1028 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
1029 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1030 notmuch_database_destroy (notmuch);
1032 status = NOTMUCH_STATUS_FILE_ERROR;
1036 /* Check features. */
1037 incompat_features = NULL;
1038 notmuch->features = _parse_features (
1039 local, notmuch->xapian_db->get_metadata ("features").c_str (),
1040 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1041 &incompat_features);
1042 if (incompat_features) {
1043 IGNORE_RESULT (asprintf (&message,
1044 "Error: Notmuch database at %s\n"
1045 " requires features (%s)\n"
1046 " not supported by this version of notmuch.\n",
1047 notmuch_path, incompat_features));
1048 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1049 notmuch_database_destroy (notmuch);
1051 status = NOTMUCH_STATUS_FILE_ERROR;
1055 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1056 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1057 if (last_thread_id.empty ()) {
1058 notmuch->last_thread_id = 0;
1063 str = last_thread_id.c_str ();
1064 notmuch->last_thread_id = strtoull (str, &end, 16);
1066 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1069 /* Get current highest revision number. */
1070 last_mod = notmuch->xapian_db->get_value_upper_bound (
1071 NOTMUCH_VALUE_LAST_MOD);
1072 if (last_mod.empty ())
1073 notmuch->revision = 0;
1075 notmuch->revision = Xapian::sortable_unserialise (last_mod);
1076 notmuch->uuid = talloc_strdup (
1077 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1079 notmuch->query_parser = new Xapian::QueryParser;
1080 notmuch->term_gen = new Xapian::TermGenerator;
1081 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1082 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1083 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1084 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1086 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1087 notmuch->query_parser->set_database (*notmuch->xapian_db);
1088 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1089 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1090 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1091 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1092 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1094 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1095 const prefix_t *prefix = &prefix_table[i];
1096 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1097 _setup_query_field (prefix, notmuch);
1100 } catch (const Xapian::Error &error) {
1101 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1102 error.get_msg().c_str()));
1103 notmuch_database_destroy (notmuch);
1105 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1109 talloc_free (local);
1113 *status_string = message;
1119 *database = notmuch;
1121 talloc_free (notmuch);
1126 notmuch_database_close (notmuch_database_t *notmuch)
1128 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1130 /* Many Xapian objects (and thus notmuch objects) hold references to
1131 * the database, so merely deleting the database may not suffice to
1132 * close it. Thus, we explicitly close it here. */
1133 if (notmuch->xapian_db != NULL) {
1135 /* If there's an outstanding transaction, it's unclear if
1136 * closing the Xapian database commits everything up to
1137 * that transaction, or may discard committed (but
1138 * unflushed) transactions. To be certain, explicitly
1139 * cancel any outstanding transaction before closing. */
1140 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1141 notmuch->atomic_nesting)
1142 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1143 ->cancel_transaction ();
1145 /* Close the database. This implicitly flushes
1146 * outstanding changes. */
1147 notmuch->xapian_db->close();
1148 } catch (const Xapian::Error &error) {
1149 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1150 if (! notmuch->exception_reported) {
1151 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1152 error.get_msg().c_str());
1157 delete notmuch->term_gen;
1158 notmuch->term_gen = NULL;
1159 delete notmuch->query_parser;
1160 notmuch->query_parser = NULL;
1161 delete notmuch->xapian_db;
1162 notmuch->xapian_db = NULL;
1163 delete notmuch->value_range_processor;
1164 notmuch->value_range_processor = NULL;
1165 delete notmuch->date_range_processor;
1166 notmuch->date_range_processor = NULL;
1167 delete notmuch->last_mod_range_processor;
1168 notmuch->last_mod_range_processor = NULL;
1174 _notmuch_database_reopen (notmuch_database_t *notmuch)
1176 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1177 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1180 notmuch->xapian_db->reopen ();
1181 } catch (const Xapian::Error &error) {
1182 if (! notmuch->exception_reported) {
1183 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1184 error.get_msg ().c_str ());
1185 notmuch->exception_reported = TRUE;
1187 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1192 return NOTMUCH_STATUS_SUCCESS;
1196 unlink_cb (const char *path,
1197 unused (const struct stat *sb),
1199 unused (struct FTW *ftw))
1201 return remove (path);
1205 rmtree (const char *path)
1207 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1210 class NotmuchCompactor : public Xapian::Compactor
1212 notmuch_compact_status_cb_t status_cb;
1213 void *status_closure;
1216 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1217 status_cb (cb), status_closure (closure) { }
1220 set_status (const std::string &table, const std::string &status)
1224 if (status_cb == NULL)
1227 if (status.length () == 0)
1228 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1230 msg = talloc_asprintf (NULL, " %s", status.c_str());
1236 status_cb (msg, status_closure);
1241 /* Compacts the given database, optionally saving the original database
1242 * in backup_path. Additionally, a callback function can be provided to
1243 * give the user feedback on the progress of the (likely long-lived)
1244 * compaction process.
1246 * The backup path must point to a directory on the same volume as the
1247 * original database. Passing a NULL backup_path will result in the
1248 * uncompacted database being deleted after compaction has finished.
1249 * Note that the database write lock will be held during the
1250 * compaction process to protect data integrity.
1253 notmuch_database_compact (const char *path,
1254 const char *backup_path,
1255 notmuch_compact_status_cb_t status_cb,
1259 char *notmuch_path, *xapian_path, *compact_xapian_path;
1260 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1261 notmuch_database_t *notmuch = NULL;
1262 struct stat statbuf;
1263 notmuch_bool_t keep_backup;
1264 char *message = NULL;
1266 local = talloc_new (NULL);
1268 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1270 ret = notmuch_database_open_verbose (path,
1271 NOTMUCH_DATABASE_MODE_READ_WRITE,
1275 if (status_cb) status_cb (message, closure);
1279 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1280 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1284 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1285 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1289 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1290 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1294 if (backup_path == NULL) {
1295 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1296 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1299 keep_backup = FALSE;
1305 if (stat (backup_path, &statbuf) != -1) {
1306 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1307 ret = NOTMUCH_STATUS_FILE_ERROR;
1310 if (errno != ENOENT) {
1311 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1313 ret = NOTMUCH_STATUS_FILE_ERROR;
1317 /* Unconditionally attempt to remove old work-in-progress database (if
1318 * any). This is "protected" by database lock. If this fails due to write
1319 * errors (etc), the following code will fail and provide error message.
1321 (void) rmtree (compact_xapian_path);
1324 NotmuchCompactor compactor (status_cb, closure);
1326 compactor.set_renumber (false);
1327 compactor.add_source (xapian_path);
1328 compactor.set_destdir (compact_xapian_path);
1329 compactor.compact ();
1330 } catch (const Xapian::Error &error) {
1331 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1332 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1336 if (rename (xapian_path, backup_path)) {
1337 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1338 xapian_path, backup_path, strerror (errno));
1339 ret = NOTMUCH_STATUS_FILE_ERROR;
1343 if (rename (compact_xapian_path, xapian_path)) {
1344 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1345 compact_xapian_path, xapian_path, strerror (errno));
1346 ret = NOTMUCH_STATUS_FILE_ERROR;
1350 if (! keep_backup) {
1351 if (rmtree (backup_path)) {
1352 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1353 backup_path, strerror (errno));
1354 ret = NOTMUCH_STATUS_FILE_ERROR;
1361 notmuch_status_t ret2;
1363 const char *str = notmuch_database_status_string (notmuch);
1364 if (status_cb && str)
1365 status_cb (str, closure);
1367 ret2 = notmuch_database_destroy (notmuch);
1369 /* don't clobber previous error status */
1370 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1374 talloc_free (local);
1380 notmuch_database_destroy (notmuch_database_t *notmuch)
1382 notmuch_status_t status;
1384 status = notmuch_database_close (notmuch);
1385 talloc_free (notmuch);
1391 notmuch_database_get_path (notmuch_database_t *notmuch)
1393 return notmuch->path;
1397 notmuch_database_get_version (notmuch_database_t *notmuch)
1399 unsigned int version;
1400 string version_string;
1404 version_string = notmuch->xapian_db->get_metadata ("version");
1405 if (version_string.empty ())
1408 str = version_string.c_str ();
1409 if (str == NULL || *str == '\0')
1412 version = strtoul (str, &end, 10);
1414 INTERNAL_ERROR ("Malformed database version: %s", str);
1420 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1422 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1423 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1424 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1427 static volatile sig_atomic_t do_progress_notify = 0;
1430 handle_sigalrm (unused (int signal))
1432 do_progress_notify = 1;
1435 /* Upgrade the current database.
1437 * After opening a database in read-write mode, the client should
1438 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1439 * if so, upgrade with this function before making any modifications.
1441 * The optional progress_notify callback can be used by the caller to
1442 * provide progress indication to the user. If non-NULL it will be
1443 * called periodically with 'count' as the number of messages upgraded
1444 * so far and 'total' the overall number of messages that will be
1448 notmuch_database_upgrade (notmuch_database_t *notmuch,
1449 void (*progress_notify) (void *closure,
1453 void *local = talloc_new (NULL);
1454 Xapian::TermIterator t, t_end;
1455 Xapian::WritableDatabase *db;
1456 struct sigaction action;
1457 struct itimerval timerval;
1458 notmuch_bool_t timer_is_active = FALSE;
1459 enum _notmuch_features target_features, new_features;
1460 notmuch_status_t status;
1461 notmuch_private_status_t private_status;
1462 notmuch_query_t *query = NULL;
1463 unsigned int count = 0, total = 0;
1465 status = _notmuch_database_ensure_writable (notmuch);
1469 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1471 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1472 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1474 if (! notmuch_database_needs_upgrade (notmuch))
1475 return NOTMUCH_STATUS_SUCCESS;
1477 if (progress_notify) {
1478 /* Set up our handler for SIGALRM */
1479 memset (&action, 0, sizeof (struct sigaction));
1480 action.sa_handler = handle_sigalrm;
1481 sigemptyset (&action.sa_mask);
1482 action.sa_flags = SA_RESTART;
1483 sigaction (SIGALRM, &action, NULL);
1485 /* Then start a timer to send SIGALRM once per second. */
1486 timerval.it_interval.tv_sec = 1;
1487 timerval.it_interval.tv_usec = 0;
1488 timerval.it_value.tv_sec = 1;
1489 timerval.it_value.tv_usec = 0;
1490 setitimer (ITIMER_REAL, &timerval, NULL);
1492 timer_is_active = TRUE;
1495 /* Figure out how much total work we need to do. */
1497 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1498 NOTMUCH_FEATURE_LAST_MOD)) {
1499 query = notmuch_query_create (notmuch, "");
1502 status = notmuch_query_count_messages (query, &msg_count);
1507 notmuch_query_destroy (query);
1510 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1511 t_end = db->allterms_end ("XTIMESTAMP");
1512 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1515 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1516 /* The ghost message upgrade converts all thread_id_*
1517 * metadata values into ghost message documents. */
1518 t_end = db->metadata_keys_end ("thread_id_");
1519 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1523 /* Perform the upgrade in a transaction. */
1524 db->begin_transaction (true);
1526 /* Set the target features so we write out changes in the desired
1528 notmuch->features = target_features;
1530 /* Perform per-message upgrades. */
1532 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1533 NOTMUCH_FEATURE_LAST_MOD)) {
1534 notmuch_messages_t *messages;
1535 notmuch_message_t *message;
1538 query = notmuch_query_create (notmuch, "");
1540 status = notmuch_query_search_messages (query, &messages);
1544 notmuch_messages_valid (messages);
1545 notmuch_messages_move_to_next (messages))
1547 if (do_progress_notify) {
1548 progress_notify (closure, (double) count / total);
1549 do_progress_notify = 0;
1552 message = notmuch_messages_get (messages);
1554 /* Before version 1, each message document had its
1555 * filename in the data field. Copy that into the new
1556 * format by calling notmuch_message_add_filename.
1558 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1559 filename = _notmuch_message_talloc_copy_data (message);
1560 if (filename && *filename != '\0') {
1561 _notmuch_message_add_filename (message, filename);
1562 _notmuch_message_clear_data (message);
1564 talloc_free (filename);
1567 /* Prior to version 2, the "folder:" prefix was
1568 * probabilistic and stemmed. Change it to the current
1569 * boolean prefix. Add "path:" prefixes while at it.
1571 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1572 _notmuch_message_upgrade_folder (message);
1574 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1575 * track modification revisions. Give all messages the
1576 * next available revision; since we just started tracking
1577 * revisions for this database, that will be 1.
1579 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1580 _notmuch_message_upgrade_last_mod (message);
1582 _notmuch_message_sync (message);
1584 notmuch_message_destroy (message);
1589 notmuch_query_destroy (query);
1593 /* Perform per-directory upgrades. */
1595 /* Before version 1 we stored directory timestamps in
1596 * XTIMESTAMP documents instead of the current XDIRECTORY
1597 * documents. So copy those as well. */
1598 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1599 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1601 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1605 Xapian::PostingIterator p, p_end;
1606 std::string term = *t;
1608 p_end = notmuch->xapian_db->postlist_end (term);
1610 for (p = notmuch->xapian_db->postlist_begin (term);
1614 Xapian::Document document;
1616 notmuch_directory_t *directory;
1618 if (do_progress_notify) {
1619 progress_notify (closure, (double) count / total);
1620 do_progress_notify = 0;
1623 document = find_document_for_doc_id (notmuch, *p);
1624 mtime = Xapian::sortable_unserialise (
1625 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1627 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1628 NOTMUCH_FIND_CREATE, &status);
1629 notmuch_directory_set_mtime (directory, mtime);
1630 notmuch_directory_destroy (directory);
1632 db->delete_document (*p);
1639 /* Perform metadata upgrades. */
1641 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1642 * messages were stored as database metadata. Change these to
1645 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1646 notmuch_message_t *message;
1647 std::string message_id, thread_id;
1649 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1650 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1652 if (do_progress_notify) {
1653 progress_notify (closure, (double) count / total);
1654 do_progress_notify = 0;
1657 message_id = (*t).substr (
1658 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1659 thread_id = db->get_metadata (*t);
1661 /* Create ghost message */
1662 message = _notmuch_message_create_for_message_id (
1663 notmuch, message_id.c_str (), &private_status);
1664 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1665 /* Document already exists; ignore the stored thread ID */
1666 } else if (private_status ==
1667 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1668 private_status = _notmuch_message_initialize_ghost (
1669 message, thread_id.c_str ());
1670 if (! private_status)
1671 _notmuch_message_sync (message);
1674 if (private_status) {
1675 _notmuch_database_log (notmuch,
1676 "Upgrade failed while creating ghost messages.\n");
1677 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1681 /* Clear saved metadata thread ID */
1682 db->set_metadata (*t, "");
1688 status = NOTMUCH_STATUS_SUCCESS;
1689 db->set_metadata ("features", _print_features (local, notmuch->features));
1690 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1693 if (status == NOTMUCH_STATUS_SUCCESS)
1694 db->commit_transaction ();
1696 db->cancel_transaction ();
1698 if (timer_is_active) {
1699 /* Now stop the timer. */
1700 timerval.it_interval.tv_sec = 0;
1701 timerval.it_interval.tv_usec = 0;
1702 timerval.it_value.tv_sec = 0;
1703 timerval.it_value.tv_usec = 0;
1704 setitimer (ITIMER_REAL, &timerval, NULL);
1706 /* And disable the signal handler. */
1707 action.sa_handler = SIG_IGN;
1708 sigaction (SIGALRM, &action, NULL);
1712 notmuch_query_destroy (query);
1714 talloc_free (local);
1719 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1721 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1722 notmuch->atomic_nesting > 0)
1725 if (notmuch_database_needs_upgrade (notmuch))
1726 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1729 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1730 } catch (const Xapian::Error &error) {
1731 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1732 error.get_msg().c_str());
1733 notmuch->exception_reported = TRUE;
1734 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1738 notmuch->atomic_nesting++;
1739 return NOTMUCH_STATUS_SUCCESS;
1743 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1745 Xapian::WritableDatabase *db;
1747 if (notmuch->atomic_nesting == 0)
1748 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1750 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1751 notmuch->atomic_nesting > 1)
1754 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1756 db->commit_transaction ();
1758 /* This is a hack for testing. Xapian never flushes on a
1759 * non-flushed commit, even if the flush threshold is 1.
1760 * However, we rely on flushing to test atomicity. */
1761 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1762 if (thresh && atoi (thresh) == 1)
1764 } catch (const Xapian::Error &error) {
1765 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1766 error.get_msg().c_str());
1767 notmuch->exception_reported = TRUE;
1768 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1771 if (notmuch->atomic_dirty) {
1772 ++notmuch->revision;
1773 notmuch->atomic_dirty = FALSE;
1777 notmuch->atomic_nesting--;
1778 return NOTMUCH_STATUS_SUCCESS;
1782 notmuch_database_get_revision (notmuch_database_t *notmuch,
1786 *uuid = notmuch->uuid;
1787 return notmuch->revision;
1790 /* We allow the user to use arbitrarily long paths for directories. But
1791 * we have a term-length limit. So if we exceed that, we'll use the
1792 * SHA-1 of the path for the database term.
1794 * Note: This function may return the original value of 'path'. If it
1795 * does not, then the caller is responsible to free() the returned
1799 _notmuch_database_get_directory_db_path (const char *path)
1801 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1803 if (term_len > NOTMUCH_TERM_MAX)
1804 return _notmuch_sha1_of_string (path);
1809 /* Given a path, split it into two parts: the directory part is all
1810 * components except for the last, and the basename is that last
1811 * component. Getting the return-value for either part is optional
1812 * (the caller can pass NULL).
1814 * The original 'path' can represent either a regular file or a
1815 * directory---the splitting will be carried out in the same way in
1816 * either case. Trailing slashes on 'path' will be ignored, and any
1817 * cases of multiple '/' characters appearing in series will be
1818 * treated as a single '/'.
1820 * Allocation (if any) will have 'ctx' as the talloc owner. But
1821 * pointers will be returned within the original path string whenever
1824 * Note: If 'path' is non-empty and contains no non-trailing slash,
1825 * (that is, consists of a filename with no parent directory), then
1826 * the directory returned will be an empty string. However, if 'path'
1827 * is an empty string, then both directory and basename will be
1831 _notmuch_database_split_path (void *ctx,
1833 const char **directory,
1834 const char **basename)
1838 if (path == NULL || *path == '\0') {
1843 return NOTMUCH_STATUS_SUCCESS;
1846 /* Find the last slash (not counting a trailing slash), if any. */
1848 slash = path + strlen (path) - 1;
1850 /* First, skip trailing slashes. */
1851 while (slash != path && *slash == '/')
1854 /* Then, find a slash. */
1855 while (slash != path && *slash != '/') {
1862 /* Finally, skip multiple slashes. */
1863 while (slash != path && *(slash - 1) == '/')
1866 if (slash == path) {
1868 *directory = talloc_strdup (ctx, "");
1873 *directory = talloc_strndup (ctx, path, slash - path);
1876 return NOTMUCH_STATUS_SUCCESS;
1879 /* Find the document ID of the specified directory.
1881 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1882 * created if one does not exist for 'path'. Otherwise, if the
1883 * directory document does not exist, this sets *directory_id to
1884 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1887 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1889 notmuch_find_flags_t flags,
1890 unsigned int *directory_id)
1892 notmuch_directory_t *directory;
1893 notmuch_status_t status;
1897 return NOTMUCH_STATUS_SUCCESS;
1900 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1901 if (status || !directory) {
1906 *directory_id = _notmuch_directory_get_document_id (directory);
1908 notmuch_directory_destroy (directory);
1910 return NOTMUCH_STATUS_SUCCESS;
1914 _notmuch_database_get_directory_path (void *ctx,
1915 notmuch_database_t *notmuch,
1916 unsigned int doc_id)
1918 Xapian::Document document;
1920 document = find_document_for_doc_id (notmuch, doc_id);
1922 return talloc_strdup (ctx, document.get_data ().c_str ());
1925 /* Given a legal 'filename' for the database, (either relative to
1926 * database path or absolute with initial components identical to
1927 * database path), return a new string (with 'ctx' as the talloc
1928 * owner) suitable for use as a direntry term value.
1930 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1931 * will be created in the database as needed. Otherwise, if the
1932 * necessary directory documents do not exist, this sets
1933 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1936 _notmuch_database_filename_to_direntry (void *ctx,
1937 notmuch_database_t *notmuch,
1938 const char *filename,
1939 notmuch_find_flags_t flags,
1942 const char *relative, *directory, *basename;
1943 Xapian::docid directory_id;
1944 notmuch_status_t status;
1946 relative = _notmuch_database_relative_path (notmuch, filename);
1948 status = _notmuch_database_split_path (ctx, relative,
1949 &directory, &basename);
1953 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1955 if (status || directory_id == (unsigned int)-1) {
1960 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1962 return NOTMUCH_STATUS_SUCCESS;
1965 /* Given a legal 'path' for the database, return the relative path.
1967 * The return value will be a pointer to the original path contents,
1968 * and will be either the original string (if 'path' was relative) or
1969 * a portion of the string (if path was absolute and begins with the
1973 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1976 const char *db_path, *relative;
1977 unsigned int db_path_len;
1979 db_path = notmuch_database_get_path (notmuch);
1980 db_path_len = strlen (db_path);
1984 if (*relative == '/') {
1985 while (*relative == '/' && *(relative+1) == '/')
1988 if (strncmp (relative, db_path, db_path_len) == 0)
1990 relative += db_path_len;
1991 while (*relative == '/')
2000 notmuch_database_get_directory (notmuch_database_t *notmuch,
2002 notmuch_directory_t **directory)
2004 notmuch_status_t status;
2006 if (directory == NULL)
2007 return NOTMUCH_STATUS_NULL_POINTER;
2011 *directory = _notmuch_directory_create (notmuch, path,
2012 NOTMUCH_FIND_LOOKUP, &status);
2013 } catch (const Xapian::Error &error) {
2014 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
2015 error.get_msg().c_str());
2016 notmuch->exception_reported = TRUE;
2017 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2022 /* Allocate a document ID that satisfies the following criteria:
2024 * 1. The ID does not exist for any document in the Xapian database
2026 * 2. The ID was not previously returned from this function
2028 * 3. The ID is the smallest integer satisfying (1) and (2)
2030 * This function will trigger an internal error if these constraints
2031 * cannot all be satisfied, (that is, the pool of available document
2032 * IDs has been exhausted).
2035 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2037 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2039 notmuch->last_doc_id++;
2041 if (notmuch->last_doc_id == 0)
2042 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2044 return notmuch->last_doc_id;
2048 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
2050 /* 16 bytes (+ terminator) for hexadecimal representation of
2051 * a 64-bit integer. */
2052 static char thread_id[17];
2053 Xapian::WritableDatabase *db;
2055 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2057 notmuch->last_thread_id++;
2059 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2061 db->set_metadata ("last_thread_id", thread_id);
2067 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2069 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2070 message_id = _notmuch_message_id_compressed (ctx, message_id);
2072 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2076 static notmuch_status_t
2077 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2079 const char *message_id,
2080 const char **thread_id_ret);
2082 /* Find the thread ID to which the message with 'message_id' belongs.
2084 * Note: 'thread_id_ret' must not be NULL!
2085 * On success '*thread_id_ret' is set to a newly talloced string belonging to
2088 * Note: If there is no message in the database with the given
2089 * 'message_id' then a new thread_id will be allocated for this
2090 * message ID and stored in the database metadata so that the
2091 * thread ID can be looked up if the message is added to the database
2094 static notmuch_status_t
2095 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2097 const char *message_id,
2098 const char **thread_id_ret)
2100 notmuch_private_status_t status;
2101 notmuch_message_t *message;
2103 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2104 return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2107 /* Look for this message (regular or ghost) */
2108 message = _notmuch_message_create_for_message_id (
2109 notmuch, message_id, &status);
2110 if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2111 /* Message exists */
2112 *thread_id_ret = talloc_steal (
2113 ctx, notmuch_message_get_thread_id (message));
2114 } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2115 /* Message did not exist. Give it a fresh thread ID and
2116 * populate this message as a ghost message. */
2117 *thread_id_ret = talloc_strdup (
2118 ctx, _notmuch_database_generate_thread_id (notmuch));
2119 if (! *thread_id_ret) {
2120 status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2122 status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2124 /* Commit the new ghost message */
2125 _notmuch_message_sync (message);
2128 /* Create failed. Fall through. */
2131 notmuch_message_destroy (message);
2133 return COERCE_STATUS (status, "Error creating ghost message");
2136 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2137 static notmuch_status_t
2138 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2140 const char *message_id,
2141 const char **thread_id_ret)
2143 notmuch_status_t status;
2144 notmuch_message_t *message;
2145 string thread_id_string;
2147 Xapian::WritableDatabase *db;
2149 status = notmuch_database_find_message (notmuch, message_id, &message);
2155 *thread_id_ret = talloc_steal (ctx,
2156 notmuch_message_get_thread_id (message));
2158 notmuch_message_destroy (message);
2160 return NOTMUCH_STATUS_SUCCESS;
2163 /* Message has not been seen yet.
2165 * We may have seen a reference to it already, in which case, we
2166 * can return the thread ID stored in the metadata. Otherwise, we
2167 * generate a new thread ID and store it there.
2169 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2170 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2171 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2173 if (thread_id_string.empty()) {
2174 *thread_id_ret = talloc_strdup (ctx,
2175 _notmuch_database_generate_thread_id (notmuch));
2176 db->set_metadata (metadata_key, *thread_id_ret);
2178 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2181 talloc_free (metadata_key);
2183 return NOTMUCH_STATUS_SUCCESS;
2186 static notmuch_status_t
2187 _merge_threads (notmuch_database_t *notmuch,
2188 const char *winner_thread_id,
2189 const char *loser_thread_id)
2191 Xapian::PostingIterator loser, loser_end;
2192 notmuch_message_t *message = NULL;
2193 notmuch_private_status_t private_status;
2194 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2196 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2198 for ( ; loser != loser_end; loser++) {
2199 message = _notmuch_message_create (notmuch, notmuch,
2200 *loser, &private_status);
2201 if (message == NULL) {
2202 ret = COERCE_STATUS (private_status,
2203 "Cannot find document for doc_id from query");
2207 _notmuch_message_remove_term (message, "thread", loser_thread_id);
2208 _notmuch_message_add_term (message, "thread", winner_thread_id);
2209 _notmuch_message_sync (message);
2211 notmuch_message_destroy (message);
2217 notmuch_message_destroy (message);
2223 _my_talloc_free_for_g_hash (void *ptr)
2228 static notmuch_status_t
2229 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2230 notmuch_message_t *message,
2231 notmuch_message_file_t *message_file,
2232 const char **thread_id)
2234 GHashTable *parents = NULL;
2235 const char *refs, *in_reply_to, *in_reply_to_message_id;
2236 const char *last_ref_message_id, *this_message_id;
2237 GList *l, *keys = NULL;
2238 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2240 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2241 _my_talloc_free_for_g_hash, NULL);
2242 this_message_id = notmuch_message_get_message_id (message);
2244 refs = _notmuch_message_file_get_header (message_file, "references");
2245 last_ref_message_id = parse_references (message,
2249 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2250 in_reply_to_message_id = parse_references (message,
2252 parents, in_reply_to);
2254 /* For the parent of this message, use the last message ID of the
2255 * References header, if available. If not, fall back to the
2256 * first message ID in the In-Reply-To header. */
2257 if (last_ref_message_id) {
2258 _notmuch_message_add_term (message, "replyto",
2259 last_ref_message_id);
2260 } else if (in_reply_to_message_id) {
2261 _notmuch_message_add_term (message, "replyto",
2262 in_reply_to_message_id);
2265 keys = g_hash_table_get_keys (parents);
2266 for (l = keys; l; l = l->next) {
2267 char *parent_message_id;
2268 const char *parent_thread_id = NULL;
2270 parent_message_id = (char *) l->data;
2272 _notmuch_message_add_term (message, "reference",
2275 ret = _resolve_message_id_to_thread_id (notmuch,
2282 if (*thread_id == NULL) {
2283 *thread_id = talloc_strdup (message, parent_thread_id);
2284 _notmuch_message_add_term (message, "thread", *thread_id);
2285 } else if (strcmp (*thread_id, parent_thread_id)) {
2286 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2296 g_hash_table_unref (parents);
2301 static notmuch_status_t
2302 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2303 notmuch_message_t *message,
2304 const char **thread_id)
2306 const char *message_id = notmuch_message_get_message_id (message);
2307 Xapian::PostingIterator child, children_end;
2308 notmuch_message_t *child_message = NULL;
2309 const char *child_thread_id;
2310 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2311 notmuch_private_status_t private_status;
2313 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2315 for ( ; child != children_end; child++) {
2317 child_message = _notmuch_message_create (message, notmuch,
2318 *child, &private_status);
2319 if (child_message == NULL) {
2320 ret = COERCE_STATUS (private_status,
2321 "Cannot find document for doc_id from query");
2325 child_thread_id = notmuch_message_get_thread_id (child_message);
2326 if (*thread_id == NULL) {
2327 *thread_id = talloc_strdup (message, child_thread_id);
2328 _notmuch_message_add_term (message, "thread", *thread_id);
2329 } else if (strcmp (*thread_id, child_thread_id)) {
2330 _notmuch_message_remove_term (child_message, "reference",
2332 _notmuch_message_sync (child_message);
2333 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2338 notmuch_message_destroy (child_message);
2339 child_message = NULL;
2344 notmuch_message_destroy (child_message);
2349 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2351 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2352 notmuch_message_t *message)
2354 const char *message_id;
2358 message_id = notmuch_message_get_message_id (message);
2359 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2361 /* Check if we have already seen related messages to this one.
2362 * If we have then use the thread_id that we stored at that time.
2364 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2365 if (stored_id.empty ()) {
2368 Xapian::WritableDatabase *db;
2370 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2372 /* Clear the metadata for this message ID. We don't need it
2374 db->set_metadata (metadata_key, "");
2376 return talloc_strdup (ctx, stored_id.c_str ());
2380 /* Given a blank or ghost 'message' and its corresponding
2381 * 'message_file' link it to existing threads in the database.
2383 * First, if is_ghost, this retrieves the thread ID already stored in
2384 * the message (which will be the case if a message was previously
2385 * added that referenced this one). If the message is blank
2386 * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2387 * later in this function). If the database does not support ghost
2388 * messages, this checks for a thread ID stored in database metadata
2389 * for this message ID.
2391 * Second, we look at 'message_file' and its link-relevant headers
2392 * (References and In-Reply-To) for message IDs.
2394 * Finally, we look in the database for existing message that
2395 * reference 'message'.
2397 * In all cases, we assign to the current message the first thread ID
2398 * found. We will also merge any existing, distinct threads where this
2399 * message belongs to both, (which is not uncommon when messages are
2400 * processed out of order).
2402 * Finally, if no thread ID has been found through referenced messages, we
2403 * call _notmuch_message_generate_thread_id to generate a new thread
2404 * ID. This should only happen for new, top-level messages, (no
2405 * References or In-Reply-To header in this message, and no previously
2406 * added message refers to this message).
2408 static notmuch_status_t
2409 _notmuch_database_link_message (notmuch_database_t *notmuch,
2410 notmuch_message_t *message,
2411 notmuch_message_file_t *message_file,
2412 notmuch_bool_t is_ghost)
2414 void *local = talloc_new (NULL);
2415 notmuch_status_t status;
2416 const char *thread_id = NULL;
2418 /* Check if the message already had a thread ID */
2419 if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2421 thread_id = notmuch_message_get_thread_id (message);
2423 thread_id = _consume_metadata_thread_id (local, notmuch, message);
2425 _notmuch_message_add_term (message, "thread", thread_id);
2428 status = _notmuch_database_link_message_to_parents (notmuch, message,
2434 if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2435 /* In general, it shouldn't be necessary to link children,
2436 * since the earlier indexing of those children will have
2437 * stored a thread ID for the missing parent. However, prior
2438 * to ghost messages, these stored thread IDs were NOT
2439 * rewritten during thread merging (and there was no
2440 * performant way to do so), so if indexed children were
2441 * pulled into a different thread ID by a merge, it was
2442 * necessary to pull them *back* into the stored thread ID of
2443 * the parent. With ghost messages, we just rewrite the
2444 * stored thread IDs during merging, so this workaround isn't
2446 status = _notmuch_database_link_message_to_children (notmuch, message,
2452 /* If not part of any existing thread, generate a new thread ID. */
2453 if (thread_id == NULL) {
2454 thread_id = _notmuch_database_generate_thread_id (notmuch);
2456 _notmuch_message_add_term (message, "thread", thread_id);
2460 talloc_free (local);
2466 notmuch_database_add_message (notmuch_database_t *notmuch,
2467 const char *filename,
2468 notmuch_message_t **message_ret)
2470 notmuch_message_file_t *message_file;
2471 notmuch_message_t *message = NULL;
2472 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2473 notmuch_private_status_t private_status;
2474 notmuch_bool_t is_ghost = false;
2476 const char *date, *header;
2477 const char *from, *to, *subject;
2478 char *message_id = NULL;
2481 *message_ret = NULL;
2483 ret = _notmuch_database_ensure_writable (notmuch);
2487 message_file = _notmuch_message_file_open (notmuch, filename);
2488 if (message_file == NULL)
2489 return NOTMUCH_STATUS_FILE_ERROR;
2491 /* Adding a message may change many documents. Do this all
2493 ret = notmuch_database_begin_atomic (notmuch);
2497 /* Parse message up front to get better error status. */
2498 ret = _notmuch_message_file_parse (message_file);
2502 /* Before we do any real work, (especially before doing a
2503 * potential SHA-1 computation on the entire file's contents),
2504 * let's make sure that what we're looking at looks like an
2505 * actual email message.
2507 from = _notmuch_message_file_get_header (message_file, "from");
2508 subject = _notmuch_message_file_get_header (message_file, "subject");
2509 to = _notmuch_message_file_get_header (message_file, "to");
2511 if ((from == NULL || *from == '\0') &&
2512 (subject == NULL || *subject == '\0') &&
2513 (to == NULL || *to == '\0')) {
2514 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2518 /* Now that we're sure it's mail, the first order of business
2519 * is to find a message ID (or else create one ourselves).
2521 header = _notmuch_message_file_get_header (message_file, "message-id");
2522 if (header && *header != '\0') {
2523 message_id = _parse_message_id (message_file, header, NULL);
2525 /* So the header value isn't RFC-compliant, but it's
2526 * better than no message-id at all.
2528 if (message_id == NULL)
2529 message_id = talloc_strdup (message_file, header);
2532 if (message_id == NULL ) {
2533 /* No message-id at all, let's generate one by taking a
2534 * hash over the file's contents.
2536 char *sha1 = _notmuch_sha1_of_file (filename);
2538 /* If that failed too, something is really wrong. Give up. */
2540 ret = NOTMUCH_STATUS_FILE_ERROR;
2544 message_id = talloc_asprintf (message_file, "notmuch-sha1-%s", sha1);
2549 /* Now that we have a message ID, we get a message object,
2550 * (which may or may not reference an existing document in the
2553 message = _notmuch_message_create_for_message_id (notmuch,
2557 talloc_free (message_id);
2559 if (message == NULL) {
2560 ret = COERCE_STATUS (private_status,
2561 "Unexpected status value from _notmuch_message_create_for_message_id");
2565 _notmuch_message_add_filename (message, filename);
2567 /* Is this a newly created message object or a ghost
2568 * message? We have to be slightly careful: if this is a
2569 * blank message, it's not safe to call
2570 * notmuch_message_get_flag yet. */
2571 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2572 (is_ghost = notmuch_message_get_flag (
2573 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2574 _notmuch_message_add_term (message, "type", "mail");
2576 /* Convert ghost message to a regular message */
2577 _notmuch_message_remove_term (message, "type", "ghost");
2579 ret = _notmuch_database_link_message (notmuch, message,
2580 message_file, is_ghost);
2584 date = _notmuch_message_file_get_header (message_file, "date");
2585 _notmuch_message_set_header_values (message, date, from, subject);
2587 ret = _notmuch_message_index_file (message, message_file);
2591 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2594 _notmuch_message_sync (message);
2595 } catch (const Xapian::Error &error) {
2596 _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2597 error.get_msg().c_str());
2598 notmuch->exception_reported = TRUE;
2599 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2605 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2606 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2607 *message_ret = message;
2609 notmuch_message_destroy (message);
2613 _notmuch_message_file_close (message_file);
2615 ret2 = notmuch_database_end_atomic (notmuch);
2616 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2617 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2618 ret2 != NOTMUCH_STATUS_SUCCESS)
2625 notmuch_database_remove_message (notmuch_database_t *notmuch,
2626 const char *filename)
2628 notmuch_status_t status;
2629 notmuch_message_t *message;
2631 status = notmuch_database_find_message_by_filename (notmuch, filename,
2634 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2635 status = _notmuch_message_remove_filename (message, filename);
2636 if (status == NOTMUCH_STATUS_SUCCESS)
2637 _notmuch_message_delete (message);
2638 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2639 _notmuch_message_sync (message);
2641 notmuch_message_destroy (message);
2648 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2649 const char *filename,
2650 notmuch_message_t **message_ret)
2653 const char *prefix = _find_prefix ("file-direntry");
2654 char *direntry, *term;
2655 Xapian::PostingIterator i, end;
2656 notmuch_status_t status;
2658 if (message_ret == NULL)
2659 return NOTMUCH_STATUS_NULL_POINTER;
2661 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2662 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2664 /* return NULL on any failure */
2665 *message_ret = NULL;
2667 local = talloc_new (notmuch);
2670 status = _notmuch_database_filename_to_direntry (
2671 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2672 if (status || !direntry)
2675 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2677 find_doc_ids_for_term (notmuch, term, &i, &end);
2680 notmuch_private_status_t private_status;
2682 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2684 if (*message_ret == NULL)
2685 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2687 } catch (const Xapian::Error &error) {
2688 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2689 error.get_msg().c_str());
2690 notmuch->exception_reported = TRUE;
2691 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2695 talloc_free (local);
2697 if (status && *message_ret) {
2698 notmuch_message_destroy (*message_ret);
2699 *message_ret = NULL;
2704 notmuch_string_list_t *
2705 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2706 Xapian::TermIterator &end,
2709 int prefix_len = strlen (prefix);
2710 notmuch_string_list_t *list;
2712 list = _notmuch_string_list_create (ctx);
2713 if (unlikely (list == NULL))
2716 for (i.skip_to (prefix); i != end; i++) {
2717 /* Terminate loop at first term without desired prefix. */
2718 if (strncmp ((*i).c_str (), prefix, prefix_len))
2721 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2728 notmuch_database_get_all_tags (notmuch_database_t *db)
2730 Xapian::TermIterator i, end;
2731 notmuch_string_list_t *tags;
2734 i = db->xapian_db->allterms_begin();
2735 end = db->xapian_db->allterms_end();
2736 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2737 _find_prefix ("tag"));
2738 _notmuch_string_list_sort (tags);
2739 return _notmuch_tags_create (db, tags);
2740 } catch (const Xapian::Error &error) {
2741 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2742 error.get_msg().c_str());
2743 db->exception_reported = TRUE;
2749 notmuch_database_status_string (const notmuch_database_t *notmuch)
2751 return notmuch->status_string;