+ Xapian::WritableDatabase *db;
+ struct sigaction action;
+ struct itimerval timerval;
+ notmuch_bool_t timer_is_active = FALSE;
+ unsigned int version;
+ notmuch_status_t status;
+ unsigned int count = 0, total = 0;
+
+ status = _notmuch_database_ensure_writable (notmuch);
+ if (status)
+ return status;
+
+ db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
+
+ version = notmuch_database_get_version (notmuch);
+
+ if (version >= NOTMUCH_DATABASE_VERSION)
+ return NOTMUCH_STATUS_SUCCESS;
+
+ if (progress_notify) {
+ /* Setup our handler for SIGALRM */
+ memset (&action, 0, sizeof (struct sigaction));
+ action.sa_handler = handle_sigalrm;
+ sigemptyset (&action.sa_mask);
+ action.sa_flags = SA_RESTART;
+ sigaction (SIGALRM, &action, NULL);
+
+ /* Then start a timer to send SIGALRM once per second. */
+ timerval.it_interval.tv_sec = 1;
+ timerval.it_interval.tv_usec = 0;
+ timerval.it_value.tv_sec = 1;
+ timerval.it_value.tv_usec = 0;
+ setitimer (ITIMER_REAL, &timerval, NULL);
+
+ timer_is_active = TRUE;
+ }
+
+ /* Before version 1, each message document had its filename in the
+ * data field. Copy that into the new format by calling
+ * notmuch_message_add_filename.
+ */
+ if (version < 1) {
+ notmuch_query_t *query = notmuch_query_create (notmuch, "");
+ notmuch_messages_t *messages;
+ notmuch_message_t *message;
+ char *filename;
+ Xapian::TermIterator t, t_end;
+
+ total = notmuch_query_count_messages (query);
+
+ for (messages = notmuch_query_search_messages (query);
+ notmuch_messages_valid (messages);
+ notmuch_messages_move_to_next (messages))
+ {
+ if (do_progress_notify) {
+ progress_notify (closure, (double) count / total);
+ do_progress_notify = 0;
+ }
+
+ message = notmuch_messages_get (messages);
+
+ filename = _notmuch_message_talloc_copy_data (message);
+ if (filename && *filename != '\0') {
+ _notmuch_message_add_filename (message, filename);
+ _notmuch_message_sync (message);
+ }
+ talloc_free (filename);
+
+ notmuch_message_destroy (message);
+
+ count++;
+ }
+
+ notmuch_query_destroy (query);
+
+ /* Also, before version 1 we stored directory timestamps in
+ * XTIMESTAMP documents instead of the current XDIRECTORY
+ * documents. So copy those as well. */
+
+ t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
+
+ for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
+ t != t_end;
+ t++)
+ {
+ Xapian::PostingIterator p, p_end;
+ std::string term = *t;
+
+ p_end = notmuch->xapian_db->postlist_end (term);
+
+ for (p = notmuch->xapian_db->postlist_begin (term);
+ p != p_end;
+ p++)
+ {
+ Xapian::Document document;
+ time_t mtime;
+ notmuch_directory_t *directory;
+
+ if (do_progress_notify) {
+ progress_notify (closure, (double) count / total);
+ do_progress_notify = 0;
+ }
+
+ document = find_document_for_doc_id (notmuch, *p);
+ mtime = Xapian::sortable_unserialise (
+ document.get_value (NOTMUCH_VALUE_TIMESTAMP));
+
+ directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
+ NOTMUCH_FIND_CREATE, &status);
+ notmuch_directory_set_mtime (directory, mtime);
+ notmuch_directory_destroy (directory);
+ }
+ }
+ }
+
+ /*
+ * Prior to version 2, the "folder:" prefix was probabilistic and
+ * stemmed. Change it to the current boolean prefix. Add "path:"
+ * prefixes while at it.
+ */
+ if (version < 2) {
+ notmuch_query_t *query = notmuch_query_create (notmuch, "");
+ notmuch_messages_t *messages;
+ notmuch_message_t *message;
+
+ count = 0;
+ total = notmuch_query_count_messages (query);
+
+ for (messages = notmuch_query_search_messages (query);
+ notmuch_messages_valid (messages);
+ notmuch_messages_move_to_next (messages)) {
+ if (do_progress_notify) {
+ progress_notify (closure, (double) count / total);
+ do_progress_notify = 0;
+ }
+
+ message = notmuch_messages_get (messages);
+
+ _notmuch_message_upgrade_folder (message);
+ _notmuch_message_sync (message);
+
+ notmuch_message_destroy (message);
+
+ count++;
+ }
+
+ notmuch_query_destroy (query);
+ }
+
+ db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
+ db->flush ();
+
+ /* Now that the upgrade is complete we can remove the old data
+ * and documents that are no longer needed. */
+ if (version < 1) {
+ notmuch_query_t *query = notmuch_query_create (notmuch, "");
+ notmuch_messages_t *messages;
+ notmuch_message_t *message;
+ char *filename;
+
+ for (messages = notmuch_query_search_messages (query);
+ notmuch_messages_valid (messages);
+ notmuch_messages_move_to_next (messages))
+ {
+ if (do_progress_notify) {
+ progress_notify (closure, (double) count / total);
+ do_progress_notify = 0;
+ }
+
+ message = notmuch_messages_get (messages);
+
+ filename = _notmuch_message_talloc_copy_data (message);
+ if (filename && *filename != '\0') {
+ _notmuch_message_clear_data (message);
+ _notmuch_message_sync (message);
+ }
+ talloc_free (filename);
+
+ notmuch_message_destroy (message);
+ }
+
+ notmuch_query_destroy (query);
+ }
+
+ if (version < 1) {
+ Xapian::TermIterator t, t_end;
+
+ t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
+
+ for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
+ t != t_end;
+ t++)
+ {
+ Xapian::PostingIterator p, p_end;
+ std::string term = *t;
+
+ p_end = notmuch->xapian_db->postlist_end (term);
+
+ for (p = notmuch->xapian_db->postlist_begin (term);
+ p != p_end;
+ p++)
+ {
+ if (do_progress_notify) {
+ progress_notify (closure, (double) count / total);
+ do_progress_notify = 0;
+ }
+
+ db->delete_document (*p);
+ }
+ }
+ }
+
+ if (timer_is_active) {
+ /* Now stop the timer. */
+ timerval.it_interval.tv_sec = 0;
+ timerval.it_interval.tv_usec = 0;
+ timerval.it_value.tv_sec = 0;
+ timerval.it_value.tv_usec = 0;
+ setitimer (ITIMER_REAL, &timerval, NULL);
+
+ /* And disable the signal handler. */
+ action.sa_handler = SIG_IGN;
+ sigaction (SIGALRM, &action, NULL);
+ }
+
+ return NOTMUCH_STATUS_SUCCESS;
+}
+
+notmuch_status_t
+notmuch_database_begin_atomic (notmuch_database_t *notmuch)
+{
+ if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
+ notmuch->atomic_nesting > 0)
+ goto DONE;
+
+ try {
+ (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
+ } catch (const Xapian::Error &error) {
+ fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
+ error.get_msg().c_str());
+ notmuch->exception_reported = TRUE;
+ return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
+ }
+
+DONE:
+ notmuch->atomic_nesting++;
+ return NOTMUCH_STATUS_SUCCESS;
+}
+
+notmuch_status_t
+notmuch_database_end_atomic (notmuch_database_t *notmuch)
+{
+ Xapian::WritableDatabase *db;
+
+ if (notmuch->atomic_nesting == 0)
+ return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
+
+ if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
+ notmuch->atomic_nesting > 1)
+ goto DONE;
+
+ db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
+ try {
+ db->commit_transaction ();
+
+ /* This is a hack for testing. Xapian never flushes on a
+ * non-flushed commit, even if the flush threshold is 1.
+ * However, we rely on flushing to test atomicity. */
+ const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
+ if (thresh && atoi (thresh) == 1)
+ db->flush ();
+ } catch (const Xapian::Error &error) {
+ fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
+ error.get_msg().c_str());
+ notmuch->exception_reported = TRUE;
+ return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
+ }
+
+DONE:
+ notmuch->atomic_nesting--;
+ return NOTMUCH_STATUS_SUCCESS;
+}
+
+/* We allow the user to use arbitrarily long paths for directories. But
+ * we have a term-length limit. So if we exceed that, we'll use the
+ * SHA-1 of the path for the database term.
+ *
+ * Note: This function may return the original value of 'path'. If it
+ * does not, then the caller is responsible to free() the returned
+ * value.
+ */
+const char *
+_notmuch_database_get_directory_db_path (const char *path)
+{
+ int term_len = strlen (_find_prefix ("directory")) + strlen (path);
+
+ if (term_len > NOTMUCH_TERM_MAX)
+ return notmuch_sha1_of_string (path);
+ else
+ return path;
+}
+
+/* Given a path, split it into two parts: the directory part is all
+ * components except for the last, and the basename is that last
+ * component. Getting the return-value for either part is optional
+ * (the caller can pass NULL).
+ *
+ * The original 'path' can represent either a regular file or a
+ * directory---the splitting will be carried out in the same way in
+ * either case. Trailing slashes on 'path' will be ignored, and any
+ * cases of multiple '/' characters appearing in series will be
+ * treated as a single '/'.
+ *
+ * Allocation (if any) will have 'ctx' as the talloc owner. But
+ * pointers will be returned within the original path string whenever
+ * possible.
+ *
+ * Note: If 'path' is non-empty and contains no non-trailing slash,
+ * (that is, consists of a filename with no parent directory), then
+ * the directory returned will be an empty string. However, if 'path'
+ * is an empty string, then both directory and basename will be
+ * returned as NULL.
+ */
+notmuch_status_t
+_notmuch_database_split_path (void *ctx,
+ const char *path,
+ const char **directory,
+ const char **basename)
+{
+ const char *slash;
+
+ if (path == NULL || *path == '\0') {
+ if (directory)
+ *directory = NULL;
+ if (basename)
+ *basename = NULL;
+ return NOTMUCH_STATUS_SUCCESS;
+ }
+
+ /* Find the last slash (not counting a trailing slash), if any. */
+
+ slash = path + strlen (path) - 1;
+
+ /* First, skip trailing slashes. */
+ while (slash != path) {
+ if (*slash != '/')
+ break;
+
+ --slash;
+ }
+
+ /* Then, find a slash. */
+ while (slash != path) {
+ if (*slash == '/')
+ break;
+
+ if (basename)
+ *basename = slash;
+
+ --slash;
+ }
+
+ /* Finally, skip multiple slashes. */
+ while (slash != path) {
+ if (*slash != '/')
+ break;
+
+ --slash;
+ }
+
+ if (slash == path) {
+ if (directory)
+ *directory = talloc_strdup (ctx, "");
+ if (basename)
+ *basename = path;
+ } else {
+ if (directory)
+ *directory = talloc_strndup (ctx, path, slash - path + 1);
+ }
+
+ return NOTMUCH_STATUS_SUCCESS;
+}
+
+/* Find the document ID of the specified directory.
+ *
+ * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
+ * created if one does not exist for 'path'. Otherwise, if the
+ * directory document does not exist, this sets *directory_id to
+ * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
+ */
+notmuch_status_t
+_notmuch_database_find_directory_id (notmuch_database_t *notmuch,
+ const char *path,
+ notmuch_find_flags_t flags,
+ unsigned int *directory_id)
+{
+ notmuch_directory_t *directory;
+ notmuch_status_t status;
+
+ if (path == NULL) {
+ *directory_id = 0;
+ return NOTMUCH_STATUS_SUCCESS;
+ }
+
+ directory = _notmuch_directory_create (notmuch, path, flags, &status);
+ if (status || !directory) {
+ *directory_id = -1;
+ return status;
+ }
+
+ *directory_id = _notmuch_directory_get_document_id (directory);
+
+ notmuch_directory_destroy (directory);
+
+ return NOTMUCH_STATUS_SUCCESS;
+}
+
+const char *
+_notmuch_database_get_directory_path (void *ctx,
+ notmuch_database_t *notmuch,
+ unsigned int doc_id)
+{
+ Xapian::Document document;
+
+ document = find_document_for_doc_id (notmuch, doc_id);
+
+ return talloc_strdup (ctx, document.get_data ().c_str ());
+}
+
+/* Given a legal 'filename' for the database, (either relative to
+ * database path or absolute with initial components identical to
+ * database path), return a new string (with 'ctx' as the talloc
+ * owner) suitable for use as a direntry term value.
+ *
+ * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
+ * will be created in the database as needed. Otherwise, if the
+ * necessary directory documents do not exist, this sets
+ * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
+ */
+notmuch_status_t
+_notmuch_database_filename_to_direntry (void *ctx,
+ notmuch_database_t *notmuch,
+ const char *filename,
+ notmuch_find_flags_t flags,
+ char **direntry)
+{
+ const char *relative, *directory, *basename;
+ Xapian::docid directory_id;
+ notmuch_status_t status;
+
+ relative = _notmuch_database_relative_path (notmuch, filename);
+
+ status = _notmuch_database_split_path (ctx, relative,
+ &directory, &basename);
+ if (status)
+ return status;
+
+ status = _notmuch_database_find_directory_id (notmuch, directory, flags,
+ &directory_id);
+ if (status || directory_id == (unsigned int)-1) {
+ *direntry = NULL;
+ return status;
+ }
+
+ *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
+
+ return NOTMUCH_STATUS_SUCCESS;
+}
+
+/* Given a legal 'path' for the database, return the relative path.
+ *
+ * The return value will be a pointer to the original path contents,
+ * and will be either the original string (if 'path' was relative) or
+ * a portion of the string (if path was absolute and begins with the
+ * database path).
+ */
+const char *
+_notmuch_database_relative_path (notmuch_database_t *notmuch,
+ const char *path)
+{
+ const char *db_path, *relative;
+ unsigned int db_path_len;
+
+ db_path = notmuch_database_get_path (notmuch);
+ db_path_len = strlen (db_path);
+
+ relative = path;
+
+ if (*relative == '/') {
+ while (*relative == '/' && *(relative+1) == '/')
+ relative++;
+
+ if (strncmp (relative, db_path, db_path_len) == 0)
+ {
+ relative += db_path_len;
+ while (*relative == '/')
+ relative++;
+ }
+ }
+
+ return relative;
+}
+
+notmuch_status_t
+notmuch_database_get_directory (notmuch_database_t *notmuch,
+ const char *path,
+ notmuch_directory_t **directory)
+{
+ notmuch_status_t status;
+
+ if (directory == NULL)
+ return NOTMUCH_STATUS_NULL_POINTER;
+ *directory = NULL;
+
+ try {
+ *directory = _notmuch_directory_create (notmuch, path,
+ NOTMUCH_FIND_LOOKUP, &status);
+ } catch (const Xapian::Error &error) {
+ fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
+ error.get_msg().c_str());
+ notmuch->exception_reported = TRUE;
+ status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
+ }
+ return status;
+}
+
+/* Allocate a document ID that satisfies the following criteria:
+ *
+ * 1. The ID does not exist for any document in the Xapian database
+ *
+ * 2. The ID was not previously returned from this function
+ *
+ * 3. The ID is the smallest integer satisfying (1) and (2)
+ *
+ * This function will trigger an internal error if these constraints
+ * cannot all be satisfied, (that is, the pool of available document
+ * IDs has been exhausted).
+ */
+unsigned int
+_notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
+{
+ assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
+
+ notmuch->last_doc_id++;
+
+ if (notmuch->last_doc_id == 0)
+ INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
+
+ return notmuch->last_doc_id;
+}
+
+static const char *
+_notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
+{
+ /* 16 bytes (+ terminator) for hexadecimal representation of
+ * a 64-bit integer. */
+ static char thread_id[17];
+ Xapian::WritableDatabase *db;
+
+ db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
+
+ notmuch->last_thread_id++;
+
+ sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
+
+ db->set_metadata ("last_thread_id", thread_id);
+
+ return thread_id;
+}
+
+static char *
+_get_metadata_thread_id_key (void *ctx, const char *message_id)
+{
+ if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
+ message_id = _message_id_compressed (ctx, message_id);
+
+ return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
+ message_id);
+}
+
+/* Find the thread ID to which the message with 'message_id' belongs.
+ *
+ * Note: 'thread_id_ret' must not be NULL!
+ * On success '*thread_id_ret' is set to a newly talloced string belonging to
+ * 'ctx'.
+ *
+ * Note: If there is no message in the database with the given
+ * 'message_id' then a new thread_id will be allocated for this
+ * message and stored in the database metadata, (where this same
+ * thread ID can be looked up if the message is added to the database
+ * later).
+ */
+static notmuch_status_t
+_resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
+ void *ctx,
+ const char *message_id,
+ const char **thread_id_ret)
+{
+ notmuch_status_t status;
+ notmuch_message_t *message;
+ string thread_id_string;
+ char *metadata_key;
+ Xapian::WritableDatabase *db;
+
+ status = notmuch_database_find_message (notmuch, message_id, &message);
+
+ if (status)
+ return status;
+
+ if (message) {
+ *thread_id_ret = talloc_steal (ctx,
+ notmuch_message_get_thread_id (message));
+
+ notmuch_message_destroy (message);
+
+ return NOTMUCH_STATUS_SUCCESS;
+ }
+
+ /* Message has not been seen yet.
+ *
+ * We may have seen a reference to it already, in which case, we
+ * can return the thread ID stored in the metadata. Otherwise, we
+ * generate a new thread ID and store it there.
+ */
+ db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
+ metadata_key = _get_metadata_thread_id_key (ctx, message_id);
+ thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
+
+ if (thread_id_string.empty()) {
+ *thread_id_ret = talloc_strdup (ctx,
+ _notmuch_database_generate_thread_id (notmuch));
+ db->set_metadata (metadata_key, *thread_id_ret);
+ } else {
+ *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
+ }
+
+ talloc_free (metadata_key);
+
+ return NOTMUCH_STATUS_SUCCESS;
+}
+
+static notmuch_status_t
+_merge_threads (notmuch_database_t *notmuch,
+ const char *winner_thread_id,
+ const char *loser_thread_id)
+{
+ Xapian::PostingIterator loser, loser_end;
+ notmuch_message_t *message = NULL;
+ notmuch_private_status_t private_status;
+ notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
+
+ find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
+
+ for ( ; loser != loser_end; loser++) {
+ message = _notmuch_message_create (notmuch, notmuch,
+ *loser, &private_status);
+ if (message == NULL) {
+ ret = COERCE_STATUS (private_status,
+ "Cannot find document for doc_id from query");
+ goto DONE;
+ }
+
+ _notmuch_message_remove_term (message, "thread", loser_thread_id);
+ _notmuch_message_add_term (message, "thread", winner_thread_id);
+ _notmuch_message_sync (message);
+
+ notmuch_message_destroy (message);
+ message = NULL;
+ }
+
+ DONE:
+ if (message)
+ notmuch_message_destroy (message);
+
+ return ret;
+}
+
+static void
+_my_talloc_free_for_g_hash (void *ptr)
+{
+ talloc_free (ptr);
+}
+
+static notmuch_status_t
+_notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
+ notmuch_message_t *message,
+ notmuch_message_file_t *message_file,
+ const char **thread_id)
+{
+ GHashTable *parents = NULL;
+ const char *refs, *in_reply_to, *in_reply_to_message_id;
+ const char *last_ref_message_id, *this_message_id;
+ GList *l, *keys = NULL;
+ notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;