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 "parse-time-vrp.h"
24 #include "thread-fp.h"
25 #include "regexp-fields.h"
26 #include "string-util.h"
35 #include <glib.h> /* g_free, GPtrArray, GHashTable */
36 #include <glib-object.h> /* g_type_init */
38 #include <gmime/gmime.h> /* g_mime_init */
42 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
47 notmuch_field_flag_t flags;
50 #define NOTMUCH_DATABASE_VERSION 3
52 #define STRINGIFY(s) _SUB_STRINGIFY(s)
53 #define _SUB_STRINGIFY(s) #s
55 #if HAVE_XAPIAN_DB_RETRY_LOCK
56 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
58 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
61 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
63 * We currently have three different types of documents (mail, ghost,
64 * and directory) and also some metadata.
68 * A mail document is associated with a particular email message. It
69 * is stored in one or more files on disk and is uniquely identified
70 * by its "id" field (which is generally the message ID). It is
71 * indexed with the following prefixed terms which the database uses
72 * to construct threads, etc.:
74 * Single terms of given prefix:
78 * id: Unique ID of mail. This is from the Message-ID header
79 * if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
80 * If it's present and too long, then we use
81 * "notmuch-sha1-<sha1_sum_of_message_id>".
82 * If this header is not present, we use
83 * "notmuch-sha1-<sha1_sum_of_entire_file>".
85 * thread: The ID of the thread to which the mail belongs
87 * replyto: The ID from the In-Reply-To header of the mail (if any).
89 * Multiple terms of given prefix:
91 * reference: All message IDs from In-Reply-To and References
92 * headers in the message.
94 * tag: Any tags associated with this message by the user.
96 * file-direntry: A colon-separated pair of values
97 * (INTEGER:STRING), where INTEGER is the
98 * document ID of a directory document, and
99 * STRING is the name of a file within that
100 * directory for this mail message.
102 * property: Has a property with key=value
103 * FIXME: if no = is present, should match on any value
105 * A mail document also has four values:
107 * TIMESTAMP: The time_t value corresponding to the message's
110 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
112 * FROM: The value of the "From" header
114 * SUBJECT: The value of the "Subject" header
116 * LAST_MOD: The revision number as of the last tag or
119 * In addition, terms from the content of the message are added with
120 * "from", "to", "attachment", and "subject" prefixes for use by the
121 * user in searching. Similarly, terms from the path of the mail
122 * message are added with "folder" and "path" prefixes. But the
123 * database doesn't really care itself about any of these.
125 * The data portion of a mail document is empty.
127 * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
128 * -----------------------------------------------
129 * A ghost mail document is like a mail document, but where we don't
130 * have the message content. These are used to track thread reference
131 * information for messages we haven't received.
133 * A ghost mail document has type: ghost; id and thread fields that
134 * are identical to the mail document fields; and a MESSAGE_ID value.
138 * A directory document is used by a client of the notmuch library to
139 * maintain data necessary to allow for efficient polling of mail
142 * All directory documents contain one term:
144 * directory: The directory path (relative to the database path)
145 * Or the SHA1 sum of the directory path (if the
146 * path itself is too long to fit in a Xapian
149 * And all directory documents for directories other than top-level
150 * directories also contain the following term:
152 * directory-direntry: A colon-separated pair of values
153 * (INTEGER:STRING), where INTEGER is the
154 * document ID of the parent directory
155 * document, and STRING is the name of this
156 * directory within that parent.
158 * All directory documents have a single value:
160 * TIMESTAMP: The mtime of the directory (at last scan)
162 * The data portion of a directory document contains the path of the
163 * directory (relative to the database path).
167 * Xapian allows us to store arbitrary name-value pairs as
168 * "metadata". We currently use the following metadata names with the
171 * version The database schema version, (which is distinct
172 * from both the notmuch package version (see
173 * notmuch --version) and the libnotmuch library
174 * version. The version is stored as an base-10
175 * ASCII integer. The initial database version
176 * was 1, (though a schema existed before that
177 * were no "version" database value existed at
178 * all). Successive versions are allocated as
179 * changes are made to the database (such as by
180 * indexing new fields).
182 * features The set of features supported by this
183 * database. This consists of a set of
184 * '\n'-separated lines, where each is a feature
185 * name, a '\t', and compatibility flags. If the
186 * compatibility flags contain 'w', then the
187 * opener must support this feature to safely
188 * write this database. If the compatibility
189 * flags contain 'r', then the opener must
190 * support this feature to read this database.
191 * Introduced in database version 3.
193 * last_thread_id The last thread ID generated. This is stored
194 * as a 16-byte hexadecimal ASCII representation
195 * of a 64-bit unsigned integer. The first ID
196 * generated is 1 and the value will be
197 * incremented for each thread ID.
199 * C* metadata keys starting with C indicate
200 * configuration data. It can be managed with the
201 * n_database_*config* API. There is a convention
202 * of hierarchical keys separated by '.' (e.g.
203 * query.notmuch stores the value for the named
204 * query 'notmuch'), but it is not enforced by the
210 * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
211 * Instead, the database has the following additional database
214 * thread_id_* A pre-allocated thread ID for a particular
215 * message. This is actually an arbitrarily large
216 * family of metadata name. Any particular name is
217 * formed by concatenating "thread_id_" with a message
218 * ID (or the SHA1 sum of a message ID if it is very
219 * long---see description of 'id' in the mail
220 * document). The value stored is a thread ID.
222 * These thread ID metadata values are stored
223 * whenever a message references a parent message
224 * that does not yet exist in the database. A
225 * thread ID will be allocated and stored, and if
226 * the message is later added, the stored thread
227 * ID will be used (and the metadata value will
230 * Even before a message is added, it's
231 * pre-allocated thread ID is useful so that all
232 * descendant messages that reference this common
233 * parent can be recognized as belonging to the
237 /* With these prefix values we follow the conventions published here:
239 * https://xapian.org/docs/omega/termprefixes.html
241 * as much as makes sense. Note that I took some liberty in matching
242 * the reserved prefix values to notmuch concepts, (for example, 'G'
243 * is documented as "newsGroup (or similar entity - e.g. a web forum
244 * name)", for which I think the thread is the closest analogue in
245 * notmuch. This in spite of the fact that we will eventually be
246 * storing mailing-list messages where 'G' for "mailing list name"
247 * might be even a closer analogue. I'm treating the single-character
248 * prefixes preferentially for core notmuch concepts (which will be
249 * nearly universal to all mail messages).
253 prefix_t prefix_table[] = {
254 /* name term prefix flags */
255 { "type", "T", NOTMUCH_FIELD_NO_FLAGS },
256 { "reference", "XREFERENCE", NOTMUCH_FIELD_NO_FLAGS },
257 { "replyto", "XREPLYTO", NOTMUCH_FIELD_NO_FLAGS },
258 { "directory", "XDIRECTORY", NOTMUCH_FIELD_NO_FLAGS },
259 { "file-direntry", "XFDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
260 { "directory-direntry", "XDDIRENTRY", NOTMUCH_FIELD_NO_FLAGS },
261 { "thread", "G", NOTMUCH_FIELD_EXTERNAL |
262 NOTMUCH_FIELD_PROCESSOR },
263 { "tag", "K", NOTMUCH_FIELD_EXTERNAL |
264 NOTMUCH_FIELD_PROCESSOR },
265 { "is", "K", NOTMUCH_FIELD_EXTERNAL |
266 NOTMUCH_FIELD_PROCESSOR },
267 { "id", "Q", NOTMUCH_FIELD_EXTERNAL },
268 { "mid", "Q", NOTMUCH_FIELD_EXTERNAL |
269 NOTMUCH_FIELD_PROCESSOR },
270 { "path", "P", NOTMUCH_FIELD_EXTERNAL|
271 NOTMUCH_FIELD_PROCESSOR },
272 { "property", "XPROPERTY", NOTMUCH_FIELD_EXTERNAL },
274 * Unconditionally add ':' to reduce potential ambiguity with
275 * overlapping prefixes and/or terms that start with capital
276 * letters. See Xapian document termprefixes.html for related
279 { "folder", "XFOLDER:", NOTMUCH_FIELD_EXTERNAL |
280 NOTMUCH_FIELD_PROCESSOR },
281 #if HAVE_XAPIAN_FIELD_PROCESSOR
282 { "date", NULL, NOTMUCH_FIELD_EXTERNAL |
283 NOTMUCH_FIELD_PROCESSOR },
284 { "query", NULL, NOTMUCH_FIELD_EXTERNAL |
285 NOTMUCH_FIELD_PROCESSOR },
287 { "from", "XFROM", NOTMUCH_FIELD_EXTERNAL |
288 NOTMUCH_FIELD_PROBABILISTIC |
289 NOTMUCH_FIELD_PROCESSOR },
290 { "to", "XTO", NOTMUCH_FIELD_EXTERNAL |
291 NOTMUCH_FIELD_PROBABILISTIC },
292 { "attachment", "XATTACHMENT", NOTMUCH_FIELD_EXTERNAL |
293 NOTMUCH_FIELD_PROBABILISTIC },
294 { "mimetype", "XMIMETYPE", NOTMUCH_FIELD_EXTERNAL |
295 NOTMUCH_FIELD_PROBABILISTIC },
296 { "subject", "XSUBJECT", NOTMUCH_FIELD_EXTERNAL |
297 NOTMUCH_FIELD_PROBABILISTIC |
298 NOTMUCH_FIELD_PROCESSOR},
302 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
304 if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
305 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
307 notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
310 #if HAVE_XAPIAN_FIELD_PROCESSOR
312 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
314 if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
315 Xapian::FieldProcessor *fp;
317 if (STRNCMP_LITERAL (prefix->name, "date") == 0)
318 fp = (new DateFieldProcessor())->release ();
319 else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
320 fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
321 else if (STRNCMP_LITERAL(prefix->name, "thread") == 0)
322 fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
324 fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
325 *notmuch->query_parser, notmuch))->release ();
327 /* we treat all field-processor fields as boolean in order to get the raw input */
328 notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
330 _setup_query_field_default (prefix, notmuch);
335 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
337 _setup_query_field_default (prefix, notmuch);
342 _find_prefix (const char *name)
346 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
347 if (strcmp (name, prefix_table[i].name) == 0)
348 return prefix_table[i].prefix;
351 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
356 static const struct {
357 /* NOTMUCH_FEATURE_* value. */
358 _notmuch_features value;
359 /* Feature name as it appears in the database. This name should
360 * be appropriate for displaying to the user if an older version
361 * of notmuch doesn't support this feature. */
363 /* Compatibility flags when this feature is declared. */
365 } feature_names[] = {
366 { NOTMUCH_FEATURE_FILE_TERMS,
367 "multiple paths per message", "rw" },
368 { NOTMUCH_FEATURE_DIRECTORY_DOCS,
369 "relative directory paths", "rw" },
370 /* Header values are not required for reading a database because a
371 * reader can just refer to the message file. */
372 { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
373 "from/subject/message-ID in database", "w" },
374 { NOTMUCH_FEATURE_BOOL_FOLDER,
375 "exact folder:/path: search", "rw" },
376 { NOTMUCH_FEATURE_GHOSTS,
377 "mail documents for missing messages", "w"},
378 /* Knowledge of the index mime-types are not required for reading
379 * a database because a reader will just be unable to query
381 { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
382 "indexed MIME types", "w"},
383 { NOTMUCH_FEATURE_LAST_MOD,
384 "modification tracking", "w"},
388 notmuch_status_to_string (notmuch_status_t status)
391 case NOTMUCH_STATUS_SUCCESS:
392 return "No error occurred";
393 case NOTMUCH_STATUS_OUT_OF_MEMORY:
394 return "Out of memory";
395 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
396 return "Attempt to write to a read-only database";
397 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
398 return "A Xapian exception occurred";
399 case NOTMUCH_STATUS_FILE_ERROR:
400 return "Something went wrong trying to read or write a file";
401 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
402 return "File is not an email";
403 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
404 return "Message ID is identical to a message in database";
405 case NOTMUCH_STATUS_NULL_POINTER:
406 return "Erroneous NULL pointer";
407 case NOTMUCH_STATUS_TAG_TOO_LONG:
408 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
409 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
410 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
411 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
412 return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
413 case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
414 return "Unsupported operation";
415 case NOTMUCH_STATUS_UPGRADE_REQUIRED:
416 return "Operation requires a database upgrade";
417 case NOTMUCH_STATUS_PATH_ERROR:
418 return "Path supplied is illegal for this function";
419 case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
420 return "Crypto protocol missing, malformed, or unintelligible";
421 case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
422 return "Crypto engine initialization failure";
423 case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
424 return "Unknown crypto protocol";
426 case NOTMUCH_STATUS_LAST_STATUS:
427 return "Unknown error status value";
432 _notmuch_database_log (notmuch_database_t *notmuch,
438 va_start (va_args, format);
440 if (notmuch->status_string)
441 talloc_free (notmuch->status_string);
443 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
448 _notmuch_database_log_append (notmuch_database_t *notmuch,
454 va_start (va_args, format);
456 if (notmuch->status_string)
457 notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
459 notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
465 find_doc_ids_for_term (notmuch_database_t *notmuch,
467 Xapian::PostingIterator *begin,
468 Xapian::PostingIterator *end)
470 *begin = notmuch->xapian_db->postlist_begin (term);
472 *end = notmuch->xapian_db->postlist_end (term);
476 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
477 const char *prefix_name,
479 Xapian::PostingIterator *begin,
480 Xapian::PostingIterator *end)
484 term = talloc_asprintf (notmuch, "%s%s",
485 _find_prefix (prefix_name), value);
487 find_doc_ids_for_term (notmuch, term, begin, end);
492 notmuch_private_status_t
493 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
494 const char *prefix_name,
496 unsigned int *doc_id)
498 Xapian::PostingIterator i, end;
500 _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
504 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
509 #if DEBUG_DATABASE_SANITY
513 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
517 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
520 static Xapian::Document
521 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
523 return notmuch->xapian_db->get_document (doc_id);
526 /* Generate a compressed version of 'message_id' of the form:
528 * notmuch-sha1-<sha1_sum_of_message_id>
531 _notmuch_message_id_compressed (void *ctx, const char *message_id)
533 char *sha1, *compressed;
535 sha1 = _notmuch_sha1_of_string (message_id);
537 compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
544 notmuch_database_find_message (notmuch_database_t *notmuch,
545 const char *message_id,
546 notmuch_message_t **message_ret)
548 notmuch_private_status_t status;
551 if (message_ret == NULL)
552 return NOTMUCH_STATUS_NULL_POINTER;
554 if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
555 message_id = _notmuch_message_id_compressed (notmuch, message_id);
558 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
559 message_id, &doc_id);
561 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
564 *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
566 if (*message_ret == NULL)
567 return NOTMUCH_STATUS_OUT_OF_MEMORY;
570 return NOTMUCH_STATUS_SUCCESS;
571 } catch (const Xapian::Error &error) {
572 _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
573 error.get_msg().c_str());
574 notmuch->exception_reported = true;
576 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
581 notmuch_database_create (const char *path, notmuch_database_t **database)
583 char *status_string = NULL;
584 notmuch_status_t status;
586 status = notmuch_database_create_verbose (path, database,
590 fputs (status_string, stderr);
591 free (status_string);
598 notmuch_database_create_verbose (const char *path,
599 notmuch_database_t **database,
600 char **status_string)
602 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
603 notmuch_database_t *notmuch = NULL;
604 char *notmuch_path = NULL;
605 char *message = NULL;
610 message = strdup ("Error: Cannot create a database for a NULL path.\n");
611 status = NOTMUCH_STATUS_NULL_POINTER;
615 if (path[0] != '/') {
616 message = strdup ("Error: Database path must be absolute.\n");
617 status = NOTMUCH_STATUS_PATH_ERROR;
621 err = stat (path, &st);
623 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
624 path, strerror (errno)));
625 status = NOTMUCH_STATUS_FILE_ERROR;
629 if (! S_ISDIR (st.st_mode)) {
630 IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
631 "Not a directory.\n",
633 status = NOTMUCH_STATUS_FILE_ERROR;
637 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
639 err = mkdir (notmuch_path, 0755);
642 IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
643 notmuch_path, strerror (errno)));
644 status = NOTMUCH_STATUS_FILE_ERROR;
648 status = notmuch_database_open_verbose (path,
649 NOTMUCH_DATABASE_MODE_READ_WRITE,
654 /* Upgrade doesn't add these feature to existing databases, but
655 * new databases have them. */
656 notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
657 notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
659 status = notmuch_database_upgrade (notmuch, NULL, NULL);
661 notmuch_database_close(notmuch);
667 talloc_free (notmuch_path);
671 *status_string = message;
678 talloc_free (notmuch);
683 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
685 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
686 _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
687 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
690 return NOTMUCH_STATUS_SUCCESS;
693 /* Allocate a revision number for the next change. */
695 _notmuch_database_new_revision (notmuch_database_t *notmuch)
697 unsigned long new_revision = notmuch->revision + 1;
699 /* If we're in an atomic section, hold off on updating the
700 * committed revision number until we commit the atomic section.
702 if (notmuch->atomic_nesting)
703 notmuch->atomic_dirty = true;
705 notmuch->revision = new_revision;
710 /* Parse a database features string from the given database version.
711 * Returns the feature bit set.
713 * For version < 3, this ignores the features string and returns a
714 * hard-coded set of features.
716 * If there are unrecognized features that are required to open the
717 * database in mode (which should be 'r' or 'w'), return a
718 * comma-separated list of unrecognized but required features in
719 * *incompat_out suitable for presenting to the user. *incompat_out
720 * will be allocated from ctx.
722 static _notmuch_features
723 _parse_features (const void *ctx, const char *features, unsigned int version,
724 char mode, char **incompat_out)
726 _notmuch_features res = static_cast<_notmuch_features>(0);
727 unsigned int namelen, i;
731 /* Prior to database version 3, features were implied by the
734 return NOTMUCH_FEATURES_V0;
735 else if (version == 1)
736 return NOTMUCH_FEATURES_V1;
737 else if (version == 2)
738 return NOTMUCH_FEATURES_V2;
740 /* Parse the features string */
741 while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
742 flags = strchr (features, '\t');
743 if (! flags || flags > features + llen)
745 namelen = flags - features;
747 for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
748 if (strlen (feature_names[i].name) == namelen &&
749 strncmp (feature_names[i].name, features, namelen) == 0) {
750 res |= feature_names[i].value;
755 if (i == ARRAY_SIZE (feature_names) && incompat_out) {
756 /* Unrecognized feature */
757 const char *have = strchr (flags, mode);
758 if (have && have < features + llen) {
759 /* This feature is required to access this database in
760 * 'mode', but we don't understand it. */
762 *incompat_out = talloc_strdup (ctx, "");
763 *incompat_out = talloc_asprintf_append_buffer (
764 *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
774 _print_features (const void *ctx, unsigned int features)
777 char *res = talloc_strdup (ctx, "");
779 for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
780 if (features & feature_names[i].value)
781 res = talloc_asprintf_append_buffer (
782 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
788 notmuch_database_open (const char *path,
789 notmuch_database_mode_t mode,
790 notmuch_database_t **database)
792 char *status_string = NULL;
793 notmuch_status_t status;
795 status = notmuch_database_open_verbose (path, mode, database,
799 fputs (status_string, stderr);
800 free (status_string);
807 notmuch_database_open_verbose (const char *path,
808 notmuch_database_mode_t mode,
809 notmuch_database_t **database,
810 char **status_string)
812 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
813 void *local = talloc_new (NULL);
814 notmuch_database_t *notmuch = NULL;
815 char *notmuch_path, *xapian_path, *incompat_features;
816 char *message = NULL;
819 unsigned int i, version;
820 static int initialized = 0;
823 message = strdup ("Error: Cannot open a database for a NULL path.\n");
824 status = NOTMUCH_STATUS_NULL_POINTER;
828 if (path[0] != '/') {
829 message = strdup ("Error: Database path must be absolute.\n");
830 status = NOTMUCH_STATUS_PATH_ERROR;
834 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
835 message = strdup ("Out of memory\n");
836 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
840 err = stat (notmuch_path, &st);
842 IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
843 notmuch_path, strerror (errno)));
844 status = NOTMUCH_STATUS_FILE_ERROR;
848 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
849 message = strdup ("Out of memory\n");
850 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
854 /* Initialize the GLib type system and threads */
855 #if !GLIB_CHECK_VERSION(2, 35, 1)
859 /* Initialize gmime */
861 g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
865 notmuch = talloc_zero (NULL, notmuch_database_t);
866 notmuch->exception_reported = false;
867 notmuch->status_string = NULL;
868 notmuch->path = talloc_strdup (notmuch, path);
870 strip_trailing(notmuch->path, '/');
872 notmuch->mode = mode;
873 notmuch->atomic_nesting = 0;
876 string last_thread_id;
879 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
880 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
883 notmuch->xapian_db = new Xapian::Database (xapian_path);
886 /* Check version. As of database version 3, we represent
887 * changes in terms of features, so assume a version bump
888 * means a dramatically incompatible change. */
889 version = notmuch_database_get_version (notmuch);
890 if (version > NOTMUCH_DATABASE_VERSION) {
891 IGNORE_RESULT (asprintf (&message,
892 "Error: Notmuch database at %s\n"
893 " has a newer database format version (%u) than supported by this\n"
894 " version of notmuch (%u).\n",
895 notmuch_path, version, NOTMUCH_DATABASE_VERSION));
896 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
897 notmuch_database_destroy (notmuch);
899 status = NOTMUCH_STATUS_FILE_ERROR;
903 /* Check features. */
904 incompat_features = NULL;
905 notmuch->features = _parse_features (
906 local, notmuch->xapian_db->get_metadata ("features").c_str (),
907 version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
909 if (incompat_features) {
910 IGNORE_RESULT (asprintf (&message,
911 "Error: Notmuch database at %s\n"
912 " requires features (%s)\n"
913 " not supported by this version of notmuch.\n",
914 notmuch_path, incompat_features));
915 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
916 notmuch_database_destroy (notmuch);
918 status = NOTMUCH_STATUS_FILE_ERROR;
922 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
923 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
924 if (last_thread_id.empty ()) {
925 notmuch->last_thread_id = 0;
930 str = last_thread_id.c_str ();
931 notmuch->last_thread_id = strtoull (str, &end, 16);
933 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
936 /* Get current highest revision number. */
937 last_mod = notmuch->xapian_db->get_value_upper_bound (
938 NOTMUCH_VALUE_LAST_MOD);
939 if (last_mod.empty ())
940 notmuch->revision = 0;
942 notmuch->revision = Xapian::sortable_unserialise (last_mod);
943 notmuch->uuid = talloc_strdup (
944 notmuch, notmuch->xapian_db->get_uuid ().c_str ());
946 notmuch->query_parser = new Xapian::QueryParser;
947 notmuch->term_gen = new Xapian::TermGenerator;
948 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
949 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
950 notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
951 notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
953 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
954 notmuch->query_parser->set_database (*notmuch->xapian_db);
955 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
956 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
957 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
958 notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
959 notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
961 for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
962 const prefix_t *prefix = &prefix_table[i];
963 if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
964 _setup_query_field (prefix, notmuch);
967 } catch (const Xapian::Error &error) {
968 IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
969 error.get_msg().c_str()));
970 notmuch_database_destroy (notmuch);
972 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
980 *status_string = message;
988 talloc_free (notmuch);
993 notmuch_database_close (notmuch_database_t *notmuch)
995 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
997 /* Many Xapian objects (and thus notmuch objects) hold references to
998 * the database, so merely deleting the database may not suffice to
999 * close it. Thus, we explicitly close it here. */
1000 if (notmuch->xapian_db != NULL) {
1002 /* If there's an outstanding transaction, it's unclear if
1003 * closing the Xapian database commits everything up to
1004 * that transaction, or may discard committed (but
1005 * unflushed) transactions. To be certain, explicitly
1006 * cancel any outstanding transaction before closing. */
1007 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1008 notmuch->atomic_nesting)
1009 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1010 ->cancel_transaction ();
1012 /* Close the database. This implicitly flushes
1013 * outstanding changes. */
1014 notmuch->xapian_db->close();
1015 } catch (const Xapian::Error &error) {
1016 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1017 if (! notmuch->exception_reported) {
1018 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1019 error.get_msg().c_str());
1024 delete notmuch->term_gen;
1025 notmuch->term_gen = NULL;
1026 delete notmuch->query_parser;
1027 notmuch->query_parser = NULL;
1028 delete notmuch->xapian_db;
1029 notmuch->xapian_db = NULL;
1030 delete notmuch->value_range_processor;
1031 notmuch->value_range_processor = NULL;
1032 delete notmuch->date_range_processor;
1033 notmuch->date_range_processor = NULL;
1034 delete notmuch->last_mod_range_processor;
1035 notmuch->last_mod_range_processor = NULL;
1041 _notmuch_database_reopen (notmuch_database_t *notmuch)
1043 if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1044 return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1047 notmuch->xapian_db->reopen ();
1048 } catch (const Xapian::Error &error) {
1049 if (! notmuch->exception_reported) {
1050 _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1051 error.get_msg ().c_str ());
1052 notmuch->exception_reported = true;
1054 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1059 return NOTMUCH_STATUS_SUCCESS;
1063 unlink_cb (const char *path,
1064 unused (const struct stat *sb),
1066 unused (struct FTW *ftw))
1068 return remove (path);
1072 rmtree (const char *path)
1074 return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1077 class NotmuchCompactor : public Xapian::Compactor
1079 notmuch_compact_status_cb_t status_cb;
1080 void *status_closure;
1083 NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1084 status_cb (cb), status_closure (closure) { }
1087 set_status (const std::string &table, const std::string &status)
1091 if (status_cb == NULL)
1094 if (status.length () == 0)
1095 msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1097 msg = talloc_asprintf (NULL, " %s", status.c_str());
1103 status_cb (msg, status_closure);
1108 /* Compacts the given database, optionally saving the original database
1109 * in backup_path. Additionally, a callback function can be provided to
1110 * give the user feedback on the progress of the (likely long-lived)
1111 * compaction process.
1113 * The backup path must point to a directory on the same volume as the
1114 * original database. Passing a NULL backup_path will result in the
1115 * uncompacted database being deleted after compaction has finished.
1116 * Note that the database write lock will be held during the
1117 * compaction process to protect data integrity.
1120 notmuch_database_compact (const char *path,
1121 const char *backup_path,
1122 notmuch_compact_status_cb_t status_cb,
1126 char *notmuch_path, *xapian_path, *compact_xapian_path;
1127 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1128 notmuch_database_t *notmuch = NULL;
1129 struct stat statbuf;
1131 char *message = NULL;
1133 local = talloc_new (NULL);
1135 return NOTMUCH_STATUS_OUT_OF_MEMORY;
1137 ret = notmuch_database_open_verbose (path,
1138 NOTMUCH_DATABASE_MODE_READ_WRITE,
1142 if (status_cb) status_cb (message, closure);
1146 if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1147 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1151 if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1152 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1156 if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1157 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1161 if (backup_path == NULL) {
1162 if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1163 ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1166 keep_backup = false;
1172 if (stat (backup_path, &statbuf) != -1) {
1173 _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1174 ret = NOTMUCH_STATUS_FILE_ERROR;
1177 if (errno != ENOENT) {
1178 _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1180 ret = NOTMUCH_STATUS_FILE_ERROR;
1184 /* Unconditionally attempt to remove old work-in-progress database (if
1185 * any). This is "protected" by database lock. If this fails due to write
1186 * errors (etc), the following code will fail and provide error message.
1188 (void) rmtree (compact_xapian_path);
1191 NotmuchCompactor compactor (status_cb, closure);
1193 compactor.set_renumber (false);
1194 compactor.add_source (xapian_path);
1195 compactor.set_destdir (compact_xapian_path);
1196 compactor.compact ();
1197 } catch (const Xapian::Error &error) {
1198 _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1199 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1203 if (rename (xapian_path, backup_path)) {
1204 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1205 xapian_path, backup_path, strerror (errno));
1206 ret = NOTMUCH_STATUS_FILE_ERROR;
1210 if (rename (compact_xapian_path, xapian_path)) {
1211 _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1212 compact_xapian_path, xapian_path, strerror (errno));
1213 ret = NOTMUCH_STATUS_FILE_ERROR;
1217 if (! keep_backup) {
1218 if (rmtree (backup_path)) {
1219 _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1220 backup_path, strerror (errno));
1221 ret = NOTMUCH_STATUS_FILE_ERROR;
1228 notmuch_status_t ret2;
1230 const char *str = notmuch_database_status_string (notmuch);
1231 if (status_cb && str)
1232 status_cb (str, closure);
1234 ret2 = notmuch_database_destroy (notmuch);
1236 /* don't clobber previous error status */
1237 if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1241 talloc_free (local);
1247 notmuch_database_destroy (notmuch_database_t *notmuch)
1249 notmuch_status_t status;
1251 status = notmuch_database_close (notmuch);
1252 talloc_free (notmuch);
1258 notmuch_database_get_path (notmuch_database_t *notmuch)
1260 return notmuch->path;
1264 notmuch_database_get_version (notmuch_database_t *notmuch)
1266 unsigned int version;
1267 string version_string;
1271 version_string = notmuch->xapian_db->get_metadata ("version");
1272 if (version_string.empty ())
1275 str = version_string.c_str ();
1276 if (str == NULL || *str == '\0')
1279 version = strtoul (str, &end, 10);
1281 INTERNAL_ERROR ("Malformed database version: %s", str);
1287 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1289 return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1290 ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1291 (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1294 static volatile sig_atomic_t do_progress_notify = 0;
1297 handle_sigalrm (unused (int signal))
1299 do_progress_notify = 1;
1302 /* Upgrade the current database.
1304 * After opening a database in read-write mode, the client should
1305 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1306 * if so, upgrade with this function before making any modifications.
1308 * The optional progress_notify callback can be used by the caller to
1309 * provide progress indication to the user. If non-NULL it will be
1310 * called periodically with 'count' as the number of messages upgraded
1311 * so far and 'total' the overall number of messages that will be
1315 notmuch_database_upgrade (notmuch_database_t *notmuch,
1316 void (*progress_notify) (void *closure,
1320 void *local = talloc_new (NULL);
1321 Xapian::TermIterator t, t_end;
1322 Xapian::WritableDatabase *db;
1323 struct sigaction action;
1324 struct itimerval timerval;
1325 bool timer_is_active = false;
1326 enum _notmuch_features target_features, new_features;
1327 notmuch_status_t status;
1328 notmuch_private_status_t private_status;
1329 notmuch_query_t *query = NULL;
1330 unsigned int count = 0, total = 0;
1332 status = _notmuch_database_ensure_writable (notmuch);
1336 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1338 target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1339 new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1341 if (! notmuch_database_needs_upgrade (notmuch))
1342 return NOTMUCH_STATUS_SUCCESS;
1344 if (progress_notify) {
1345 /* Set up our handler for SIGALRM */
1346 memset (&action, 0, sizeof (struct sigaction));
1347 action.sa_handler = handle_sigalrm;
1348 sigemptyset (&action.sa_mask);
1349 action.sa_flags = SA_RESTART;
1350 sigaction (SIGALRM, &action, NULL);
1352 /* Then start a timer to send SIGALRM once per second. */
1353 timerval.it_interval.tv_sec = 1;
1354 timerval.it_interval.tv_usec = 0;
1355 timerval.it_value.tv_sec = 1;
1356 timerval.it_value.tv_usec = 0;
1357 setitimer (ITIMER_REAL, &timerval, NULL);
1359 timer_is_active = true;
1362 /* Figure out how much total work we need to do. */
1364 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1365 NOTMUCH_FEATURE_LAST_MOD)) {
1366 query = notmuch_query_create (notmuch, "");
1369 status = notmuch_query_count_messages (query, &msg_count);
1374 notmuch_query_destroy (query);
1377 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1378 t_end = db->allterms_end ("XTIMESTAMP");
1379 for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1382 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1383 /* The ghost message upgrade converts all thread_id_*
1384 * metadata values into ghost message documents. */
1385 t_end = db->metadata_keys_end ("thread_id_");
1386 for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1390 /* Perform the upgrade in a transaction. */
1391 db->begin_transaction (true);
1393 /* Set the target features so we write out changes in the desired
1395 notmuch->features = target_features;
1397 /* Perform per-message upgrades. */
1399 (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1400 NOTMUCH_FEATURE_LAST_MOD)) {
1401 notmuch_messages_t *messages;
1402 notmuch_message_t *message;
1405 query = notmuch_query_create (notmuch, "");
1407 status = notmuch_query_search_messages (query, &messages);
1411 notmuch_messages_valid (messages);
1412 notmuch_messages_move_to_next (messages))
1414 if (do_progress_notify) {
1415 progress_notify (closure, (double) count / total);
1416 do_progress_notify = 0;
1419 message = notmuch_messages_get (messages);
1421 /* Before version 1, each message document had its
1422 * filename in the data field. Copy that into the new
1423 * format by calling notmuch_message_add_filename.
1425 if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1426 filename = _notmuch_message_talloc_copy_data (message);
1427 if (filename && *filename != '\0') {
1428 _notmuch_message_add_filename (message, filename);
1429 _notmuch_message_clear_data (message);
1431 talloc_free (filename);
1434 /* Prior to version 2, the "folder:" prefix was
1435 * probabilistic and stemmed. Change it to the current
1436 * boolean prefix. Add "path:" prefixes while at it.
1438 if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1439 _notmuch_message_upgrade_folder (message);
1441 /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1442 * track modification revisions. Give all messages the
1443 * next available revision; since we just started tracking
1444 * revisions for this database, that will be 1.
1446 if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1447 _notmuch_message_upgrade_last_mod (message);
1449 _notmuch_message_sync (message);
1451 notmuch_message_destroy (message);
1456 notmuch_query_destroy (query);
1460 /* Perform per-directory upgrades. */
1462 /* Before version 1 we stored directory timestamps in
1463 * XTIMESTAMP documents instead of the current XDIRECTORY
1464 * documents. So copy those as well. */
1465 if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1466 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1468 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1472 Xapian::PostingIterator p, p_end;
1473 std::string term = *t;
1475 p_end = notmuch->xapian_db->postlist_end (term);
1477 for (p = notmuch->xapian_db->postlist_begin (term);
1481 Xapian::Document document;
1483 notmuch_directory_t *directory;
1485 if (do_progress_notify) {
1486 progress_notify (closure, (double) count / total);
1487 do_progress_notify = 0;
1490 document = find_document_for_doc_id (notmuch, *p);
1491 mtime = Xapian::sortable_unserialise (
1492 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1494 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1495 NOTMUCH_FIND_CREATE, &status);
1496 notmuch_directory_set_mtime (directory, mtime);
1497 notmuch_directory_destroy (directory);
1499 db->delete_document (*p);
1506 /* Perform metadata upgrades. */
1508 /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1509 * messages were stored as database metadata. Change these to
1512 if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1513 notmuch_message_t *message;
1514 std::string message_id, thread_id;
1516 t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1517 for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1519 if (do_progress_notify) {
1520 progress_notify (closure, (double) count / total);
1521 do_progress_notify = 0;
1524 message_id = (*t).substr (
1525 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1526 thread_id = db->get_metadata (*t);
1528 /* Create ghost message */
1529 message = _notmuch_message_create_for_message_id (
1530 notmuch, message_id.c_str (), &private_status);
1531 if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1532 /* Document already exists; ignore the stored thread ID */
1533 } else if (private_status ==
1534 NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1535 private_status = _notmuch_message_initialize_ghost (
1536 message, thread_id.c_str ());
1537 if (! private_status)
1538 _notmuch_message_sync (message);
1541 if (private_status) {
1542 _notmuch_database_log (notmuch,
1543 "Upgrade failed while creating ghost messages.\n");
1544 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1548 /* Clear saved metadata thread ID */
1549 db->set_metadata (*t, "");
1555 status = NOTMUCH_STATUS_SUCCESS;
1556 db->set_metadata ("features", _print_features (local, notmuch->features));
1557 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1560 if (status == NOTMUCH_STATUS_SUCCESS)
1561 db->commit_transaction ();
1563 db->cancel_transaction ();
1565 if (timer_is_active) {
1566 /* Now stop the timer. */
1567 timerval.it_interval.tv_sec = 0;
1568 timerval.it_interval.tv_usec = 0;
1569 timerval.it_value.tv_sec = 0;
1570 timerval.it_value.tv_usec = 0;
1571 setitimer (ITIMER_REAL, &timerval, NULL);
1573 /* And disable the signal handler. */
1574 action.sa_handler = SIG_IGN;
1575 sigaction (SIGALRM, &action, NULL);
1579 notmuch_query_destroy (query);
1581 talloc_free (local);
1586 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1588 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1589 notmuch->atomic_nesting > 0)
1592 if (notmuch_database_needs_upgrade (notmuch))
1593 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1596 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1597 } catch (const Xapian::Error &error) {
1598 _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1599 error.get_msg().c_str());
1600 notmuch->exception_reported = true;
1601 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1605 notmuch->atomic_nesting++;
1606 return NOTMUCH_STATUS_SUCCESS;
1610 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1612 Xapian::WritableDatabase *db;
1614 if (notmuch->atomic_nesting == 0)
1615 return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1617 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1618 notmuch->atomic_nesting > 1)
1621 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1623 db->commit_transaction ();
1625 /* This is a hack for testing. Xapian never flushes on a
1626 * non-flushed commit, even if the flush threshold is 1.
1627 * However, we rely on flushing to test atomicity. */
1628 const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1629 if (thresh && atoi (thresh) == 1)
1631 } catch (const Xapian::Error &error) {
1632 _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1633 error.get_msg().c_str());
1634 notmuch->exception_reported = true;
1635 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1638 if (notmuch->atomic_dirty) {
1639 ++notmuch->revision;
1640 notmuch->atomic_dirty = false;
1644 notmuch->atomic_nesting--;
1645 return NOTMUCH_STATUS_SUCCESS;
1649 notmuch_database_get_revision (notmuch_database_t *notmuch,
1653 *uuid = notmuch->uuid;
1654 return notmuch->revision;
1657 /* We allow the user to use arbitrarily long paths for directories. But
1658 * we have a term-length limit. So if we exceed that, we'll use the
1659 * SHA-1 of the path for the database term.
1661 * Note: This function may return the original value of 'path'. If it
1662 * does not, then the caller is responsible to free() the returned
1666 _notmuch_database_get_directory_db_path (const char *path)
1668 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1670 if (term_len > NOTMUCH_TERM_MAX)
1671 return _notmuch_sha1_of_string (path);
1676 /* Given a path, split it into two parts: the directory part is all
1677 * components except for the last, and the basename is that last
1678 * component. Getting the return-value for either part is optional
1679 * (the caller can pass NULL).
1681 * The original 'path' can represent either a regular file or a
1682 * directory---the splitting will be carried out in the same way in
1683 * either case. Trailing slashes on 'path' will be ignored, and any
1684 * cases of multiple '/' characters appearing in series will be
1685 * treated as a single '/'.
1687 * Allocation (if any) will have 'ctx' as the talloc owner. But
1688 * pointers will be returned within the original path string whenever
1691 * Note: If 'path' is non-empty and contains no non-trailing slash,
1692 * (that is, consists of a filename with no parent directory), then
1693 * the directory returned will be an empty string. However, if 'path'
1694 * is an empty string, then both directory and basename will be
1698 _notmuch_database_split_path (void *ctx,
1700 const char **directory,
1701 const char **basename)
1705 if (path == NULL || *path == '\0') {
1710 return NOTMUCH_STATUS_SUCCESS;
1713 /* Find the last slash (not counting a trailing slash), if any. */
1715 slash = path + strlen (path) - 1;
1717 /* First, skip trailing slashes. */
1718 while (slash != path && *slash == '/')
1721 /* Then, find a slash. */
1722 while (slash != path && *slash != '/') {
1729 /* Finally, skip multiple slashes. */
1730 while (slash != path && *(slash - 1) == '/')
1733 if (slash == path) {
1735 *directory = talloc_strdup (ctx, "");
1740 *directory = talloc_strndup (ctx, path, slash - path);
1743 return NOTMUCH_STATUS_SUCCESS;
1746 /* Find the document ID of the specified directory.
1748 * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1749 * created if one does not exist for 'path'. Otherwise, if the
1750 * directory document does not exist, this sets *directory_id to
1751 * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1754 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1756 notmuch_find_flags_t flags,
1757 unsigned int *directory_id)
1759 notmuch_directory_t *directory;
1760 notmuch_status_t status;
1764 return NOTMUCH_STATUS_SUCCESS;
1767 directory = _notmuch_directory_create (notmuch, path, flags, &status);
1768 if (status || !directory) {
1773 *directory_id = _notmuch_directory_get_document_id (directory);
1775 notmuch_directory_destroy (directory);
1777 return NOTMUCH_STATUS_SUCCESS;
1781 _notmuch_database_get_directory_path (void *ctx,
1782 notmuch_database_t *notmuch,
1783 unsigned int doc_id)
1785 Xapian::Document document;
1787 document = find_document_for_doc_id (notmuch, doc_id);
1789 return talloc_strdup (ctx, document.get_data ().c_str ());
1792 /* Given a legal 'filename' for the database, (either relative to
1793 * database path or absolute with initial components identical to
1794 * database path), return a new string (with 'ctx' as the talloc
1795 * owner) suitable for use as a direntry term value.
1797 * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1798 * will be created in the database as needed. Otherwise, if the
1799 * necessary directory documents do not exist, this sets
1800 * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1803 _notmuch_database_filename_to_direntry (void *ctx,
1804 notmuch_database_t *notmuch,
1805 const char *filename,
1806 notmuch_find_flags_t flags,
1809 const char *relative, *directory, *basename;
1810 Xapian::docid directory_id;
1811 notmuch_status_t status;
1813 relative = _notmuch_database_relative_path (notmuch, filename);
1815 status = _notmuch_database_split_path (ctx, relative,
1816 &directory, &basename);
1820 status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1822 if (status || directory_id == (unsigned int)-1) {
1827 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1829 return NOTMUCH_STATUS_SUCCESS;
1832 /* Given a legal 'path' for the database, return the relative path.
1834 * The return value will be a pointer to the original path contents,
1835 * and will be either the original string (if 'path' was relative) or
1836 * a portion of the string (if path was absolute and begins with the
1840 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1843 const char *db_path, *relative;
1844 unsigned int db_path_len;
1846 db_path = notmuch_database_get_path (notmuch);
1847 db_path_len = strlen (db_path);
1851 if (*relative == '/') {
1852 while (*relative == '/' && *(relative+1) == '/')
1855 if (strncmp (relative, db_path, db_path_len) == 0)
1857 relative += db_path_len;
1858 while (*relative == '/')
1867 notmuch_database_get_directory (notmuch_database_t *notmuch,
1869 notmuch_directory_t **directory)
1871 notmuch_status_t status;
1873 if (directory == NULL)
1874 return NOTMUCH_STATUS_NULL_POINTER;
1878 *directory = _notmuch_directory_create (notmuch, path,
1879 NOTMUCH_FIND_LOOKUP, &status);
1880 } catch (const Xapian::Error &error) {
1881 _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1882 error.get_msg().c_str());
1883 notmuch->exception_reported = true;
1884 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1889 /* Allocate a document ID that satisfies the following criteria:
1891 * 1. The ID does not exist for any document in the Xapian database
1893 * 2. The ID was not previously returned from this function
1895 * 3. The ID is the smallest integer satisfying (1) and (2)
1897 * This function will trigger an internal error if these constraints
1898 * cannot all be satisfied, (that is, the pool of available document
1899 * IDs has been exhausted).
1902 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1904 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1906 notmuch->last_doc_id++;
1908 if (notmuch->last_doc_id == 0)
1909 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1911 return notmuch->last_doc_id;
1915 notmuch_database_remove_message (notmuch_database_t *notmuch,
1916 const char *filename)
1918 notmuch_status_t status;
1919 notmuch_message_t *message;
1921 status = notmuch_database_find_message_by_filename (notmuch, filename,
1924 if (status == NOTMUCH_STATUS_SUCCESS && message) {
1925 status = _notmuch_message_remove_filename (message, filename);
1926 if (status == NOTMUCH_STATUS_SUCCESS)
1927 _notmuch_message_delete (message);
1928 else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1929 _notmuch_message_sync (message);
1931 notmuch_message_destroy (message);
1938 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1939 const char *filename,
1940 notmuch_message_t **message_ret)
1943 const char *prefix = _find_prefix ("file-direntry");
1944 char *direntry, *term;
1945 Xapian::PostingIterator i, end;
1946 notmuch_status_t status;
1948 if (message_ret == NULL)
1949 return NOTMUCH_STATUS_NULL_POINTER;
1951 if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1952 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1954 /* return NULL on any failure */
1955 *message_ret = NULL;
1957 local = talloc_new (notmuch);
1960 status = _notmuch_database_filename_to_direntry (
1961 local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1962 if (status || !direntry)
1965 term = talloc_asprintf (local, "%s%s", prefix, direntry);
1967 find_doc_ids_for_term (notmuch, term, &i, &end);
1970 notmuch_private_status_t private_status;
1972 *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1974 if (*message_ret == NULL)
1975 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1977 } catch (const Xapian::Error &error) {
1978 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1979 error.get_msg().c_str());
1980 notmuch->exception_reported = true;
1981 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1985 talloc_free (local);
1987 if (status && *message_ret) {
1988 notmuch_message_destroy (*message_ret);
1989 *message_ret = NULL;
1994 notmuch_string_list_t *
1995 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1996 Xapian::TermIterator &end,
1999 int prefix_len = strlen (prefix);
2000 notmuch_string_list_t *list;
2002 list = _notmuch_string_list_create (ctx);
2003 if (unlikely (list == NULL))
2006 for (i.skip_to (prefix); i != end; i++) {
2007 /* Terminate loop at first term without desired prefix. */
2008 if (strncmp ((*i).c_str (), prefix, prefix_len))
2011 _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2018 notmuch_database_get_all_tags (notmuch_database_t *db)
2020 Xapian::TermIterator i, end;
2021 notmuch_string_list_t *tags;
2024 i = db->xapian_db->allterms_begin();
2025 end = db->xapian_db->allterms_end();
2026 tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2027 _find_prefix ("tag"));
2028 _notmuch_string_list_sort (tags);
2029 return _notmuch_tags_create (db, tags);
2030 } catch (const Xapian::Error &error) {
2031 _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2032 error.get_msg().c_str());
2033 db->exception_reported = true;
2039 notmuch_database_status_string (const notmuch_database_t *notmuch)
2041 return notmuch->status_string;