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 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
626 if (last_thread_id.empty ()) {
627 notmuch->last_thread_id = 0;
632 str = last_thread_id.c_str ();
633 notmuch->last_thread_id = strtoull (str, &end, 16);
635 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
638 notmuch->query_parser = new Xapian::QueryParser;
639 notmuch->term_gen = new Xapian::TermGenerator;
640 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
641 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
643 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
644 notmuch->query_parser->set_database (*notmuch->xapian_db);
645 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
646 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
647 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
649 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
650 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
651 notmuch->query_parser->add_boolean_prefix (prefix->name,
655 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
656 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
657 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
659 } catch (const Xapian::Error &error) {
660 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
661 error.get_msg().c_str());
675 notmuch_database_close (notmuch_database_t *notmuch)
678 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
679 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
680 } catch (const Xapian::Error &error) {
681 if (! notmuch->exception_reported) {
682 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
683 error.get_msg().c_str());
687 delete notmuch->term_gen;
688 delete notmuch->query_parser;
689 delete notmuch->xapian_db;
690 delete notmuch->value_range_processor;
691 talloc_free (notmuch);
695 notmuch_database_get_path (notmuch_database_t *notmuch)
697 return notmuch->path;
701 notmuch_database_get_version (notmuch_database_t *notmuch)
703 unsigned int version;
704 string version_string;
708 version_string = notmuch->xapian_db->get_metadata ("version");
709 if (version_string.empty ())
712 str = version_string.c_str ();
713 if (str == NULL || *str == '\0')
716 version = strtoul (str, &end, 10);
718 INTERNAL_ERROR ("Malformed database version: %s", str);
724 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
726 return notmuch->needs_upgrade;
729 static volatile sig_atomic_t do_progress_notify = 0;
732 handle_sigalrm (unused (int signal))
734 do_progress_notify = 1;
737 /* Upgrade the current database.
739 * After opening a database in read-write mode, the client should
740 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
741 * if so, upgrade with this function before making any modifications.
743 * The optional progress_notify callback can be used by the caller to
744 * provide progress indication to the user. If non-NULL it will be
745 * called periodically with 'count' as the number of messages upgraded
746 * so far and 'total' the overall number of messages that will be
750 notmuch_database_upgrade (notmuch_database_t *notmuch,
751 void (*progress_notify) (void *closure,
755 Xapian::WritableDatabase *db;
756 struct sigaction action;
757 struct itimerval timerval;
758 notmuch_bool_t timer_is_active = FALSE;
759 unsigned int version;
760 notmuch_status_t status;
761 unsigned int count = 0, total = 0;
763 status = _notmuch_database_ensure_writable (notmuch);
767 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
769 version = notmuch_database_get_version (notmuch);
771 if (version >= NOTMUCH_DATABASE_VERSION)
772 return NOTMUCH_STATUS_SUCCESS;
774 if (progress_notify) {
775 /* Setup our handler for SIGALRM */
776 memset (&action, 0, sizeof (struct sigaction));
777 action.sa_handler = handle_sigalrm;
778 sigemptyset (&action.sa_mask);
779 action.sa_flags = SA_RESTART;
780 sigaction (SIGALRM, &action, NULL);
782 /* Then start a timer to send SIGALRM once per second. */
783 timerval.it_interval.tv_sec = 1;
784 timerval.it_interval.tv_usec = 0;
785 timerval.it_value.tv_sec = 1;
786 timerval.it_value.tv_usec = 0;
787 setitimer (ITIMER_REAL, &timerval, NULL);
789 timer_is_active = TRUE;
792 /* Before version 1, each message document had its filename in the
793 * data field. Copy that into the new format by calling
794 * notmuch_message_add_filename.
797 notmuch_query_t *query = notmuch_query_create (notmuch, "");
798 notmuch_messages_t *messages;
799 notmuch_message_t *message;
801 Xapian::TermIterator t, t_end;
803 total = notmuch_query_count_messages (query);
805 for (messages = notmuch_query_search_messages (query);
806 notmuch_messages_valid (messages);
807 notmuch_messages_move_to_next (messages))
809 if (do_progress_notify) {
810 progress_notify (closure, (double) count / total);
811 do_progress_notify = 0;
814 message = notmuch_messages_get (messages);
816 filename = _notmuch_message_talloc_copy_data (message);
817 if (filename && *filename != '\0') {
818 _notmuch_message_add_filename (message, filename);
819 _notmuch_message_sync (message);
821 talloc_free (filename);
823 notmuch_message_destroy (message);
828 notmuch_query_destroy (query);
830 /* Also, before version 1 we stored directory timestamps in
831 * XTIMESTAMP documents instead of the current XDIRECTORY
832 * documents. So copy those as well. */
834 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
836 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
840 Xapian::PostingIterator p, p_end;
841 std::string term = *t;
843 p_end = notmuch->xapian_db->postlist_end (term);
845 for (p = notmuch->xapian_db->postlist_begin (term);
849 Xapian::Document document;
851 notmuch_directory_t *directory;
853 if (do_progress_notify) {
854 progress_notify (closure, (double) count / total);
855 do_progress_notify = 0;
858 document = find_document_for_doc_id (notmuch, *p);
859 mtime = Xapian::sortable_unserialise (
860 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
862 directory = notmuch_database_get_directory (notmuch,
864 notmuch_directory_set_mtime (directory, mtime);
865 notmuch_directory_destroy (directory);
870 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
873 /* Now that the upgrade is complete we can remove the old data
874 * and documents that are no longer needed. */
876 notmuch_query_t *query = notmuch_query_create (notmuch, "");
877 notmuch_messages_t *messages;
878 notmuch_message_t *message;
881 for (messages = notmuch_query_search_messages (query);
882 notmuch_messages_valid (messages);
883 notmuch_messages_move_to_next (messages))
885 if (do_progress_notify) {
886 progress_notify (closure, (double) count / total);
887 do_progress_notify = 0;
890 message = notmuch_messages_get (messages);
892 filename = _notmuch_message_talloc_copy_data (message);
893 if (filename && *filename != '\0') {
894 _notmuch_message_clear_data (message);
895 _notmuch_message_sync (message);
897 talloc_free (filename);
899 notmuch_message_destroy (message);
902 notmuch_query_destroy (query);
906 Xapian::TermIterator t, t_end;
908 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
910 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
914 Xapian::PostingIterator p, p_end;
915 std::string term = *t;
917 p_end = notmuch->xapian_db->postlist_end (term);
919 for (p = notmuch->xapian_db->postlist_begin (term);
923 if (do_progress_notify) {
924 progress_notify (closure, (double) count / total);
925 do_progress_notify = 0;
928 db->delete_document (*p);
933 if (timer_is_active) {
934 /* Now stop the timer. */
935 timerval.it_interval.tv_sec = 0;
936 timerval.it_interval.tv_usec = 0;
937 timerval.it_value.tv_sec = 0;
938 timerval.it_value.tv_usec = 0;
939 setitimer (ITIMER_REAL, &timerval, NULL);
941 /* And disable the signal handler. */
942 action.sa_handler = SIG_IGN;
943 sigaction (SIGALRM, &action, NULL);
946 return NOTMUCH_STATUS_SUCCESS;
949 /* We allow the user to use arbitrarily long paths for directories. But
950 * we have a term-length limit. So if we exceed that, we'll use the
951 * SHA-1 of the path for the database term.
953 * Note: This function may return the original value of 'path'. If it
954 * does not, then the caller is responsible to free() the returned
958 _notmuch_database_get_directory_db_path (const char *path)
960 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
962 if (term_len > NOTMUCH_TERM_MAX)
963 return notmuch_sha1_of_string (path);
968 /* Given a path, split it into two parts: the directory part is all
969 * components except for the last, and the basename is that last
970 * component. Getting the return-value for either part is optional
971 * (the caller can pass NULL).
973 * The original 'path' can represent either a regular file or a
974 * directory---the splitting will be carried out in the same way in
975 * either case. Trailing slashes on 'path' will be ignored, and any
976 * cases of multiple '/' characters appearing in series will be
977 * treated as a single '/'.
979 * Allocation (if any) will have 'ctx' as the talloc owner. But
980 * pointers will be returned within the original path string whenever
983 * Note: If 'path' is non-empty and contains no non-trailing slash,
984 * (that is, consists of a filename with no parent directory), then
985 * the directory returned will be an empty string. However, if 'path'
986 * is an empty string, then both directory and basename will be
990 _notmuch_database_split_path (void *ctx,
992 const char **directory,
993 const char **basename)
997 if (path == NULL || *path == '\0') {
1002 return NOTMUCH_STATUS_SUCCESS;
1005 /* Find the last slash (not counting a trailing slash), if any. */
1007 slash = path + strlen (path) - 1;
1009 /* First, skip trailing slashes. */
1010 while (slash != path) {
1017 /* Then, find a slash. */
1018 while (slash != path) {
1028 /* Finally, skip multiple slashes. */
1029 while (slash != path) {
1036 if (slash == path) {
1038 *directory = talloc_strdup (ctx, "");
1043 *directory = talloc_strndup (ctx, path, slash - path + 1);
1046 return NOTMUCH_STATUS_SUCCESS;
1050 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1052 unsigned int *directory_id)
1054 notmuch_directory_t *directory;
1055 notmuch_status_t status;
1059 return NOTMUCH_STATUS_SUCCESS;
1062 directory = _notmuch_directory_create (notmuch, path, &status);
1068 *directory_id = _notmuch_directory_get_document_id (directory);
1070 notmuch_directory_destroy (directory);
1072 return NOTMUCH_STATUS_SUCCESS;
1076 _notmuch_database_get_directory_path (void *ctx,
1077 notmuch_database_t *notmuch,
1078 unsigned int doc_id)
1080 Xapian::Document document;
1082 document = find_document_for_doc_id (notmuch, doc_id);
1084 return talloc_strdup (ctx, document.get_data ().c_str ());
1087 /* Given a legal 'filename' for the database, (either relative to
1088 * database path or absolute with initial components identical to
1089 * database path), return a new string (with 'ctx' as the talloc
1090 * owner) suitable for use as a direntry term value.
1092 * The necessary directory documents will be created in the database
1096 _notmuch_database_filename_to_direntry (void *ctx,
1097 notmuch_database_t *notmuch,
1098 const char *filename,
1101 const char *relative, *directory, *basename;
1102 Xapian::docid directory_id;
1103 notmuch_status_t status;
1105 relative = _notmuch_database_relative_path (notmuch, filename);
1107 status = _notmuch_database_split_path (ctx, relative,
1108 &directory, &basename);
1112 status = _notmuch_database_find_directory_id (notmuch, directory,
1117 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1119 return NOTMUCH_STATUS_SUCCESS;
1122 /* Given a legal 'path' for the database, return the relative path.
1124 * The return value will be a pointer to the originl path contents,
1125 * and will be either the original string (if 'path' was relative) or
1126 * a portion of the string (if path was absolute and begins with the
1130 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1133 const char *db_path, *relative;
1134 unsigned int db_path_len;
1136 db_path = notmuch_database_get_path (notmuch);
1137 db_path_len = strlen (db_path);
1141 if (*relative == '/') {
1142 while (*relative == '/' && *(relative+1) == '/')
1145 if (strncmp (relative, db_path, db_path_len) == 0)
1147 relative += db_path_len;
1148 while (*relative == '/')
1156 notmuch_directory_t *
1157 notmuch_database_get_directory (notmuch_database_t *notmuch,
1160 notmuch_status_t status;
1163 return _notmuch_directory_create (notmuch, path, &status);
1164 } catch (const Xapian::Error &error) {
1165 fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1166 error.get_msg().c_str());
1167 notmuch->exception_reported = TRUE;
1173 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1175 /* 16 bytes (+ terminator) for hexadecimal representation of
1176 * a 64-bit integer. */
1177 static char thread_id[17];
1178 Xapian::WritableDatabase *db;
1180 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1182 notmuch->last_thread_id++;
1184 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1186 db->set_metadata ("last_thread_id", thread_id);
1192 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1194 return talloc_asprintf (ctx, "thread_id_%s", message_id);
1197 /* Find the thread ID to which the message with 'message_id' belongs.
1199 * Always returns a newly talloced string belonging to 'ctx'.
1201 * Note: If there is no message in the database with the given
1202 * 'message_id' then a new thread_id will be allocated for this
1203 * message and stored in the database metadata, (where this same
1204 * thread ID can be looked up if the message is added to the database
1208 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1210 const char *message_id)
1212 notmuch_message_t *message;
1213 string thread_id_string;
1214 const char *thread_id;
1216 Xapian::WritableDatabase *db;
1218 message = notmuch_database_find_message (notmuch, message_id);
1221 thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1223 notmuch_message_destroy (message);
1228 /* Message has not been seen yet.
1230 * We may have seen a reference to it already, in which case, we
1231 * can return the thread ID stored in the metadata. Otherwise, we
1232 * generate a new thread ID and store it there.
1234 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1235 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1236 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1238 if (thread_id_string.empty()) {
1239 thread_id = _notmuch_database_generate_thread_id (notmuch);
1240 db->set_metadata (metadata_key, thread_id);
1242 thread_id = thread_id_string.c_str();
1245 talloc_free (metadata_key);
1250 static notmuch_status_t
1251 _merge_threads (notmuch_database_t *notmuch,
1252 const char *winner_thread_id,
1253 const char *loser_thread_id)
1255 Xapian::PostingIterator loser, loser_end;
1256 notmuch_message_t *message = NULL;
1257 notmuch_private_status_t private_status;
1258 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1260 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1262 for ( ; loser != loser_end; loser++) {
1263 message = _notmuch_message_create (notmuch, notmuch,
1264 *loser, &private_status);
1265 if (message == NULL) {
1266 ret = COERCE_STATUS (private_status,
1267 "Cannot find document for doc_id from query");
1271 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1272 _notmuch_message_add_term (message, "thread", winner_thread_id);
1273 _notmuch_message_sync (message);
1275 notmuch_message_destroy (message);
1281 notmuch_message_destroy (message);
1287 _my_talloc_free_for_g_hash (void *ptr)
1292 static notmuch_status_t
1293 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1294 notmuch_message_t *message,
1295 notmuch_message_file_t *message_file,
1296 const char **thread_id)
1298 GHashTable *parents = NULL;
1299 const char *refs, *in_reply_to, *in_reply_to_message_id;
1300 GList *l, *keys = NULL;
1301 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1303 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1304 _my_talloc_free_for_g_hash, NULL);
1306 refs = notmuch_message_file_get_header (message_file, "references");
1307 parse_references (message, notmuch_message_get_message_id (message),
1310 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1311 parse_references (message, notmuch_message_get_message_id (message),
1312 parents, in_reply_to);
1314 /* Carefully avoid adding any self-referential in-reply-to term. */
1315 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1316 if (in_reply_to_message_id &&
1317 strcmp (in_reply_to_message_id,
1318 notmuch_message_get_message_id (message)))
1320 _notmuch_message_add_term (message, "replyto",
1321 _parse_message_id (message, in_reply_to, NULL));
1324 keys = g_hash_table_get_keys (parents);
1325 for (l = keys; l; l = l->next) {
1326 char *parent_message_id;
1327 const char *parent_thread_id;
1329 parent_message_id = (char *) l->data;
1331 _notmuch_message_add_term (message, "reference",
1334 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1338 if (*thread_id == NULL) {
1339 *thread_id = talloc_strdup (message, parent_thread_id);
1340 _notmuch_message_add_term (message, "thread", *thread_id);
1341 } else if (strcmp (*thread_id, parent_thread_id)) {
1342 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1352 g_hash_table_unref (parents);
1357 static notmuch_status_t
1358 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1359 notmuch_message_t *message,
1360 const char **thread_id)
1362 const char *message_id = notmuch_message_get_message_id (message);
1363 Xapian::PostingIterator child, children_end;
1364 notmuch_message_t *child_message = NULL;
1365 const char *child_thread_id;
1366 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1367 notmuch_private_status_t private_status;
1369 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1371 for ( ; child != children_end; child++) {
1373 child_message = _notmuch_message_create (message, notmuch,
1374 *child, &private_status);
1375 if (child_message == NULL) {
1376 ret = COERCE_STATUS (private_status,
1377 "Cannot find document for doc_id from query");
1381 child_thread_id = notmuch_message_get_thread_id (child_message);
1382 if (*thread_id == NULL) {
1383 *thread_id = talloc_strdup (message, child_thread_id);
1384 _notmuch_message_add_term (message, "thread", *thread_id);
1385 } else if (strcmp (*thread_id, child_thread_id)) {
1386 _notmuch_message_remove_term (child_message, "reference",
1388 _notmuch_message_sync (child_message);
1389 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1394 notmuch_message_destroy (child_message);
1395 child_message = NULL;
1400 notmuch_message_destroy (child_message);
1405 /* Given a (mostly empty) 'message' and its corresponding
1406 * 'message_file' link it to existing threads in the database.
1408 * The first check is in the metadata of the database to see if we
1409 * have pre-allocated a thread_id in advance for this message, (which
1410 * would have happened if a message was previously added that
1411 * referenced this one).
1413 * Second, we look at 'message_file' and its link-relevant headers
1414 * (References and In-Reply-To) for message IDs.
1416 * Finally, we look in the database for existing message that
1417 * reference 'message'.
1419 * In all cases, we assign to the current message the first thread_id
1420 * found (through either parent or child). We will also merge any
1421 * existing, distinct threads where this message belongs to both,
1422 * (which is not uncommon when mesages are processed out of order).
1424 * Finally, if no thread ID has been found through parent or child, we
1425 * call _notmuch_message_generate_thread_id to generate a new thread
1426 * ID. This should only happen for new, top-level messages, (no
1427 * References or In-Reply-To header in this message, and no previously
1428 * added message refers to this message).
1430 static notmuch_status_t
1431 _notmuch_database_link_message (notmuch_database_t *notmuch,
1432 notmuch_message_t *message,
1433 notmuch_message_file_t *message_file)
1435 notmuch_status_t status;
1436 const char *message_id, *thread_id = NULL;
1440 message_id = notmuch_message_get_message_id (message);
1441 metadata_key = _get_metadata_thread_id_key (message, message_id);
1443 /* Check if we have already seen related messages to this one.
1444 * If we have then use the thread_id that we stored at that time.
1446 stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1447 if (! stored_id.empty()) {
1448 Xapian::WritableDatabase *db;
1450 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1452 /* Clear the metadata for this message ID. We don't need it
1454 db->set_metadata (metadata_key, "");
1455 thread_id = stored_id.c_str();
1457 _notmuch_message_add_term (message, "thread", thread_id);
1459 talloc_free (metadata_key);
1461 status = _notmuch_database_link_message_to_parents (notmuch, message,
1467 status = _notmuch_database_link_message_to_children (notmuch, message,
1472 /* If not part of any existing thread, generate a new thread ID. */
1473 if (thread_id == NULL) {
1474 thread_id = _notmuch_database_generate_thread_id (notmuch);
1476 _notmuch_message_add_term (message, "thread", thread_id);
1479 return NOTMUCH_STATUS_SUCCESS;
1483 notmuch_database_add_message (notmuch_database_t *notmuch,
1484 const char *filename,
1485 notmuch_message_t **message_ret)
1487 notmuch_message_file_t *message_file;
1488 notmuch_message_t *message = NULL;
1489 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1490 notmuch_private_status_t private_status;
1492 const char *date, *header;
1493 const char *from, *to, *subject;
1494 char *message_id = NULL;
1497 *message_ret = NULL;
1499 ret = _notmuch_database_ensure_writable (notmuch);
1503 message_file = notmuch_message_file_open (filename);
1504 if (message_file == NULL)
1505 return NOTMUCH_STATUS_FILE_ERROR;
1507 notmuch_message_file_restrict_headers (message_file,
1518 /* Before we do any real work, (especially before doing a
1519 * potential SHA-1 computation on the entire file's contents),
1520 * let's make sure that what we're looking at looks like an
1521 * actual email message.
1523 from = notmuch_message_file_get_header (message_file, "from");
1524 subject = notmuch_message_file_get_header (message_file, "subject");
1525 to = notmuch_message_file_get_header (message_file, "to");
1527 if ((from == NULL || *from == '\0') &&
1528 (subject == NULL || *subject == '\0') &&
1529 (to == NULL || *to == '\0'))
1531 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1535 /* Now that we're sure it's mail, the first order of business
1536 * is to find a message ID (or else create one ourselves). */
1538 header = notmuch_message_file_get_header (message_file, "message-id");
1539 if (header && *header != '\0') {
1540 message_id = _parse_message_id (message_file, header, NULL);
1542 /* So the header value isn't RFC-compliant, but it's
1543 * better than no message-id at all. */
1544 if (message_id == NULL)
1545 message_id = talloc_strdup (message_file, header);
1547 /* Reject a Message ID that's too long. */
1548 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1549 talloc_free (message_id);
1554 if (message_id == NULL ) {
1555 /* No message-id at all, let's generate one by taking a
1556 * hash over the file's contents. */
1557 char *sha1 = notmuch_sha1_of_file (filename);
1559 /* If that failed too, something is really wrong. Give up. */
1561 ret = NOTMUCH_STATUS_FILE_ERROR;
1565 message_id = talloc_asprintf (message_file,
1566 "notmuch-sha1-%s", sha1);
1570 /* Now that we have a message ID, we get a message object,
1571 * (which may or may not reference an existing document in the
1574 message = _notmuch_message_create_for_message_id (notmuch,
1578 talloc_free (message_id);
1580 if (message == NULL) {
1581 ret = COERCE_STATUS (private_status,
1582 "Unexpected status value from _notmuch_message_create_for_message_id");
1586 _notmuch_message_add_filename (message, filename);
1588 /* Is this a newly created message object? */
1589 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1590 _notmuch_message_add_term (message, "type", "mail");
1592 ret = _notmuch_database_link_message (notmuch, message,
1597 date = notmuch_message_file_get_header (message_file, "date");
1598 _notmuch_message_set_date (message, date);
1600 _notmuch_message_index_file (message, filename);
1602 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1605 _notmuch_message_sync (message);
1606 } catch (const Xapian::Error &error) {
1607 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1608 error.get_msg().c_str());
1609 notmuch->exception_reported = TRUE;
1610 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1616 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1617 *message_ret = message;
1619 notmuch_message_destroy (message);
1623 notmuch_message_file_close (message_file);
1629 notmuch_database_remove_message (notmuch_database_t *notmuch,
1630 const char *filename)
1632 Xapian::WritableDatabase *db;
1634 const char *prefix = _find_prefix ("file-direntry");
1635 char *direntry, *term;
1636 Xapian::PostingIterator i, end;
1637 Xapian::Document document;
1638 notmuch_status_t status;
1640 status = _notmuch_database_ensure_writable (notmuch);
1644 local = talloc_new (notmuch);
1646 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1650 status = _notmuch_database_filename_to_direntry (local, notmuch,
1651 filename, &direntry);
1655 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1657 find_doc_ids_for_term (notmuch, term, &i, &end);
1659 for ( ; i != end; i++) {
1660 Xapian::TermIterator j;
1662 document = find_document_for_doc_id (notmuch, *i);
1664 document.remove_term (term);
1666 j = document.termlist_begin ();
1669 /* Was this the last file-direntry in the message? */
1670 if (j == document.termlist_end () ||
1671 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1673 db->delete_document (document.get_docid ());
1674 status = NOTMUCH_STATUS_SUCCESS;
1676 db->replace_document (document.get_docid (), document);
1677 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1680 } catch (const Xapian::Error &error) {
1681 fprintf (stderr, "Error: A Xapian exception occurred removing message: %s\n",
1682 error.get_msg().c_str());
1683 notmuch->exception_reported = TRUE;
1684 status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1687 talloc_free (local);
1693 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1694 Xapian::TermIterator &end)
1696 const char *prefix = _find_prefix ("tag");
1697 notmuch_tags_t *tags;
1700 /* Currently this iteration is written with the assumption that
1701 * "tag" has a single-character prefix. */
1702 assert (strlen (prefix) == 1);
1704 tags = _notmuch_tags_create (ctx);
1705 if (unlikely (tags == NULL))
1713 if (tag.empty () || tag[0] != *prefix)
1716 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1721 _notmuch_tags_prepare_iterator (tags);
1727 notmuch_database_get_all_tags (notmuch_database_t *db)
1729 Xapian::TermIterator i, end;
1732 i = db->xapian_db->allterms_begin();
1733 end = db->xapian_db->allterms_end();
1734 return _notmuch_convert_tags(db, i, end);
1735 } catch (const Xapian::Error &error) {
1736 fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1737 error.get_msg().c_str());
1738 db->exception_reported = TRUE;