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 http://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "parse-time-vrp.h"
31 #include <glib.h> /* g_free, GPtrArray, GHashTable */
32 #include <glib-object.h> /* g_type_init */
34 #include <gmime/gmime.h> /* g_mime_init */
38 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
45 #define NOTMUCH_DATABASE_VERSION 1
47 #define STRINGIFY(s) _SUB_STRINGIFY(s)
48 #define _SUB_STRINGIFY(s) #s
50 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
52 * We currently have two different types of documents (mail and
53 * directory) and also some metadata.
57 * A mail document is associated with a particular email message file
58 * on disk. It is indexed with the following prefixed terms which the
59 * database uses to construct threads, etc.:
61 * Single terms of given prefix:
65 * id: Unique ID of mail. This is from the Message-ID header
66 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
67 * If it's present and too long, then we use
68 * "notmuch-sha1-<sha1_sum_of_message_id>".
69 * If this header is not present, we use
70 * "notmuch-sha1-<sha1_sum_of_entire_file>".
72 * thread: The ID of the thread to which the mail belongs
74 * replyto: The ID from the In-Reply-To header of the mail (if any).
76 * Multiple terms of given prefix:
78 * reference: All message IDs from In-Reply-To and References
79 * headers in the message.
81 * tag: Any tags associated with this message by the user.
83 * file-direntry: A colon-separated pair of values
84 * (INTEGER:STRING), where INTEGER is the
85 * document ID of a directory document, and
86 * STRING is the name of a file within that
87 * directory for this mail message.
89 * A mail document also has four values:
91 * TIMESTAMP: The time_t value corresponding to the message's
94 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
96 * FROM: The value of the "From" header
98 * SUBJECT: The value of the "Subject" header
100 * In addition, terms from the content of the message are added with
101 * "from", "to", "attachment", and "subject" prefixes for use by the
102 * user in searching. Similarly, terms from the path of the mail
103 * message are added with a "folder" prefix. But the database doesn't
104 * really care itself about any of these.
106 * The data portion of a mail document is empty.
110 * A directory document is used by a client of the notmuch library to
111 * maintain data necessary to allow for efficient polling of mail
114 * All directory documents contain one term:
116 * directory: The directory path (relative to the database path)
117 * Or the SHA1 sum of the directory path (if the
118 * path itself is too long to fit in a Xapian
121 * And all directory documents for directories other than top-level
122 * directories also contain the following term:
124 * directory-direntry: A colon-separated pair of values
125 * (INTEGER:STRING), where INTEGER is the
126 * document ID of the parent directory
127 * document, and STRING is the name of this
128 * directory within that parent.
130 * All directory documents have a single value:
132 * TIMESTAMP: The mtime of the directory (at last scan)
134 * The data portion of a directory document contains the path of the
135 * directory (relative to the database path).
139 * Xapian allows us to store arbitrary name-value pairs as
140 * "metadata". We currently use the following metadata names with the
143 * version The database schema version, (which is distinct
144 * from both the notmuch package version (see
145 * notmuch --version) and the libnotmuch library
146 * version. The version is stored as an base-10
147 * ASCII integer. The initial database version
148 * was 1, (though a schema existed before that
149 * were no "version" database value existed at
150 * all). Successive versions are allocated as
151 * changes are made to the database (such as by
152 * indexing new fields).
154 * last_thread_id The last thread ID generated. This is stored
155 * as a 16-byte hexadecimal ASCII representation
156 * of a 64-bit unsigned integer. The first ID
157 * generated is 1 and the value will be
158 * incremented for each thread ID.
160 * thread_id_* A pre-allocated thread ID for a particular
161 * message. This is actually an arbitrarily large
162 * family of metadata name. Any particular name is
163 * formed by concatenating "thread_id_" with a message
164 * ID (or the SHA1 sum of a message ID if it is very
165 * long---see description of 'id' in the mail
166 * document). The value stored is a thread ID.
168 * These thread ID metadata values are stored
169 * whenever a message references a parent message
170 * that does not yet exist in the database. A
171 * thread ID will be allocated and stored, and if
172 * the message is later added, the stored thread
173 * ID will be used (and the metadata value will
176 * Even before a message is added, it's
177 * pre-allocated thread ID is useful so that all
178 * descendant messages that reference this common
179 * parent can be recognized as belonging to the
183 /* With these prefix values we follow the conventions published here:
185 * http://xapian.org/docs/omega/termprefixes.html
187 * as much as makes sense. Note that I took some liberty in matching
188 * the reserved prefix values to notmuch concepts, (for example, 'G'
189 * is documented as "newsGroup (or similar entity - e.g. a web forum
190 * name)", for which I think the thread is the closest analogue in
191 * notmuch. This in spite of the fact that we will eventually be
192 * storing mailing-list messages where 'G' for "mailing list name"
193 * might be even a closer analogue. I'm treating the single-character
194 * prefixes preferentially for core notmuch concepts (which will be
195 * nearly universal to all mail messages).
198 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
200 { "reference", "XREFERENCE" },
201 { "replyto", "XREPLYTO" },
202 { "directory", "XDIRECTORY" },
203 { "file-direntry", "XFDIRENTRY" },
204 { "directory-direntry", "XDDIRENTRY" },
207 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
214 static prefix_t PROBABILISTIC_PREFIX[]= {
217 { "attachment", "XATTACHMENT" },
218 { "subject", "XSUBJECT"},
219 { "folder", "XFOLDER"}
223 _find_prefix (const char *name)
227 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
228 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
229 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
232 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
233 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
234 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
237 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
238 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
239 return PROBABILISTIC_PREFIX[i].prefix;
242 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
248 notmuch_status_to_string (notmuch_status_t status)
251 case NOTMUCH_STATUS_SUCCESS:
252 return "No error occurred";
253 case NOTMUCH_STATUS_OUT_OF_MEMORY:
254 return "Out of memory";
255 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
256 return "Attempt to write to a read-only database";
257 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
258 return "A Xapian exception occurred";
259 case NOTMUCH_STATUS_FILE_ERROR:
260 return "Something went wrong trying to read or write a file";
261 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
262 return "File is not an email";
263 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
264 return "Message ID is identical to a message in database";
265 case NOTMUCH_STATUS_NULL_POINTER:
266 return "Erroneous NULL pointer";
267 case NOTMUCH_STATUS_TAG_TOO_LONG:
268 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
269 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
270 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
271 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
272 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
273 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
274 return "Unsupported operation";
276 case NOTMUCH_STATUS_LAST_STATUS:
277 return "Unknown error status value";
282 find_doc_ids_for_term (notmuch_database_t *notmuch,
284 Xapian::PostingIterator *begin,
285 Xapian::PostingIterator *end)
287 *begin = notmuch->xapian_db->postlist_begin (term);
289 *end = notmuch->xapian_db->postlist_end (term);
293 find_doc_ids (notmuch_database_t *notmuch,
294 const char *prefix_name,
296 Xapian::PostingIterator *begin,
297 Xapian::PostingIterator *end)
301 term = talloc_asprintf (notmuch, "%s%s",
302 _find_prefix (prefix_name), value);
304 find_doc_ids_for_term (notmuch, term, begin, end);
309 notmuch_private_status_t
310 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
311 const char *prefix_name,
313 unsigned int *doc_id)
315 Xapian::PostingIterator i, end;
317 find_doc_ids (notmuch, prefix_name, value, &i, &end);
321 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
326 #if DEBUG_DATABASE_SANITY
330 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
334 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
337 static Xapian::Document
338 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
340 return notmuch->xapian_db->get_document (doc_id);
343 /* Generate a compressed version of 'message_id' of the form:
345 * notmuch-sha1-<sha1_sum_of_message_id>
348 _message_id_compressed (void *ctx, const char *message_id)
350 char *sha1, *compressed;
352 sha1 = notmuch_sha1_of_string (message_id);
354 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
361 notmuch_database_find_message (notmuch_database_t *notmuch,
362 const char *message_id,
363 notmuch_message_t **message_ret)
365 notmuch_private_status_t status;
368 if (message_ret == NULL)
369 return NOTMUCH_STATUS_NULL_POINTER;
371 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
372 message_id = _message_id_compressed (notmuch, message_id);
375 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
376 message_id, &doc_id);
378 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
381 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
383 if (*message_ret == NULL)
384 return NOTMUCH_STATUS_OUT_OF_MEMORY;
387 return NOTMUCH_STATUS_SUCCESS;
388 } catch (const Xapian::Error &error) {
389 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
390 error.get_msg().c_str());
391 notmuch->exception_reported = TRUE;
393 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
397 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
398 * a (potentially nested) parenthesized sequence with '\' used to
399 * escape any character (including parentheses).
401 * If the sequence to be skipped continues to the end of the string,
402 * then 'str' will be left pointing at the final terminating '\0'
406 skip_space_and_comments (const char **str)
411 while (*s && (isspace (*s) || *s == '(')) {
412 while (*s && isspace (*s))
417 while (*s && nesting) {
420 } else if (*s == ')') {
422 } else if (*s == '\\') {
434 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
435 * comments, and the '<' and '>' delimiters.
437 * If not NULL, then *next will be made to point to the first character
438 * not parsed, (possibly pointing to the final '\0' terminator.
440 * Returns a newly talloc'ed string belonging to 'ctx'.
442 * Returns NULL if there is any error parsing the message-id. */
444 _parse_message_id (void *ctx, const char *message_id, const char **next)
449 if (message_id == NULL || *message_id == '\0')
454 skip_space_and_comments (&s);
456 /* Skip any unstructured text as well. */
457 while (*s && *s != '<')
468 skip_space_and_comments (&s);
471 while (*end && *end != '>')
480 if (end > s && *end == '>')
485 result = talloc_strndup (ctx, s, end - s + 1);
487 /* Finally, collapse any whitespace that is within the message-id
493 for (r = result, len = strlen (r); *r; r++, len--)
494 if (*r == ' ' || *r == '\t')
495 memmove (r, r+1, len);
501 /* Parse a References header value, putting a (talloc'ed under 'ctx')
502 * copy of each referenced message-id into 'hash'.
504 * We explicitly avoid including any reference identical to
505 * 'message_id' in the result (to avoid mass confusion when a single
506 * message references itself cyclically---and yes, mail messages are
507 * not infrequent in the wild that do this---don't ask me why).
509 * Return the last reference parsed, if it is not equal to message_id.
512 parse_references (void *ctx,
513 const char *message_id,
519 if (refs == NULL || *refs == '\0')
523 ref = _parse_message_id (ctx, refs, &refs);
525 if (ref && strcmp (ref, message_id))
526 g_hash_table_insert (hash, ref, NULL);
529 /* The return value of this function is used to add a parent
530 * reference to the database. We should avoid making a message
531 * its own parent, thus the following check.
534 if (ref && strcmp(ref, message_id)) {
542 notmuch_database_create (const char *path, notmuch_database_t **database)
544 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
545 notmuch_database_t *notmuch = NULL;
546 char *notmuch_path = NULL;
551 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
552 status = NOTMUCH_STATUS_NULL_POINTER;
556 err = stat (path, &st);
558 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
559 path, strerror (errno));
560 status = NOTMUCH_STATUS_FILE_ERROR;
564 if (! S_ISDIR (st.st_mode)) {
565 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
567 status = NOTMUCH_STATUS_FILE_ERROR;
571 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
573 err = mkdir (notmuch_path, 0755);
576 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
577 notmuch_path, strerror (errno));
578 status = NOTMUCH_STATUS_FILE_ERROR;
582 status = notmuch_database_open (path,
583 NOTMUCH_DATABASE_MODE_READ_WRITE,
587 status = notmuch_database_upgrade (notmuch, NULL, NULL);
589 notmuch_database_close(notmuch);
595 talloc_free (notmuch_path);
600 talloc_free (notmuch);
605 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
607 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
608 fprintf (stderr, "Cannot write to a read-only database.\n");
609 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
612 return NOTMUCH_STATUS_SUCCESS;
616 notmuch_database_open (const char *path,
617 notmuch_database_mode_t mode,
618 notmuch_database_t **database)
620 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
621 void *local = talloc_new (NULL);
622 notmuch_database_t *notmuch = NULL;
623 char *notmuch_path, *xapian_path;
626 unsigned int i, version;
627 static int initialized = 0;
630 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
631 status = NOTMUCH_STATUS_NULL_POINTER;
635 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
636 fprintf (stderr, "Out of memory\n");
637 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
641 err = stat (notmuch_path, &st);
643 fprintf (stderr, "Error opening database at %s: %s\n",
644 notmuch_path, strerror (errno));
645 status = NOTMUCH_STATUS_FILE_ERROR;
649 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
650 fprintf (stderr, "Out of memory\n");
651 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
655 /* Initialize the GLib type system and threads */
656 #if !GLIB_CHECK_VERSION(2, 35, 1)
660 /* Initialize gmime */
662 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
666 notmuch = talloc_zero (NULL, notmuch_database_t);
667 notmuch->exception_reported = FALSE;
668 notmuch->path = talloc_strdup (notmuch, path);
670 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
671 notmuch->path[strlen (notmuch->path) - 1] = '\0';
673 notmuch->needs_upgrade = FALSE;
674 notmuch->mode = mode;
675 notmuch->atomic_nesting = 0;
677 string last_thread_id;
679 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
680 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
681 Xapian::DB_CREATE_OR_OPEN);
682 version = notmuch_database_get_version (notmuch);
684 if (version > NOTMUCH_DATABASE_VERSION) {
686 "Error: Notmuch database at %s\n"
687 " has a newer database format version (%u) than supported by this\n"
688 " version of notmuch (%u). Refusing to open this database in\n"
689 " read-write mode.\n",
690 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
691 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
692 notmuch_database_destroy (notmuch);
694 status = NOTMUCH_STATUS_FILE_ERROR;
698 if (version < NOTMUCH_DATABASE_VERSION)
699 notmuch->needs_upgrade = TRUE;
701 notmuch->xapian_db = new Xapian::Database (xapian_path);
702 version = notmuch_database_get_version (notmuch);
703 if (version > NOTMUCH_DATABASE_VERSION)
706 "Warning: Notmuch database at %s\n"
707 " has a newer database format version (%u) than supported by this\n"
708 " version of notmuch (%u). Some operations may behave incorrectly,\n"
709 " (but the database will not be harmed since it is being opened\n"
710 " in read-only mode).\n",
711 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
715 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
716 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
717 if (last_thread_id.empty ()) {
718 notmuch->last_thread_id = 0;
723 str = last_thread_id.c_str ();
724 notmuch->last_thread_id = strtoull (str, &end, 16);
726 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
729 notmuch->query_parser = new Xapian::QueryParser;
730 notmuch->term_gen = new Xapian::TermGenerator;
731 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
732 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
733 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
735 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
736 notmuch->query_parser->set_database (*notmuch->xapian_db);
737 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
738 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
739 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
740 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
742 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
743 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
744 notmuch->query_parser->add_boolean_prefix (prefix->name,
748 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
749 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
750 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
752 } catch (const Xapian::Error &error) {
753 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
754 error.get_msg().c_str());
755 notmuch_database_destroy (notmuch);
757 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
766 talloc_free (notmuch);
771 notmuch_database_close (notmuch_database_t *notmuch)
774 if (notmuch->xapian_db != NULL &&
775 notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
776 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
777 } catch (const Xapian::Error &error) {
778 if (! notmuch->exception_reported) {
779 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
780 error.get_msg().c_str());
784 /* Many Xapian objects (and thus notmuch objects) hold references to
785 * the database, so merely deleting the database may not suffice to
786 * close it. Thus, we explicitly close it here. */
787 if (notmuch->xapian_db != NULL) {
789 notmuch->xapian_db->close();
790 } catch (const Xapian::Error &error) {
795 delete notmuch->term_gen;
796 notmuch->term_gen = NULL;
797 delete notmuch->query_parser;
798 notmuch->query_parser = NULL;
799 delete notmuch->xapian_db;
800 notmuch->xapian_db = NULL;
801 delete notmuch->value_range_processor;
802 notmuch->value_range_processor = NULL;
803 delete notmuch->date_range_processor;
804 notmuch->date_range_processor = NULL;
807 #if HAVE_XAPIAN_COMPACT
809 unlink_cb (const char *path,
810 unused (const struct stat *sb),
812 unused (struct FTW *ftw))
814 return remove (path);
818 rmtree (const char *path)
820 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
823 class NotmuchCompactor : public Xapian::Compactor
825 notmuch_compact_status_cb_t status_cb;
826 void *status_closure;
829 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
830 status_cb (cb), status_closure (closure) { }
833 set_status (const std::string &table, const std::string &status)
837 if (status_cb == NULL)
840 if (status.length () == 0)
841 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
843 msg = talloc_asprintf (NULL, " %s", status.c_str());
849 status_cb (msg, status_closure);
854 /* Compacts the given database, optionally saving the original database
855 * in backup_path. Additionally, a callback function can be provided to
856 * give the user feedback on the progress of the (likely long-lived)
857 * compaction process.
859 * The backup path must point to a directory on the same volume as the
860 * original database. Passing a NULL backup_path will result in the
861 * uncompacted database being deleted after compaction has finished.
862 * Note that the database write lock will be held during the
863 * compaction process to protect data integrity.
866 notmuch_database_compact (const char *path,
867 const char *backup_path,
868 notmuch_compact_status_cb_t status_cb,
872 char *notmuch_path, *xapian_path, *compact_xapian_path;
873 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
874 notmuch_database_t *notmuch = NULL;
876 notmuch_bool_t keep_backup;
878 local = talloc_new (NULL);
880 return NOTMUCH_STATUS_OUT_OF_MEMORY;
882 ret = notmuch_database_open (path, NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much);
887 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
888 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
892 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
893 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
897 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
898 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
902 if (backup_path == NULL) {
903 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
904 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
913 if (stat (backup_path, &statbuf) != -1) {
914 fprintf (stderr, "Path already exists: %s\n", backup_path);
915 ret = NOTMUCH_STATUS_FILE_ERROR;
918 if (errno != ENOENT) {
919 fprintf (stderr, "Unknown error while stat()ing path: %s\n",
921 ret = NOTMUCH_STATUS_FILE_ERROR;
925 /* Unconditionally attempt to remove old work-in-progress database (if
926 * any). This is "protected" by database lock. If this fails due to write
927 * errors (etc), the following code will fail and provide error message.
929 (void) rmtree (compact_xapian_path);
932 NotmuchCompactor compactor (status_cb, closure);
934 compactor.set_renumber (false);
935 compactor.add_source (xapian_path);
936 compactor.set_destdir (compact_xapian_path);
937 compactor.compact ();
938 } catch (const Xapian::Error &error) {
939 fprintf (stderr, "Error while compacting: %s\n", error.get_msg().c_str());
940 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
944 if (rename (xapian_path, backup_path)) {
945 fprintf (stderr, "Error moving old database out of the way\n");
946 ret = NOTMUCH_STATUS_FILE_ERROR;
950 if (rename (compact_xapian_path, xapian_path)) {
951 fprintf (stderr, "Error moving compacted database\n");
952 ret = NOTMUCH_STATUS_FILE_ERROR;
957 rmtree (backup_path);
961 notmuch_database_destroy (notmuch);
969 notmuch_database_compact (unused (const char *path),
970 unused (const char *backup_path),
971 unused (notmuch_compact_status_cb_t status_cb),
972 unused (void *closure))
974 fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
975 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
980 notmuch_database_destroy (notmuch_database_t *notmuch)
982 notmuch_database_close (notmuch);
983 talloc_free (notmuch);
987 notmuch_database_get_path (notmuch_database_t *notmuch)
989 return notmuch->path;
993 notmuch_database_get_version (notmuch_database_t *notmuch)
995 unsigned int version;
996 string version_string;
1000 version_string = notmuch->xapian_db->get_metadata ("version");
1001 if (version_string.empty ())
1004 str = version_string.c_str ();
1005 if (str == NULL || *str == '\0')
1008 version = strtoul (str, &end, 10);
1010 INTERNAL_ERROR ("Malformed database version: %s", str);
1016 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1018 return notmuch->needs_upgrade;
1021 static volatile sig_atomic_t do_progress_notify = 0;
1024 handle_sigalrm (unused (int signal))
1026 do_progress_notify = 1;
1029 /* Upgrade the current database.
1031 * After opening a database in read-write mode, the client should
1032 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1033 * if so, upgrade with this function before making any modifications.
1035 * The optional progress_notify callback can be used by the caller to
1036 * provide progress indication to the user. If non-NULL it will be
1037 * called periodically with 'count' as the number of messages upgraded
1038 * so far and 'total' the overall number of messages that will be
1042 notmuch_database_upgrade (notmuch_database_t *notmuch,
1043 void (*progress_notify) (void *closure,
1047 Xapian::WritableDatabase *db;
1048 struct sigaction action;
1049 struct itimerval timerval;
1050 notmuch_bool_t timer_is_active = FALSE;
1051 unsigned int version;
1052 notmuch_status_t status;
1053 unsigned int count = 0, total = 0;
1055 status = _notmuch_database_ensure_writable (notmuch);
1059 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1061 version = notmuch_database_get_version (notmuch);
1063 if (version >= NOTMUCH_DATABASE_VERSION)
1064 return NOTMUCH_STATUS_SUCCESS;
1066 if (progress_notify) {
1067 /* Setup our handler for SIGALRM */
1068 memset (&action, 0, sizeof (struct sigaction));
1069 action.sa_handler = handle_sigalrm;
1070 sigemptyset (&action.sa_mask);
1071 action.sa_flags = SA_RESTART;
1072 sigaction (SIGALRM, &action, NULL);
1074 /* Then start a timer to send SIGALRM once per second. */
1075 timerval.it_interval.tv_sec = 1;
1076 timerval.it_interval.tv_usec = 0;
1077 timerval.it_value.tv_sec = 1;
1078 timerval.it_value.tv_usec = 0;
1079 setitimer (ITIMER_REAL, &timerval, NULL);
1081 timer_is_active = TRUE;
1084 /* Before version 1, each message document had its filename in the
1085 * data field. Copy that into the new format by calling
1086 * notmuch_message_add_filename.
1089 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1090 notmuch_messages_t *messages;
1091 notmuch_message_t *message;
1093 Xapian::TermIterator t, t_end;
1095 total = notmuch_query_count_messages (query);
1097 for (messages = notmuch_query_search_messages (query);
1098 notmuch_messages_valid (messages);
1099 notmuch_messages_move_to_next (messages))
1101 if (do_progress_notify) {
1102 progress_notify (closure, (double) count / total);
1103 do_progress_notify = 0;
1106 message = notmuch_messages_get (messages);
1108 filename = _notmuch_message_talloc_copy_data (message);
1109 if (filename && *filename != '\0') {
1110 _notmuch_message_add_filename (message, filename);
1111 _notmuch_message_sync (message);
1113 talloc_free (filename);
1115 notmuch_message_destroy (message);
1120 notmuch_query_destroy (query);
1122 /* Also, before version 1 we stored directory timestamps in
1123 * XTIMESTAMP documents instead of the current XDIRECTORY
1124 * documents. So copy those as well. */
1126 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1128 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1132 Xapian::PostingIterator p, p_end;
1133 std::string term = *t;
1135 p_end = notmuch->xapian_db->postlist_end (term);
1137 for (p = notmuch->xapian_db->postlist_begin (term);
1141 Xapian::Document document;
1143 notmuch_directory_t *directory;
1145 if (do_progress_notify) {
1146 progress_notify (closure, (double) count / total);
1147 do_progress_notify = 0;
1150 document = find_document_for_doc_id (notmuch, *p);
1151 mtime = Xapian::sortable_unserialise (
1152 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1154 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1155 NOTMUCH_FIND_CREATE, &status);
1156 notmuch_directory_set_mtime (directory, mtime);
1157 notmuch_directory_destroy (directory);
1162 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1165 /* Now that the upgrade is complete we can remove the old data
1166 * and documents that are no longer needed. */
1168 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1169 notmuch_messages_t *messages;
1170 notmuch_message_t *message;
1173 for (messages = notmuch_query_search_messages (query);
1174 notmuch_messages_valid (messages);
1175 notmuch_messages_move_to_next (messages))
1177 if (do_progress_notify) {
1178 progress_notify (closure, (double) count / total);
1179 do_progress_notify = 0;
1182 message = notmuch_messages_get (messages);
1184 filename = _notmuch_message_talloc_copy_data (message);
1185 if (filename && *filename != '\0') {
1186 _notmuch_message_clear_data (message);
1187 _notmuch_message_sync (message);
1189 talloc_free (filename);
1191 notmuch_message_destroy (message);
1194 notmuch_query_destroy (query);
1198 Xapian::TermIterator t, t_end;
1200 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1202 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1206 Xapian::PostingIterator p, p_end;
1207 std::string term = *t;
1209 p_end = notmuch->xapian_db->postlist_end (term);
1211 for (p = notmuch->xapian_db->postlist_begin (term);
1215 if (do_progress_notify) {
1216 progress_notify (closure, (double) count / total);
1217 do_progress_notify = 0;
1220 db->delete_document (*p);
1225 if (timer_is_active) {
1226 /* Now stop the timer. */
1227 timerval.it_interval.tv_sec = 0;
1228 timerval.it_interval.tv_usec = 0;
1229 timerval.it_value.tv_sec = 0;
1230 timerval.it_value.tv_usec = 0;
1231 setitimer (ITIMER_REAL, &timerval, NULL);
1233 /* And disable the signal handler. */
1234 action.sa_handler = SIG_IGN;
1235 sigaction (SIGALRM, &action, NULL);
1238 return NOTMUCH_STATUS_SUCCESS;
1242 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1244 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1245 notmuch->atomic_nesting > 0)
1249 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1250 } catch (const Xapian::Error &error) {
1251 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1252 error.get_msg().c_str());
1253 notmuch->exception_reported = TRUE;
1254 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1258 notmuch->atomic_nesting++;
1259 return NOTMUCH_STATUS_SUCCESS;
1263 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1265 Xapian::WritableDatabase *db;
1267 if (notmuch->atomic_nesting == 0)
1268 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1270 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1271 notmuch->atomic_nesting > 1)
1274 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1276 db->commit_transaction ();
1278 /* This is a hack for testing. Xapian never flushes on a
1279 * non-flushed commit, even if the flush threshold is 1.
1280 * However, we rely on flushing to test atomicity. */
1281 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1282 if (thresh && atoi (thresh) == 1)
1284 } catch (const Xapian::Error &error) {
1285 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1286 error.get_msg().c_str());
1287 notmuch->exception_reported = TRUE;
1288 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1292 notmuch->atomic_nesting--;
1293 return NOTMUCH_STATUS_SUCCESS;
1296 /* We allow the user to use arbitrarily long paths for directories. But
1297 * we have a term-length limit. So if we exceed that, we'll use the
1298 * SHA-1 of the path for the database term.
1300 * Note: This function may return the original value of 'path'. If it
1301 * does not, then the caller is responsible to free() the returned
1305 _notmuch_database_get_directory_db_path (const char *path)
1307 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1309 if (term_len > NOTMUCH_TERM_MAX)
1310 return notmuch_sha1_of_string (path);
1315 /* Given a path, split it into two parts: the directory part is all
1316 * components except for the last, and the basename is that last
1317 * component. Getting the return-value for either part is optional
1318 * (the caller can pass NULL).
1320 * The original 'path' can represent either a regular file or a
1321 * directory---the splitting will be carried out in the same way in
1322 * either case. Trailing slashes on 'path' will be ignored, and any
1323 * cases of multiple '/' characters appearing in series will be
1324 * treated as a single '/'.
1326 * Allocation (if any) will have 'ctx' as the talloc owner. But
1327 * pointers will be returned within the original path string whenever
1330 * Note: If 'path' is non-empty and contains no non-trailing slash,
1331 * (that is, consists of a filename with no parent directory), then
1332 * the directory returned will be an empty string. However, if 'path'
1333 * is an empty string, then both directory and basename will be
1337 _notmuch_database_split_path (void *ctx,
1339 const char **directory,
1340 const char **basename)
1344 if (path == NULL || *path == '\0') {
1349 return NOTMUCH_STATUS_SUCCESS;
1352 /* Find the last slash (not counting a trailing slash), if any. */
1354 slash = path + strlen (path) - 1;
1356 /* First, skip trailing slashes. */
1357 while (slash != path) {
1364 /* Then, find a slash. */
1365 while (slash != path) {
1375 /* Finally, skip multiple slashes. */
1376 while (slash != path) {
1383 if (slash == path) {
1385 *directory = talloc_strdup (ctx, "");
1390 *directory = talloc_strndup (ctx, path, slash - path + 1);
1393 return NOTMUCH_STATUS_SUCCESS;
1396 /* Find the document ID of the specified directory.
1398 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1399 * created if one does not exist for 'path'. Otherwise, if the
1400 * directory document does not exist, this sets *directory_id to
1401 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1404 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1406 notmuch_find_flags_t flags,
1407 unsigned int *directory_id)
1409 notmuch_directory_t *directory;
1410 notmuch_status_t status;
1414 return NOTMUCH_STATUS_SUCCESS;
1417 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1418 if (status || !directory) {
1423 *directory_id = _notmuch_directory_get_document_id (directory);
1425 notmuch_directory_destroy (directory);
1427 return NOTMUCH_STATUS_SUCCESS;
1431 _notmuch_database_get_directory_path (void *ctx,
1432 notmuch_database_t *notmuch,
1433 unsigned int doc_id)
1435 Xapian::Document document;
1437 document = find_document_for_doc_id (notmuch, doc_id);
1439 return talloc_strdup (ctx, document.get_data ().c_str ());
1442 /* Given a legal 'filename' for the database, (either relative to
1443 * database path or absolute with initial components identical to
1444 * database path), return a new string (with 'ctx' as the talloc
1445 * owner) suitable for use as a direntry term value.
1447 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1448 * will be created in the database as needed. Otherwise, if the
1449 * necessary directory documents do not exist, this sets
1450 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1453 _notmuch_database_filename_to_direntry (void *ctx,
1454 notmuch_database_t *notmuch,
1455 const char *filename,
1456 notmuch_find_flags_t flags,
1459 const char *relative, *directory, *basename;
1460 Xapian::docid directory_id;
1461 notmuch_status_t status;
1463 relative = _notmuch_database_relative_path (notmuch, filename);
1465 status = _notmuch_database_split_path (ctx, relative,
1466 &directory, &basename);
1470 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1472 if (status || directory_id == (unsigned int)-1) {
1477 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1479 return NOTMUCH_STATUS_SUCCESS;
1482 /* Given a legal 'path' for the database, return the relative path.
1484 * The return value will be a pointer to the original path contents,
1485 * and will be either the original string (if 'path' was relative) or
1486 * a portion of the string (if path was absolute and begins with the
1490 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1493 const char *db_path, *relative;
1494 unsigned int db_path_len;
1496 db_path = notmuch_database_get_path (notmuch);
1497 db_path_len = strlen (db_path);
1501 if (*relative == '/') {
1502 while (*relative == '/' && *(relative+1) == '/')
1505 if (strncmp (relative, db_path, db_path_len) == 0)
1507 relative += db_path_len;
1508 while (*relative == '/')
1517 notmuch_database_get_directory (notmuch_database_t *notmuch,
1519 notmuch_directory_t **directory)
1521 notmuch_status_t status;
1523 if (directory == NULL)
1524 return NOTMUCH_STATUS_NULL_POINTER;
1528 *directory = _notmuch_directory_create (notmuch, path,
1529 NOTMUCH_FIND_LOOKUP, &status);
1530 } catch (const Xapian::Error &error) {
1531 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1532 error.get_msg().c_str());
1533 notmuch->exception_reported = TRUE;
1534 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1539 /* Allocate a document ID that satisfies the following criteria:
1541 * 1. The ID does not exist for any document in the Xapian database
1543 * 2. The ID was not previously returned from this function
1545 * 3. The ID is the smallest integer satisfying (1) and (2)
1547 * This function will trigger an internal error if these constraints
1548 * cannot all be satisfied, (that is, the pool of available document
1549 * IDs has been exhausted).
1552 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1554 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1556 notmuch->last_doc_id++;
1558 if (notmuch->last_doc_id == 0)
1559 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1561 return notmuch->last_doc_id;
1565 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1567 /* 16 bytes (+ terminator) for hexadecimal representation of
1568 * a 64-bit integer. */
1569 static char thread_id[17];
1570 Xapian::WritableDatabase *db;
1572 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1574 notmuch->last_thread_id++;
1576 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1578 db->set_metadata ("last_thread_id", thread_id);
1584 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1586 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1587 message_id = _message_id_compressed (ctx, message_id);
1589 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1593 /* Find the thread ID to which the message with 'message_id' belongs.
1595 * Note: 'thread_id_ret' must not be NULL!
1596 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1599 * Note: If there is no message in the database with the given
1600 * 'message_id' then a new thread_id will be allocated for this
1601 * message and stored in the database metadata, (where this same
1602 * thread ID can be looked up if the message is added to the database
1605 static notmuch_status_t
1606 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1608 const char *message_id,
1609 const char **thread_id_ret)
1611 notmuch_status_t status;
1612 notmuch_message_t *message;
1613 string thread_id_string;
1615 Xapian::WritableDatabase *db;
1617 status = notmuch_database_find_message (notmuch, message_id, &message);
1623 *thread_id_ret = talloc_steal (ctx,
1624 notmuch_message_get_thread_id (message));
1626 notmuch_message_destroy (message);
1628 return NOTMUCH_STATUS_SUCCESS;
1631 /* Message has not been seen yet.
1633 * We may have seen a reference to it already, in which case, we
1634 * can return the thread ID stored in the metadata. Otherwise, we
1635 * generate a new thread ID and store it there.
1637 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1638 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1639 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1641 if (thread_id_string.empty()) {
1642 *thread_id_ret = talloc_strdup (ctx,
1643 _notmuch_database_generate_thread_id (notmuch));
1644 db->set_metadata (metadata_key, *thread_id_ret);
1646 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1649 talloc_free (metadata_key);
1651 return NOTMUCH_STATUS_SUCCESS;
1654 static notmuch_status_t
1655 _merge_threads (notmuch_database_t *notmuch,
1656 const char *winner_thread_id,
1657 const char *loser_thread_id)
1659 Xapian::PostingIterator loser, loser_end;
1660 notmuch_message_t *message = NULL;
1661 notmuch_private_status_t private_status;
1662 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1664 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1666 for ( ; loser != loser_end; loser++) {
1667 message = _notmuch_message_create (notmuch, notmuch,
1668 *loser, &private_status);
1669 if (message == NULL) {
1670 ret = COERCE_STATUS (private_status,
1671 "Cannot find document for doc_id from query");
1675 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1676 _notmuch_message_add_term (message, "thread", winner_thread_id);
1677 _notmuch_message_sync (message);
1679 notmuch_message_destroy (message);
1685 notmuch_message_destroy (message);
1691 _my_talloc_free_for_g_hash (void *ptr)
1696 static notmuch_status_t
1697 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1698 notmuch_message_t *message,
1699 notmuch_message_file_t *message_file,
1700 const char **thread_id)
1702 GHashTable *parents = NULL;
1703 const char *refs, *in_reply_to, *in_reply_to_message_id;
1704 const char *last_ref_message_id, *this_message_id;
1705 GList *l, *keys = NULL;
1706 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1708 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1709 _my_talloc_free_for_g_hash, NULL);
1710 this_message_id = notmuch_message_get_message_id (message);
1712 refs = notmuch_message_file_get_header (message_file, "references");
1713 last_ref_message_id = parse_references (message,
1717 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1718 in_reply_to_message_id = parse_references (message,
1720 parents, in_reply_to);
1722 /* For the parent of this message, use the last message ID of the
1723 * References header, if available. If not, fall back to the
1724 * first message ID in the In-Reply-To header. */
1725 if (last_ref_message_id) {
1726 _notmuch_message_add_term (message, "replyto",
1727 last_ref_message_id);
1728 } else if (in_reply_to_message_id) {
1729 _notmuch_message_add_term (message, "replyto",
1730 in_reply_to_message_id);
1733 keys = g_hash_table_get_keys (parents);
1734 for (l = keys; l; l = l->next) {
1735 char *parent_message_id;
1736 const char *parent_thread_id = NULL;
1738 parent_message_id = (char *) l->data;
1740 _notmuch_message_add_term (message, "reference",
1743 ret = _resolve_message_id_to_thread_id (notmuch,
1750 if (*thread_id == NULL) {
1751 *thread_id = talloc_strdup (message, parent_thread_id);
1752 _notmuch_message_add_term (message, "thread", *thread_id);
1753 } else if (strcmp (*thread_id, parent_thread_id)) {
1754 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1764 g_hash_table_unref (parents);
1769 static notmuch_status_t
1770 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1771 notmuch_message_t *message,
1772 const char **thread_id)
1774 const char *message_id = notmuch_message_get_message_id (message);
1775 Xapian::PostingIterator child, children_end;
1776 notmuch_message_t *child_message = NULL;
1777 const char *child_thread_id;
1778 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1779 notmuch_private_status_t private_status;
1781 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1783 for ( ; child != children_end; child++) {
1785 child_message = _notmuch_message_create (message, notmuch,
1786 *child, &private_status);
1787 if (child_message == NULL) {
1788 ret = COERCE_STATUS (private_status,
1789 "Cannot find document for doc_id from query");
1793 child_thread_id = notmuch_message_get_thread_id (child_message);
1794 if (*thread_id == NULL) {
1795 *thread_id = talloc_strdup (message, child_thread_id);
1796 _notmuch_message_add_term (message, "thread", *thread_id);
1797 } else if (strcmp (*thread_id, child_thread_id)) {
1798 _notmuch_message_remove_term (child_message, "reference",
1800 _notmuch_message_sync (child_message);
1801 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1806 notmuch_message_destroy (child_message);
1807 child_message = NULL;
1812 notmuch_message_destroy (child_message);
1817 /* Given a (mostly empty) 'message' and its corresponding
1818 * 'message_file' link it to existing threads in the database.
1820 * The first check is in the metadata of the database to see if we
1821 * have pre-allocated a thread_id in advance for this message, (which
1822 * would have happened if a message was previously added that
1823 * referenced this one).
1825 * Second, we look at 'message_file' and its link-relevant headers
1826 * (References and In-Reply-To) for message IDs.
1828 * Finally, we look in the database for existing message that
1829 * reference 'message'.
1831 * In all cases, we assign to the current message the first thread_id
1832 * found (through either parent or child). We will also merge any
1833 * existing, distinct threads where this message belongs to both,
1834 * (which is not uncommon when messages are processed out of order).
1836 * Finally, if no thread ID has been found through parent or child, we
1837 * call _notmuch_message_generate_thread_id to generate a new thread
1838 * ID. This should only happen for new, top-level messages, (no
1839 * References or In-Reply-To header in this message, and no previously
1840 * added message refers to this message).
1842 static notmuch_status_t
1843 _notmuch_database_link_message (notmuch_database_t *notmuch,
1844 notmuch_message_t *message,
1845 notmuch_message_file_t *message_file)
1847 notmuch_status_t status;
1848 const char *message_id, *thread_id = NULL;
1852 message_id = notmuch_message_get_message_id (message);
1853 metadata_key = _get_metadata_thread_id_key (message, message_id);
1855 /* Check if we have already seen related messages to this one.
1856 * If we have then use the thread_id that we stored at that time.
1858 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1859 if (! stored_id.empty()) {
1860 Xapian::WritableDatabase *db;
1862 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1864 /* Clear the metadata for this message ID. We don't need it
1866 db->set_metadata (metadata_key, "");
1867 thread_id = stored_id.c_str();
1869 _notmuch_message_add_term (message, "thread", thread_id);
1871 talloc_free (metadata_key);
1873 status = _notmuch_database_link_message_to_parents (notmuch, message,
1879 status = _notmuch_database_link_message_to_children (notmuch, message,
1884 /* If not part of any existing thread, generate a new thread ID. */
1885 if (thread_id == NULL) {
1886 thread_id = _notmuch_database_generate_thread_id (notmuch);
1888 _notmuch_message_add_term (message, "thread", thread_id);
1891 return NOTMUCH_STATUS_SUCCESS;
1895 notmuch_database_add_message (notmuch_database_t *notmuch,
1896 const char *filename,
1897 notmuch_message_t **message_ret)
1899 notmuch_message_file_t *message_file;
1900 notmuch_message_t *message = NULL;
1901 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1902 notmuch_private_status_t private_status;
1904 const char *date, *header;
1905 const char *from, *to, *subject;
1906 char *message_id = NULL;
1909 *message_ret = NULL;
1911 ret = _notmuch_database_ensure_writable (notmuch);
1915 message_file = notmuch_message_file_open (filename);
1916 if (message_file == NULL)
1917 return NOTMUCH_STATUS_FILE_ERROR;
1919 /* Adding a message may change many documents. Do this all
1921 ret = notmuch_database_begin_atomic (notmuch);
1925 notmuch_message_file_restrict_headers (message_file,
1936 /* Before we do any real work, (especially before doing a
1937 * potential SHA-1 computation on the entire file's contents),
1938 * let's make sure that what we're looking at looks like an
1939 * actual email message.
1941 from = notmuch_message_file_get_header (message_file, "from");
1942 subject = notmuch_message_file_get_header (message_file, "subject");
1943 to = notmuch_message_file_get_header (message_file, "to");
1945 if ((from == NULL || *from == '\0') &&
1946 (subject == NULL || *subject == '\0') &&
1947 (to == NULL || *to == '\0'))
1949 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1953 /* Now that we're sure it's mail, the first order of business
1954 * is to find a message ID (or else create one ourselves). */
1956 header = notmuch_message_file_get_header (message_file, "message-id");
1957 if (header && *header != '\0') {
1958 message_id = _parse_message_id (message_file, header, NULL);
1960 /* So the header value isn't RFC-compliant, but it's
1961 * better than no message-id at all. */
1962 if (message_id == NULL)
1963 message_id = talloc_strdup (message_file, header);
1965 /* If a message ID is too long, substitute its sha1 instead. */
1966 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1967 char *compressed = _message_id_compressed (message_file,
1969 talloc_free (message_id);
1970 message_id = compressed;
1974 if (message_id == NULL ) {
1975 /* No message-id at all, let's generate one by taking a
1976 * hash over the file's contents. */
1977 char *sha1 = notmuch_sha1_of_file (filename);
1979 /* If that failed too, something is really wrong. Give up. */
1981 ret = NOTMUCH_STATUS_FILE_ERROR;
1985 message_id = talloc_asprintf (message_file,
1986 "notmuch-sha1-%s", sha1);
1990 /* Now that we have a message ID, we get a message object,
1991 * (which may or may not reference an existing document in the
1994 message = _notmuch_message_create_for_message_id (notmuch,
1998 talloc_free (message_id);
2000 if (message == NULL) {
2001 ret = COERCE_STATUS (private_status,
2002 "Unexpected status value from _notmuch_message_create_for_message_id");
2006 _notmuch_message_add_filename (message, filename);
2008 /* Is this a newly created message object? */
2009 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2010 _notmuch_message_add_term (message, "type", "mail");
2012 ret = _notmuch_database_link_message (notmuch, message,
2017 date = notmuch_message_file_get_header (message_file, "date");
2018 _notmuch_message_set_header_values (message, date, from, subject);
2020 ret = _notmuch_message_index_file (message, filename);
2024 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2027 _notmuch_message_sync (message);
2028 } catch (const Xapian::Error &error) {
2029 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2030 error.get_msg().c_str());
2031 notmuch->exception_reported = TRUE;
2032 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2038 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2039 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2040 *message_ret = message;
2042 notmuch_message_destroy (message);
2046 notmuch_message_file_close (message_file);
2048 ret2 = notmuch_database_end_atomic (notmuch);
2049 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2050 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2051 ret2 != NOTMUCH_STATUS_SUCCESS)
2058 notmuch_database_remove_message (notmuch_database_t *notmuch,
2059 const char *filename)
2061 notmuch_status_t status;
2062 notmuch_message_t *message;
2064 status = notmuch_database_find_message_by_filename (notmuch, filename,
2067 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2068 status = _notmuch_message_remove_filename (message, filename);
2069 if (status == NOTMUCH_STATUS_SUCCESS)
2070 _notmuch_message_delete (message);
2071 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2072 _notmuch_message_sync (message);
2074 notmuch_message_destroy (message);
2081 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2082 const char *filename,
2083 notmuch_message_t **message_ret)
2086 const char *prefix = _find_prefix ("file-direntry");
2087 char *direntry, *term;
2088 Xapian::PostingIterator i, end;
2089 notmuch_status_t status;
2091 if (message_ret == NULL)
2092 return NOTMUCH_STATUS_NULL_POINTER;
2094 /* return NULL on any failure */
2095 *message_ret = NULL;
2097 local = talloc_new (notmuch);
2100 status = _notmuch_database_filename_to_direntry (
2101 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2102 if (status || !direntry)
2105 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2107 find_doc_ids_for_term (notmuch, term, &i, &end);
2110 notmuch_private_status_t private_status;
2112 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2114 if (*message_ret == NULL)
2115 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2117 } catch (const Xapian::Error &error) {
2118 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2119 error.get_msg().c_str());
2120 notmuch->exception_reported = TRUE;
2121 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2125 talloc_free (local);
2127 if (status && *message_ret) {
2128 notmuch_message_destroy (*message_ret);
2129 *message_ret = NULL;
2134 notmuch_string_list_t *
2135 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2136 Xapian::TermIterator &end,
2139 int prefix_len = strlen (prefix);
2140 notmuch_string_list_t *list;
2142 list = _notmuch_string_list_create (ctx);
2143 if (unlikely (list == NULL))
2146 for (i.skip_to (prefix); i != end; i++) {
2147 /* Terminate loop at first term without desired prefix. */
2148 if (strncmp ((*i).c_str (), prefix, prefix_len))
2151 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2158 notmuch_database_get_all_tags (notmuch_database_t *db)
2160 Xapian::TermIterator i, end;
2161 notmuch_string_list_t *tags;
2164 i = db->xapian_db->allterms_begin();
2165 end = db->xapian_db->allterms_end();
2166 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2167 _find_prefix ("tag"));
2168 _notmuch_string_list_sort (tags);
2169 return _notmuch_tags_create (db, tags);
2170 } catch (const Xapian::Error &error) {
2171 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2172 error.get_msg().c_str());
2173 db->exception_reported = TRUE;