1 /* database.cc - The database interfaces of the notmuch mail library
3 * Copyright © 2009 Carl Worth
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see http://www.gnu.org/licenses/ .
18 * Author: Carl Worth <cworth@cworth.org>
21 #include "database-private.h"
29 #include <glib.h> /* g_free, GPtrArray, GHashTable */
33 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
40 #define NOTMUCH_DATABASE_VERSION 1
42 #define STRINGIFY(s) _SUB_STRINGIFY(s)
43 #define _SUB_STRINGIFY(s) #s
45 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
47 * We currently have two different types of documents (mail and
48 * directory) and also some metadata.
52 * A mail document is associated with a particular email message file
53 * on disk. It is indexed with the following prefixed terms which the
54 * database uses to construct threads, etc.:
56 * Single terms of given prefix:
60 * id: Unique ID of mail, (from Message-ID header or generated
61 * as "notmuch-sha1-<sha1_sum_of_entire_file>.
63 * thread: The ID of the thread to which the mail belongs
65 * replyto: The ID from the In-Reply-To header of the mail (if any).
67 * Multiple terms of given prefix:
69 * reference: All message IDs from In-Reply-To and Re ferences
70 * headers in the message.
72 * tag: Any tags associated with this message by the user.
74 * file-direntry: A colon-separated pair of values
75 * (INTEGER:STRING), where INTEGER is the
76 * document ID of a directory document, and
77 * STRING is the name of a file within that
78 * directory for this mail message.
80 * A mail document also has two values:
82 * TIMESTAMP: The time_t value corresponding to the message's
85 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
87 * In addition, terms from the content of the message are added with
88 * "from", "to", "attachment", and "subject" prefixes for use by the
89 * user in searching. But the database doesn't really care itself
92 * The data portion of a mail document is empty.
96 * A directory document is used by a client of the notmuch library to
97 * maintain data necessary to allow for efficient polling of mail
100 * All directory documents contain one term:
102 * directory: The directory path (relative to the database path)
103 * Or the SHA1 sum of the directory path (if the
104 * path itself is too long to fit in a Xapian
107 * And all directory documents for directories other than top-level
108 * directories also contain the following term:
110 * directory-direntry: A colon-separated pair of values
111 * (INTEGER:STRING), where INTEGER is the
112 * document ID of the parent directory
113 * document, and STRING is the name of this
114 * directory within that parent.
116 * All directory documents have a single value:
118 * TIMESTAMP: The mtime of the directory (at last scan)
120 * The data portion of a directory document contains the path of the
121 * directory (relative to the database path).
125 * Xapian allows us to store arbitrary name-value pairs as
126 * "metadata". We currently use the following metadata names with the
129 * version The database schema version, (which is distinct
130 * from both the notmuch package version (see
131 * notmuch --version) and the libnotmuch library
132 * version. The version is stored as an base-10
133 * ASCII integer. The initial database version
134 * was 1, (though a schema existed before that
135 * were no "version" database value existed at
136 * all). Succesive versions are allocated as
137 * changes are made to the database (such as by
138 * indexing new fields).
140 * last_thread_id The last thread ID generated. This is stored
141 * as a 16-byte hexadecimal ASCII representation
142 * of a 64-bit unsigned integer. The first ID
143 * generated is 1 and the value will be
144 * incremented for each thread ID.
146 * thread_id_* A pre-allocated thread ID for a particular
147 * message. This is actually an arbitarily large
148 * family of metadata name. Any particular name
149 * is formed by concatenating "thread_id_" with a
150 * message ID. The value stored is a thread ID.
152 * These thread ID metadata values are stored
153 * whenever a message references a parent message
154 * that does not yet exist in the database. A
155 * thread ID will be allocated and stored, and if
156 * the message is later added, the stored thread
157 * ID will be used (and the metadata value will
160 * Even before a message is added, it's
161 * pre-allocated thread ID is useful so that all
162 * descendant messages that reference this common
163 * parent can be recognized as belonging to the
167 /* With these prefix values we follow the conventions published here:
169 * http://xapian.org/docs/omega/termprefixes.html
171 * as much as makes sense. Note that I took some liberty in matching
172 * the reserved prefix values to notmuch concepts, (for example, 'G'
173 * is documented as "newsGroup (or similar entity - e.g. a web forum
174 * name)", for which I think the thread is the closest analogue in
175 * notmuch. This in spite of the fact that we will eventually be
176 * storing mailing-list messages where 'G' for "mailing list name"
177 * might be even a closer analogue. I'm treating the single-character
178 * prefixes preferentially for core notmuch concepts (which will be
179 * nearly universal to all mail messages).
182 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
184 { "reference", "XREFERENCE" },
185 { "replyto", "XREPLYTO" },
186 { "directory", "XDIRECTORY" },
187 { "file-direntry", "XFDIRENTRY" },
188 { "directory-direntry", "XDDIRENTRY" },
191 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
198 prefix_t PROBABILISTIC_PREFIX[]= {
201 { "attachment", "XATTACHMENT" },
202 { "subject", "XSUBJECT"}
206 _internal_error (const char *format, ...)
210 va_start (va_args, format);
212 fprintf (stderr, "Internal error: ");
213 vfprintf (stderr, format, va_args);
221 _find_prefix (const char *name)
225 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
226 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
227 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
230 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
231 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
232 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
235 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
236 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
237 return PROBABILISTIC_PREFIX[i].prefix;
240 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
246 notmuch_status_to_string (notmuch_status_t status)
249 case NOTMUCH_STATUS_SUCCESS:
250 return "No error occurred";
251 case NOTMUCH_STATUS_OUT_OF_MEMORY:
252 return "Out of memory";
253 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
254 return "Attempt to write to a read-only database";
255 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
256 return "A Xapian exception occurred";
257 case NOTMUCH_STATUS_FILE_ERROR:
258 return "Something went wrong trying to read or write a file";
259 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
260 return "File is not an email";
261 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
262 return "Message ID is identical to a message in database";
263 case NOTMUCH_STATUS_NULL_POINTER:
264 return "Erroneous NULL pointer";
265 case NOTMUCH_STATUS_TAG_TOO_LONG:
266 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
267 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
268 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
270 case NOTMUCH_STATUS_LAST_STATUS:
271 return "Unknown error status value";
276 find_doc_ids_for_term (notmuch_database_t *notmuch,
278 Xapian::PostingIterator *begin,
279 Xapian::PostingIterator *end)
281 *begin = notmuch->xapian_db->postlist_begin (term);
283 *end = notmuch->xapian_db->postlist_end (term);
287 find_doc_ids (notmuch_database_t *notmuch,
288 const char *prefix_name,
290 Xapian::PostingIterator *begin,
291 Xapian::PostingIterator *end)
295 term = talloc_asprintf (notmuch, "%s%s",
296 _find_prefix (prefix_name), value);
298 find_doc_ids_for_term (notmuch, term, begin, end);
303 notmuch_private_status_t
304 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
305 const char *prefix_name,
307 unsigned int *doc_id)
309 Xapian::PostingIterator i, end;
311 find_doc_ids (notmuch, prefix_name, value, &i, &end);
315 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
320 #if DEBUG_DATABASE_SANITY
324 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
328 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
331 static Xapian::Document
332 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
334 return notmuch->xapian_db->get_document (doc_id);
338 notmuch_database_find_message (notmuch_database_t *notmuch,
339 const char *message_id)
341 notmuch_private_status_t status;
345 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
346 message_id, &doc_id);
348 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
351 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
352 } catch (const Xapian::Error &error) {
353 fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
354 error.get_msg().c_str());
355 notmuch->exception_reported = TRUE;
360 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
361 * a (potentially nested) parenthesized sequence with '\' used to
362 * escape any character (including parentheses).
364 * If the sequence to be skipped continues to the end of the string,
365 * then 'str' will be left pointing at the final terminating '\0'
369 skip_space_and_comments (const char **str)
374 while (*s && (isspace (*s) || *s == '(')) {
375 while (*s && isspace (*s))
380 while (*s && nesting) {
383 } else if (*s == ')') {
385 } else if (*s == '\\') {
397 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
398 * comments, and the '<' and '>' delimeters.
400 * If not NULL, then *next will be made to point to the first character
401 * not parsed, (possibly pointing to the final '\0' terminator.
403 * Returns a newly talloc'ed string belonging to 'ctx'.
405 * Returns NULL if there is any error parsing the message-id. */
407 _parse_message_id (void *ctx, const char *message_id, const char **next)
412 if (message_id == NULL || *message_id == '\0')
417 skip_space_and_comments (&s);
419 /* Skip any unstructured text as well. */
420 while (*s && *s != '<')
431 skip_space_and_comments (&s);
434 while (*end && *end != '>')
443 if (end > s && *end == '>')
448 result = talloc_strndup (ctx, s, end - s + 1);
450 /* Finally, collapse any whitespace that is within the message-id
456 for (r = result, len = strlen (r); *r; r++, len--)
457 if (*r == ' ' || *r == '\t')
458 memmove (r, r+1, len);
464 /* Parse a References header value, putting a (talloc'ed under 'ctx')
465 * copy of each referenced message-id into 'hash'.
467 * We explicitly avoid including any reference identical to
468 * 'message_id' in the result (to avoid mass confusion when a single
469 * message references itself cyclically---and yes, mail messages are
470 * not infrequent in the wild that do this---don't ask me why).
473 parse_references (void *ctx,
474 const char *message_id,
480 if (refs == NULL || *refs == '\0')
484 ref = _parse_message_id (ctx, refs, &refs);
486 if (ref && strcmp (ref, message_id))
487 g_hash_table_insert (hash, ref, NULL);
492 notmuch_database_create (const char *path)
494 notmuch_database_t *notmuch = NULL;
495 char *notmuch_path = NULL;
500 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
504 err = stat (path, &st);
506 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
507 path, strerror (errno));
511 if (! S_ISDIR (st.st_mode)) {
512 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
517 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
519 err = mkdir (notmuch_path, 0755);
522 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
523 notmuch_path, strerror (errno));
527 notmuch = notmuch_database_open (path,
528 NOTMUCH_DATABASE_MODE_READ_WRITE);
529 notmuch_database_upgrade (notmuch, NULL, NULL);
533 talloc_free (notmuch_path);
539 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
541 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
542 fprintf (stderr, "Cannot write to a read-only database.\n");
543 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
546 return NOTMUCH_STATUS_SUCCESS;
550 notmuch_database_open (const char *path,
551 notmuch_database_mode_t mode)
553 notmuch_database_t *notmuch = NULL;
554 char *notmuch_path = NULL, *xapian_path = NULL;
557 unsigned int i, version;
559 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
561 fprintf (stderr, "Out of memory\n");
565 err = stat (notmuch_path, &st);
567 fprintf (stderr, "Error opening database at %s: %s\n",
568 notmuch_path, strerror (errno));
572 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
574 fprintf (stderr, "Out of memory\n");
578 notmuch = talloc (NULL, notmuch_database_t);
579 notmuch->exception_reported = FALSE;
580 notmuch->path = talloc_strdup (notmuch, path);
582 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
583 notmuch->path[strlen (notmuch->path) - 1] = '\0';
585 notmuch->needs_upgrade = FALSE;
586 notmuch->mode = mode;
588 string last_thread_id;
590 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
591 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
592 Xapian::DB_CREATE_OR_OPEN);
593 version = notmuch_database_get_version (notmuch);
595 if (version > NOTMUCH_DATABASE_VERSION) {
597 "Error: Notmuch database at %s\n"
598 " has a newer database format version (%u) than supported by this\n"
599 " version of notmuch (%u). Refusing to open this database in\n"
600 " read-write mode.\n",
601 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
602 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
603 notmuch_database_close (notmuch);
608 if (version < NOTMUCH_DATABASE_VERSION)
609 notmuch->needs_upgrade = TRUE;
611 notmuch->xapian_db = new Xapian::Database (xapian_path);
612 version = notmuch_database_get_version (notmuch);
613 if (version > NOTMUCH_DATABASE_VERSION)
616 "Warning: Notmuch database at %s\n"
617 " has a newer database format version (%u) than supported by this\n"
618 " version of notmuch (%u). Some operations may behave incorrectly,\n"
619 " (but the database will not be harmed since it is being opened\n"
620 " in read-only mode).\n",
621 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
625 notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
626 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
627 if (last_thread_id.empty ()) {
628 notmuch->last_thread_id = 0;
633 str = last_thread_id.c_str ();
634 notmuch->last_thread_id = strtoull (str, &end, 16);
636 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
639 notmuch->query_parser = new Xapian::QueryParser;
640 notmuch->term_gen = new Xapian::TermGenerator;
641 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
642 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
644 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
645 notmuch->query_parser->set_database (*notmuch->xapian_db);
646 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
647 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
648 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
650 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
651 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
652 notmuch->query_parser->add_boolean_prefix (prefix->name,
656 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
657 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
658 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
660 } catch (const Xapian::Error &error) {
661 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
662 error.get_msg().c_str());
676 notmuch_database_close (notmuch_database_t *notmuch)
679 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
680 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
681 } catch (const Xapian::Error &error) {
682 if (! notmuch->exception_reported) {
683 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
684 error.get_msg().c_str());
688 delete notmuch->term_gen;
689 delete notmuch->query_parser;
690 delete notmuch->xapian_db;
691 delete notmuch->value_range_processor;
692 talloc_free (notmuch);
696 notmuch_database_get_path (notmuch_database_t *notmuch)
698 return notmuch->path;
702 notmuch_database_get_version (notmuch_database_t *notmuch)
704 unsigned int version;
705 string version_string;
709 version_string = notmuch->xapian_db->get_metadata ("version");
710 if (version_string.empty ())
713 str = version_string.c_str ();
714 if (str == NULL || *str == '\0')
717 version = strtoul (str, &end, 10);
719 INTERNAL_ERROR ("Malformed database version: %s", str);
725 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
727 return notmuch->needs_upgrade;
730 static volatile sig_atomic_t do_progress_notify = 0;
733 handle_sigalrm (unused (int signal))
735 do_progress_notify = 1;
738 /* Upgrade the current database.
740 * After opening a database in read-write mode, the client should
741 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
742 * if so, upgrade with this function before making any modifications.
744 * The optional progress_notify callback can be used by the caller to
745 * provide progress indication to the user. If non-NULL it will be
746 * called periodically with 'count' as the number of messages upgraded
747 * so far and 'total' the overall number of messages that will be
751 notmuch_database_upgrade (notmuch_database_t *notmuch,
752 void (*progress_notify) (void *closure,
756 Xapian::WritableDatabase *db;
757 struct sigaction action;
758 struct itimerval timerval;
759 notmuch_bool_t timer_is_active = FALSE;
760 unsigned int version;
761 notmuch_status_t status;
762 unsigned int count = 0, total = 0;
764 status = _notmuch_database_ensure_writable (notmuch);
768 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
770 version = notmuch_database_get_version (notmuch);
772 if (version >= NOTMUCH_DATABASE_VERSION)
773 return NOTMUCH_STATUS_SUCCESS;
775 if (progress_notify) {
776 /* Setup our handler for SIGALRM */
777 memset (&action, 0, sizeof (struct sigaction));
778 action.sa_handler = handle_sigalrm;
779 sigemptyset (&action.sa_mask);
780 action.sa_flags = SA_RESTART;
781 sigaction (SIGALRM, &action, NULL);
783 /* Then start a timer to send SIGALRM once per second. */
784 timerval.it_interval.tv_sec = 1;
785 timerval.it_interval.tv_usec = 0;
786 timerval.it_value.tv_sec = 1;
787 timerval.it_value.tv_usec = 0;
788 setitimer (ITIMER_REAL, &timerval, NULL);
790 timer_is_active = TRUE;
793 /* Before version 1, each message document had its filename in the
794 * data field. Copy that into the new format by calling
795 * notmuch_message_add_filename.
798 notmuch_query_t *query = notmuch_query_create (notmuch, "");
799 notmuch_messages_t *messages;
800 notmuch_message_t *message;
802 Xapian::TermIterator t, t_end;
804 total = notmuch_query_count_messages (query);
806 for (messages = notmuch_query_search_messages (query);
807 notmuch_messages_valid (messages);
808 notmuch_messages_move_to_next (messages))
810 if (do_progress_notify) {
811 progress_notify (closure, (double) count / total);
812 do_progress_notify = 0;
815 message = notmuch_messages_get (messages);
817 filename = _notmuch_message_talloc_copy_data (message);
818 if (filename && *filename != '\0') {
819 _notmuch_message_add_filename (message, filename);
820 _notmuch_message_sync (message);
822 talloc_free (filename);
824 notmuch_message_destroy (message);
829 notmuch_query_destroy (query);
831 /* Also, before version 1 we stored directory timestamps in
832 * XTIMESTAMP documents instead of the current XDIRECTORY
833 * documents. So copy those as well. */
835 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
837 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
841 Xapian::PostingIterator p, p_end;
842 std::string term = *t;
844 p_end = notmuch->xapian_db->postlist_end (term);
846 for (p = notmuch->xapian_db->postlist_begin (term);
850 Xapian::Document document;
852 notmuch_directory_t *directory;
854 if (do_progress_notify) {
855 progress_notify (closure, (double) count / total);
856 do_progress_notify = 0;
859 document = find_document_for_doc_id (notmuch, *p);
860 mtime = Xapian::sortable_unserialise (
861 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
863 directory = notmuch_database_get_directory (notmuch,
865 notmuch_directory_set_mtime (directory, mtime);
866 notmuch_directory_destroy (directory);
871 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
874 /* Now that the upgrade is complete we can remove the old data
875 * and documents that are no longer needed. */
877 notmuch_query_t *query = notmuch_query_create (notmuch, "");
878 notmuch_messages_t *messages;
879 notmuch_message_t *message;
882 for (messages = notmuch_query_search_messages (query);
883 notmuch_messages_valid (messages);
884 notmuch_messages_move_to_next (messages))
886 if (do_progress_notify) {
887 progress_notify (closure, (double) count / total);
888 do_progress_notify = 0;
891 message = notmuch_messages_get (messages);
893 filename = _notmuch_message_talloc_copy_data (message);
894 if (filename && *filename != '\0') {
895 _notmuch_message_clear_data (message);
896 _notmuch_message_sync (message);
898 talloc_free (filename);
900 notmuch_message_destroy (message);
903 notmuch_query_destroy (query);
907 Xapian::TermIterator t, t_end;
909 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
911 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
915 Xapian::PostingIterator p, p_end;
916 std::string term = *t;
918 p_end = notmuch->xapian_db->postlist_end (term);
920 for (p = notmuch->xapian_db->postlist_begin (term);
924 if (do_progress_notify) {
925 progress_notify (closure, (double) count / total);
926 do_progress_notify = 0;
929 db->delete_document (*p);
934 if (timer_is_active) {
935 /* Now stop the timer. */
936 timerval.it_interval.tv_sec = 0;
937 timerval.it_interval.tv_usec = 0;
938 timerval.it_value.tv_sec = 0;
939 timerval.it_value.tv_usec = 0;
940 setitimer (ITIMER_REAL, &timerval, NULL);
942 /* And disable the signal handler. */
943 action.sa_handler = SIG_IGN;
944 sigaction (SIGALRM, &action, NULL);
947 return NOTMUCH_STATUS_SUCCESS;
950 /* We allow the user to use arbitrarily long paths for directories. But
951 * we have a term-length limit. So if we exceed that, we'll use the
952 * SHA-1 of the path for the database term.
954 * Note: This function may return the original value of 'path'. If it
955 * does not, then the caller is responsible to free() the returned
959 _notmuch_database_get_directory_db_path (const char *path)
961 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
963 if (term_len > NOTMUCH_TERM_MAX)
964 return notmuch_sha1_of_string (path);
969 /* Given a path, split it into two parts: the directory part is all
970 * components except for the last, and the basename is that last
971 * component. Getting the return-value for either part is optional
972 * (the caller can pass NULL).
974 * The original 'path' can represent either a regular file or a
975 * directory---the splitting will be carried out in the same way in
976 * either case. Trailing slashes on 'path' will be ignored, and any
977 * cases of multiple '/' characters appearing in series will be
978 * treated as a single '/'.
980 * Allocation (if any) will have 'ctx' as the talloc owner. But
981 * pointers will be returned within the original path string whenever
984 * Note: If 'path' is non-empty and contains no non-trailing slash,
985 * (that is, consists of a filename with no parent directory), then
986 * the directory returned will be an empty string. However, if 'path'
987 * is an empty string, then both directory and basename will be
991 _notmuch_database_split_path (void *ctx,
993 const char **directory,
994 const char **basename)
998 if (path == NULL || *path == '\0') {
1003 return NOTMUCH_STATUS_SUCCESS;
1006 /* Find the last slash (not counting a trailing slash), if any. */
1008 slash = path + strlen (path) - 1;
1010 /* First, skip trailing slashes. */
1011 while (slash != path) {
1018 /* Then, find a slash. */
1019 while (slash != path) {
1029 /* Finally, skip multiple slashes. */
1030 while (slash != path) {
1037 if (slash == path) {
1039 *directory = talloc_strdup (ctx, "");
1044 *directory = talloc_strndup (ctx, path, slash - path + 1);
1047 return NOTMUCH_STATUS_SUCCESS;
1051 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1053 unsigned int *directory_id)
1055 notmuch_directory_t *directory;
1056 notmuch_status_t status;
1060 return NOTMUCH_STATUS_SUCCESS;
1063 directory = _notmuch_directory_create (notmuch, path, &status);
1069 *directory_id = _notmuch_directory_get_document_id (directory);
1071 notmuch_directory_destroy (directory);
1073 return NOTMUCH_STATUS_SUCCESS;
1077 _notmuch_database_get_directory_path (void *ctx,
1078 notmuch_database_t *notmuch,
1079 unsigned int doc_id)
1081 Xapian::Document document;
1083 document = find_document_for_doc_id (notmuch, doc_id);
1085 return talloc_strdup (ctx, document.get_data ().c_str ());
1088 /* Given a legal 'filename' for the database, (either relative to
1089 * database path or absolute with initial components identical to
1090 * database path), return a new string (with 'ctx' as the talloc
1091 * owner) suitable for use as a direntry term value.
1093 * The necessary directory documents will be created in the database
1097 _notmuch_database_filename_to_direntry (void *ctx,
1098 notmuch_database_t *notmuch,
1099 const char *filename,
1102 const char *relative, *directory, *basename;
1103 Xapian::docid directory_id;
1104 notmuch_status_t status;
1106 relative = _notmuch_database_relative_path (notmuch, filename);
1108 status = _notmuch_database_split_path (ctx, relative,
1109 &directory, &basename);
1113 status = _notmuch_database_find_directory_id (notmuch, directory,
1118 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1120 return NOTMUCH_STATUS_SUCCESS;
1123 /* Given a legal 'path' for the database, return the relative path.
1125 * The return value will be a pointer to the originl path contents,
1126 * and will be either the original string (if 'path' was relative) or
1127 * a portion of the string (if path was absolute and begins with the
1131 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1134 const char *db_path, *relative;
1135 unsigned int db_path_len;
1137 db_path = notmuch_database_get_path (notmuch);
1138 db_path_len = strlen (db_path);
1142 if (*relative == '/') {
1143 while (*relative == '/' && *(relative+1) == '/')
1146 if (strncmp (relative, db_path, db_path_len) == 0)
1148 relative += db_path_len;
1149 while (*relative == '/')
1157 notmuch_directory_t *
1158 notmuch_database_get_directory (notmuch_database_t *notmuch,
1161 notmuch_status_t status;
1164 return _notmuch_directory_create (notmuch, path, &status);
1165 } catch (const Xapian::Error &error) {
1166 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1167 error.get_msg().c_str());
1168 notmuch->exception_reported = TRUE;
1173 /* Allocate a document ID that satisfies the following criteria:
1175 * 1. The ID does not exist for any document in the Xapian database
1177 * 2. The ID was not previously returned from this function
1179 * 3. The ID is the smallest integer satisfying (1) and (2)
1181 * This function will trigger an internal error if these constraints
1182 * cannot all be satisfied, (that is, the pool of available document
1183 * IDs has been exhausted).
1186 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1188 assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1190 notmuch->last_doc_id++;
1192 if (notmuch->last_doc_id == 0)
1193 INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1195 return notmuch->last_doc_id;
1199 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1201 /* 16 bytes (+ terminator) for hexadecimal representation of
1202 * a 64-bit integer. */
1203 static char thread_id[17];
1204 Xapian::WritableDatabase *db;
1206 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1208 notmuch->last_thread_id++;
1210 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1212 db->set_metadata ("last_thread_id", thread_id);
1218 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1220 return talloc_asprintf (ctx, "thread_id_%s", message_id);
1223 /* Find the thread ID to which the message with 'message_id' belongs.
1225 * Always returns a newly talloced string belonging to 'ctx'.
1227 * Note: If there is no message in the database with the given
1228 * 'message_id' then a new thread_id will be allocated for this
1229 * message and stored in the database metadata, (where this same
1230 * thread ID can be looked up if the message is added to the database
1234 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1236 const char *message_id)
1238 notmuch_message_t *message;
1239 string thread_id_string;
1240 const char *thread_id;
1242 Xapian::WritableDatabase *db;
1244 message = notmuch_database_find_message (notmuch, message_id);
1247 thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1249 notmuch_message_destroy (message);
1254 /* Message has not been seen yet.
1256 * We may have seen a reference to it already, in which case, we
1257 * can return the thread ID stored in the metadata. Otherwise, we
1258 * generate a new thread ID and store it there.
1260 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1261 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1262 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1264 if (thread_id_string.empty()) {
1265 thread_id = _notmuch_database_generate_thread_id (notmuch);
1266 db->set_metadata (metadata_key, thread_id);
1268 thread_id = thread_id_string.c_str();
1271 talloc_free (metadata_key);
1276 static notmuch_status_t
1277 _merge_threads (notmuch_database_t *notmuch,
1278 const char *winner_thread_id,
1279 const char *loser_thread_id)
1281 Xapian::PostingIterator loser, loser_end;
1282 notmuch_message_t *message = NULL;
1283 notmuch_private_status_t private_status;
1284 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1286 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1288 for ( ; loser != loser_end; loser++) {
1289 message = _notmuch_message_create (notmuch, notmuch,
1290 *loser, &private_status);
1291 if (message == NULL) {
1292 ret = COERCE_STATUS (private_status,
1293 "Cannot find document for doc_id from query");
1297 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1298 _notmuch_message_add_term (message, "thread", winner_thread_id);
1299 _notmuch_message_sync (message);
1301 notmuch_message_destroy (message);
1307 notmuch_message_destroy (message);
1313 _my_talloc_free_for_g_hash (void *ptr)
1318 static notmuch_status_t
1319 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1320 notmuch_message_t *message,
1321 notmuch_message_file_t *message_file,
1322 const char **thread_id)
1324 GHashTable *parents = NULL;
1325 const char *refs, *in_reply_to, *in_reply_to_message_id;
1326 GList *l, *keys = NULL;
1327 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1329 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1330 _my_talloc_free_for_g_hash, NULL);
1332 refs = notmuch_message_file_get_header (message_file, "references");
1333 parse_references (message, notmuch_message_get_message_id (message),
1336 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1337 parse_references (message, notmuch_message_get_message_id (message),
1338 parents, in_reply_to);
1340 /* Carefully avoid adding any self-referential in-reply-to term. */
1341 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1342 if (in_reply_to_message_id &&
1343 strcmp (in_reply_to_message_id,
1344 notmuch_message_get_message_id (message)))
1346 _notmuch_message_add_term (message, "replyto",
1347 _parse_message_id (message, in_reply_to, NULL));
1350 keys = g_hash_table_get_keys (parents);
1351 for (l = keys; l; l = l->next) {
1352 char *parent_message_id;
1353 const char *parent_thread_id;
1355 parent_message_id = (char *) l->data;
1357 _notmuch_message_add_term (message, "reference",
1360 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1364 if (*thread_id == NULL) {
1365 *thread_id = talloc_strdup (message, parent_thread_id);
1366 _notmuch_message_add_term (message, "thread", *thread_id);
1367 } else if (strcmp (*thread_id, parent_thread_id)) {
1368 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1378 g_hash_table_unref (parents);
1383 static notmuch_status_t
1384 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1385 notmuch_message_t *message,
1386 const char **thread_id)
1388 const char *message_id = notmuch_message_get_message_id (message);
1389 Xapian::PostingIterator child, children_end;
1390 notmuch_message_t *child_message = NULL;
1391 const char *child_thread_id;
1392 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1393 notmuch_private_status_t private_status;
1395 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1397 for ( ; child != children_end; child++) {
1399 child_message = _notmuch_message_create (message, notmuch,
1400 *child, &private_status);
1401 if (child_message == NULL) {
1402 ret = COERCE_STATUS (private_status,
1403 "Cannot find document for doc_id from query");
1407 child_thread_id = notmuch_message_get_thread_id (child_message);
1408 if (*thread_id == NULL) {
1409 *thread_id = talloc_strdup (message, child_thread_id);
1410 _notmuch_message_add_term (message, "thread", *thread_id);
1411 } else if (strcmp (*thread_id, child_thread_id)) {
1412 _notmuch_message_remove_term (child_message, "reference",
1414 _notmuch_message_sync (child_message);
1415 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1420 notmuch_message_destroy (child_message);
1421 child_message = NULL;
1426 notmuch_message_destroy (child_message);
1431 /* Given a (mostly empty) 'message' and its corresponding
1432 * 'message_file' link it to existing threads in the database.
1434 * The first check is in the metadata of the database to see if we
1435 * have pre-allocated a thread_id in advance for this message, (which
1436 * would have happened if a message was previously added that
1437 * referenced this one).
1439 * Second, we look at 'message_file' and its link-relevant headers
1440 * (References and In-Reply-To) for message IDs.
1442 * Finally, we look in the database for existing message that
1443 * reference 'message'.
1445 * In all cases, we assign to the current message the first thread_id
1446 * found (through either parent or child). We will also merge any
1447 * existing, distinct threads where this message belongs to both,
1448 * (which is not uncommon when mesages are processed out of order).
1450 * Finally, if no thread ID has been found through parent or child, we
1451 * call _notmuch_message_generate_thread_id to generate a new thread
1452 * ID. This should only happen for new, top-level messages, (no
1453 * References or In-Reply-To header in this message, and no previously
1454 * added message refers to this message).
1456 static notmuch_status_t
1457 _notmuch_database_link_message (notmuch_database_t *notmuch,
1458 notmuch_message_t *message,
1459 notmuch_message_file_t *message_file)
1461 notmuch_status_t status;
1462 const char *message_id, *thread_id = NULL;
1466 message_id = notmuch_message_get_message_id (message);
1467 metadata_key = _get_metadata_thread_id_key (message, message_id);
1469 /* Check if we have already seen related messages to this one.
1470 * If we have then use the thread_id that we stored at that time.
1472 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1473 if (! stored_id.empty()) {
1474 Xapian::WritableDatabase *db;
1476 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1478 /* Clear the metadata for this message ID. We don't need it
1480 db->set_metadata (metadata_key, "");
1481 thread_id = stored_id.c_str();
1483 _notmuch_message_add_term (message, "thread", thread_id);
1485 talloc_free (metadata_key);
1487 status = _notmuch_database_link_message_to_parents (notmuch, message,
1493 status = _notmuch_database_link_message_to_children (notmuch, message,
1498 /* If not part of any existing thread, generate a new thread ID. */
1499 if (thread_id == NULL) {
1500 thread_id = _notmuch_database_generate_thread_id (notmuch);
1502 _notmuch_message_add_term (message, "thread", thread_id);
1505 return NOTMUCH_STATUS_SUCCESS;
1509 notmuch_database_add_message (notmuch_database_t *notmuch,
1510 const char *filename,
1511 notmuch_message_t **message_ret)
1513 notmuch_message_file_t *message_file;
1514 notmuch_message_t *message = NULL;
1515 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1516 notmuch_private_status_t private_status;
1518 const char *date, *header;
1519 const char *from, *to, *subject;
1520 char *message_id = NULL;
1523 *message_ret = NULL;
1525 ret = _notmuch_database_ensure_writable (notmuch);
1529 message_file = notmuch_message_file_open (filename);
1530 if (message_file == NULL)
1531 return NOTMUCH_STATUS_FILE_ERROR;
1533 notmuch_message_file_restrict_headers (message_file,
1544 /* Before we do any real work, (especially before doing a
1545 * potential SHA-1 computation on the entire file's contents),
1546 * let's make sure that what we're looking at looks like an
1547 * actual email message.
1549 from = notmuch_message_file_get_header (message_file, "from");
1550 subject = notmuch_message_file_get_header (message_file, "subject");
1551 to = notmuch_message_file_get_header (message_file, "to");
1553 if ((from == NULL || *from == '\0') &&
1554 (subject == NULL || *subject == '\0') &&
1555 (to == NULL || *to == '\0'))
1557 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1561 /* Now that we're sure it's mail, the first order of business
1562 * is to find a message ID (or else create one ourselves). */
1564 header = notmuch_message_file_get_header (message_file, "message-id");
1565 if (header && *header != '\0') {
1566 message_id = _parse_message_id (message_file, header, NULL);
1568 /* So the header value isn't RFC-compliant, but it's
1569 * better than no message-id at all. */
1570 if (message_id == NULL)
1571 message_id = talloc_strdup (message_file, header);
1573 /* Reject a Message ID that's too long. */
1574 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1575 talloc_free (message_id);
1580 if (message_id == NULL ) {
1581 /* No message-id at all, let's generate one by taking a
1582 * hash over the file's contents. */
1583 char *sha1 = notmuch_sha1_of_file (filename);
1585 /* If that failed too, something is really wrong. Give up. */
1587 ret = NOTMUCH_STATUS_FILE_ERROR;
1591 message_id = talloc_asprintf (message_file,
1592 "notmuch-sha1-%s", sha1);
1596 /* Now that we have a message ID, we get a message object,
1597 * (which may or may not reference an existing document in the
1600 message = _notmuch_message_create_for_message_id (notmuch,
1604 talloc_free (message_id);
1606 if (message == NULL) {
1607 ret = COERCE_STATUS (private_status,
1608 "Unexpected status value from _notmuch_message_create_for_message_id");
1612 _notmuch_message_add_filename (message, filename);
1614 /* Is this a newly created message object? */
1615 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1616 _notmuch_message_add_term (message, "type", "mail");
1618 ret = _notmuch_database_link_message (notmuch, message,
1623 date = notmuch_message_file_get_header (message_file, "date");
1624 _notmuch_message_set_date (message, date);
1626 _notmuch_message_index_file (message, filename);
1628 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1631 _notmuch_message_sync (message);
1632 } catch (const Xapian::Error &error) {
1633 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1634 error.get_msg().c_str());
1635 notmuch->exception_reported = TRUE;
1636 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1642 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1643 *message_ret = message;
1645 notmuch_message_destroy (message);
1649 notmuch_message_file_close (message_file);
1655 notmuch_database_remove_message (notmuch_database_t *notmuch,
1656 const char *filename)
1658 Xapian::WritableDatabase *db;
1660 const char *prefix = _find_prefix ("file-direntry");
1661 char *direntry, *term;
1662 Xapian::PostingIterator i, end;
1663 Xapian::Document document;
1664 notmuch_status_t status;
1666 status = _notmuch_database_ensure_writable (notmuch);
1670 local = talloc_new (notmuch);
1672 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1676 status = _notmuch_database_filename_to_direntry (local, notmuch,
1677 filename, &direntry);
1681 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1683 find_doc_ids_for_term (notmuch, term, &i, &end);
1685 for ( ; i != end; i++) {
1686 Xapian::TermIterator j;
1688 document = find_document_for_doc_id (notmuch, *i);
1690 document.remove_term (term);
1692 j = document.termlist_begin ();
1695 /* Was this the last file-direntry in the message? */
1696 if (j == document.termlist_end () ||
1697 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1699 db->delete_document (document.get_docid ());
1700 status = NOTMUCH_STATUS_SUCCESS;
1702 db->replace_document (document.get_docid (), document);
1703 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1706 } catch (const Xapian::Error &error) {
1707 fprintf (stderr, "Error: A Xapian exception occurred removing message: %s\n",
1708 error.get_msg().c_str());
1709 notmuch->exception_reported = TRUE;
1710 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1713 talloc_free (local);
1719 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1720 Xapian::TermIterator &end)
1722 const char *prefix = _find_prefix ("tag");
1723 notmuch_tags_t *tags;
1726 /* Currently this iteration is written with the assumption that
1727 * "tag" has a single-character prefix. */
1728 assert (strlen (prefix) == 1);
1730 tags = _notmuch_tags_create (ctx);
1731 if (unlikely (tags == NULL))
1739 if (tag.empty () || tag[0] != *prefix)
1742 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1747 _notmuch_tags_prepare_iterator (tags);
1753 notmuch_database_get_all_tags (notmuch_database_t *db)
1755 Xapian::TermIterator i, end;
1758 i = db->xapian_db->allterms_begin();
1759 end = db->xapian_db->allterms_end();
1760 return _notmuch_convert_tags(db, i, end);
1761 } catch (const Xapian::Error &error) {
1762 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1763 error.get_msg().c_str());
1764 db->exception_reported = TRUE;