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 2
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. It
58 * is stored in one or more files on disk (though only one has its
59 * content indexed) and is uniquely identified by its "id" field
60 * (which is generally the message ID). It is indexed with the
61 * following prefixed terms which the database uses to construct
64 * Single terms of given prefix:
68 * id: Unique ID of mail. This is from the Message-ID header
69 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
70 * If it's present and too long, then we use
71 * "notmuch-sha1-<sha1_sum_of_message_id>".
72 * If this header is not present, we use
73 * "notmuch-sha1-<sha1_sum_of_entire_file>".
75 * thread: The ID of the thread to which the mail belongs
77 * replyto: The ID from the In-Reply-To header of the mail (if any).
79 * Multiple terms of given prefix:
81 * reference: All message IDs from In-Reply-To and References
82 * headers in the message.
84 * tag: Any tags associated with this message by the user.
86 * file-direntry: A colon-separated pair of values
87 * (INTEGER:STRING), where INTEGER is the
88 * document ID of a directory document, and
89 * STRING is the name of a file within that
90 * directory for this mail message.
92 * A mail document also has four values:
94 * TIMESTAMP: The time_t value corresponding to the message's
97 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
99 * FROM: The value of the "From" header
101 * SUBJECT: The value of the "Subject" header
103 * In addition, terms from the content of the message are added with
104 * "from", "to", "attachment", and "subject" prefixes for use by the
105 * user in searching. Similarly, terms from the path of the mail
106 * message are added with "folder" and "path" prefixes. But the
107 * database doesn't really care itself about any of these.
109 * The data portion of a mail document is empty.
113 * A directory document is used by a client of the notmuch library to
114 * maintain data necessary to allow for efficient polling of mail
117 * All directory documents contain one term:
119 * directory: The directory path (relative to the database path)
120 * Or the SHA1 sum of the directory path (if the
121 * path itself is too long to fit in a Xapian
124 * And all directory documents for directories other than top-level
125 * directories also contain the following term:
127 * directory-direntry: A colon-separated pair of values
128 * (INTEGER:STRING), where INTEGER is the
129 * document ID of the parent directory
130 * document, and STRING is the name of this
131 * directory within that parent.
133 * All directory documents have a single value:
135 * TIMESTAMP: The mtime of the directory (at last scan)
137 * The data portion of a directory document contains the path of the
138 * directory (relative to the database path).
142 * Xapian allows us to store arbitrary name-value pairs as
143 * "metadata". We currently use the following metadata names with the
146 * version The database schema version, (which is distinct
147 * from both the notmuch package version (see
148 * notmuch --version) and the libnotmuch library
149 * version. The version is stored as an base-10
150 * ASCII integer. The initial database version
151 * was 1, (though a schema existed before that
152 * were no "version" database value existed at
153 * all). Successive versions are allocated as
154 * changes are made to the database (such as by
155 * indexing new fields).
157 * last_thread_id The last thread ID generated. This is stored
158 * as a 16-byte hexadecimal ASCII representation
159 * of a 64-bit unsigned integer. The first ID
160 * generated is 1 and the value will be
161 * incremented for each thread ID.
163 * thread_id_* A pre-allocated thread ID for a particular
164 * message. This is actually an arbitrarily large
165 * family of metadata name. Any particular name is
166 * formed by concatenating "thread_id_" with a message
167 * ID (or the SHA1 sum of a message ID if it is very
168 * long---see description of 'id' in the mail
169 * document). The value stored is a thread ID.
171 * These thread ID metadata values are stored
172 * whenever a message references a parent message
173 * that does not yet exist in the database. A
174 * thread ID will be allocated and stored, and if
175 * the message is later added, the stored thread
176 * ID will be used (and the metadata value will
179 * Even before a message is added, it's
180 * pre-allocated thread ID is useful so that all
181 * descendant messages that reference this common
182 * parent can be recognized as belonging to the
186 /* With these prefix values we follow the conventions published here:
188 * http://xapian.org/docs/omega/termprefixes.html
190 * as much as makes sense. Note that I took some liberty in matching
191 * the reserved prefix values to notmuch concepts, (for example, 'G'
192 * is documented as "newsGroup (or similar entity - e.g. a web forum
193 * name)", for which I think the thread is the closest analogue in
194 * notmuch. This in spite of the fact that we will eventually be
195 * storing mailing-list messages where 'G' for "mailing list name"
196 * might be even a closer analogue. I'm treating the single-character
197 * prefixes preferentially for core notmuch concepts (which will be
198 * nearly universal to all mail messages).
201 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
203 { "reference", "XREFERENCE" },
204 { "replyto", "XREPLYTO" },
205 { "directory", "XDIRECTORY" },
206 { "file-direntry", "XFDIRENTRY" },
207 { "directory-direntry", "XDDIRENTRY" },
210 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
217 * Without the ":", since this is a multi-letter prefix, Xapian
218 * will add a colon itself if the first letter of the path is
219 * upper-case ASCII. Including the ":" forces there to always be a
220 * colon, which keeps our own logic simpler.
222 { "folder", "XFOLDER:" },
225 static prefix_t PROBABILISTIC_PREFIX[]= {
228 { "attachment", "XATTACHMENT" },
229 { "subject", "XSUBJECT"},
233 _find_prefix (const char *name)
237 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
238 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
239 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
242 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
243 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
244 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
247 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
248 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
249 return PROBABILISTIC_PREFIX[i].prefix;
252 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
258 notmuch_status_to_string (notmuch_status_t status)
261 case NOTMUCH_STATUS_SUCCESS:
262 return "No error occurred";
263 case NOTMUCH_STATUS_OUT_OF_MEMORY:
264 return "Out of memory";
265 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
266 return "Attempt to write to a read-only database";
267 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
268 return "A Xapian exception occurred";
269 case NOTMUCH_STATUS_FILE_ERROR:
270 return "Something went wrong trying to read or write a file";
271 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
272 return "File is not an email";
273 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
274 return "Message ID is identical to a message in database";
275 case NOTMUCH_STATUS_NULL_POINTER:
276 return "Erroneous NULL pointer";
277 case NOTMUCH_STATUS_TAG_TOO_LONG:
278 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
279 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
280 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
281 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
282 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
283 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
284 return "Unsupported operation";
286 case NOTMUCH_STATUS_LAST_STATUS:
287 return "Unknown error status value";
292 find_doc_ids_for_term (notmuch_database_t *notmuch,
294 Xapian::PostingIterator *begin,
295 Xapian::PostingIterator *end)
297 *begin = notmuch->xapian_db->postlist_begin (term);
299 *end = notmuch->xapian_db->postlist_end (term);
303 find_doc_ids (notmuch_database_t *notmuch,
304 const char *prefix_name,
306 Xapian::PostingIterator *begin,
307 Xapian::PostingIterator *end)
311 term = talloc_asprintf (notmuch, "%s%s",
312 _find_prefix (prefix_name), value);
314 find_doc_ids_for_term (notmuch, term, begin, end);
319 notmuch_private_status_t
320 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
321 const char *prefix_name,
323 unsigned int *doc_id)
325 Xapian::PostingIterator i, end;
327 find_doc_ids (notmuch, prefix_name, value, &i, &end);
331 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
336 #if DEBUG_DATABASE_SANITY
340 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
344 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
347 static Xapian::Document
348 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
350 return notmuch->xapian_db->get_document (doc_id);
353 /* Generate a compressed version of 'message_id' of the form:
355 * notmuch-sha1-<sha1_sum_of_message_id>
358 _message_id_compressed (void *ctx, const char *message_id)
360 char *sha1, *compressed;
362 sha1 = _notmuch_sha1_of_string (message_id);
364 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
371 notmuch_database_find_message (notmuch_database_t *notmuch,
372 const char *message_id,
373 notmuch_message_t **message_ret)
375 notmuch_private_status_t status;
378 if (message_ret == NULL)
379 return NOTMUCH_STATUS_NULL_POINTER;
381 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
382 message_id = _message_id_compressed (notmuch, message_id);
385 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
386 message_id, &doc_id);
388 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
391 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
393 if (*message_ret == NULL)
394 return NOTMUCH_STATUS_OUT_OF_MEMORY;
397 return NOTMUCH_STATUS_SUCCESS;
398 } catch (const Xapian::Error &error) {
399 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
400 error.get_msg().c_str());
401 notmuch->exception_reported = TRUE;
403 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
407 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
408 * a (potentially nested) parenthesized sequence with '\' used to
409 * escape any character (including parentheses).
411 * If the sequence to be skipped continues to the end of the string,
412 * then 'str' will be left pointing at the final terminating '\0'
416 skip_space_and_comments (const char **str)
421 while (*s && (isspace (*s) || *s == '(')) {
422 while (*s && isspace (*s))
427 while (*s && nesting) {
430 } else if (*s == ')') {
432 } else if (*s == '\\') {
444 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
445 * comments, and the '<' and '>' delimiters.
447 * If not NULL, then *next will be made to point to the first character
448 * not parsed, (possibly pointing to the final '\0' terminator.
450 * Returns a newly talloc'ed string belonging to 'ctx'.
452 * Returns NULL if there is any error parsing the message-id. */
454 _parse_message_id (void *ctx, const char *message_id, const char **next)
459 if (message_id == NULL || *message_id == '\0')
464 skip_space_and_comments (&s);
466 /* Skip any unstructured text as well. */
467 while (*s && *s != '<')
478 skip_space_and_comments (&s);
481 while (*end && *end != '>')
490 if (end > s && *end == '>')
495 result = talloc_strndup (ctx, s, end - s + 1);
497 /* Finally, collapse any whitespace that is within the message-id
503 for (r = result, len = strlen (r); *r; r++, len--)
504 if (*r == ' ' || *r == '\t')
505 memmove (r, r+1, len);
511 /* Parse a References header value, putting a (talloc'ed under 'ctx')
512 * copy of each referenced message-id into 'hash'.
514 * We explicitly avoid including any reference identical to
515 * 'message_id' in the result (to avoid mass confusion when a single
516 * message references itself cyclically---and yes, mail messages are
517 * not infrequent in the wild that do this---don't ask me why).
519 * Return the last reference parsed, if it is not equal to message_id.
522 parse_references (void *ctx,
523 const char *message_id,
529 if (refs == NULL || *refs == '\0')
533 ref = _parse_message_id (ctx, refs, &refs);
535 if (ref && strcmp (ref, message_id))
536 g_hash_table_insert (hash, ref, NULL);
539 /* The return value of this function is used to add a parent
540 * reference to the database. We should avoid making a message
541 * its own parent, thus the following check.
544 if (ref && strcmp(ref, message_id)) {
552 notmuch_database_create (const char *path, notmuch_database_t **database)
554 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
555 notmuch_database_t *notmuch = NULL;
556 char *notmuch_path = NULL;
561 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
562 status = NOTMUCH_STATUS_NULL_POINTER;
566 err = stat (path, &st);
568 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
569 path, strerror (errno));
570 status = NOTMUCH_STATUS_FILE_ERROR;
574 if (! S_ISDIR (st.st_mode)) {
575 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
577 status = NOTMUCH_STATUS_FILE_ERROR;
581 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
583 err = mkdir (notmuch_path, 0755);
586 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
587 notmuch_path, strerror (errno));
588 status = NOTMUCH_STATUS_FILE_ERROR;
592 status = notmuch_database_open (path,
593 NOTMUCH_DATABASE_MODE_READ_WRITE,
597 status = notmuch_database_upgrade (notmuch, NULL, NULL);
599 notmuch_database_close(notmuch);
605 talloc_free (notmuch_path);
610 talloc_free (notmuch);
615 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
617 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
618 fprintf (stderr, "Cannot write to a read-only database.\n");
619 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
622 return NOTMUCH_STATUS_SUCCESS;
626 notmuch_database_open (const char *path,
627 notmuch_database_mode_t mode,
628 notmuch_database_t **database)
630 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
631 void *local = talloc_new (NULL);
632 notmuch_database_t *notmuch = NULL;
633 char *notmuch_path, *xapian_path;
636 unsigned int i, version;
637 static int initialized = 0;
640 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
641 status = NOTMUCH_STATUS_NULL_POINTER;
645 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
646 fprintf (stderr, "Out of memory\n");
647 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
651 err = stat (notmuch_path, &st);
653 fprintf (stderr, "Error opening database at %s: %s\n",
654 notmuch_path, strerror (errno));
655 status = NOTMUCH_STATUS_FILE_ERROR;
659 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
660 fprintf (stderr, "Out of memory\n");
661 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
665 /* Initialize the GLib type system and threads */
666 #if !GLIB_CHECK_VERSION(2, 35, 1)
670 /* Initialize gmime */
672 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
676 notmuch = talloc_zero (NULL, notmuch_database_t);
677 notmuch->exception_reported = FALSE;
678 notmuch->path = talloc_strdup (notmuch, path);
680 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
681 notmuch->path[strlen (notmuch->path) - 1] = '\0';
683 notmuch->needs_upgrade = FALSE;
684 notmuch->mode = mode;
685 notmuch->atomic_nesting = 0;
687 string last_thread_id;
689 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
690 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
691 Xapian::DB_CREATE_OR_OPEN);
692 version = notmuch_database_get_version (notmuch);
694 if (version > NOTMUCH_DATABASE_VERSION) {
696 "Error: Notmuch database at %s\n"
697 " has a newer database format version (%u) than supported by this\n"
698 " version of notmuch (%u). Refusing to open this database in\n"
699 " read-write mode.\n",
700 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
701 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
702 notmuch_database_destroy (notmuch);
704 status = NOTMUCH_STATUS_FILE_ERROR;
708 if (version < NOTMUCH_DATABASE_VERSION)
709 notmuch->needs_upgrade = TRUE;
711 notmuch->xapian_db = new Xapian::Database (xapian_path);
712 version = notmuch_database_get_version (notmuch);
713 if (version > NOTMUCH_DATABASE_VERSION)
716 "Warning: Notmuch database at %s\n"
717 " has a newer database format version (%u) than supported by this\n"
718 " version of notmuch (%u). Some operations may behave incorrectly,\n"
719 " (but the database will not be harmed since it is being opened\n"
720 " in read-only mode).\n",
721 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
725 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
726 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
727 if (last_thread_id.empty ()) {
728 notmuch->last_thread_id = 0;
733 str = last_thread_id.c_str ();
734 notmuch->last_thread_id = strtoull (str, &end, 16);
736 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
739 notmuch->query_parser = new Xapian::QueryParser;
740 notmuch->term_gen = new Xapian::TermGenerator;
741 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
742 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
743 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
745 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
746 notmuch->query_parser->set_database (*notmuch->xapian_db);
747 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
748 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
749 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
750 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
752 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
753 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
754 notmuch->query_parser->add_boolean_prefix (prefix->name,
758 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
759 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
760 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
762 } catch (const Xapian::Error &error) {
763 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
764 error.get_msg().c_str());
765 notmuch_database_destroy (notmuch);
767 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
776 talloc_free (notmuch);
781 notmuch_database_close (notmuch_database_t *notmuch)
783 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
786 if (notmuch->xapian_db != NULL &&
787 notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
788 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
789 } catch (const Xapian::Error &error) {
790 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
791 if (! notmuch->exception_reported) {
792 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
793 error.get_msg().c_str());
797 /* Many Xapian objects (and thus notmuch objects) hold references to
798 * the database, so merely deleting the database may not suffice to
799 * close it. Thus, we explicitly close it here. */
800 if (notmuch->xapian_db != NULL) {
802 notmuch->xapian_db->close();
803 } catch (const Xapian::Error &error) {
804 /* don't clobber previous error status */
805 if (status == NOTMUCH_STATUS_SUCCESS)
806 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
810 delete notmuch->term_gen;
811 notmuch->term_gen = NULL;
812 delete notmuch->query_parser;
813 notmuch->query_parser = NULL;
814 delete notmuch->xapian_db;
815 notmuch->xapian_db = NULL;
816 delete notmuch->value_range_processor;
817 notmuch->value_range_processor = NULL;
818 delete notmuch->date_range_processor;
819 notmuch->date_range_processor = NULL;
824 #if HAVE_XAPIAN_COMPACT
826 unlink_cb (const char *path,
827 unused (const struct stat *sb),
829 unused (struct FTW *ftw))
831 return remove (path);
835 rmtree (const char *path)
837 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
840 class NotmuchCompactor : public Xapian::Compactor
842 notmuch_compact_status_cb_t status_cb;
843 void *status_closure;
846 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
847 status_cb (cb), status_closure (closure) { }
850 set_status (const std::string &table, const std::string &status)
854 if (status_cb == NULL)
857 if (status.length () == 0)
858 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
860 msg = talloc_asprintf (NULL, " %s", status.c_str());
866 status_cb (msg, status_closure);
871 /* Compacts the given database, optionally saving the original database
872 * in backup_path. Additionally, a callback function can be provided to
873 * give the user feedback on the progress of the (likely long-lived)
874 * compaction process.
876 * The backup path must point to a directory on the same volume as the
877 * original database. Passing a NULL backup_path will result in the
878 * uncompacted database being deleted after compaction has finished.
879 * Note that the database write lock will be held during the
880 * compaction process to protect data integrity.
883 notmuch_database_compact (const char *path,
884 const char *backup_path,
885 notmuch_compact_status_cb_t status_cb,
889 char *notmuch_path, *xapian_path, *compact_xapian_path;
890 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
891 notmuch_database_t *notmuch = NULL;
893 notmuch_bool_t keep_backup;
895 local = talloc_new (NULL);
897 return NOTMUCH_STATUS_OUT_OF_MEMORY;
899 ret = notmuch_database_open (path, NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much);
904 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
905 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
909 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
910 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
914 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
915 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
919 if (backup_path == NULL) {
920 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
921 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
930 if (stat (backup_path, &statbuf) != -1) {
931 fprintf (stderr, "Path already exists: %s\n", backup_path);
932 ret = NOTMUCH_STATUS_FILE_ERROR;
935 if (errno != ENOENT) {
936 fprintf (stderr, "Unknown error while stat()ing path: %s\n",
938 ret = NOTMUCH_STATUS_FILE_ERROR;
942 /* Unconditionally attempt to remove old work-in-progress database (if
943 * any). This is "protected" by database lock. If this fails due to write
944 * errors (etc), the following code will fail and provide error message.
946 (void) rmtree (compact_xapian_path);
949 NotmuchCompactor compactor (status_cb, closure);
951 compactor.set_renumber (false);
952 compactor.add_source (xapian_path);
953 compactor.set_destdir (compact_xapian_path);
954 compactor.compact ();
955 } catch (const Xapian::Error &error) {
956 fprintf (stderr, "Error while compacting: %s\n", error.get_msg().c_str());
957 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
961 if (rename (xapian_path, backup_path)) {
962 fprintf (stderr, "Error moving %s to %s: %s\n",
963 xapian_path, backup_path, strerror (errno));
964 ret = NOTMUCH_STATUS_FILE_ERROR;
968 if (rename (compact_xapian_path, xapian_path)) {
969 fprintf (stderr, "Error moving %s to %s: %s\n",
970 compact_xapian_path, xapian_path, strerror (errno));
971 ret = NOTMUCH_STATUS_FILE_ERROR;
976 if (rmtree (backup_path)) {
977 fprintf (stderr, "Error removing old database %s: %s\n",
978 backup_path, strerror (errno));
979 ret = NOTMUCH_STATUS_FILE_ERROR;
986 notmuch_status_t ret2;
988 ret2 = notmuch_database_destroy (notmuch);
990 /* don't clobber previous error status */
991 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1001 notmuch_database_compact (unused (const char *path),
1002 unused (const char *backup_path),
1003 unused (notmuch_compact_status_cb_t status_cb),
1004 unused (void *closure))
1006 fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
1007 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1012 notmuch_database_destroy (notmuch_database_t *notmuch)
1014 notmuch_status_t status;
1016 status = notmuch_database_close (notmuch);
1017 talloc_free (notmuch);
1023 notmuch_database_get_path (notmuch_database_t *notmuch)
1025 return notmuch->path;
1029 notmuch_database_get_version (notmuch_database_t *notmuch)
1031 unsigned int version;
1032 string version_string;
1036 version_string = notmuch->xapian_db->get_metadata ("version");
1037 if (version_string.empty ())
1040 str = version_string.c_str ();
1041 if (str == NULL || *str == '\0')
1044 version = strtoul (str, &end, 10);
1046 INTERNAL_ERROR ("Malformed database version: %s", str);
1052 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1054 return notmuch->needs_upgrade;
1057 static volatile sig_atomic_t do_progress_notify = 0;
1060 handle_sigalrm (unused (int signal))
1062 do_progress_notify = 1;
1065 /* Upgrade the current database.
1067 * After opening a database in read-write mode, the client should
1068 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1069 * if so, upgrade with this function before making any modifications.
1071 * The optional progress_notify callback can be used by the caller to
1072 * provide progress indication to the user. If non-NULL it will be
1073 * called periodically with 'count' as the number of messages upgraded
1074 * so far and 'total' the overall number of messages that will be
1078 notmuch_database_upgrade (notmuch_database_t *notmuch,
1079 void (*progress_notify) (void *closure,
1083 Xapian::WritableDatabase *db;
1084 struct sigaction action;
1085 struct itimerval timerval;
1086 notmuch_bool_t timer_is_active = FALSE;
1087 unsigned int version;
1088 notmuch_status_t status;
1089 unsigned int count = 0, total = 0;
1091 status = _notmuch_database_ensure_writable (notmuch);
1095 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1097 version = notmuch_database_get_version (notmuch);
1099 if (version >= NOTMUCH_DATABASE_VERSION)
1100 return NOTMUCH_STATUS_SUCCESS;
1102 if (progress_notify) {
1103 /* Setup our handler for SIGALRM */
1104 memset (&action, 0, sizeof (struct sigaction));
1105 action.sa_handler = handle_sigalrm;
1106 sigemptyset (&action.sa_mask);
1107 action.sa_flags = SA_RESTART;
1108 sigaction (SIGALRM, &action, NULL);
1110 /* Then start a timer to send SIGALRM once per second. */
1111 timerval.it_interval.tv_sec = 1;
1112 timerval.it_interval.tv_usec = 0;
1113 timerval.it_value.tv_sec = 1;
1114 timerval.it_value.tv_usec = 0;
1115 setitimer (ITIMER_REAL, &timerval, NULL);
1117 timer_is_active = TRUE;
1120 /* Before version 1, each message document had its filename in the
1121 * data field. Copy that into the new format by calling
1122 * notmuch_message_add_filename.
1125 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1126 notmuch_messages_t *messages;
1127 notmuch_message_t *message;
1129 Xapian::TermIterator t, t_end;
1131 total = notmuch_query_count_messages (query);
1133 for (messages = notmuch_query_search_messages (query);
1134 notmuch_messages_valid (messages);
1135 notmuch_messages_move_to_next (messages))
1137 if (do_progress_notify) {
1138 progress_notify (closure, (double) count / total);
1139 do_progress_notify = 0;
1142 message = notmuch_messages_get (messages);
1144 filename = _notmuch_message_talloc_copy_data (message);
1145 if (filename && *filename != '\0') {
1146 _notmuch_message_add_filename (message, filename);
1147 _notmuch_message_sync (message);
1149 talloc_free (filename);
1151 notmuch_message_destroy (message);
1156 notmuch_query_destroy (query);
1158 /* Also, before version 1 we stored directory timestamps in
1159 * XTIMESTAMP documents instead of the current XDIRECTORY
1160 * documents. So copy those as well. */
1162 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1164 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1168 Xapian::PostingIterator p, p_end;
1169 std::string term = *t;
1171 p_end = notmuch->xapian_db->postlist_end (term);
1173 for (p = notmuch->xapian_db->postlist_begin (term);
1177 Xapian::Document document;
1179 notmuch_directory_t *directory;
1181 if (do_progress_notify) {
1182 progress_notify (closure, (double) count / total);
1183 do_progress_notify = 0;
1186 document = find_document_for_doc_id (notmuch, *p);
1187 mtime = Xapian::sortable_unserialise (
1188 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1190 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1191 NOTMUCH_FIND_CREATE, &status);
1192 notmuch_directory_set_mtime (directory, mtime);
1193 notmuch_directory_destroy (directory);
1199 * Prior to version 2, the "folder:" prefix was probabilistic and
1200 * stemmed. Change it to the current boolean prefix. Add "path:"
1201 * prefixes while at it.
1204 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1205 notmuch_messages_t *messages;
1206 notmuch_message_t *message;
1209 total = notmuch_query_count_messages (query);
1211 for (messages = notmuch_query_search_messages (query);
1212 notmuch_messages_valid (messages);
1213 notmuch_messages_move_to_next (messages)) {
1214 if (do_progress_notify) {
1215 progress_notify (closure, (double) count / total);
1216 do_progress_notify = 0;
1219 message = notmuch_messages_get (messages);
1221 _notmuch_message_upgrade_folder (message);
1222 _notmuch_message_sync (message);
1224 notmuch_message_destroy (message);
1229 notmuch_query_destroy (query);
1232 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1235 /* Now that the upgrade is complete we can remove the old data
1236 * and documents that are no longer needed. */
1238 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1239 notmuch_messages_t *messages;
1240 notmuch_message_t *message;
1243 for (messages = notmuch_query_search_messages (query);
1244 notmuch_messages_valid (messages);
1245 notmuch_messages_move_to_next (messages))
1247 if (do_progress_notify) {
1248 progress_notify (closure, (double) count / total);
1249 do_progress_notify = 0;
1252 message = notmuch_messages_get (messages);
1254 filename = _notmuch_message_talloc_copy_data (message);
1255 if (filename && *filename != '\0') {
1256 _notmuch_message_clear_data (message);
1257 _notmuch_message_sync (message);
1259 talloc_free (filename);
1261 notmuch_message_destroy (message);
1264 notmuch_query_destroy (query);
1268 Xapian::TermIterator t, t_end;
1270 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1272 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1276 Xapian::PostingIterator p, p_end;
1277 std::string term = *t;
1279 p_end = notmuch->xapian_db->postlist_end (term);
1281 for (p = notmuch->xapian_db->postlist_begin (term);
1285 if (do_progress_notify) {
1286 progress_notify (closure, (double) count / total);
1287 do_progress_notify = 0;
1290 db->delete_document (*p);
1295 if (timer_is_active) {
1296 /* Now stop the timer. */
1297 timerval.it_interval.tv_sec = 0;
1298 timerval.it_interval.tv_usec = 0;
1299 timerval.it_value.tv_sec = 0;
1300 timerval.it_value.tv_usec = 0;
1301 setitimer (ITIMER_REAL, &timerval, NULL);
1303 /* And disable the signal handler. */
1304 action.sa_handler = SIG_IGN;
1305 sigaction (SIGALRM, &action, NULL);
1308 return NOTMUCH_STATUS_SUCCESS;
1312 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1314 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1315 notmuch->atomic_nesting > 0)
1319 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1320 } catch (const Xapian::Error &error) {
1321 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1322 error.get_msg().c_str());
1323 notmuch->exception_reported = TRUE;
1324 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1328 notmuch->atomic_nesting++;
1329 return NOTMUCH_STATUS_SUCCESS;
1333 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1335 Xapian::WritableDatabase *db;
1337 if (notmuch->atomic_nesting == 0)
1338 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1340 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1341 notmuch->atomic_nesting > 1)
1344 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1346 db->commit_transaction ();
1348 /* This is a hack for testing. Xapian never flushes on a
1349 * non-flushed commit, even if the flush threshold is 1.
1350 * However, we rely on flushing to test atomicity. */
1351 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1352 if (thresh && atoi (thresh) == 1)
1354 } catch (const Xapian::Error &error) {
1355 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1356 error.get_msg().c_str());
1357 notmuch->exception_reported = TRUE;
1358 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1362 notmuch->atomic_nesting--;
1363 return NOTMUCH_STATUS_SUCCESS;
1366 /* We allow the user to use arbitrarily long paths for directories. But
1367 * we have a term-length limit. So if we exceed that, we'll use the
1368 * SHA-1 of the path for the database term.
1370 * Note: This function may return the original value of 'path'. If it
1371 * does not, then the caller is responsible to free() the returned
1375 _notmuch_database_get_directory_db_path (const char *path)
1377 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1379 if (term_len > NOTMUCH_TERM_MAX)
1380 return _notmuch_sha1_of_string (path);
1385 /* Given a path, split it into two parts: the directory part is all
1386 * components except for the last, and the basename is that last
1387 * component. Getting the return-value for either part is optional
1388 * (the caller can pass NULL).
1390 * The original 'path' can represent either a regular file or a
1391 * directory---the splitting will be carried out in the same way in
1392 * either case. Trailing slashes on 'path' will be ignored, and any
1393 * cases of multiple '/' characters appearing in series will be
1394 * treated as a single '/'.
1396 * Allocation (if any) will have 'ctx' as the talloc owner. But
1397 * pointers will be returned within the original path string whenever
1400 * Note: If 'path' is non-empty and contains no non-trailing slash,
1401 * (that is, consists of a filename with no parent directory), then
1402 * the directory returned will be an empty string. However, if 'path'
1403 * is an empty string, then both directory and basename will be
1407 _notmuch_database_split_path (void *ctx,
1409 const char **directory,
1410 const char **basename)
1414 if (path == NULL || *path == '\0') {
1419 return NOTMUCH_STATUS_SUCCESS;
1422 /* Find the last slash (not counting a trailing slash), if any. */
1424 slash = path + strlen (path) - 1;
1426 /* First, skip trailing slashes. */
1427 while (slash != path) {
1434 /* Then, find a slash. */
1435 while (slash != path) {
1445 /* Finally, skip multiple slashes. */
1446 while (slash != path) {
1453 if (slash == path) {
1455 *directory = talloc_strdup (ctx, "");
1460 *directory = talloc_strndup (ctx, path, slash - path + 1);
1463 return NOTMUCH_STATUS_SUCCESS;
1466 /* Find the document ID of the specified directory.
1468 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1469 * created if one does not exist for 'path'. Otherwise, if the
1470 * directory document does not exist, this sets *directory_id to
1471 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1474 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1476 notmuch_find_flags_t flags,
1477 unsigned int *directory_id)
1479 notmuch_directory_t *directory;
1480 notmuch_status_t status;
1484 return NOTMUCH_STATUS_SUCCESS;
1487 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1488 if (status || !directory) {
1493 *directory_id = _notmuch_directory_get_document_id (directory);
1495 notmuch_directory_destroy (directory);
1497 return NOTMUCH_STATUS_SUCCESS;
1501 _notmuch_database_get_directory_path (void *ctx,
1502 notmuch_database_t *notmuch,
1503 unsigned int doc_id)
1505 Xapian::Document document;
1507 document = find_document_for_doc_id (notmuch, doc_id);
1509 return talloc_strdup (ctx, document.get_data ().c_str ());
1512 /* Given a legal 'filename' for the database, (either relative to
1513 * database path or absolute with initial components identical to
1514 * database path), return a new string (with 'ctx' as the talloc
1515 * owner) suitable for use as a direntry term value.
1517 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1518 * will be created in the database as needed. Otherwise, if the
1519 * necessary directory documents do not exist, this sets
1520 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1523 _notmuch_database_filename_to_direntry (void *ctx,
1524 notmuch_database_t *notmuch,
1525 const char *filename,
1526 notmuch_find_flags_t flags,
1529 const char *relative, *directory, *basename;
1530 Xapian::docid directory_id;
1531 notmuch_status_t status;
1533 relative = _notmuch_database_relative_path (notmuch, filename);
1535 status = _notmuch_database_split_path (ctx, relative,
1536 &directory, &basename);
1540 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1542 if (status || directory_id == (unsigned int)-1) {
1547 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1549 return NOTMUCH_STATUS_SUCCESS;
1552 /* Given a legal 'path' for the database, return the relative path.
1554 * The return value will be a pointer to the original path contents,
1555 * and will be either the original string (if 'path' was relative) or
1556 * a portion of the string (if path was absolute and begins with the
1560 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1563 const char *db_path, *relative;
1564 unsigned int db_path_len;
1566 db_path = notmuch_database_get_path (notmuch);
1567 db_path_len = strlen (db_path);
1571 if (*relative == '/') {
1572 while (*relative == '/' && *(relative+1) == '/')
1575 if (strncmp (relative, db_path, db_path_len) == 0)
1577 relative += db_path_len;
1578 while (*relative == '/')
1587 notmuch_database_get_directory (notmuch_database_t *notmuch,
1589 notmuch_directory_t **directory)
1591 notmuch_status_t status;
1593 if (directory == NULL)
1594 return NOTMUCH_STATUS_NULL_POINTER;
1598 *directory = _notmuch_directory_create (notmuch, path,
1599 NOTMUCH_FIND_LOOKUP, &status);
1600 } catch (const Xapian::Error &error) {
1601 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1602 error.get_msg().c_str());
1603 notmuch->exception_reported = TRUE;
1604 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1609 /* Allocate a document ID that satisfies the following criteria:
1611 * 1. The ID does not exist for any document in the Xapian database
1613 * 2. The ID was not previously returned from this function
1615 * 3. The ID is the smallest integer satisfying (1) and (2)
1617 * This function will trigger an internal error if these constraints
1618 * cannot all be satisfied, (that is, the pool of available document
1619 * IDs has been exhausted).
1622 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1624 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1626 notmuch->last_doc_id++;
1628 if (notmuch->last_doc_id == 0)
1629 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1631 return notmuch->last_doc_id;
1635 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1637 /* 16 bytes (+ terminator) for hexadecimal representation of
1638 * a 64-bit integer. */
1639 static char thread_id[17];
1640 Xapian::WritableDatabase *db;
1642 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1644 notmuch->last_thread_id++;
1646 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1648 db->set_metadata ("last_thread_id", thread_id);
1654 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1656 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1657 message_id = _message_id_compressed (ctx, message_id);
1659 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1663 /* Find the thread ID to which the message with 'message_id' belongs.
1665 * Note: 'thread_id_ret' must not be NULL!
1666 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1669 * Note: If there is no message in the database with the given
1670 * 'message_id' then a new thread_id will be allocated for this
1671 * message and stored in the database metadata, (where this same
1672 * thread ID can be looked up if the message is added to the database
1675 static notmuch_status_t
1676 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1678 const char *message_id,
1679 const char **thread_id_ret)
1681 notmuch_status_t status;
1682 notmuch_message_t *message;
1683 string thread_id_string;
1685 Xapian::WritableDatabase *db;
1687 status = notmuch_database_find_message (notmuch, message_id, &message);
1693 *thread_id_ret = talloc_steal (ctx,
1694 notmuch_message_get_thread_id (message));
1696 notmuch_message_destroy (message);
1698 return NOTMUCH_STATUS_SUCCESS;
1701 /* Message has not been seen yet.
1703 * We may have seen a reference to it already, in which case, we
1704 * can return the thread ID stored in the metadata. Otherwise, we
1705 * generate a new thread ID and store it there.
1707 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1708 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1709 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1711 if (thread_id_string.empty()) {
1712 *thread_id_ret = talloc_strdup (ctx,
1713 _notmuch_database_generate_thread_id (notmuch));
1714 db->set_metadata (metadata_key, *thread_id_ret);
1716 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1719 talloc_free (metadata_key);
1721 return NOTMUCH_STATUS_SUCCESS;
1724 static notmuch_status_t
1725 _merge_threads (notmuch_database_t *notmuch,
1726 const char *winner_thread_id,
1727 const char *loser_thread_id)
1729 Xapian::PostingIterator loser, loser_end;
1730 notmuch_message_t *message = NULL;
1731 notmuch_private_status_t private_status;
1732 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1734 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1736 for ( ; loser != loser_end; loser++) {
1737 message = _notmuch_message_create (notmuch, notmuch,
1738 *loser, &private_status);
1739 if (message == NULL) {
1740 ret = COERCE_STATUS (private_status,
1741 "Cannot find document for doc_id from query");
1745 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1746 _notmuch_message_add_term (message, "thread", winner_thread_id);
1747 _notmuch_message_sync (message);
1749 notmuch_message_destroy (message);
1755 notmuch_message_destroy (message);
1761 _my_talloc_free_for_g_hash (void *ptr)
1766 static notmuch_status_t
1767 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1768 notmuch_message_t *message,
1769 notmuch_message_file_t *message_file,
1770 const char **thread_id)
1772 GHashTable *parents = NULL;
1773 const char *refs, *in_reply_to, *in_reply_to_message_id;
1774 const char *last_ref_message_id, *this_message_id;
1775 GList *l, *keys = NULL;
1776 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1778 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1779 _my_talloc_free_for_g_hash, NULL);
1780 this_message_id = notmuch_message_get_message_id (message);
1782 refs = _notmuch_message_file_get_header (message_file, "references");
1783 last_ref_message_id = parse_references (message,
1787 in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
1788 in_reply_to_message_id = parse_references (message,
1790 parents, in_reply_to);
1792 /* For the parent of this message, use the last message ID of the
1793 * References header, if available. If not, fall back to the
1794 * first message ID in the In-Reply-To header. */
1795 if (last_ref_message_id) {
1796 _notmuch_message_add_term (message, "replyto",
1797 last_ref_message_id);
1798 } else if (in_reply_to_message_id) {
1799 _notmuch_message_add_term (message, "replyto",
1800 in_reply_to_message_id);
1803 keys = g_hash_table_get_keys (parents);
1804 for (l = keys; l; l = l->next) {
1805 char *parent_message_id;
1806 const char *parent_thread_id = NULL;
1808 parent_message_id = (char *) l->data;
1810 _notmuch_message_add_term (message, "reference",
1813 ret = _resolve_message_id_to_thread_id (notmuch,
1820 if (*thread_id == NULL) {
1821 *thread_id = talloc_strdup (message, parent_thread_id);
1822 _notmuch_message_add_term (message, "thread", *thread_id);
1823 } else if (strcmp (*thread_id, parent_thread_id)) {
1824 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1834 g_hash_table_unref (parents);
1839 static notmuch_status_t
1840 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1841 notmuch_message_t *message,
1842 const char **thread_id)
1844 const char *message_id = notmuch_message_get_message_id (message);
1845 Xapian::PostingIterator child, children_end;
1846 notmuch_message_t *child_message = NULL;
1847 const char *child_thread_id;
1848 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1849 notmuch_private_status_t private_status;
1851 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1853 for ( ; child != children_end; child++) {
1855 child_message = _notmuch_message_create (message, notmuch,
1856 *child, &private_status);
1857 if (child_message == NULL) {
1858 ret = COERCE_STATUS (private_status,
1859 "Cannot find document for doc_id from query");
1863 child_thread_id = notmuch_message_get_thread_id (child_message);
1864 if (*thread_id == NULL) {
1865 *thread_id = talloc_strdup (message, child_thread_id);
1866 _notmuch_message_add_term (message, "thread", *thread_id);
1867 } else if (strcmp (*thread_id, child_thread_id)) {
1868 _notmuch_message_remove_term (child_message, "reference",
1870 _notmuch_message_sync (child_message);
1871 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1876 notmuch_message_destroy (child_message);
1877 child_message = NULL;
1882 notmuch_message_destroy (child_message);
1887 /* Given a (mostly empty) 'message' and its corresponding
1888 * 'message_file' link it to existing threads in the database.
1890 * The first check is in the metadata of the database to see if we
1891 * have pre-allocated a thread_id in advance for this message, (which
1892 * would have happened if a message was previously added that
1893 * referenced this one).
1895 * Second, we look at 'message_file' and its link-relevant headers
1896 * (References and In-Reply-To) for message IDs.
1898 * Finally, we look in the database for existing message that
1899 * reference 'message'.
1901 * In all cases, we assign to the current message the first thread_id
1902 * found (through either parent or child). We will also merge any
1903 * existing, distinct threads where this message belongs to both,
1904 * (which is not uncommon when messages are processed out of order).
1906 * Finally, if no thread ID has been found through parent or child, we
1907 * call _notmuch_message_generate_thread_id to generate a new thread
1908 * ID. This should only happen for new, top-level messages, (no
1909 * References or In-Reply-To header in this message, and no previously
1910 * added message refers to this message).
1912 static notmuch_status_t
1913 _notmuch_database_link_message (notmuch_database_t *notmuch,
1914 notmuch_message_t *message,
1915 notmuch_message_file_t *message_file)
1917 notmuch_status_t status;
1918 const char *message_id, *thread_id = NULL;
1922 message_id = notmuch_message_get_message_id (message);
1923 metadata_key = _get_metadata_thread_id_key (message, message_id);
1925 /* Check if we have already seen related messages to this one.
1926 * If we have then use the thread_id that we stored at that time.
1928 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1929 if (! stored_id.empty()) {
1930 Xapian::WritableDatabase *db;
1932 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1934 /* Clear the metadata for this message ID. We don't need it
1936 db->set_metadata (metadata_key, "");
1937 thread_id = stored_id.c_str();
1939 _notmuch_message_add_term (message, "thread", thread_id);
1941 talloc_free (metadata_key);
1943 status = _notmuch_database_link_message_to_parents (notmuch, message,
1949 status = _notmuch_database_link_message_to_children (notmuch, message,
1954 /* If not part of any existing thread, generate a new thread ID. */
1955 if (thread_id == NULL) {
1956 thread_id = _notmuch_database_generate_thread_id (notmuch);
1958 _notmuch_message_add_term (message, "thread", thread_id);
1961 return NOTMUCH_STATUS_SUCCESS;
1965 notmuch_database_add_message (notmuch_database_t *notmuch,
1966 const char *filename,
1967 notmuch_message_t **message_ret)
1969 notmuch_message_file_t *message_file;
1970 notmuch_message_t *message = NULL;
1971 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1972 notmuch_private_status_t private_status;
1974 const char *date, *header;
1975 const char *from, *to, *subject;
1976 char *message_id = NULL;
1979 *message_ret = NULL;
1981 ret = _notmuch_database_ensure_writable (notmuch);
1985 message_file = _notmuch_message_file_open (filename);
1986 if (message_file == NULL)
1987 return NOTMUCH_STATUS_FILE_ERROR;
1989 /* Adding a message may change many documents. Do this all
1991 ret = notmuch_database_begin_atomic (notmuch);
1995 /* Parse message up front to get better error status. */
1996 ret = _notmuch_message_file_parse (message_file);
2001 /* Before we do any real work, (especially before doing a
2002 * potential SHA-1 computation on the entire file's contents),
2003 * let's make sure that what we're looking at looks like an
2004 * actual email message.
2006 from = _notmuch_message_file_get_header (message_file, "from");
2007 subject = _notmuch_message_file_get_header (message_file, "subject");
2008 to = _notmuch_message_file_get_header (message_file, "to");
2010 if ((from == NULL || *from == '\0') &&
2011 (subject == NULL || *subject == '\0') &&
2012 (to == NULL || *to == '\0'))
2014 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2018 /* Now that we're sure it's mail, the first order of business
2019 * is to find a message ID (or else create one ourselves). */
2021 header = _notmuch_message_file_get_header (message_file, "message-id");
2022 if (header && *header != '\0') {
2023 message_id = _parse_message_id (message_file, header, NULL);
2025 /* So the header value isn't RFC-compliant, but it's
2026 * better than no message-id at all. */
2027 if (message_id == NULL)
2028 message_id = talloc_strdup (message_file, header);
2030 /* If a message ID is too long, substitute its sha1 instead. */
2031 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
2032 char *compressed = _message_id_compressed (message_file,
2034 talloc_free (message_id);
2035 message_id = compressed;
2039 if (message_id == NULL ) {
2040 /* No message-id at all, let's generate one by taking a
2041 * hash over the file's contents. */
2042 char *sha1 = _notmuch_sha1_of_file (filename);
2044 /* If that failed too, something is really wrong. Give up. */
2046 ret = NOTMUCH_STATUS_FILE_ERROR;
2050 message_id = talloc_asprintf (message_file,
2051 "notmuch-sha1-%s", sha1);
2055 /* Now that we have a message ID, we get a message object,
2056 * (which may or may not reference an existing document in the
2059 message = _notmuch_message_create_for_message_id (notmuch,
2063 talloc_free (message_id);
2065 if (message == NULL) {
2066 ret = COERCE_STATUS (private_status,
2067 "Unexpected status value from _notmuch_message_create_for_message_id");
2071 _notmuch_message_add_filename (message, filename);
2073 /* Is this a newly created message object? */
2074 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2075 _notmuch_message_add_term (message, "type", "mail");
2077 ret = _notmuch_database_link_message (notmuch, message,
2082 date = _notmuch_message_file_get_header (message_file, "date");
2083 _notmuch_message_set_header_values (message, date, from, subject);
2085 ret = _notmuch_message_index_file (message, message_file);
2089 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2092 _notmuch_message_sync (message);
2093 } catch (const Xapian::Error &error) {
2094 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2095 error.get_msg().c_str());
2096 notmuch->exception_reported = TRUE;
2097 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2103 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2104 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2105 *message_ret = message;
2107 notmuch_message_destroy (message);
2111 _notmuch_message_file_close (message_file);
2113 ret2 = notmuch_database_end_atomic (notmuch);
2114 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2115 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2116 ret2 != NOTMUCH_STATUS_SUCCESS)
2123 notmuch_database_remove_message (notmuch_database_t *notmuch,
2124 const char *filename)
2126 notmuch_status_t status;
2127 notmuch_message_t *message;
2129 status = notmuch_database_find_message_by_filename (notmuch, filename,
2132 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2133 status = _notmuch_message_remove_filename (message, filename);
2134 if (status == NOTMUCH_STATUS_SUCCESS)
2135 _notmuch_message_delete (message);
2136 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2137 _notmuch_message_sync (message);
2139 notmuch_message_destroy (message);
2146 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2147 const char *filename,
2148 notmuch_message_t **message_ret)
2151 const char *prefix = _find_prefix ("file-direntry");
2152 char *direntry, *term;
2153 Xapian::PostingIterator i, end;
2154 notmuch_status_t status;
2156 if (message_ret == NULL)
2157 return NOTMUCH_STATUS_NULL_POINTER;
2159 /* return NULL on any failure */
2160 *message_ret = NULL;
2162 local = talloc_new (notmuch);
2165 status = _notmuch_database_filename_to_direntry (
2166 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2167 if (status || !direntry)
2170 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2172 find_doc_ids_for_term (notmuch, term, &i, &end);
2175 notmuch_private_status_t private_status;
2177 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2179 if (*message_ret == NULL)
2180 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2182 } catch (const Xapian::Error &error) {
2183 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2184 error.get_msg().c_str());
2185 notmuch->exception_reported = TRUE;
2186 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2190 talloc_free (local);
2192 if (status && *message_ret) {
2193 notmuch_message_destroy (*message_ret);
2194 *message_ret = NULL;
2199 notmuch_string_list_t *
2200 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2201 Xapian::TermIterator &end,
2204 int prefix_len = strlen (prefix);
2205 notmuch_string_list_t *list;
2207 list = _notmuch_string_list_create (ctx);
2208 if (unlikely (list == NULL))
2211 for (i.skip_to (prefix); i != end; i++) {
2212 /* Terminate loop at first term without desired prefix. */
2213 if (strncmp ((*i).c_str (), prefix, prefix_len))
2216 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2223 notmuch_database_get_all_tags (notmuch_database_t *db)
2225 Xapian::TermIterator i, end;
2226 notmuch_string_list_t *tags;
2229 i = db->xapian_db->allterms_begin();
2230 end = db->xapian_db->allterms_end();
2231 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2232 _find_prefix ("tag"));
2233 _notmuch_string_list_sort (tags);
2234 return _notmuch_tags_create (db, tags);
2235 } catch (const Xapian::Error &error) {
2236 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2237 error.get_msg().c_str());
2238 db->exception_reported = TRUE;