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 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 "folder" and "path" prefixes. But the
104 * database doesn't 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 * Without the ":", since this is a multi-letter prefix, Xapian
215 * will add a colon itself if the first letter of the path is
216 * upper-case ASCII. Including the ":" forces there to always be a
217 * colon, which keeps our own logic simpler.
219 { "folder", "XFOLDER:" },
222 static prefix_t PROBABILISTIC_PREFIX[]= {
225 { "attachment", "XATTACHMENT" },
226 { "subject", "XSUBJECT"},
230 _find_prefix (const char *name)
234 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
235 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
236 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
239 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
240 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
241 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
244 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
245 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
246 return PROBABILISTIC_PREFIX[i].prefix;
249 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
255 notmuch_status_to_string (notmuch_status_t status)
258 case NOTMUCH_STATUS_SUCCESS:
259 return "No error occurred";
260 case NOTMUCH_STATUS_OUT_OF_MEMORY:
261 return "Out of memory";
262 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
263 return "Attempt to write to a read-only database";
264 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
265 return "A Xapian exception occurred";
266 case NOTMUCH_STATUS_FILE_ERROR:
267 return "Something went wrong trying to read or write a file";
268 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
269 return "File is not an email";
270 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
271 return "Message ID is identical to a message in database";
272 case NOTMUCH_STATUS_NULL_POINTER:
273 return "Erroneous NULL pointer";
274 case NOTMUCH_STATUS_TAG_TOO_LONG:
275 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
276 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
277 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
278 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
279 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
280 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
281 return "Unsupported operation";
283 case NOTMUCH_STATUS_LAST_STATUS:
284 return "Unknown error status value";
289 find_doc_ids_for_term (notmuch_database_t *notmuch,
291 Xapian::PostingIterator *begin,
292 Xapian::PostingIterator *end)
294 *begin = notmuch->xapian_db->postlist_begin (term);
296 *end = notmuch->xapian_db->postlist_end (term);
300 find_doc_ids (notmuch_database_t *notmuch,
301 const char *prefix_name,
303 Xapian::PostingIterator *begin,
304 Xapian::PostingIterator *end)
308 term = talloc_asprintf (notmuch, "%s%s",
309 _find_prefix (prefix_name), value);
311 find_doc_ids_for_term (notmuch, term, begin, end);
316 notmuch_private_status_t
317 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
318 const char *prefix_name,
320 unsigned int *doc_id)
322 Xapian::PostingIterator i, end;
324 find_doc_ids (notmuch, prefix_name, value, &i, &end);
328 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
333 #if DEBUG_DATABASE_SANITY
337 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
341 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
344 static Xapian::Document
345 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
347 return notmuch->xapian_db->get_document (doc_id);
350 /* Generate a compressed version of 'message_id' of the form:
352 * notmuch-sha1-<sha1_sum_of_message_id>
355 _message_id_compressed (void *ctx, const char *message_id)
357 char *sha1, *compressed;
359 sha1 = notmuch_sha1_of_string (message_id);
361 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
368 notmuch_database_find_message (notmuch_database_t *notmuch,
369 const char *message_id,
370 notmuch_message_t **message_ret)
372 notmuch_private_status_t status;
375 if (message_ret == NULL)
376 return NOTMUCH_STATUS_NULL_POINTER;
378 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
379 message_id = _message_id_compressed (notmuch, message_id);
382 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
383 message_id, &doc_id);
385 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
388 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
390 if (*message_ret == NULL)
391 return NOTMUCH_STATUS_OUT_OF_MEMORY;
394 return NOTMUCH_STATUS_SUCCESS;
395 } catch (const Xapian::Error &error) {
396 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
397 error.get_msg().c_str());
398 notmuch->exception_reported = TRUE;
400 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
404 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
405 * a (potentially nested) parenthesized sequence with '\' used to
406 * escape any character (including parentheses).
408 * If the sequence to be skipped continues to the end of the string,
409 * then 'str' will be left pointing at the final terminating '\0'
413 skip_space_and_comments (const char **str)
418 while (*s && (isspace (*s) || *s == '(')) {
419 while (*s && isspace (*s))
424 while (*s && nesting) {
427 } else if (*s == ')') {
429 } else if (*s == '\\') {
441 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
442 * comments, and the '<' and '>' delimiters.
444 * If not NULL, then *next will be made to point to the first character
445 * not parsed, (possibly pointing to the final '\0' terminator.
447 * Returns a newly talloc'ed string belonging to 'ctx'.
449 * Returns NULL if there is any error parsing the message-id. */
451 _parse_message_id (void *ctx, const char *message_id, const char **next)
456 if (message_id == NULL || *message_id == '\0')
461 skip_space_and_comments (&s);
463 /* Skip any unstructured text as well. */
464 while (*s && *s != '<')
475 skip_space_and_comments (&s);
478 while (*end && *end != '>')
487 if (end > s && *end == '>')
492 result = talloc_strndup (ctx, s, end - s + 1);
494 /* Finally, collapse any whitespace that is within the message-id
500 for (r = result, len = strlen (r); *r; r++, len--)
501 if (*r == ' ' || *r == '\t')
502 memmove (r, r+1, len);
508 /* Parse a References header value, putting a (talloc'ed under 'ctx')
509 * copy of each referenced message-id into 'hash'.
511 * We explicitly avoid including any reference identical to
512 * 'message_id' in the result (to avoid mass confusion when a single
513 * message references itself cyclically---and yes, mail messages are
514 * not infrequent in the wild that do this---don't ask me why).
516 * Return the last reference parsed, if it is not equal to message_id.
519 parse_references (void *ctx,
520 const char *message_id,
526 if (refs == NULL || *refs == '\0')
530 ref = _parse_message_id (ctx, refs, &refs);
532 if (ref && strcmp (ref, message_id))
533 g_hash_table_insert (hash, ref, NULL);
536 /* The return value of this function is used to add a parent
537 * reference to the database. We should avoid making a message
538 * its own parent, thus the following check.
541 if (ref && strcmp(ref, message_id)) {
549 notmuch_database_create (const char *path, notmuch_database_t **database)
551 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
552 notmuch_database_t *notmuch = NULL;
553 char *notmuch_path = NULL;
558 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
559 status = NOTMUCH_STATUS_NULL_POINTER;
563 err = stat (path, &st);
565 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
566 path, strerror (errno));
567 status = NOTMUCH_STATUS_FILE_ERROR;
571 if (! S_ISDIR (st.st_mode)) {
572 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
574 status = NOTMUCH_STATUS_FILE_ERROR;
578 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
580 err = mkdir (notmuch_path, 0755);
583 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
584 notmuch_path, strerror (errno));
585 status = NOTMUCH_STATUS_FILE_ERROR;
589 status = notmuch_database_open (path,
590 NOTMUCH_DATABASE_MODE_READ_WRITE,
594 status = notmuch_database_upgrade (notmuch, NULL, NULL);
596 notmuch_database_close(notmuch);
602 talloc_free (notmuch_path);
607 talloc_free (notmuch);
612 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
614 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
615 fprintf (stderr, "Cannot write to a read-only database.\n");
616 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
619 return NOTMUCH_STATUS_SUCCESS;
623 notmuch_database_open (const char *path,
624 notmuch_database_mode_t mode,
625 notmuch_database_t **database)
627 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
628 void *local = talloc_new (NULL);
629 notmuch_database_t *notmuch = NULL;
630 char *notmuch_path, *xapian_path;
633 unsigned int i, version;
634 static int initialized = 0;
637 fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
638 status = NOTMUCH_STATUS_NULL_POINTER;
642 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
643 fprintf (stderr, "Out of memory\n");
644 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
648 err = stat (notmuch_path, &st);
650 fprintf (stderr, "Error opening database at %s: %s\n",
651 notmuch_path, strerror (errno));
652 status = NOTMUCH_STATUS_FILE_ERROR;
656 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
657 fprintf (stderr, "Out of memory\n");
658 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
662 /* Initialize the GLib type system and threads */
663 #if !GLIB_CHECK_VERSION(2, 35, 1)
667 /* Initialize gmime */
669 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
673 notmuch = talloc_zero (NULL, notmuch_database_t);
674 notmuch->exception_reported = FALSE;
675 notmuch->path = talloc_strdup (notmuch, path);
677 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
678 notmuch->path[strlen (notmuch->path) - 1] = '\0';
680 notmuch->needs_upgrade = FALSE;
681 notmuch->mode = mode;
682 notmuch->atomic_nesting = 0;
684 string last_thread_id;
686 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
687 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
688 Xapian::DB_CREATE_OR_OPEN);
689 version = notmuch_database_get_version (notmuch);
691 if (version > NOTMUCH_DATABASE_VERSION) {
693 "Error: Notmuch database at %s\n"
694 " has a newer database format version (%u) than supported by this\n"
695 " version of notmuch (%u). Refusing to open this database in\n"
696 " read-write mode.\n",
697 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
698 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
699 notmuch_database_destroy (notmuch);
701 status = NOTMUCH_STATUS_FILE_ERROR;
705 if (version < NOTMUCH_DATABASE_VERSION)
706 notmuch->needs_upgrade = TRUE;
708 notmuch->xapian_db = new Xapian::Database (xapian_path);
709 version = notmuch_database_get_version (notmuch);
710 if (version > NOTMUCH_DATABASE_VERSION)
713 "Warning: Notmuch database at %s\n"
714 " has a newer database format version (%u) than supported by this\n"
715 " version of notmuch (%u). Some operations may behave incorrectly,\n"
716 " (but the database will not be harmed since it is being opened\n"
717 " in read-only mode).\n",
718 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
722 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
723 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
724 if (last_thread_id.empty ()) {
725 notmuch->last_thread_id = 0;
730 str = last_thread_id.c_str ();
731 notmuch->last_thread_id = strtoull (str, &end, 16);
733 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
736 notmuch->query_parser = new Xapian::QueryParser;
737 notmuch->term_gen = new Xapian::TermGenerator;
738 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
739 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
740 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
742 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
743 notmuch->query_parser->set_database (*notmuch->xapian_db);
744 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
745 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
746 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
747 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
749 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
750 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
751 notmuch->query_parser->add_boolean_prefix (prefix->name,
755 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
756 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
757 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
759 } catch (const Xapian::Error &error) {
760 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
761 error.get_msg().c_str());
762 notmuch_database_destroy (notmuch);
764 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
773 talloc_free (notmuch);
778 notmuch_database_close (notmuch_database_t *notmuch)
781 if (notmuch->xapian_db != NULL &&
782 notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
783 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
784 } catch (const Xapian::Error &error) {
785 if (! notmuch->exception_reported) {
786 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
787 error.get_msg().c_str());
791 /* Many Xapian objects (and thus notmuch objects) hold references to
792 * the database, so merely deleting the database may not suffice to
793 * close it. Thus, we explicitly close it here. */
794 if (notmuch->xapian_db != NULL) {
796 notmuch->xapian_db->close();
797 } catch (const Xapian::Error &error) {
802 delete notmuch->term_gen;
803 notmuch->term_gen = NULL;
804 delete notmuch->query_parser;
805 notmuch->query_parser = NULL;
806 delete notmuch->xapian_db;
807 notmuch->xapian_db = NULL;
808 delete notmuch->value_range_processor;
809 notmuch->value_range_processor = NULL;
810 delete notmuch->date_range_processor;
811 notmuch->date_range_processor = NULL;
814 #if HAVE_XAPIAN_COMPACT
816 unlink_cb (const char *path,
817 unused (const struct stat *sb),
819 unused (struct FTW *ftw))
821 return remove (path);
825 rmtree (const char *path)
827 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
830 class NotmuchCompactor : public Xapian::Compactor
832 notmuch_compact_status_cb_t status_cb;
833 void *status_closure;
836 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
837 status_cb (cb), status_closure (closure) { }
840 set_status (const std::string &table, const std::string &status)
844 if (status_cb == NULL)
847 if (status.length () == 0)
848 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
850 msg = talloc_asprintf (NULL, " %s", status.c_str());
856 status_cb (msg, status_closure);
861 /* Compacts the given database, optionally saving the original database
862 * in backup_path. Additionally, a callback function can be provided to
863 * give the user feedback on the progress of the (likely long-lived)
864 * compaction process.
866 * The backup path must point to a directory on the same volume as the
867 * original database. Passing a NULL backup_path will result in the
868 * uncompacted database being deleted after compaction has finished.
869 * Note that the database write lock will be held during the
870 * compaction process to protect data integrity.
873 notmuch_database_compact (const char *path,
874 const char *backup_path,
875 notmuch_compact_status_cb_t status_cb,
879 char *notmuch_path, *xapian_path, *compact_xapian_path;
880 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
881 notmuch_database_t *notmuch = NULL;
883 notmuch_bool_t keep_backup;
885 local = talloc_new (NULL);
887 return NOTMUCH_STATUS_OUT_OF_MEMORY;
889 ret = notmuch_database_open (path, NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much);
894 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
895 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
899 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
900 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
904 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
905 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
909 if (backup_path == NULL) {
910 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
911 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
920 if (stat (backup_path, &statbuf) != -1) {
921 fprintf (stderr, "Path already exists: %s\n", backup_path);
922 ret = NOTMUCH_STATUS_FILE_ERROR;
925 if (errno != ENOENT) {
926 fprintf (stderr, "Unknown error while stat()ing path: %s\n",
928 ret = NOTMUCH_STATUS_FILE_ERROR;
932 /* Unconditionally attempt to remove old work-in-progress database (if
933 * any). This is "protected" by database lock. If this fails due to write
934 * errors (etc), the following code will fail and provide error message.
936 (void) rmtree (compact_xapian_path);
939 NotmuchCompactor compactor (status_cb, closure);
941 compactor.set_renumber (false);
942 compactor.add_source (xapian_path);
943 compactor.set_destdir (compact_xapian_path);
944 compactor.compact ();
945 } catch (const Xapian::Error &error) {
946 fprintf (stderr, "Error while compacting: %s\n", error.get_msg().c_str());
947 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
951 if (rename (xapian_path, backup_path)) {
952 fprintf (stderr, "Error moving %s to %s: %s\n",
953 xapian_path, backup_path, strerror (errno));
954 ret = NOTMUCH_STATUS_FILE_ERROR;
958 if (rename (compact_xapian_path, xapian_path)) {
959 fprintf (stderr, "Error moving %s to %s: %s\n",
960 compact_xapian_path, xapian_path, strerror (errno));
961 ret = NOTMUCH_STATUS_FILE_ERROR;
966 if (rmtree (backup_path)) {
967 fprintf (stderr, "Error removing old database %s: %s\n",
968 backup_path, strerror (errno));
969 ret = NOTMUCH_STATUS_FILE_ERROR;
976 notmuch_database_destroy (notmuch);
984 notmuch_database_compact (unused (const char *path),
985 unused (const char *backup_path),
986 unused (notmuch_compact_status_cb_t status_cb),
987 unused (void *closure))
989 fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
990 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
995 notmuch_database_destroy (notmuch_database_t *notmuch)
997 notmuch_database_close (notmuch);
998 talloc_free (notmuch);
1002 notmuch_database_get_path (notmuch_database_t *notmuch)
1004 return notmuch->path;
1008 notmuch_database_get_version (notmuch_database_t *notmuch)
1010 unsigned int version;
1011 string version_string;
1015 version_string = notmuch->xapian_db->get_metadata ("version");
1016 if (version_string.empty ())
1019 str = version_string.c_str ();
1020 if (str == NULL || *str == '\0')
1023 version = strtoul (str, &end, 10);
1025 INTERNAL_ERROR ("Malformed database version: %s", str);
1031 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1033 return notmuch->needs_upgrade;
1036 static volatile sig_atomic_t do_progress_notify = 0;
1039 handle_sigalrm (unused (int signal))
1041 do_progress_notify = 1;
1044 /* Upgrade the current database.
1046 * After opening a database in read-write mode, the client should
1047 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1048 * if so, upgrade with this function before making any modifications.
1050 * The optional progress_notify callback can be used by the caller to
1051 * provide progress indication to the user. If non-NULL it will be
1052 * called periodically with 'count' as the number of messages upgraded
1053 * so far and 'total' the overall number of messages that will be
1057 notmuch_database_upgrade (notmuch_database_t *notmuch,
1058 void (*progress_notify) (void *closure,
1062 Xapian::WritableDatabase *db;
1063 struct sigaction action;
1064 struct itimerval timerval;
1065 notmuch_bool_t timer_is_active = FALSE;
1066 unsigned int version;
1067 notmuch_status_t status;
1068 unsigned int count = 0, total = 0;
1070 status = _notmuch_database_ensure_writable (notmuch);
1074 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1076 version = notmuch_database_get_version (notmuch);
1078 if (version >= NOTMUCH_DATABASE_VERSION)
1079 return NOTMUCH_STATUS_SUCCESS;
1081 if (progress_notify) {
1082 /* Setup our handler for SIGALRM */
1083 memset (&action, 0, sizeof (struct sigaction));
1084 action.sa_handler = handle_sigalrm;
1085 sigemptyset (&action.sa_mask);
1086 action.sa_flags = SA_RESTART;
1087 sigaction (SIGALRM, &action, NULL);
1089 /* Then start a timer to send SIGALRM once per second. */
1090 timerval.it_interval.tv_sec = 1;
1091 timerval.it_interval.tv_usec = 0;
1092 timerval.it_value.tv_sec = 1;
1093 timerval.it_value.tv_usec = 0;
1094 setitimer (ITIMER_REAL, &timerval, NULL);
1096 timer_is_active = TRUE;
1099 /* Before version 1, each message document had its filename in the
1100 * data field. Copy that into the new format by calling
1101 * notmuch_message_add_filename.
1104 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1105 notmuch_messages_t *messages;
1106 notmuch_message_t *message;
1108 Xapian::TermIterator t, t_end;
1110 total = notmuch_query_count_messages (query);
1112 for (messages = notmuch_query_search_messages (query);
1113 notmuch_messages_valid (messages);
1114 notmuch_messages_move_to_next (messages))
1116 if (do_progress_notify) {
1117 progress_notify (closure, (double) count / total);
1118 do_progress_notify = 0;
1121 message = notmuch_messages_get (messages);
1123 filename = _notmuch_message_talloc_copy_data (message);
1124 if (filename && *filename != '\0') {
1125 _notmuch_message_add_filename (message, filename);
1126 _notmuch_message_sync (message);
1128 talloc_free (filename);
1130 notmuch_message_destroy (message);
1135 notmuch_query_destroy (query);
1137 /* Also, before version 1 we stored directory timestamps in
1138 * XTIMESTAMP documents instead of the current XDIRECTORY
1139 * documents. So copy those as well. */
1141 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1143 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1147 Xapian::PostingIterator p, p_end;
1148 std::string term = *t;
1150 p_end = notmuch->xapian_db->postlist_end (term);
1152 for (p = notmuch->xapian_db->postlist_begin (term);
1156 Xapian::Document document;
1158 notmuch_directory_t *directory;
1160 if (do_progress_notify) {
1161 progress_notify (closure, (double) count / total);
1162 do_progress_notify = 0;
1165 document = find_document_for_doc_id (notmuch, *p);
1166 mtime = Xapian::sortable_unserialise (
1167 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1169 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1170 NOTMUCH_FIND_CREATE, &status);
1171 notmuch_directory_set_mtime (directory, mtime);
1172 notmuch_directory_destroy (directory);
1178 * Prior to version 2, the "folder:" prefix was probabilistic and
1179 * stemmed. Change it to the current boolean prefix. Add "path:"
1180 * prefixes while at it.
1183 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1184 notmuch_messages_t *messages;
1185 notmuch_message_t *message;
1188 total = notmuch_query_count_messages (query);
1190 for (messages = notmuch_query_search_messages (query);
1191 notmuch_messages_valid (messages);
1192 notmuch_messages_move_to_next (messages)) {
1193 if (do_progress_notify) {
1194 progress_notify (closure, (double) count / total);
1195 do_progress_notify = 0;
1198 message = notmuch_messages_get (messages);
1200 _notmuch_message_upgrade_folder (message);
1201 _notmuch_message_sync (message);
1203 notmuch_message_destroy (message);
1208 notmuch_query_destroy (query);
1211 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1214 /* Now that the upgrade is complete we can remove the old data
1215 * and documents that are no longer needed. */
1217 notmuch_query_t *query = notmuch_query_create (notmuch, "");
1218 notmuch_messages_t *messages;
1219 notmuch_message_t *message;
1222 for (messages = notmuch_query_search_messages (query);
1223 notmuch_messages_valid (messages);
1224 notmuch_messages_move_to_next (messages))
1226 if (do_progress_notify) {
1227 progress_notify (closure, (double) count / total);
1228 do_progress_notify = 0;
1231 message = notmuch_messages_get (messages);
1233 filename = _notmuch_message_talloc_copy_data (message);
1234 if (filename && *filename != '\0') {
1235 _notmuch_message_clear_data (message);
1236 _notmuch_message_sync (message);
1238 talloc_free (filename);
1240 notmuch_message_destroy (message);
1243 notmuch_query_destroy (query);
1247 Xapian::TermIterator t, t_end;
1249 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1251 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1255 Xapian::PostingIterator p, p_end;
1256 std::string term = *t;
1258 p_end = notmuch->xapian_db->postlist_end (term);
1260 for (p = notmuch->xapian_db->postlist_begin (term);
1264 if (do_progress_notify) {
1265 progress_notify (closure, (double) count / total);
1266 do_progress_notify = 0;
1269 db->delete_document (*p);
1274 if (timer_is_active) {
1275 /* Now stop the timer. */
1276 timerval.it_interval.tv_sec = 0;
1277 timerval.it_interval.tv_usec = 0;
1278 timerval.it_value.tv_sec = 0;
1279 timerval.it_value.tv_usec = 0;
1280 setitimer (ITIMER_REAL, &timerval, NULL);
1282 /* And disable the signal handler. */
1283 action.sa_handler = SIG_IGN;
1284 sigaction (SIGALRM, &action, NULL);
1287 return NOTMUCH_STATUS_SUCCESS;
1291 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1293 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1294 notmuch->atomic_nesting > 0)
1298 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1299 } catch (const Xapian::Error &error) {
1300 fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1301 error.get_msg().c_str());
1302 notmuch->exception_reported = TRUE;
1303 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1307 notmuch->atomic_nesting++;
1308 return NOTMUCH_STATUS_SUCCESS;
1312 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1314 Xapian::WritableDatabase *db;
1316 if (notmuch->atomic_nesting == 0)
1317 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1319 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1320 notmuch->atomic_nesting > 1)
1323 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1325 db->commit_transaction ();
1327 /* This is a hack for testing. Xapian never flushes on a
1328 * non-flushed commit, even if the flush threshold is 1.
1329 * However, we rely on flushing to test atomicity. */
1330 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1331 if (thresh && atoi (thresh) == 1)
1333 } catch (const Xapian::Error &error) {
1334 fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1335 error.get_msg().c_str());
1336 notmuch->exception_reported = TRUE;
1337 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1341 notmuch->atomic_nesting--;
1342 return NOTMUCH_STATUS_SUCCESS;
1345 /* We allow the user to use arbitrarily long paths for directories. But
1346 * we have a term-length limit. So if we exceed that, we'll use the
1347 * SHA-1 of the path for the database term.
1349 * Note: This function may return the original value of 'path'. If it
1350 * does not, then the caller is responsible to free() the returned
1354 _notmuch_database_get_directory_db_path (const char *path)
1356 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1358 if (term_len > NOTMUCH_TERM_MAX)
1359 return notmuch_sha1_of_string (path);
1364 /* Given a path, split it into two parts: the directory part is all
1365 * components except for the last, and the basename is that last
1366 * component. Getting the return-value for either part is optional
1367 * (the caller can pass NULL).
1369 * The original 'path' can represent either a regular file or a
1370 * directory---the splitting will be carried out in the same way in
1371 * either case. Trailing slashes on 'path' will be ignored, and any
1372 * cases of multiple '/' characters appearing in series will be
1373 * treated as a single '/'.
1375 * Allocation (if any) will have 'ctx' as the talloc owner. But
1376 * pointers will be returned within the original path string whenever
1379 * Note: If 'path' is non-empty and contains no non-trailing slash,
1380 * (that is, consists of a filename with no parent directory), then
1381 * the directory returned will be an empty string. However, if 'path'
1382 * is an empty string, then both directory and basename will be
1386 _notmuch_database_split_path (void *ctx,
1388 const char **directory,
1389 const char **basename)
1393 if (path == NULL || *path == '\0') {
1398 return NOTMUCH_STATUS_SUCCESS;
1401 /* Find the last slash (not counting a trailing slash), if any. */
1403 slash = path + strlen (path) - 1;
1405 /* First, skip trailing slashes. */
1406 while (slash != path) {
1413 /* Then, find a slash. */
1414 while (slash != path) {
1424 /* Finally, skip multiple slashes. */
1425 while (slash != path) {
1432 if (slash == path) {
1434 *directory = talloc_strdup (ctx, "");
1439 *directory = talloc_strndup (ctx, path, slash - path + 1);
1442 return NOTMUCH_STATUS_SUCCESS;
1445 /* Find the document ID of the specified directory.
1447 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1448 * created if one does not exist for 'path'. Otherwise, if the
1449 * directory document does not exist, this sets *directory_id to
1450 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1453 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1455 notmuch_find_flags_t flags,
1456 unsigned int *directory_id)
1458 notmuch_directory_t *directory;
1459 notmuch_status_t status;
1463 return NOTMUCH_STATUS_SUCCESS;
1466 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1467 if (status || !directory) {
1472 *directory_id = _notmuch_directory_get_document_id (directory);
1474 notmuch_directory_destroy (directory);
1476 return NOTMUCH_STATUS_SUCCESS;
1480 _notmuch_database_get_directory_path (void *ctx,
1481 notmuch_database_t *notmuch,
1482 unsigned int doc_id)
1484 Xapian::Document document;
1486 document = find_document_for_doc_id (notmuch, doc_id);
1488 return talloc_strdup (ctx, document.get_data ().c_str ());
1491 /* Given a legal 'filename' for the database, (either relative to
1492 * database path or absolute with initial components identical to
1493 * database path), return a new string (with 'ctx' as the talloc
1494 * owner) suitable for use as a direntry term value.
1496 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1497 * will be created in the database as needed. Otherwise, if the
1498 * necessary directory documents do not exist, this sets
1499 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1502 _notmuch_database_filename_to_direntry (void *ctx,
1503 notmuch_database_t *notmuch,
1504 const char *filename,
1505 notmuch_find_flags_t flags,
1508 const char *relative, *directory, *basename;
1509 Xapian::docid directory_id;
1510 notmuch_status_t status;
1512 relative = _notmuch_database_relative_path (notmuch, filename);
1514 status = _notmuch_database_split_path (ctx, relative,
1515 &directory, &basename);
1519 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1521 if (status || directory_id == (unsigned int)-1) {
1526 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1528 return NOTMUCH_STATUS_SUCCESS;
1531 /* Given a legal 'path' for the database, return the relative path.
1533 * The return value will be a pointer to the original path contents,
1534 * and will be either the original string (if 'path' was relative) or
1535 * a portion of the string (if path was absolute and begins with the
1539 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1542 const char *db_path, *relative;
1543 unsigned int db_path_len;
1545 db_path = notmuch_database_get_path (notmuch);
1546 db_path_len = strlen (db_path);
1550 if (*relative == '/') {
1551 while (*relative == '/' && *(relative+1) == '/')
1554 if (strncmp (relative, db_path, db_path_len) == 0)
1556 relative += db_path_len;
1557 while (*relative == '/')
1566 notmuch_database_get_directory (notmuch_database_t *notmuch,
1568 notmuch_directory_t **directory)
1570 notmuch_status_t status;
1572 if (directory == NULL)
1573 return NOTMUCH_STATUS_NULL_POINTER;
1577 *directory = _notmuch_directory_create (notmuch, path,
1578 NOTMUCH_FIND_LOOKUP, &status);
1579 } catch (const Xapian::Error &error) {
1580 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1581 error.get_msg().c_str());
1582 notmuch->exception_reported = TRUE;
1583 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1588 /* Allocate a document ID that satisfies the following criteria:
1590 * 1. The ID does not exist for any document in the Xapian database
1592 * 2. The ID was not previously returned from this function
1594 * 3. The ID is the smallest integer satisfying (1) and (2)
1596 * This function will trigger an internal error if these constraints
1597 * cannot all be satisfied, (that is, the pool of available document
1598 * IDs has been exhausted).
1601 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1603 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1605 notmuch->last_doc_id++;
1607 if (notmuch->last_doc_id == 0)
1608 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1610 return notmuch->last_doc_id;
1614 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1616 /* 16 bytes (+ terminator) for hexadecimal representation of
1617 * a 64-bit integer. */
1618 static char thread_id[17];
1619 Xapian::WritableDatabase *db;
1621 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1623 notmuch->last_thread_id++;
1625 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1627 db->set_metadata ("last_thread_id", thread_id);
1633 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1635 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1636 message_id = _message_id_compressed (ctx, message_id);
1638 return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1642 /* Find the thread ID to which the message with 'message_id' belongs.
1644 * Note: 'thread_id_ret' must not be NULL!
1645 * On success '*thread_id_ret' is set to a newly talloced string belonging to
1648 * Note: If there is no message in the database with the given
1649 * 'message_id' then a new thread_id will be allocated for this
1650 * message and stored in the database metadata, (where this same
1651 * thread ID can be looked up if the message is added to the database
1654 static notmuch_status_t
1655 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1657 const char *message_id,
1658 const char **thread_id_ret)
1660 notmuch_status_t status;
1661 notmuch_message_t *message;
1662 string thread_id_string;
1664 Xapian::WritableDatabase *db;
1666 status = notmuch_database_find_message (notmuch, message_id, &message);
1672 *thread_id_ret = talloc_steal (ctx,
1673 notmuch_message_get_thread_id (message));
1675 notmuch_message_destroy (message);
1677 return NOTMUCH_STATUS_SUCCESS;
1680 /* Message has not been seen yet.
1682 * We may have seen a reference to it already, in which case, we
1683 * can return the thread ID stored in the metadata. Otherwise, we
1684 * generate a new thread ID and store it there.
1686 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1687 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1688 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1690 if (thread_id_string.empty()) {
1691 *thread_id_ret = talloc_strdup (ctx,
1692 _notmuch_database_generate_thread_id (notmuch));
1693 db->set_metadata (metadata_key, *thread_id_ret);
1695 *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1698 talloc_free (metadata_key);
1700 return NOTMUCH_STATUS_SUCCESS;
1703 static notmuch_status_t
1704 _merge_threads (notmuch_database_t *notmuch,
1705 const char *winner_thread_id,
1706 const char *loser_thread_id)
1708 Xapian::PostingIterator loser, loser_end;
1709 notmuch_message_t *message = NULL;
1710 notmuch_private_status_t private_status;
1711 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1713 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1715 for ( ; loser != loser_end; loser++) {
1716 message = _notmuch_message_create (notmuch, notmuch,
1717 *loser, &private_status);
1718 if (message == NULL) {
1719 ret = COERCE_STATUS (private_status,
1720 "Cannot find document for doc_id from query");
1724 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1725 _notmuch_message_add_term (message, "thread", winner_thread_id);
1726 _notmuch_message_sync (message);
1728 notmuch_message_destroy (message);
1734 notmuch_message_destroy (message);
1740 _my_talloc_free_for_g_hash (void *ptr)
1745 static notmuch_status_t
1746 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1747 notmuch_message_t *message,
1748 notmuch_message_file_t *message_file,
1749 const char **thread_id)
1751 GHashTable *parents = NULL;
1752 const char *refs, *in_reply_to, *in_reply_to_message_id;
1753 const char *last_ref_message_id, *this_message_id;
1754 GList *l, *keys = NULL;
1755 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1757 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1758 _my_talloc_free_for_g_hash, NULL);
1759 this_message_id = notmuch_message_get_message_id (message);
1761 refs = notmuch_message_file_get_header (message_file, "references");
1762 last_ref_message_id = parse_references (message,
1766 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1767 in_reply_to_message_id = parse_references (message,
1769 parents, in_reply_to);
1771 /* For the parent of this message, use the last message ID of the
1772 * References header, if available. If not, fall back to the
1773 * first message ID in the In-Reply-To header. */
1774 if (last_ref_message_id) {
1775 _notmuch_message_add_term (message, "replyto",
1776 last_ref_message_id);
1777 } else if (in_reply_to_message_id) {
1778 _notmuch_message_add_term (message, "replyto",
1779 in_reply_to_message_id);
1782 keys = g_hash_table_get_keys (parents);
1783 for (l = keys; l; l = l->next) {
1784 char *parent_message_id;
1785 const char *parent_thread_id = NULL;
1787 parent_message_id = (char *) l->data;
1789 _notmuch_message_add_term (message, "reference",
1792 ret = _resolve_message_id_to_thread_id (notmuch,
1799 if (*thread_id == NULL) {
1800 *thread_id = talloc_strdup (message, parent_thread_id);
1801 _notmuch_message_add_term (message, "thread", *thread_id);
1802 } else if (strcmp (*thread_id, parent_thread_id)) {
1803 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1813 g_hash_table_unref (parents);
1818 static notmuch_status_t
1819 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1820 notmuch_message_t *message,
1821 const char **thread_id)
1823 const char *message_id = notmuch_message_get_message_id (message);
1824 Xapian::PostingIterator child, children_end;
1825 notmuch_message_t *child_message = NULL;
1826 const char *child_thread_id;
1827 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1828 notmuch_private_status_t private_status;
1830 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1832 for ( ; child != children_end; child++) {
1834 child_message = _notmuch_message_create (message, notmuch,
1835 *child, &private_status);
1836 if (child_message == NULL) {
1837 ret = COERCE_STATUS (private_status,
1838 "Cannot find document for doc_id from query");
1842 child_thread_id = notmuch_message_get_thread_id (child_message);
1843 if (*thread_id == NULL) {
1844 *thread_id = talloc_strdup (message, child_thread_id);
1845 _notmuch_message_add_term (message, "thread", *thread_id);
1846 } else if (strcmp (*thread_id, child_thread_id)) {
1847 _notmuch_message_remove_term (child_message, "reference",
1849 _notmuch_message_sync (child_message);
1850 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1855 notmuch_message_destroy (child_message);
1856 child_message = NULL;
1861 notmuch_message_destroy (child_message);
1866 /* Given a (mostly empty) 'message' and its corresponding
1867 * 'message_file' link it to existing threads in the database.
1869 * The first check is in the metadata of the database to see if we
1870 * have pre-allocated a thread_id in advance for this message, (which
1871 * would have happened if a message was previously added that
1872 * referenced this one).
1874 * Second, we look at 'message_file' and its link-relevant headers
1875 * (References and In-Reply-To) for message IDs.
1877 * Finally, we look in the database for existing message that
1878 * reference 'message'.
1880 * In all cases, we assign to the current message the first thread_id
1881 * found (through either parent or child). We will also merge any
1882 * existing, distinct threads where this message belongs to both,
1883 * (which is not uncommon when messages are processed out of order).
1885 * Finally, if no thread ID has been found through parent or child, we
1886 * call _notmuch_message_generate_thread_id to generate a new thread
1887 * ID. This should only happen for new, top-level messages, (no
1888 * References or In-Reply-To header in this message, and no previously
1889 * added message refers to this message).
1891 static notmuch_status_t
1892 _notmuch_database_link_message (notmuch_database_t *notmuch,
1893 notmuch_message_t *message,
1894 notmuch_message_file_t *message_file)
1896 notmuch_status_t status;
1897 const char *message_id, *thread_id = NULL;
1901 message_id = notmuch_message_get_message_id (message);
1902 metadata_key = _get_metadata_thread_id_key (message, message_id);
1904 /* Check if we have already seen related messages to this one.
1905 * If we have then use the thread_id that we stored at that time.
1907 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1908 if (! stored_id.empty()) {
1909 Xapian::WritableDatabase *db;
1911 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1913 /* Clear the metadata for this message ID. We don't need it
1915 db->set_metadata (metadata_key, "");
1916 thread_id = stored_id.c_str();
1918 _notmuch_message_add_term (message, "thread", thread_id);
1920 talloc_free (metadata_key);
1922 status = _notmuch_database_link_message_to_parents (notmuch, message,
1928 status = _notmuch_database_link_message_to_children (notmuch, message,
1933 /* If not part of any existing thread, generate a new thread ID. */
1934 if (thread_id == NULL) {
1935 thread_id = _notmuch_database_generate_thread_id (notmuch);
1937 _notmuch_message_add_term (message, "thread", thread_id);
1940 return NOTMUCH_STATUS_SUCCESS;
1944 notmuch_database_add_message (notmuch_database_t *notmuch,
1945 const char *filename,
1946 notmuch_message_t **message_ret)
1948 notmuch_message_file_t *message_file;
1949 notmuch_message_t *message = NULL;
1950 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1951 notmuch_private_status_t private_status;
1953 const char *date, *header;
1954 const char *from, *to, *subject;
1955 char *message_id = NULL;
1958 *message_ret = NULL;
1960 ret = _notmuch_database_ensure_writable (notmuch);
1964 message_file = notmuch_message_file_open (filename);
1965 if (message_file == NULL)
1966 return NOTMUCH_STATUS_FILE_ERROR;
1968 /* Adding a message may change many documents. Do this all
1970 ret = notmuch_database_begin_atomic (notmuch);
1974 /* Parse message up front to get better error status. */
1975 ret = _notmuch_message_file_parse (message_file);
1980 /* Before we do any real work, (especially before doing a
1981 * potential SHA-1 computation on the entire file's contents),
1982 * let's make sure that what we're looking at looks like an
1983 * actual email message.
1985 from = notmuch_message_file_get_header (message_file, "from");
1986 subject = notmuch_message_file_get_header (message_file, "subject");
1987 to = notmuch_message_file_get_header (message_file, "to");
1989 if ((from == NULL || *from == '\0') &&
1990 (subject == NULL || *subject == '\0') &&
1991 (to == NULL || *to == '\0'))
1993 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1997 /* Now that we're sure it's mail, the first order of business
1998 * is to find a message ID (or else create one ourselves). */
2000 header = notmuch_message_file_get_header (message_file, "message-id");
2001 if (header && *header != '\0') {
2002 message_id = _parse_message_id (message_file, header, NULL);
2004 /* So the header value isn't RFC-compliant, but it's
2005 * better than no message-id at all. */
2006 if (message_id == NULL)
2007 message_id = talloc_strdup (message_file, header);
2009 /* If a message ID is too long, substitute its sha1 instead. */
2010 if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
2011 char *compressed = _message_id_compressed (message_file,
2013 talloc_free (message_id);
2014 message_id = compressed;
2018 if (message_id == NULL ) {
2019 /* No message-id at all, let's generate one by taking a
2020 * hash over the file's contents. */
2021 char *sha1 = notmuch_sha1_of_file (filename);
2023 /* If that failed too, something is really wrong. Give up. */
2025 ret = NOTMUCH_STATUS_FILE_ERROR;
2029 message_id = talloc_asprintf (message_file,
2030 "notmuch-sha1-%s", sha1);
2034 /* Now that we have a message ID, we get a message object,
2035 * (which may or may not reference an existing document in the
2038 message = _notmuch_message_create_for_message_id (notmuch,
2042 talloc_free (message_id);
2044 if (message == NULL) {
2045 ret = COERCE_STATUS (private_status,
2046 "Unexpected status value from _notmuch_message_create_for_message_id");
2050 _notmuch_message_add_filename (message, filename);
2052 /* Is this a newly created message object? */
2053 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2054 _notmuch_message_add_term (message, "type", "mail");
2056 ret = _notmuch_database_link_message (notmuch, message,
2061 date = notmuch_message_file_get_header (message_file, "date");
2062 _notmuch_message_set_header_values (message, date, from, subject);
2064 ret = _notmuch_message_index_file (message, message_file);
2068 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2071 _notmuch_message_sync (message);
2072 } catch (const Xapian::Error &error) {
2073 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2074 error.get_msg().c_str());
2075 notmuch->exception_reported = TRUE;
2076 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2082 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2083 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2084 *message_ret = message;
2086 notmuch_message_destroy (message);
2090 notmuch_message_file_close (message_file);
2092 ret2 = notmuch_database_end_atomic (notmuch);
2093 if ((ret == NOTMUCH_STATUS_SUCCESS ||
2094 ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2095 ret2 != NOTMUCH_STATUS_SUCCESS)
2102 notmuch_database_remove_message (notmuch_database_t *notmuch,
2103 const char *filename)
2105 notmuch_status_t status;
2106 notmuch_message_t *message;
2108 status = notmuch_database_find_message_by_filename (notmuch, filename,
2111 if (status == NOTMUCH_STATUS_SUCCESS && message) {
2112 status = _notmuch_message_remove_filename (message, filename);
2113 if (status == NOTMUCH_STATUS_SUCCESS)
2114 _notmuch_message_delete (message);
2115 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2116 _notmuch_message_sync (message);
2118 notmuch_message_destroy (message);
2125 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2126 const char *filename,
2127 notmuch_message_t **message_ret)
2130 const char *prefix = _find_prefix ("file-direntry");
2131 char *direntry, *term;
2132 Xapian::PostingIterator i, end;
2133 notmuch_status_t status;
2135 if (message_ret == NULL)
2136 return NOTMUCH_STATUS_NULL_POINTER;
2138 /* return NULL on any failure */
2139 *message_ret = NULL;
2141 local = talloc_new (notmuch);
2144 status = _notmuch_database_filename_to_direntry (
2145 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2146 if (status || !direntry)
2149 term = talloc_asprintf (local, "%s%s", prefix, direntry);
2151 find_doc_ids_for_term (notmuch, term, &i, &end);
2154 notmuch_private_status_t private_status;
2156 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2158 if (*message_ret == NULL)
2159 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2161 } catch (const Xapian::Error &error) {
2162 fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2163 error.get_msg().c_str());
2164 notmuch->exception_reported = TRUE;
2165 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2169 talloc_free (local);
2171 if (status && *message_ret) {
2172 notmuch_message_destroy (*message_ret);
2173 *message_ret = NULL;
2178 notmuch_string_list_t *
2179 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2180 Xapian::TermIterator &end,
2183 int prefix_len = strlen (prefix);
2184 notmuch_string_list_t *list;
2186 list = _notmuch_string_list_create (ctx);
2187 if (unlikely (list == NULL))
2190 for (i.skip_to (prefix); i != end; i++) {
2191 /* Terminate loop at first term without desired prefix. */
2192 if (strncmp ((*i).c_str (), prefix, prefix_len))
2195 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2202 notmuch_database_get_all_tags (notmuch_database_t *db)
2204 Xapian::TermIterator i, end;
2205 notmuch_string_list_t *tags;
2208 i = db->xapian_db->allterms_begin();
2209 end = db->xapian_db->allterms_end();
2210 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2211 _find_prefix ("tag"));
2212 _notmuch_string_list_sort (tags);
2213 return _notmuch_tags_create (db, tags);
2214 } catch (const Xapian::Error &error) {
2215 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2216 error.get_msg().c_str());
2217 db->exception_reported = TRUE;