1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see https://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
22 #include "string-util.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 */
41 notmuch_field_flag_t flags;
44 #define NOTMUCH_DATABASE_VERSION 3
46 #define STRINGIFY(s) _SUB_STRINGIFY (s)
47 #define _SUB_STRINGIFY(s) #s
49 #define LOG_XAPIAN_EXCEPTION(message, error) _log_xapian_exception (__location__, message, error)
52 _log_xapian_exception (const char *where, notmuch_database_t *notmuch, const Xapian::Error error)
54 _notmuch_database_log (notmuch,
55 "A Xapian exception occurred at %s: %s\n",
57 error.get_msg ().c_str ());
58 notmuch->exception_reported = true;
61 notmuch_database_mode_t
62 _notmuch_database_mode (notmuch_database_t *notmuch)
64 if (notmuch->writable_xapian_db)
65 return NOTMUCH_DATABASE_MODE_READ_WRITE;
67 return NOTMUCH_DATABASE_MODE_READ_ONLY;
70 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
72 * We currently have three different types of documents (mail, ghost,
73 * and directory) and also some metadata.
75 * There are two kinds of prefixes used in notmuch. There are the
76 * human friendly 'prefix names' like "thread:", which are also used
77 * in the query parser, and the actual prefix terms in the database
78 * (e.g. "G"). The correspondence is maintained in the file scope data
79 * structure 'prefix_table'.
83 * A mail document is associated with a particular email message. It
84 * is stored in one or more files on disk and is uniquely identified
85 * by its "id" field (which is generally the message ID). It is
86 * indexed with the following prefixed terms which the database uses
87 * to construct threads, etc.:
89 * Single terms of given prefix:
93 * id: Unique ID of mail. This is from the Message-ID header
94 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
95 * If it's present and too long, then we use
96 * "notmuch-sha1-<sha1_sum_of_message_id>".
97 * If this header is not present, we use
98 * "notmuch-sha1-<sha1_sum_of_entire_file>".
100 * thread: The ID of the thread to which the mail belongs
102 * replyto: The ID from the In-Reply-To header of the mail (if any).
104 * Multiple terms of given prefix:
106 * reference: All message IDs from In-Reply-To and References
107 * headers in the message.
109 * tag: Any tags associated with this message by the user.
111 * file-direntry: A colon-separated pair of values
112 * (INTEGER:STRING), where INTEGER is the
113 * document ID of a directory document, and
114 * STRING is the name of a file within that
115 * directory for this mail message.
117 * property: Has a property with key=value
118 * FIXME: if no = is present, should match on any value
120 * A mail document also has four values:
122 * TIMESTAMP: The time_t value corresponding to the message's
125 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
127 * FROM: The value of the "From" header
129 * SUBJECT: The value of the "Subject" header
131 * LAST_MOD: The revision number as of the last tag or
134 * The prefixed terms described above are also searchable without an
135 * explicit field name, but as of notmuch 0.29 this is due to
136 * query-parser setup, not extra terms in the database. In addition,
137 * terms from the content of the message are added without a prefix
138 * for use by the user in searching. Note that the prefix name "body"
139 * is used to refer to the empty prefix string in the database.
141 * The path of the containing folder is added with the "folder" prefix
142 * (see _notmuch_message_add_folder_terms). Sub-paths of the the path
143 * of the mail message are added with the "path" prefix.
145 * The data portion of a mail document is empty.
147 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
148 * -----------------------------------------------
149 * A ghost mail document is like a mail document, but where we don't
150 * have the message content. These are used to track thread reference
151 * information for messages we haven't received.
153 * A ghost mail document has type: ghost; id and thread fields that
154 * are identical to the mail document fields; and a MESSAGE_ID value.
158 * A directory document is used by a client of the notmuch library to
159 * maintain data necessary to allow for efficient polling of mail
162 * All directory documents contain one term:
164 * directory: The directory path (relative to the database path)
165 * Or the SHA1 sum of the directory path (if the
166 * path itself is too long to fit in a Xapian
169 * And all directory documents for directories other than top-level
170 * directories also contain the following term:
172 * directory-direntry: A colon-separated pair of values
173 * (INTEGER:STRING), where INTEGER is the
174 * document ID of the parent directory
175 * document, and STRING is the name of this
176 * directory within that parent.
178 * All directory documents have a single value:
180 * TIMESTAMP: The mtime of the directory (at last scan)
182 * The data portion of a directory document contains the path of the
183 * directory (relative to the database path).
187 * Xapian allows us to store arbitrary name-value pairs as
188 * "metadata". We currently use the following metadata names with the
191 * version The database schema version, (which is distinct
192 * from both the notmuch package version (see
193 * notmuch --version) and the libnotmuch library
194 * version. The version is stored as an base-10
195 * ASCII integer. The initial database version
196 * was 1, (though a schema existed before that
197 * were no "version" database value existed at
198 * all). Successive versions are allocated as
199 * changes are made to the database (such as by
200 * indexing new fields).
202 * features The set of features supported by this
203 * database. This consists of a set of
204 * '\n'-separated lines, where each is a feature
205 * name, a '\t', and compatibility flags. If the
206 * compatibility flags contain 'w', then the
207 * opener must support this feature to safely
208 * write this database. If the compatibility
209 * flags contain 'r', then the opener must
210 * support this feature to read this database.
211 * Introduced in database version 3.
213 * last_thread_id The last thread ID generated. This is stored
214 * as a 16-byte hexadecimal ASCII representation
215 * of a 64-bit unsigned integer. The first ID
216 * generated is 1 and the value will be
217 * incremented for each thread ID.
219 * C* metadata keys starting with C indicate
220 * configuration data. It can be managed with the
221 * n_database_*config* API. There is a convention
222 * of hierarchical keys separated by '.' (e.g.
223 * query.notmuch stores the value for the named
224 * query 'notmuch'), but it is not enforced by the
230 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
231 * Instead, the database has the following additional database
234 * thread_id_* A pre-allocated thread ID for a particular
235 * message. This is actually an arbitrarily large
236 * family of metadata name. Any particular name is
237 * formed by concatenating "thread_id_" with a message
238 * ID (or the SHA1 sum of a message ID if it is very
239 * long---see description of 'id' in the mail
240 * document). The value stored is a thread ID.
242 * These thread ID metadata values are stored
243 * whenever a message references a parent message
244 * that does not yet exist in the database. A
245 * thread ID will be allocated and stored, and if
246 * the message is later added, the stored thread
247 * ID will be used (and the metadata value will
250 * Even before a message is added, it's
251 * pre-allocated thread ID is useful so that all
252 * descendant messages that reference this common
253 * parent can be recognized as belonging to the
258 notmuch_string_map_iterator_t *
259 _notmuch_database_user_headers (notmuch_database_t *notmuch)
261 return _notmuch_string_map_iterator_create (notmuch->user_header, "", false);
265 notmuch_status_to_string (notmuch_status_t status)
268 case NOTMUCH_STATUS_SUCCESS:
269 return "No error occurred";
270 case NOTMUCH_STATUS_OUT_OF_MEMORY:
271 return "Out of memory";
272 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
273 return "Attempt to write to a read-only database";
274 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
275 return "A Xapian exception occurred";
276 case NOTMUCH_STATUS_FILE_ERROR:
277 return "Something went wrong trying to read or write a file";
278 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
279 return "File is not an email";
280 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
281 return "Message ID is identical to a message in database";
282 case NOTMUCH_STATUS_NULL_POINTER:
283 return "Erroneous NULL pointer";
284 case NOTMUCH_STATUS_TAG_TOO_LONG:
285 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
286 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
287 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
288 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
289 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
290 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
291 return "Unsupported operation";
292 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
293 return "Operation requires a database upgrade";
294 case NOTMUCH_STATUS_PATH_ERROR:
295 return "Path supplied is illegal for this function";
296 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
297 return "Crypto protocol missing, malformed, or unintelligible";
298 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
299 return "Crypto engine initialization failure";
300 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
301 return "Unknown crypto protocol";
303 case NOTMUCH_STATUS_LAST_STATUS:
304 return "Unknown error status value";
309 _notmuch_database_log (notmuch_database_t *notmuch,
315 va_start (va_args, format);
317 if (notmuch->status_string)
318 talloc_free (notmuch->status_string);
320 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
325 _notmuch_database_log_append (notmuch_database_t *notmuch,
331 va_start (va_args, format);
333 if (notmuch->status_string)
334 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
336 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
342 find_doc_ids_for_term (notmuch_database_t *notmuch,
344 Xapian::PostingIterator *begin,
345 Xapian::PostingIterator *end)
347 *begin = notmuch->xapian_db->postlist_begin (term);
349 *end = notmuch->xapian_db->postlist_end (term);
353 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
354 const char *prefix_name,
356 Xapian::PostingIterator *begin,
357 Xapian::PostingIterator *end)
361 term = talloc_asprintf (notmuch, "%s%s",
362 _find_prefix (prefix_name), value);
364 find_doc_ids_for_term (notmuch, term, begin, end);
369 notmuch_private_status_t
370 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
371 const char *prefix_name,
373 unsigned int *doc_id)
375 Xapian::PostingIterator i, end;
377 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
381 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
386 #if DEBUG_DATABASE_SANITY
390 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
394 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
397 static Xapian::Document
398 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
400 return notmuch->xapian_db->get_document (doc_id);
403 /* Generate a compressed version of 'message_id' of the form:
405 * notmuch-sha1-<sha1_sum_of_message_id>
408 _notmuch_message_id_compressed (void *ctx, const char *message_id)
410 char *sha1, *compressed;
412 sha1 = _notmuch_sha1_of_string (message_id);
414 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
421 notmuch_database_find_message (notmuch_database_t *notmuch,
422 const char *message_id,
423 notmuch_message_t **message_ret)
425 notmuch_private_status_t status;
428 if (message_ret == NULL)
429 return NOTMUCH_STATUS_NULL_POINTER;
431 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
432 message_id = _notmuch_message_id_compressed (notmuch, message_id);
435 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
436 message_id, &doc_id);
438 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
441 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
443 if (*message_ret == NULL)
444 return NOTMUCH_STATUS_OUT_OF_MEMORY;
447 return NOTMUCH_STATUS_SUCCESS;
448 } catch (const Xapian::Error &error) {
449 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
450 error.get_msg ().c_str ());
451 notmuch->exception_reported = true;
453 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
458 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
460 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY) {
461 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
462 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
465 return NOTMUCH_STATUS_SUCCESS;
468 /* Allocate a revision number for the next change. */
470 _notmuch_database_new_revision (notmuch_database_t *notmuch)
472 unsigned long new_revision = notmuch->revision + 1;
474 /* If we're in an atomic section, hold off on updating the
475 * committed revision number until we commit the atomic section.
477 if (notmuch->atomic_nesting)
478 notmuch->atomic_dirty = true;
480 notmuch->revision = new_revision;
486 notmuch_database_close (notmuch_database_t *notmuch)
488 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
490 /* Many Xapian objects (and thus notmuch objects) hold references to
491 * the database, so merely deleting the database may not suffice to
492 * close it. Thus, we explicitly close it here. */
495 /* If there's an outstanding transaction, it's unclear if
496 * closing the Xapian database commits everything up to
497 * that transaction, or may discard committed (but
498 * unflushed) transactions. To be certain, explicitly
499 * cancel any outstanding transaction before closing. */
500 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_WRITE &&
501 notmuch->atomic_nesting)
502 notmuch->writable_xapian_db->cancel_transaction ();
504 /* Close the database. This implicitly flushes
505 * outstanding changes. */
506 notmuch->xapian_db->close ();
507 } catch (const Xapian::Error &error) {
508 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
509 if (! notmuch->exception_reported) {
510 _notmuch_database_log (notmuch,
511 "Error: A Xapian exception occurred closing database: %s\n",
512 error.get_msg ().c_str ());
516 notmuch->open = false;
521 unlink_cb (const char *path,
522 unused (const struct stat *sb),
524 unused (struct FTW *ftw))
526 return remove (path);
530 rmtree (const char *path)
532 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
535 class NotmuchCompactor : public Xapian::Compactor
537 notmuch_compact_status_cb_t status_cb;
538 void *status_closure;
541 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
542 status_cb (cb), status_closure (closure)
547 set_status (const std::string &table, const std::string &status)
551 if (status_cb == NULL)
554 if (status.length () == 0)
555 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
557 msg = talloc_asprintf (NULL, " %s", status.c_str ());
563 status_cb (msg, status_closure);
568 /* Compacts the given database, optionally saving the original database
569 * in backup_path. Additionally, a callback function can be provided to
570 * give the user feedback on the progress of the (likely long-lived)
571 * compaction process.
573 * The backup path must point to a directory on the same volume as the
574 * original database. Passing a NULL backup_path will result in the
575 * uncompacted database being deleted after compaction has finished.
576 * Note that the database write lock will be held during the
577 * compaction process to protect data integrity.
580 notmuch_database_compact (const char *path,
581 const char *backup_path,
582 notmuch_compact_status_cb_t status_cb,
585 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
586 notmuch_database_t *notmuch = NULL;
587 char *message = NULL;
589 ret = notmuch_database_open_verbose (path,
590 NOTMUCH_DATABASE_MODE_READ_WRITE,
594 if (status_cb) status_cb (message, closure);
598 _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_DATABASE_PATH, path);
600 return notmuch_database_compact_db (notmuch,
607 notmuch_database_compact_db (notmuch_database_t *notmuch,
608 const char *backup_path,
609 notmuch_compact_status_cb_t status_cb,
613 char *notmuch_path, *xapian_path, *compact_xapian_path;
615 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
619 ret = _notmuch_database_ensure_writable (notmuch);
623 path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
625 return NOTMUCH_STATUS_PATH_ERROR;
627 local = talloc_new (NULL);
629 return NOTMUCH_STATUS_OUT_OF_MEMORY;
631 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
632 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
636 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
637 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
641 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
642 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
646 if (backup_path == NULL) {
647 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
648 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
656 if (stat (backup_path, &statbuf) != -1) {
657 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
658 ret = NOTMUCH_STATUS_FILE_ERROR;
661 if (errno != ENOENT) {
662 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
664 ret = NOTMUCH_STATUS_FILE_ERROR;
668 /* Unconditionally attempt to remove old work-in-progress database (if
669 * any). This is "protected" by database lock. If this fails due to write
670 * errors (etc), the following code will fail and provide error message.
672 (void) rmtree (compact_xapian_path);
675 NotmuchCompactor compactor (status_cb, closure);
676 notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0,
678 } catch (const Xapian::Error &error) {
679 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
680 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
684 if (rename (xapian_path, backup_path)) {
685 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
686 xapian_path, backup_path, strerror (errno));
687 ret = NOTMUCH_STATUS_FILE_ERROR;
691 if (rename (compact_xapian_path, xapian_path)) {
692 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
693 compact_xapian_path, xapian_path, strerror (errno));
694 ret = NOTMUCH_STATUS_FILE_ERROR;
699 if (rmtree (backup_path)) {
700 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
701 backup_path, strerror (errno));
702 ret = NOTMUCH_STATUS_FILE_ERROR;
709 notmuch_status_t ret2;
711 const char *str = notmuch_database_status_string (notmuch);
712 if (status_cb && str)
713 status_cb (str, closure);
715 ret2 = notmuch_database_destroy (notmuch);
717 /* don't clobber previous error status */
718 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
728 notmuch_database_destroy (notmuch_database_t *notmuch)
730 notmuch_status_t status;
732 status = notmuch_database_close (notmuch);
734 delete notmuch->term_gen;
735 notmuch->term_gen = NULL;
736 delete notmuch->query_parser;
737 notmuch->query_parser = NULL;
738 delete notmuch->xapian_db;
739 notmuch->xapian_db = NULL;
740 delete notmuch->value_range_processor;
741 notmuch->value_range_processor = NULL;
742 delete notmuch->date_range_processor;
743 notmuch->date_range_processor = NULL;
744 delete notmuch->last_mod_range_processor;
745 notmuch->last_mod_range_processor = NULL;
747 talloc_free (notmuch);
753 notmuch_database_get_path (notmuch_database_t *notmuch)
755 return notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
759 notmuch_database_get_version (notmuch_database_t *notmuch)
761 unsigned int version;
762 string version_string;
767 version_string = notmuch->xapian_db->get_metadata ("version");
768 } catch (const Xapian::Error &error) {
769 LOG_XAPIAN_EXCEPTION (notmuch, error);
773 if (version_string.empty ())
776 str = version_string.c_str ();
777 if (str == NULL || *str == '\0')
780 version = strtoul (str, &end, 10);
782 INTERNAL_ERROR ("Malformed database version: %s", str);
788 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
790 unsigned int version;
792 if (_notmuch_database_mode (notmuch) != NOTMUCH_DATABASE_MODE_READ_WRITE)
795 if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
798 version = notmuch_database_get_version (notmuch);
800 return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
803 static volatile sig_atomic_t do_progress_notify = 0;
806 handle_sigalrm (unused (int signal))
808 do_progress_notify = 1;
811 /* Upgrade the current database.
813 * After opening a database in read-write mode, the client should
814 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
815 * if so, upgrade with this function before making any modifications.
817 * The optional progress_notify callback can be used by the caller to
818 * provide progress indication to the user. If non-NULL it will be
819 * called periodically with 'count' as the number of messages upgraded
820 * so far and 'total' the overall number of messages that will be
824 notmuch_database_upgrade (notmuch_database_t *notmuch,
825 void (*progress_notify)(void *closure,
829 void *local = talloc_new (NULL);
830 Xapian::TermIterator t, t_end;
831 Xapian::WritableDatabase *db;
832 struct sigaction action;
833 struct itimerval timerval;
834 bool timer_is_active = false;
835 enum _notmuch_features target_features, new_features;
836 notmuch_status_t status;
837 notmuch_private_status_t private_status;
838 notmuch_query_t *query = NULL;
839 unsigned int count = 0, total = 0;
841 status = _notmuch_database_ensure_writable (notmuch);
845 db = notmuch->writable_xapian_db;
847 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
848 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
850 if (! notmuch_database_needs_upgrade (notmuch))
851 return NOTMUCH_STATUS_SUCCESS;
853 if (progress_notify) {
854 /* Set up our handler for SIGALRM */
855 memset (&action, 0, sizeof (struct sigaction));
856 action.sa_handler = handle_sigalrm;
857 sigemptyset (&action.sa_mask);
858 action.sa_flags = SA_RESTART;
859 sigaction (SIGALRM, &action, NULL);
861 /* Then start a timer to send SIGALRM once per second. */
862 timerval.it_interval.tv_sec = 1;
863 timerval.it_interval.tv_usec = 0;
864 timerval.it_value.tv_sec = 1;
865 timerval.it_value.tv_usec = 0;
866 setitimer (ITIMER_REAL, &timerval, NULL);
868 timer_is_active = true;
871 /* Figure out how much total work we need to do. */
873 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
874 NOTMUCH_FEATURE_LAST_MOD)) {
875 query = notmuch_query_create (notmuch, "");
878 status = notmuch_query_count_messages (query, &msg_count);
883 notmuch_query_destroy (query);
886 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
887 t_end = db->allterms_end ("XTIMESTAMP");
888 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
891 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
892 /* The ghost message upgrade converts all thread_id_*
893 * metadata values into ghost message documents. */
894 t_end = db->metadata_keys_end ("thread_id_");
895 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
899 /* Perform the upgrade in a transaction. */
900 db->begin_transaction (true);
902 /* Set the target features so we write out changes in the desired
904 notmuch->features = target_features;
906 /* Perform per-message upgrades. */
908 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
909 NOTMUCH_FEATURE_LAST_MOD)) {
910 notmuch_messages_t *messages;
911 notmuch_message_t *message;
914 query = notmuch_query_create (notmuch, "");
916 status = notmuch_query_search_messages (query, &messages);
920 notmuch_messages_valid (messages);
921 notmuch_messages_move_to_next (messages)) {
922 if (do_progress_notify) {
923 progress_notify (closure, (double) count / total);
924 do_progress_notify = 0;
927 message = notmuch_messages_get (messages);
929 /* Before version 1, each message document had its
930 * filename in the data field. Copy that into the new
931 * format by calling notmuch_message_add_filename.
933 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
934 filename = _notmuch_message_talloc_copy_data (message);
935 if (filename && *filename != '\0') {
936 _notmuch_message_add_filename (message, filename);
937 _notmuch_message_clear_data (message);
939 talloc_free (filename);
942 /* Prior to version 2, the "folder:" prefix was
943 * probabilistic and stemmed. Change it to the current
944 * boolean prefix. Add "path:" prefixes while at it.
946 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
947 _notmuch_message_upgrade_folder (message);
949 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
950 * track modification revisions. Give all messages the
951 * next available revision; since we just started tracking
952 * revisions for this database, that will be 1.
954 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
955 _notmuch_message_upgrade_last_mod (message);
957 _notmuch_message_sync (message);
959 notmuch_message_destroy (message);
964 notmuch_query_destroy (query);
968 /* Perform per-directory upgrades. */
970 /* Before version 1 we stored directory timestamps in
971 * XTIMESTAMP documents instead of the current XDIRECTORY
972 * documents. So copy those as well. */
973 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
974 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
976 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
979 Xapian::PostingIterator p, p_end;
980 std::string term = *t;
982 p_end = notmuch->xapian_db->postlist_end (term);
984 for (p = notmuch->xapian_db->postlist_begin (term);
987 Xapian::Document document;
989 notmuch_directory_t *directory;
991 if (do_progress_notify) {
992 progress_notify (closure, (double) count / total);
993 do_progress_notify = 0;
996 document = find_document_for_doc_id (notmuch, *p);
997 mtime = Xapian::sortable_unserialise (
998 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1000 directory = _notmuch_directory_find_or_create (notmuch, term.c_str () + 10,
1001 NOTMUCH_FIND_CREATE, &status);
1002 notmuch_directory_set_mtime (directory, mtime);
1003 notmuch_directory_destroy (directory);
1005 db->delete_document (*p);
1012 /* Perform metadata upgrades. */
1014 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1015 * messages were stored as database metadata. Change these to
1018 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1019 notmuch_message_t *message;
1020 std::string message_id, thread_id;
1022 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1023 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1025 if (do_progress_notify) {
1026 progress_notify (closure, (double) count / total);
1027 do_progress_notify = 0;
1030 message_id = (*t).substr (
1031 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1032 thread_id = db->get_metadata (*t);
1034 /* Create ghost message */
1035 message = _notmuch_message_create_for_message_id (
1036 notmuch, message_id.c_str (), &private_status);
1037 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1038 /* Document already exists; ignore the stored thread ID */
1039 } else if (private_status ==
1040 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1041 private_status = _notmuch_message_initialize_ghost (
1042 message, thread_id.c_str ());
1043 if (! private_status)
1044 _notmuch_message_sync (message);
1047 if (private_status) {
1048 _notmuch_database_log (notmuch,
1049 "Upgrade failed while creating ghost messages.\n");
1050 status = COERCE_STATUS (private_status,
1051 "Unexpected status from _notmuch_message_initialize_ghost");
1055 /* Clear saved metadata thread ID */
1056 db->set_metadata (*t, "");
1062 status = NOTMUCH_STATUS_SUCCESS;
1063 db->set_metadata ("features", _notmuch_database_print_features (local, notmuch->features));
1064 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1067 if (status == NOTMUCH_STATUS_SUCCESS)
1068 db->commit_transaction ();
1070 db->cancel_transaction ();
1072 if (timer_is_active) {
1073 /* Now stop the timer. */
1074 timerval.it_interval.tv_sec = 0;
1075 timerval.it_interval.tv_usec = 0;
1076 timerval.it_value.tv_sec = 0;
1077 timerval.it_value.tv_usec = 0;
1078 setitimer (ITIMER_REAL, &timerval, NULL);
1080 /* And disable the signal handler. */
1081 action.sa_handler = SIG_IGN;
1082 sigaction (SIGALRM, &action, NULL);
1086 notmuch_query_destroy (query);
1088 talloc_free (local);
1093 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1095 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1096 notmuch->atomic_nesting > 0)
1099 if (notmuch_database_needs_upgrade (notmuch))
1100 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1103 notmuch->writable_xapian_db->begin_transaction (false);
1104 } catch (const Xapian::Error &error) {
1105 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1106 error.get_msg ().c_str ());
1107 notmuch->exception_reported = true;
1108 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1112 notmuch->atomic_nesting++;
1113 return NOTMUCH_STATUS_SUCCESS;
1117 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1119 Xapian::WritableDatabase *db;
1121 if (notmuch->atomic_nesting == 0)
1122 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1124 if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1125 notmuch->atomic_nesting > 1)
1128 db = notmuch->writable_xapian_db;
1130 db->commit_transaction ();
1132 /* This is a hack for testing. Xapian never flushes on a
1133 * non-flushed commit, even if the flush threshold is 1.
1134 * However, we rely on flushing to test atomicity. */
1135 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1136 if (thresh && atoi (thresh) == 1)
1138 } catch (const Xapian::Error &error) {
1139 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1140 error.get_msg ().c_str ());
1141 notmuch->exception_reported = true;
1142 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1145 if (notmuch->atomic_dirty) {
1146 ++notmuch->revision;
1147 notmuch->atomic_dirty = false;
1151 notmuch->atomic_nesting--;
1152 return NOTMUCH_STATUS_SUCCESS;
1156 notmuch_database_get_revision (notmuch_database_t *notmuch,
1160 *uuid = notmuch->uuid;
1161 return notmuch->revision;
1164 /* We allow the user to use arbitrarily long paths for directories. But
1165 * we have a term-length limit. So if we exceed that, we'll use the
1166 * SHA-1 of the path for the database term.
1168 * Note: This function may return the original value of 'path'. If it
1169 * does not, then the caller is responsible to free() the returned
1173 _notmuch_database_get_directory_db_path (const char *path)
1175 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1177 if (term_len > NOTMUCH_TERM_MAX)
1178 return _notmuch_sha1_of_string (path);
1183 /* Given a path, split it into two parts: the directory part is all
1184 * components except for the last, and the basename is that last
1185 * component. Getting the return-value for either part is optional
1186 * (the caller can pass NULL).
1188 * The original 'path' can represent either a regular file or a
1189 * directory---the splitting will be carried out in the same way in
1190 * either case. Trailing slashes on 'path' will be ignored, and any
1191 * cases of multiple '/' characters appearing in series will be
1192 * treated as a single '/'.
1194 * Allocation (if any) will have 'ctx' as the talloc owner. But
1195 * pointers will be returned within the original path string whenever
1198 * Note: If 'path' is non-empty and contains no non-trailing slash,
1199 * (that is, consists of a filename with no parent directory), then
1200 * the directory returned will be an empty string. However, if 'path'
1201 * is an empty string, then both directory and basename will be
1205 _notmuch_database_split_path (void *ctx,
1207 const char **directory,
1208 const char **basename)
1212 if (path == NULL || *path == '\0') {
1217 return NOTMUCH_STATUS_SUCCESS;
1220 /* Find the last slash (not counting a trailing slash), if any. */
1222 slash = path + strlen (path) - 1;
1224 /* First, skip trailing slashes. */
1225 while (slash != path && *slash == '/')
1228 /* Then, find a slash. */
1229 while (slash != path && *slash != '/') {
1236 /* Finally, skip multiple slashes. */
1237 while (slash != path && *(slash - 1) == '/')
1240 if (slash == path) {
1242 *directory = talloc_strdup (ctx, "");
1247 *directory = talloc_strndup (ctx, path, slash - path);
1250 return NOTMUCH_STATUS_SUCCESS;
1253 /* Find the document ID of the specified directory.
1255 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1256 * created if one does not exist for 'path'. Otherwise, if the
1257 * directory document does not exist, this sets *directory_id to
1258 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1261 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1263 notmuch_find_flags_t flags,
1264 unsigned int *directory_id)
1266 notmuch_directory_t *directory;
1267 notmuch_status_t status;
1271 return NOTMUCH_STATUS_SUCCESS;
1274 directory = _notmuch_directory_find_or_create (notmuch, path, flags, &status);
1275 if (status || ! directory) {
1280 *directory_id = _notmuch_directory_get_document_id (directory);
1282 notmuch_directory_destroy (directory);
1284 return NOTMUCH_STATUS_SUCCESS;
1288 _notmuch_database_get_directory_path (void *ctx,
1289 notmuch_database_t *notmuch,
1290 unsigned int doc_id)
1292 Xapian::Document document;
1294 document = find_document_for_doc_id (notmuch, doc_id);
1296 return talloc_strdup (ctx, document.get_data ().c_str ());
1299 /* Given a legal 'filename' for the database, (either relative to
1300 * database path or absolute with initial components identical to
1301 * database path), return a new string (with 'ctx' as the talloc
1302 * owner) suitable for use as a direntry term value.
1304 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1305 * will be created in the database as needed. Otherwise, if the
1306 * necessary directory documents do not exist, this sets
1307 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1310 _notmuch_database_filename_to_direntry (void *ctx,
1311 notmuch_database_t *notmuch,
1312 const char *filename,
1313 notmuch_find_flags_t flags,
1316 const char *relative, *directory, *basename;
1317 Xapian::docid directory_id;
1318 notmuch_status_t status;
1320 relative = _notmuch_database_relative_path (notmuch, filename);
1322 status = _notmuch_database_split_path (ctx, relative,
1323 &directory, &basename);
1327 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1329 if (status || directory_id == (unsigned int) -1) {
1334 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1336 return NOTMUCH_STATUS_SUCCESS;
1339 /* Given a legal 'path' for the database, return the relative path.
1341 * The return value will be a pointer to the original path contents,
1342 * and will be either the original string (if 'path' was relative) or
1343 * a portion of the string (if path was absolute and begins with the
1347 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1350 const char *db_path, *relative;
1351 unsigned int db_path_len;
1353 db_path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
1354 db_path_len = strlen (db_path);
1358 if (*relative == '/') {
1359 while (*relative == '/' && *(relative + 1) == '/')
1362 if (strncmp (relative, db_path, db_path_len) == 0) {
1363 relative += db_path_len;
1364 while (*relative == '/')
1373 notmuch_database_get_directory (notmuch_database_t *notmuch,
1375 notmuch_directory_t **directory)
1377 notmuch_status_t status;
1379 if (directory == NULL)
1380 return NOTMUCH_STATUS_NULL_POINTER;
1384 *directory = _notmuch_directory_find_or_create (notmuch, path,
1385 NOTMUCH_FIND_LOOKUP, &status);
1386 } catch (const Xapian::Error &error) {
1387 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1388 error.get_msg ().c_str ());
1389 notmuch->exception_reported = true;
1390 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1395 /* Allocate a document ID that satisfies the following criteria:
1397 * 1. The ID does not exist for any document in the Xapian database
1399 * 2. The ID was not previously returned from this function
1401 * 3. The ID is the smallest integer satisfying (1) and (2)
1403 * This function will trigger an internal error if these constraints
1404 * cannot all be satisfied, (that is, the pool of available document
1405 * IDs has been exhausted).
1408 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1410 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1412 notmuch->last_doc_id++;
1414 if (notmuch->last_doc_id == 0)
1415 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1417 return notmuch->last_doc_id;
1421 notmuch_database_remove_message (notmuch_database_t *notmuch,
1422 const char *filename)
1424 notmuch_status_t status;
1425 notmuch_message_t *message;
1427 status = notmuch_database_find_message_by_filename (notmuch, filename,
1430 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1431 status = _notmuch_message_remove_filename (message, filename);
1432 if (status == NOTMUCH_STATUS_SUCCESS)
1433 _notmuch_message_delete (message);
1434 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1435 _notmuch_message_sync (message);
1437 notmuch_message_destroy (message);
1444 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1445 const char *filename,
1446 notmuch_message_t **message_ret)
1449 const char *prefix = _find_prefix ("file-direntry");
1450 char *direntry, *term;
1451 Xapian::PostingIterator i, end;
1452 notmuch_status_t status;
1454 if (message_ret == NULL)
1455 return NOTMUCH_STATUS_NULL_POINTER;
1457 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1458 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1460 /* return NULL on any failure */
1461 *message_ret = NULL;
1463 local = talloc_new (notmuch);
1466 status = _notmuch_database_filename_to_direntry (
1467 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1468 if (status || ! direntry)
1471 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1473 find_doc_ids_for_term (notmuch, term, &i, &end);
1476 notmuch_private_status_t private_status;
1478 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1480 if (*message_ret == NULL)
1481 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1483 } catch (const Xapian::Error &error) {
1484 _notmuch_database_log (notmuch,
1485 "Error: A Xapian exception occurred finding message by filename: %s\n",
1486 error.get_msg ().c_str ());
1487 notmuch->exception_reported = true;
1488 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1492 talloc_free (local);
1494 if (status && *message_ret) {
1495 notmuch_message_destroy (*message_ret);
1496 *message_ret = NULL;
1501 notmuch_string_list_t *
1502 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1503 Xapian::TermIterator &end,
1506 int prefix_len = strlen (prefix);
1507 notmuch_string_list_t *list;
1509 list = _notmuch_string_list_create (ctx);
1510 if (unlikely (list == NULL))
1513 for (i.skip_to (prefix); i != end; i++) {
1514 /* Terminate loop at first term without desired prefix. */
1515 if (strncmp ((*i).c_str (), prefix, prefix_len))
1518 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1525 notmuch_database_get_all_tags (notmuch_database_t *db)
1527 Xapian::TermIterator i, end;
1528 notmuch_string_list_t *tags;
1531 i = db->xapian_db->allterms_begin ();
1532 end = db->xapian_db->allterms_end ();
1533 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1534 _find_prefix ("tag"));
1535 _notmuch_string_list_sort (tags);
1536 return _notmuch_tags_create (db, tags);
1537 } catch (const Xapian::Error &error) {
1538 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
1539 error.get_msg ().c_str ());
1540 db->exception_reported = true;
1546 notmuch_database_status_string (const notmuch_database_t *notmuch)
1548 return notmuch->status_string;