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;
344 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
345 message_id, &doc_id);
347 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
350 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
353 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
354 * a (potentially nested) parenthesized sequence with '\' used to
355 * escape any character (including parentheses).
357 * If the sequence to be skipped continues to the end of the string,
358 * then 'str' will be left pointing at the final terminating '\0'
362 skip_space_and_comments (const char **str)
367 while (*s && (isspace (*s) || *s == '(')) {
368 while (*s && isspace (*s))
373 while (*s && nesting) {
376 } else if (*s == ')') {
378 } else if (*s == '\\') {
390 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
391 * comments, and the '<' and '>' delimeters.
393 * If not NULL, then *next will be made to point to the first character
394 * not parsed, (possibly pointing to the final '\0' terminator.
396 * Returns a newly talloc'ed string belonging to 'ctx'.
398 * Returns NULL if there is any error parsing the message-id. */
400 _parse_message_id (void *ctx, const char *message_id, const char **next)
405 if (message_id == NULL || *message_id == '\0')
410 skip_space_and_comments (&s);
412 /* Skip any unstructured text as well. */
413 while (*s && *s != '<')
424 skip_space_and_comments (&s);
427 while (*end && *end != '>')
436 if (end > s && *end == '>')
441 result = talloc_strndup (ctx, s, end - s + 1);
443 /* Finally, collapse any whitespace that is within the message-id
449 for (r = result, len = strlen (r); *r; r++, len--)
450 if (*r == ' ' || *r == '\t')
451 memmove (r, r+1, len);
457 /* Parse a References header value, putting a (talloc'ed under 'ctx')
458 * copy of each referenced message-id into 'hash'.
460 * We explicitly avoid including any reference identical to
461 * 'message_id' in the result (to avoid mass confusion when a single
462 * message references itself cyclically---and yes, mail messages are
463 * not infrequent in the wild that do this---don't ask me why).
466 parse_references (void *ctx,
467 const char *message_id,
473 if (refs == NULL || *refs == '\0')
477 ref = _parse_message_id (ctx, refs, &refs);
479 if (ref && strcmp (ref, message_id))
480 g_hash_table_insert (hash, ref, NULL);
485 notmuch_database_create (const char *path)
487 notmuch_database_t *notmuch = NULL;
488 char *notmuch_path = NULL;
493 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
497 err = stat (path, &st);
499 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
500 path, strerror (errno));
504 if (! S_ISDIR (st.st_mode)) {
505 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
510 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
512 err = mkdir (notmuch_path, 0755);
515 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
516 notmuch_path, strerror (errno));
520 notmuch = notmuch_database_open (path,
521 NOTMUCH_DATABASE_MODE_READ_WRITE);
522 notmuch_database_upgrade (notmuch, NULL, NULL);
526 talloc_free (notmuch_path);
532 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
534 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
535 fprintf (stderr, "Cannot write to a read-only database.\n");
536 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
539 return NOTMUCH_STATUS_SUCCESS;
543 notmuch_database_open (const char *path,
544 notmuch_database_mode_t mode)
546 notmuch_database_t *notmuch = NULL;
547 char *notmuch_path = NULL, *xapian_path = NULL;
550 unsigned int i, version;
552 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
554 fprintf (stderr, "Out of memory\n");
558 err = stat (notmuch_path, &st);
560 fprintf (stderr, "Error opening database at %s: %s\n",
561 notmuch_path, strerror (errno));
565 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
567 fprintf (stderr, "Out of memory\n");
571 notmuch = talloc (NULL, notmuch_database_t);
572 notmuch->exception_reported = FALSE;
573 notmuch->path = talloc_strdup (notmuch, path);
575 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
576 notmuch->path[strlen (notmuch->path) - 1] = '\0';
578 notmuch->needs_upgrade = FALSE;
579 notmuch->mode = mode;
581 string last_thread_id;
583 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
584 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
585 Xapian::DB_CREATE_OR_OPEN);
586 version = notmuch_database_get_version (notmuch);
588 if (version > NOTMUCH_DATABASE_VERSION) {
590 "Error: Notmuch database at %s\n"
591 " has a newer database format version (%u) than supported by this\n"
592 " version of notmuch (%u). Refusing to open this database in\n"
593 " read-write mode.\n",
594 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
595 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
596 notmuch_database_close (notmuch);
601 if (version < NOTMUCH_DATABASE_VERSION)
602 notmuch->needs_upgrade = TRUE;
604 notmuch->xapian_db = new Xapian::Database (xapian_path);
605 version = notmuch_database_get_version (notmuch);
606 if (version > NOTMUCH_DATABASE_VERSION)
609 "Warning: Notmuch database at %s\n"
610 " has a newer database format version (%u) than supported by this\n"
611 " version of notmuch (%u). Some operations may behave incorrectly,\n"
612 " (but the database will not be harmed since it is being opened\n"
613 " in read-only mode).\n",
614 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
618 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
619 if (last_thread_id.empty ()) {
620 notmuch->last_thread_id = 0;
625 str = last_thread_id.c_str ();
626 notmuch->last_thread_id = strtoull (str, &end, 16);
628 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
631 notmuch->query_parser = new Xapian::QueryParser;
632 notmuch->term_gen = new Xapian::TermGenerator;
633 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
634 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
636 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
637 notmuch->query_parser->set_database (*notmuch->xapian_db);
638 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
639 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
640 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
642 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
643 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
644 notmuch->query_parser->add_boolean_prefix (prefix->name,
648 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
649 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
650 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
652 } catch (const Xapian::Error &error) {
653 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
654 error.get_msg().c_str());
668 notmuch_database_close (notmuch_database_t *notmuch)
671 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
672 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
673 } catch (const Xapian::Error &error) {
674 if (! notmuch->exception_reported) {
675 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
676 error.get_msg().c_str());
680 delete notmuch->term_gen;
681 delete notmuch->query_parser;
682 delete notmuch->xapian_db;
683 delete notmuch->value_range_processor;
684 talloc_free (notmuch);
688 notmuch_database_get_path (notmuch_database_t *notmuch)
690 return notmuch->path;
694 notmuch_database_get_version (notmuch_database_t *notmuch)
696 unsigned int version;
697 string version_string;
701 version_string = notmuch->xapian_db->get_metadata ("version");
702 if (version_string.empty ())
705 str = version_string.c_str ();
706 if (str == NULL || *str == '\0')
709 version = strtoul (str, &end, 10);
711 INTERNAL_ERROR ("Malformed database version: %s", str);
717 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
719 return notmuch->needs_upgrade;
722 static volatile sig_atomic_t do_progress_notify = 0;
725 handle_sigalrm (unused (int signal))
727 do_progress_notify = 1;
730 /* Upgrade the current database.
732 * After opening a database in read-write mode, the client should
733 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
734 * if so, upgrade with this function before making any modifications.
736 * The optional progress_notify callback can be used by the caller to
737 * provide progress indication to the user. If non-NULL it will be
738 * called periodically with 'count' as the number of messages upgraded
739 * so far and 'total' the overall number of messages that will be
743 notmuch_database_upgrade (notmuch_database_t *notmuch,
744 void (*progress_notify) (void *closure,
748 Xapian::WritableDatabase *db;
749 struct sigaction action;
750 struct itimerval timerval;
751 notmuch_bool_t timer_is_active = FALSE;
752 unsigned int version;
753 notmuch_status_t status;
754 unsigned int count = 0, total = 0;
756 status = _notmuch_database_ensure_writable (notmuch);
760 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
762 version = notmuch_database_get_version (notmuch);
764 if (version >= NOTMUCH_DATABASE_VERSION)
765 return NOTMUCH_STATUS_SUCCESS;
767 if (progress_notify) {
768 /* Setup our handler for SIGALRM */
769 memset (&action, 0, sizeof (struct sigaction));
770 action.sa_handler = handle_sigalrm;
771 sigemptyset (&action.sa_mask);
772 action.sa_flags = SA_RESTART;
773 sigaction (SIGALRM, &action, NULL);
775 /* Then start a timer to send SIGALRM once per second. */
776 timerval.it_interval.tv_sec = 1;
777 timerval.it_interval.tv_usec = 0;
778 timerval.it_value.tv_sec = 1;
779 timerval.it_value.tv_usec = 0;
780 setitimer (ITIMER_REAL, &timerval, NULL);
782 timer_is_active = TRUE;
785 /* Before version 1, each message document had its filename in the
786 * data field. Copy that into the new format by calling
787 * notmuch_message_add_filename.
790 notmuch_query_t *query = notmuch_query_create (notmuch, "");
791 notmuch_messages_t *messages;
792 notmuch_message_t *message;
794 Xapian::TermIterator t, t_end;
796 total = notmuch_query_count_messages (query);
798 for (messages = notmuch_query_search_messages (query);
799 notmuch_messages_valid (messages);
800 notmuch_messages_move_to_next (messages))
802 if (do_progress_notify) {
803 progress_notify (closure, (double) count / total);
804 do_progress_notify = 0;
807 message = notmuch_messages_get (messages);
809 filename = _notmuch_message_talloc_copy_data (message);
810 if (filename && *filename != '\0') {
811 _notmuch_message_add_filename (message, filename);
812 _notmuch_message_sync (message);
814 talloc_free (filename);
816 notmuch_message_destroy (message);
821 notmuch_query_destroy (query);
823 /* Also, before version 1 we stored directory timestamps in
824 * XTIMESTAMP documents instead of the current XDIRECTORY
825 * documents. So copy those as well. */
827 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
829 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
833 Xapian::PostingIterator p, p_end;
834 std::string term = *t;
836 p_end = notmuch->xapian_db->postlist_end (term);
838 for (p = notmuch->xapian_db->postlist_begin (term);
842 Xapian::Document document;
844 notmuch_directory_t *directory;
846 if (do_progress_notify) {
847 progress_notify (closure, (double) count / total);
848 do_progress_notify = 0;
851 document = find_document_for_doc_id (notmuch, *p);
852 mtime = Xapian::sortable_unserialise (
853 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
855 directory = notmuch_database_get_directory (notmuch,
857 notmuch_directory_set_mtime (directory, mtime);
858 notmuch_directory_destroy (directory);
863 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
866 /* Now that the upgrade is complete we can remove the old data
867 * and documents that are no longer needed. */
869 notmuch_query_t *query = notmuch_query_create (notmuch, "");
870 notmuch_messages_t *messages;
871 notmuch_message_t *message;
874 for (messages = notmuch_query_search_messages (query);
875 notmuch_messages_valid (messages);
876 notmuch_messages_move_to_next (messages))
878 if (do_progress_notify) {
879 progress_notify (closure, (double) count / total);
880 do_progress_notify = 0;
883 message = notmuch_messages_get (messages);
885 filename = _notmuch_message_talloc_copy_data (message);
886 if (filename && *filename != '\0') {
887 _notmuch_message_clear_data (message);
888 _notmuch_message_sync (message);
890 talloc_free (filename);
892 notmuch_message_destroy (message);
895 notmuch_query_destroy (query);
899 Xapian::TermIterator t, t_end;
901 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
903 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
907 Xapian::PostingIterator p, p_end;
908 std::string term = *t;
910 p_end = notmuch->xapian_db->postlist_end (term);
912 for (p = notmuch->xapian_db->postlist_begin (term);
916 if (do_progress_notify) {
917 progress_notify (closure, (double) count / total);
918 do_progress_notify = 0;
921 db->delete_document (*p);
926 if (timer_is_active) {
927 /* Now stop the timer. */
928 timerval.it_interval.tv_sec = 0;
929 timerval.it_interval.tv_usec = 0;
930 timerval.it_value.tv_sec = 0;
931 timerval.it_value.tv_usec = 0;
932 setitimer (ITIMER_REAL, &timerval, NULL);
934 /* And disable the signal handler. */
935 action.sa_handler = SIG_IGN;
936 sigaction (SIGALRM, &action, NULL);
939 return NOTMUCH_STATUS_SUCCESS;
942 /* We allow the user to use arbitrarily long paths for directories. But
943 * we have a term-length limit. So if we exceed that, we'll use the
944 * SHA-1 of the path for the database term.
946 * Note: This function may return the original value of 'path'. If it
947 * does not, then the caller is responsible to free() the returned
951 _notmuch_database_get_directory_db_path (const char *path)
953 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
955 if (term_len > NOTMUCH_TERM_MAX)
956 return notmuch_sha1_of_string (path);
961 /* Given a path, split it into two parts: the directory part is all
962 * components except for the last, and the basename is that last
963 * component. Getting the return-value for either part is optional
964 * (the caller can pass NULL).
966 * The original 'path' can represent either a regular file or a
967 * directory---the splitting will be carried out in the same way in
968 * either case. Trailing slashes on 'path' will be ignored, and any
969 * cases of multiple '/' characters appearing in series will be
970 * treated as a single '/'.
972 * Allocation (if any) will have 'ctx' as the talloc owner. But
973 * pointers will be returned within the original path string whenever
976 * Note: If 'path' is non-empty and contains no non-trailing slash,
977 * (that is, consists of a filename with no parent directory), then
978 * the directory returned will be an empty string. However, if 'path'
979 * is an empty string, then both directory and basename will be
983 _notmuch_database_split_path (void *ctx,
985 const char **directory,
986 const char **basename)
990 if (path == NULL || *path == '\0') {
995 return NOTMUCH_STATUS_SUCCESS;
998 /* Find the last slash (not counting a trailing slash), if any. */
1000 slash = path + strlen (path) - 1;
1002 /* First, skip trailing slashes. */
1003 while (slash != path) {
1010 /* Then, find a slash. */
1011 while (slash != path) {
1021 /* Finally, skip multiple slashes. */
1022 while (slash != path) {
1029 if (slash == path) {
1031 *directory = talloc_strdup (ctx, "");
1036 *directory = talloc_strndup (ctx, path, slash - path + 1);
1039 return NOTMUCH_STATUS_SUCCESS;
1043 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1045 unsigned int *directory_id)
1047 notmuch_directory_t *directory;
1048 notmuch_status_t status;
1052 return NOTMUCH_STATUS_SUCCESS;
1055 directory = _notmuch_directory_create (notmuch, path, &status);
1061 *directory_id = _notmuch_directory_get_document_id (directory);
1063 notmuch_directory_destroy (directory);
1065 return NOTMUCH_STATUS_SUCCESS;
1069 _notmuch_database_get_directory_path (void *ctx,
1070 notmuch_database_t *notmuch,
1071 unsigned int doc_id)
1073 Xapian::Document document;
1075 document = find_document_for_doc_id (notmuch, doc_id);
1077 return talloc_strdup (ctx, document.get_data ().c_str ());
1080 /* Given a legal 'filename' for the database, (either relative to
1081 * database path or absolute with initial components identical to
1082 * database path), return a new string (with 'ctx' as the talloc
1083 * owner) suitable for use as a direntry term value.
1085 * The necessary directory documents will be created in the database
1089 _notmuch_database_filename_to_direntry (void *ctx,
1090 notmuch_database_t *notmuch,
1091 const char *filename,
1094 const char *relative, *directory, *basename;
1095 Xapian::docid directory_id;
1096 notmuch_status_t status;
1098 relative = _notmuch_database_relative_path (notmuch, filename);
1100 status = _notmuch_database_split_path (ctx, relative,
1101 &directory, &basename);
1105 status = _notmuch_database_find_directory_id (notmuch, directory,
1110 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1112 return NOTMUCH_STATUS_SUCCESS;
1115 /* Given a legal 'path' for the database, return the relative path.
1117 * The return value will be a pointer to the originl path contents,
1118 * and will be either the original string (if 'path' was relative) or
1119 * a portion of the string (if path was absolute and begins with the
1123 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1126 const char *db_path, *relative;
1127 unsigned int db_path_len;
1129 db_path = notmuch_database_get_path (notmuch);
1130 db_path_len = strlen (db_path);
1134 if (*relative == '/') {
1135 while (*relative == '/' && *(relative+1) == '/')
1138 if (strncmp (relative, db_path, db_path_len) == 0)
1140 relative += db_path_len;
1141 while (*relative == '/')
1149 notmuch_directory_t *
1150 notmuch_database_get_directory (notmuch_database_t *notmuch,
1153 notmuch_status_t status;
1155 return _notmuch_directory_create (notmuch, path, &status);
1159 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1161 /* 16 bytes (+ terminator) for hexadecimal representation of
1162 * a 64-bit integer. */
1163 static char thread_id[17];
1164 Xapian::WritableDatabase *db;
1166 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1168 notmuch->last_thread_id++;
1170 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1172 db->set_metadata ("last_thread_id", thread_id);
1178 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1180 return talloc_asprintf (ctx, "thread_id_%s", message_id);
1183 /* Find the thread ID to which the message with 'message_id' belongs.
1185 * Always returns a newly talloced string belonging to 'ctx'.
1187 * Note: If there is no message in the database with the given
1188 * 'message_id' then a new thread_id will be allocated for this
1189 * message and stored in the database metadata, (where this same
1190 * thread ID can be looked up if the message is added to the database
1194 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1196 const char *message_id)
1198 notmuch_message_t *message;
1199 string thread_id_string;
1200 const char *thread_id;
1202 Xapian::WritableDatabase *db;
1204 message = notmuch_database_find_message (notmuch, message_id);
1207 thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1209 notmuch_message_destroy (message);
1214 /* Message has not been seen yet.
1216 * We may have seen a reference to it already, in which case, we
1217 * can return the thread ID stored in the metadata. Otherwise, we
1218 * generate a new thread ID and store it there.
1220 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1221 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1222 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1224 if (thread_id_string.empty()) {
1225 thread_id = _notmuch_database_generate_thread_id (notmuch);
1226 db->set_metadata (metadata_key, thread_id);
1228 thread_id = thread_id_string.c_str();
1231 talloc_free (metadata_key);
1236 static notmuch_status_t
1237 _merge_threads (notmuch_database_t *notmuch,
1238 const char *winner_thread_id,
1239 const char *loser_thread_id)
1241 Xapian::PostingIterator loser, loser_end;
1242 notmuch_message_t *message = NULL;
1243 notmuch_private_status_t private_status;
1244 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1246 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1248 for ( ; loser != loser_end; loser++) {
1249 message = _notmuch_message_create (notmuch, notmuch,
1250 *loser, &private_status);
1251 if (message == NULL) {
1252 ret = COERCE_STATUS (private_status,
1253 "Cannot find document for doc_id from query");
1257 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1258 _notmuch_message_add_term (message, "thread", winner_thread_id);
1259 _notmuch_message_sync (message);
1261 notmuch_message_destroy (message);
1267 notmuch_message_destroy (message);
1273 _my_talloc_free_for_g_hash (void *ptr)
1278 static notmuch_status_t
1279 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1280 notmuch_message_t *message,
1281 notmuch_message_file_t *message_file,
1282 const char **thread_id)
1284 GHashTable *parents = NULL;
1285 const char *refs, *in_reply_to, *in_reply_to_message_id;
1286 GList *l, *keys = NULL;
1287 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1289 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1290 _my_talloc_free_for_g_hash, NULL);
1292 refs = notmuch_message_file_get_header (message_file, "references");
1293 parse_references (message, notmuch_message_get_message_id (message),
1296 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1297 parse_references (message, notmuch_message_get_message_id (message),
1298 parents, in_reply_to);
1300 /* Carefully avoid adding any self-referential in-reply-to term. */
1301 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1302 if (in_reply_to_message_id &&
1303 strcmp (in_reply_to_message_id,
1304 notmuch_message_get_message_id (message)))
1306 _notmuch_message_add_term (message, "replyto",
1307 _parse_message_id (message, in_reply_to, NULL));
1310 keys = g_hash_table_get_keys (parents);
1311 for (l = keys; l; l = l->next) {
1312 char *parent_message_id;
1313 const char *parent_thread_id;
1315 parent_message_id = (char *) l->data;
1317 _notmuch_message_add_term (message, "reference",
1320 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1324 if (*thread_id == NULL) {
1325 *thread_id = talloc_strdup (message, parent_thread_id);
1326 _notmuch_message_add_term (message, "thread", *thread_id);
1327 } else if (strcmp (*thread_id, parent_thread_id)) {
1328 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1338 g_hash_table_unref (parents);
1343 static notmuch_status_t
1344 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1345 notmuch_message_t *message,
1346 const char **thread_id)
1348 const char *message_id = notmuch_message_get_message_id (message);
1349 Xapian::PostingIterator child, children_end;
1350 notmuch_message_t *child_message = NULL;
1351 const char *child_thread_id;
1352 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1353 notmuch_private_status_t private_status;
1355 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1357 for ( ; child != children_end; child++) {
1359 child_message = _notmuch_message_create (message, notmuch,
1360 *child, &private_status);
1361 if (child_message == NULL) {
1362 ret = COERCE_STATUS (private_status,
1363 "Cannot find document for doc_id from query");
1367 child_thread_id = notmuch_message_get_thread_id (child_message);
1368 if (*thread_id == NULL) {
1369 *thread_id = talloc_strdup (message, child_thread_id);
1370 _notmuch_message_add_term (message, "thread", *thread_id);
1371 } else if (strcmp (*thread_id, child_thread_id)) {
1372 _notmuch_message_remove_term (child_message, "reference",
1374 _notmuch_message_sync (child_message);
1375 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1380 notmuch_message_destroy (child_message);
1381 child_message = NULL;
1386 notmuch_message_destroy (child_message);
1391 /* Given a (mostly empty) 'message' and its corresponding
1392 * 'message_file' link it to existing threads in the database.
1394 * The first check is in the metadata of the database to see if we
1395 * have pre-allocated a thread_id in advance for this message, (which
1396 * would have happened if a message was previously added that
1397 * referenced this one).
1399 * Second, we look at 'message_file' and its link-relevant headers
1400 * (References and In-Reply-To) for message IDs.
1402 * Finally, we look in the database for existing message that
1403 * reference 'message'.
1405 * In all cases, we assign to the current message the first thread_id
1406 * found (through either parent or child). We will also merge any
1407 * existing, distinct threads where this message belongs to both,
1408 * (which is not uncommon when mesages are processed out of order).
1410 * Finally, if no thread ID has been found through parent or child, we
1411 * call _notmuch_message_generate_thread_id to generate a new thread
1412 * ID. This should only happen for new, top-level messages, (no
1413 * References or In-Reply-To header in this message, and no previously
1414 * added message refers to this message).
1416 static notmuch_status_t
1417 _notmuch_database_link_message (notmuch_database_t *notmuch,
1418 notmuch_message_t *message,
1419 notmuch_message_file_t *message_file)
1421 notmuch_status_t status;
1422 const char *message_id, *thread_id = NULL;
1426 message_id = notmuch_message_get_message_id (message);
1427 metadata_key = _get_metadata_thread_id_key (message, message_id);
1429 /* Check if we have already seen related messages to this one.
1430 * If we have then use the thread_id that we stored at that time.
1432 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1433 if (! stored_id.empty()) {
1434 Xapian::WritableDatabase *db;
1436 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1438 /* Clear the metadata for this message ID. We don't need it
1440 db->set_metadata (metadata_key, "");
1441 thread_id = stored_id.c_str();
1443 _notmuch_message_add_term (message, "thread", thread_id);
1445 talloc_free (metadata_key);
1447 status = _notmuch_database_link_message_to_parents (notmuch, message,
1453 status = _notmuch_database_link_message_to_children (notmuch, message,
1458 /* If not part of any existing thread, generate a new thread ID. */
1459 if (thread_id == NULL) {
1460 thread_id = _notmuch_database_generate_thread_id (notmuch);
1462 _notmuch_message_add_term (message, "thread", thread_id);
1465 return NOTMUCH_STATUS_SUCCESS;
1469 notmuch_database_add_message (notmuch_database_t *notmuch,
1470 const char *filename,
1471 notmuch_message_t **message_ret)
1473 notmuch_message_file_t *message_file;
1474 notmuch_message_t *message = NULL;
1475 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1476 notmuch_private_status_t private_status;
1478 const char *date, *header;
1479 const char *from, *to, *subject;
1480 char *message_id = NULL;
1483 *message_ret = NULL;
1485 ret = _notmuch_database_ensure_writable (notmuch);
1489 message_file = notmuch_message_file_open (filename);
1490 if (message_file == NULL)
1491 return NOTMUCH_STATUS_FILE_ERROR;
1493 notmuch_message_file_restrict_headers (message_file,
1504 /* Before we do any real work, (especially before doing a
1505 * potential SHA-1 computation on the entire file's contents),
1506 * let's make sure that what we're looking at looks like an
1507 * actual email message.
1509 from = notmuch_message_file_get_header (message_file, "from");
1510 subject = notmuch_message_file_get_header (message_file, "subject");
1511 to = notmuch_message_file_get_header (message_file, "to");
1513 if ((from == NULL || *from == '\0') &&
1514 (subject == NULL || *subject == '\0') &&
1515 (to == NULL || *to == '\0'))
1517 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1521 /* Now that we're sure it's mail, the first order of business
1522 * is to find a message ID (or else create one ourselves). */
1524 header = notmuch_message_file_get_header (message_file, "message-id");
1525 if (header && *header != '\0') {
1526 message_id = _parse_message_id (message_file, header, NULL);
1528 /* So the header value isn't RFC-compliant, but it's
1529 * better than no message-id at all. */
1530 if (message_id == NULL)
1531 message_id = talloc_strdup (message_file, header);
1533 /* Reject a Message ID that's too long. */
1534 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1535 talloc_free (message_id);
1540 if (message_id == NULL ) {
1541 /* No message-id at all, let's generate one by taking a
1542 * hash over the file's contents. */
1543 char *sha1 = notmuch_sha1_of_file (filename);
1545 /* If that failed too, something is really wrong. Give up. */
1547 ret = NOTMUCH_STATUS_FILE_ERROR;
1551 message_id = talloc_asprintf (message_file,
1552 "notmuch-sha1-%s", sha1);
1556 /* Now that we have a message ID, we get a message object,
1557 * (which may or may not reference an existing document in the
1560 message = _notmuch_message_create_for_message_id (notmuch,
1564 talloc_free (message_id);
1566 if (message == NULL) {
1567 ret = COERCE_STATUS (private_status,
1568 "Unexpected status value from _notmuch_message_create_for_message_id");
1572 _notmuch_message_add_filename (message, filename);
1574 /* Is this a newly created message object? */
1575 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1576 _notmuch_message_add_term (message, "type", "mail");
1578 ret = _notmuch_database_link_message (notmuch, message,
1583 date = notmuch_message_file_get_header (message_file, "date");
1584 _notmuch_message_set_date (message, date);
1586 _notmuch_message_index_file (message, filename);
1588 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1591 _notmuch_message_sync (message);
1592 } catch (const Xapian::Error &error) {
1593 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1594 error.get_description().c_str());
1595 notmuch->exception_reported = TRUE;
1596 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1602 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1603 *message_ret = message;
1605 notmuch_message_destroy (message);
1609 notmuch_message_file_close (message_file);
1615 notmuch_database_remove_message (notmuch_database_t *notmuch,
1616 const char *filename)
1618 Xapian::WritableDatabase *db;
1619 void *local = talloc_new (notmuch);
1620 const char *prefix = _find_prefix ("file-direntry");
1621 char *direntry, *term;
1622 Xapian::PostingIterator i, end;
1623 Xapian::Document document;
1624 notmuch_status_t status;
1626 status = _notmuch_database_ensure_writable (notmuch);
1630 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1632 status = _notmuch_database_filename_to_direntry (local, notmuch,
1633 filename, &direntry);
1637 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1639 find_doc_ids_for_term (notmuch, term, &i, &end);
1641 for ( ; i != end; i++) {
1642 Xapian::TermIterator j;
1644 document = find_document_for_doc_id (notmuch, *i);
1646 document.remove_term (term);
1648 j = document.termlist_begin ();
1651 /* Was this the last file-direntry in the message? */
1652 if (j == document.termlist_end () ||
1653 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1655 db->delete_document (document.get_docid ());
1656 status = NOTMUCH_STATUS_SUCCESS;
1658 db->replace_document (document.get_docid (), document);
1659 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1663 talloc_free (local);
1669 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1670 Xapian::TermIterator &end)
1672 const char *prefix = _find_prefix ("tag");
1673 notmuch_tags_t *tags;
1676 /* Currently this iteration is written with the assumption that
1677 * "tag" has a single-character prefix. */
1678 assert (strlen (prefix) == 1);
1680 tags = _notmuch_tags_create (ctx);
1681 if (unlikely (tags == NULL))
1689 if (tag.empty () || tag[0] != *prefix)
1692 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1697 _notmuch_tags_prepare_iterator (tags);
1703 notmuch_database_get_all_tags (notmuch_database_t *db)
1705 Xapian::TermIterator i, end;
1706 i = db->xapian_db->allterms_begin();
1707 end = db->xapian_db->allterms_end();
1708 return _notmuch_convert_tags(db, i, end);