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 directory.
51 * A mail document is associated with a particular email message file
52 * on disk. It is indexed with the following prefixed terms which the
53 * database uses to construct threads, etc.:
55 * Single terms of given prefix:
59 * id: Unique ID of mail, (from Message-ID header or generated
60 * as "notmuch-sha1-<sha1_sum_of_entire_file>.
62 * thread: The ID of the thread to which the mail belongs
64 * replyto: The ID from the In-Reply-To header of the mail (if any).
66 * Multiple terms of given prefix:
68 * reference: All message IDs from In-Reply-To and Re ferences
69 * headers in the message.
71 * tag: Any tags associated with this message by the user.
73 * file-direntry: A colon-separated pair of values
74 * (INTEGER:STRING), where INTEGER is the
75 * document ID of a directory document, and
76 * STRING is the name of a file within that
77 * directory for this mail message.
79 * A mail document also has two values:
81 * TIMESTAMP: The time_t value corresponding to the message's
84 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
86 * In addition, terms from the content of the message are added with
87 * "from", "to", "attachment", and "subject" prefixes for use by the
88 * user in searching. But the database doesn't really care itself
91 * The data portion of a mail document is empty.
95 * A directory document is used by a client of the notmuch library to
96 * maintain data necessary to allow for efficient polling of mail
99 * All directory documents contain one term:
101 * directory: The directory path (relative to the database path)
102 * Or the SHA1 sum of the directory path (if the
103 * path itself is too long to fit in a Xapian
106 * And all directory documents for directories other than top-level
107 * directories also contain the following term:
109 * directory-direntry: A colon-separated pair of values
110 * (INTEGER:STRING), where INTEGER is the
111 * document ID of the parent directory
112 * document, and STRING is the name of this
113 * directory within that parent.
115 * All directory documents have a single value:
117 * TIMESTAMP: The mtime of the directory (at last scan)
119 * The data portion of a directory document contains the path of the
120 * directory (relative to the database path).
123 /* With these prefix values we follow the conventions published here:
125 * http://xapian.org/docs/omega/termprefixes.html
127 * as much as makes sense. Note that I took some liberty in matching
128 * the reserved prefix values to notmuch concepts, (for example, 'G'
129 * is documented as "newsGroup (or similar entity - e.g. a web forum
130 * name)", for which I think the thread is the closest analogue in
131 * notmuch. This in spite of the fact that we will eventually be
132 * storing mailing-list messages where 'G' for "mailing list name"
133 * might be even a closer analogue. I'm treating the single-character
134 * prefixes preferentially for core notmuch concepts (which will be
135 * nearly universal to all mail messages).
138 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
140 { "reference", "XREFERENCE" },
141 { "replyto", "XREPLYTO" },
142 { "directory", "XDIRECTORY" },
143 { "file-direntry", "XFDIRENTRY" },
144 { "directory-direntry", "XDDIRENTRY" },
147 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
153 prefix_t PROBABILISTIC_PREFIX[]= {
156 { "attachment", "XATTACHMENT" },
157 { "subject", "XSUBJECT"}
161 _internal_error (const char *format, ...)
165 va_start (va_args, format);
167 fprintf (stderr, "Internal error: ");
168 vfprintf (stderr, format, va_args);
176 _find_prefix (const char *name)
180 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
181 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
182 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
185 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
186 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
187 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
190 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
191 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
192 return PROBABILISTIC_PREFIX[i].prefix;
195 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
201 notmuch_status_to_string (notmuch_status_t status)
204 case NOTMUCH_STATUS_SUCCESS:
205 return "No error occurred";
206 case NOTMUCH_STATUS_OUT_OF_MEMORY:
207 return "Out of memory";
208 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
209 return "Attempt to write to a read-only database";
210 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
211 return "A Xapian exception occurred";
212 case NOTMUCH_STATUS_FILE_ERROR:
213 return "Something went wrong trying to read or write a file";
214 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
215 return "File is not an email";
216 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
217 return "Message ID is identical to a message in database";
218 case NOTMUCH_STATUS_NULL_POINTER:
219 return "Erroneous NULL pointer";
220 case NOTMUCH_STATUS_TAG_TOO_LONG:
221 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
222 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
223 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
225 case NOTMUCH_STATUS_LAST_STATUS:
226 return "Unknown error status value";
231 find_doc_ids_for_term (notmuch_database_t *notmuch,
233 Xapian::PostingIterator *begin,
234 Xapian::PostingIterator *end)
236 *begin = notmuch->xapian_db->postlist_begin (term);
238 *end = notmuch->xapian_db->postlist_end (term);
242 find_doc_ids (notmuch_database_t *notmuch,
243 const char *prefix_name,
245 Xapian::PostingIterator *begin,
246 Xapian::PostingIterator *end)
250 term = talloc_asprintf (notmuch, "%s%s",
251 _find_prefix (prefix_name), value);
253 find_doc_ids_for_term (notmuch, term, begin, end);
258 notmuch_private_status_t
259 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
260 const char *prefix_name,
262 unsigned int *doc_id)
264 Xapian::PostingIterator i, end;
266 find_doc_ids (notmuch, prefix_name, value, &i, &end);
270 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
275 #if DEBUG_DATABASE_SANITY
279 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
283 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
286 static Xapian::Document
287 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
289 return notmuch->xapian_db->get_document (doc_id);
293 notmuch_database_find_message (notmuch_database_t *notmuch,
294 const char *message_id)
296 notmuch_private_status_t status;
299 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
300 message_id, &doc_id);
302 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
305 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
308 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
309 * a (potentially nested) parenthesized sequence with '\' used to
310 * escape any character (including parentheses).
312 * If the sequence to be skipped continues to the end of the string,
313 * then 'str' will be left pointing at the final terminating '\0'
317 skip_space_and_comments (const char **str)
322 while (*s && (isspace (*s) || *s == '(')) {
323 while (*s && isspace (*s))
328 while (*s && nesting) {
331 } else if (*s == ')') {
333 } else if (*s == '\\') {
345 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
346 * comments, and the '<' and '>' delimeters.
348 * If not NULL, then *next will be made to point to the first character
349 * not parsed, (possibly pointing to the final '\0' terminator.
351 * Returns a newly talloc'ed string belonging to 'ctx'.
353 * Returns NULL if there is any error parsing the message-id. */
355 _parse_message_id (void *ctx, const char *message_id, const char **next)
360 if (message_id == NULL || *message_id == '\0')
365 skip_space_and_comments (&s);
367 /* Skip any unstructured text as well. */
368 while (*s && *s != '<')
379 skip_space_and_comments (&s);
382 while (*end && *end != '>')
391 if (end > s && *end == '>')
396 result = talloc_strndup (ctx, s, end - s + 1);
398 /* Finally, collapse any whitespace that is within the message-id
404 for (r = result, len = strlen (r); *r; r++, len--)
405 if (*r == ' ' || *r == '\t')
406 memmove (r, r+1, len);
412 /* Parse a References header value, putting a (talloc'ed under 'ctx')
413 * copy of each referenced message-id into 'hash'.
415 * We explicitly avoid including any reference identical to
416 * 'message_id' in the result (to avoid mass confusion when a single
417 * message references itself cyclically---and yes, mail messages are
418 * not infrequent in the wild that do this---don't ask me why).
421 parse_references (void *ctx,
422 const char *message_id,
428 if (refs == NULL || *refs == '\0')
432 ref = _parse_message_id (ctx, refs, &refs);
434 if (ref && strcmp (ref, message_id))
435 g_hash_table_insert (hash, ref, NULL);
440 notmuch_database_create (const char *path)
442 notmuch_database_t *notmuch = NULL;
443 char *notmuch_path = NULL;
448 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
452 err = stat (path, &st);
454 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
455 path, strerror (errno));
459 if (! S_ISDIR (st.st_mode)) {
460 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
465 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
467 err = mkdir (notmuch_path, 0755);
470 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
471 notmuch_path, strerror (errno));
475 notmuch = notmuch_database_open (path,
476 NOTMUCH_DATABASE_MODE_READ_WRITE);
477 notmuch_database_upgrade (notmuch, NULL, NULL);
481 talloc_free (notmuch_path);
487 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
489 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
490 fprintf (stderr, "Cannot write to a read-only database.\n");
491 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
494 return NOTMUCH_STATUS_SUCCESS;
498 notmuch_database_open (const char *path,
499 notmuch_database_mode_t mode)
501 notmuch_database_t *notmuch = NULL;
502 char *notmuch_path = NULL, *xapian_path = NULL;
505 unsigned int i, version;
507 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
509 fprintf (stderr, "Out of memory\n");
513 err = stat (notmuch_path, &st);
515 fprintf (stderr, "Error opening database at %s: %s\n",
516 notmuch_path, strerror (errno));
520 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
522 fprintf (stderr, "Out of memory\n");
526 notmuch = talloc (NULL, notmuch_database_t);
527 notmuch->exception_reported = FALSE;
528 notmuch->path = talloc_strdup (notmuch, path);
530 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
531 notmuch->path[strlen (notmuch->path) - 1] = '\0';
533 notmuch->needs_upgrade = FALSE;
534 notmuch->mode = mode;
536 string last_thread_id;
538 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
539 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
540 Xapian::DB_CREATE_OR_OPEN);
541 version = notmuch_database_get_version (notmuch);
543 if (version > NOTMUCH_DATABASE_VERSION) {
545 "Error: Notmuch database at %s\n"
546 " has a newer database format version (%u) than supported by this\n"
547 " version of notmuch (%u). Refusing to open this database in\n"
548 " read-write mode.\n",
549 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
550 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
551 notmuch_database_close (notmuch);
556 if (version < NOTMUCH_DATABASE_VERSION)
557 notmuch->needs_upgrade = TRUE;
559 notmuch->xapian_db = new Xapian::Database (xapian_path);
560 version = notmuch_database_get_version (notmuch);
561 if (version > NOTMUCH_DATABASE_VERSION)
564 "Warning: Notmuch database at %s\n"
565 " has a newer database format version (%u) than supported by this\n"
566 " version of notmuch (%u). Some operations may behave incorrectly,\n"
567 " (but the database will not be harmed since it is being opened\n"
568 " in read-only mode).\n",
569 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
573 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
574 if (last_thread_id.empty ()) {
575 notmuch->last_thread_id = 0;
580 str = last_thread_id.c_str ();
581 notmuch->last_thread_id = strtoull (str, &end, 16);
583 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
586 notmuch->query_parser = new Xapian::QueryParser;
587 notmuch->term_gen = new Xapian::TermGenerator;
588 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
589 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
591 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
592 notmuch->query_parser->set_database (*notmuch->xapian_db);
593 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
594 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
595 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
597 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
598 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
599 notmuch->query_parser->add_boolean_prefix (prefix->name,
603 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
604 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
605 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
607 } catch (const Xapian::Error &error) {
608 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
609 error.get_msg().c_str());
623 notmuch_database_close (notmuch_database_t *notmuch)
626 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
627 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
628 } catch (const Xapian::Error &error) {
629 if (! notmuch->exception_reported) {
630 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
631 error.get_msg().c_str());
635 delete notmuch->term_gen;
636 delete notmuch->query_parser;
637 delete notmuch->xapian_db;
638 delete notmuch->value_range_processor;
639 talloc_free (notmuch);
643 notmuch_database_get_path (notmuch_database_t *notmuch)
645 return notmuch->path;
649 notmuch_database_get_version (notmuch_database_t *notmuch)
651 unsigned int version;
652 string version_string;
656 version_string = notmuch->xapian_db->get_metadata ("version");
657 if (version_string.empty ())
660 str = version_string.c_str ();
661 if (str == NULL || *str == '\0')
664 version = strtoul (str, &end, 10);
666 INTERNAL_ERROR ("Malformed database version: %s", str);
672 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
674 return notmuch->needs_upgrade;
677 static volatile sig_atomic_t do_progress_notify = 0;
680 handle_sigalrm (unused (int signal))
682 do_progress_notify = 1;
685 /* Upgrade the current database.
687 * After opening a database in read-write mode, the client should
688 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
689 * if so, upgrade with this function before making any modifications.
691 * The optional progress_notify callback can be used by the caller to
692 * provide progress indication to the user. If non-NULL it will be
693 * called periodically with 'count' as the number of messages upgraded
694 * so far and 'total' the overall number of messages that will be
698 notmuch_database_upgrade (notmuch_database_t *notmuch,
699 void (*progress_notify) (void *closure,
703 Xapian::WritableDatabase *db;
704 struct sigaction action;
705 struct itimerval timerval;
706 notmuch_bool_t timer_is_active = FALSE;
707 unsigned int version;
708 notmuch_status_t status;
709 unsigned int count = 0, total = 0;
711 status = _notmuch_database_ensure_writable (notmuch);
715 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
717 version = notmuch_database_get_version (notmuch);
719 if (version >= NOTMUCH_DATABASE_VERSION)
720 return NOTMUCH_STATUS_SUCCESS;
722 if (progress_notify) {
723 /* Setup our handler for SIGALRM */
724 memset (&action, 0, sizeof (struct sigaction));
725 action.sa_handler = handle_sigalrm;
726 sigemptyset (&action.sa_mask);
727 action.sa_flags = SA_RESTART;
728 sigaction (SIGALRM, &action, NULL);
730 /* Then start a timer to send SIGALRM once per second. */
731 timerval.it_interval.tv_sec = 1;
732 timerval.it_interval.tv_usec = 0;
733 timerval.it_value.tv_sec = 1;
734 timerval.it_value.tv_usec = 0;
735 setitimer (ITIMER_REAL, &timerval, NULL);
737 timer_is_active = TRUE;
740 /* Before version 1, each message document had its filename in the
741 * data field. Copy that into the new format by calling
742 * notmuch_message_add_filename.
745 notmuch_query_t *query = notmuch_query_create (notmuch, "");
746 notmuch_messages_t *messages;
747 notmuch_message_t *message;
749 Xapian::TermIterator t, t_end;
751 total = notmuch_query_count_messages (query);
753 for (messages = notmuch_query_search_messages (query);
754 notmuch_messages_valid (messages);
755 notmuch_messages_move_to_next (messages))
757 if (do_progress_notify) {
758 progress_notify (closure, (double) count / total);
759 do_progress_notify = 0;
762 message = notmuch_messages_get (messages);
764 filename = _notmuch_message_talloc_copy_data (message);
765 if (filename && *filename != '\0') {
766 _notmuch_message_add_filename (message, filename);
767 _notmuch_message_sync (message);
769 talloc_free (filename);
771 notmuch_message_destroy (message);
776 notmuch_query_destroy (query);
778 /* Also, before version 1 we stored directory timestamps in
779 * XTIMESTAMP documents instead of the current XDIRECTORY
780 * documents. So copy those as well. */
782 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
784 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
788 Xapian::PostingIterator p, p_end;
789 std::string term = *t;
791 p_end = notmuch->xapian_db->postlist_end (term);
793 for (p = notmuch->xapian_db->postlist_begin (term);
797 Xapian::Document document;
799 notmuch_directory_t *directory;
801 if (do_progress_notify) {
802 progress_notify (closure, (double) count / total);
803 do_progress_notify = 0;
806 document = find_document_for_doc_id (notmuch, *p);
807 mtime = Xapian::sortable_unserialise (
808 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
810 directory = notmuch_database_get_directory (notmuch,
812 notmuch_directory_set_mtime (directory, mtime);
813 notmuch_directory_destroy (directory);
818 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
821 /* Now that the upgrade is complete we can remove the old data
822 * and documents that are no longer needed. */
824 notmuch_query_t *query = notmuch_query_create (notmuch, "");
825 notmuch_messages_t *messages;
826 notmuch_message_t *message;
829 for (messages = notmuch_query_search_messages (query);
830 notmuch_messages_valid (messages);
831 notmuch_messages_move_to_next (messages))
833 if (do_progress_notify) {
834 progress_notify (closure, (double) count / total);
835 do_progress_notify = 0;
838 message = notmuch_messages_get (messages);
840 filename = _notmuch_message_talloc_copy_data (message);
841 if (filename && *filename != '\0') {
842 _notmuch_message_clear_data (message);
843 _notmuch_message_sync (message);
845 talloc_free (filename);
847 notmuch_message_destroy (message);
850 notmuch_query_destroy (query);
854 Xapian::TermIterator t, t_end;
856 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
858 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
862 Xapian::PostingIterator p, p_end;
863 std::string term = *t;
865 p_end = notmuch->xapian_db->postlist_end (term);
867 for (p = notmuch->xapian_db->postlist_begin (term);
871 if (do_progress_notify) {
872 progress_notify (closure, (double) count / total);
873 do_progress_notify = 0;
876 db->delete_document (*p);
881 if (timer_is_active) {
882 /* Now stop the timer. */
883 timerval.it_interval.tv_sec = 0;
884 timerval.it_interval.tv_usec = 0;
885 timerval.it_value.tv_sec = 0;
886 timerval.it_value.tv_usec = 0;
887 setitimer (ITIMER_REAL, &timerval, NULL);
889 /* And disable the signal handler. */
890 action.sa_handler = SIG_IGN;
891 sigaction (SIGALRM, &action, NULL);
894 return NOTMUCH_STATUS_SUCCESS;
897 /* We allow the user to use arbitrarily long paths for directories. But
898 * we have a term-length limit. So if we exceed that, we'll use the
899 * SHA-1 of the path for the database term.
901 * Note: This function may return the original value of 'path'. If it
902 * does not, then the caller is responsible to free() the returned
906 _notmuch_database_get_directory_db_path (const char *path)
908 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
910 if (term_len > NOTMUCH_TERM_MAX)
911 return notmuch_sha1_of_string (path);
916 /* Given a path, split it into two parts: the directory part is all
917 * components except for the last, and the basename is that last
918 * component. Getting the return-value for either part is optional
919 * (the caller can pass NULL).
921 * The original 'path' can represent either a regular file or a
922 * directory---the splitting will be carried out in the same way in
923 * either case. Trailing slashes on 'path' will be ignored, and any
924 * cases of multiple '/' characters appearing in series will be
925 * treated as a single '/'.
927 * Allocation (if any) will have 'ctx' as the talloc owner. But
928 * pointers will be returned within the original path string whenever
931 * Note: If 'path' is non-empty and contains no non-trailing slash,
932 * (that is, consists of a filename with no parent directory), then
933 * the directory returned will be an empty string. However, if 'path'
934 * is an empty string, then both directory and basename will be
938 _notmuch_database_split_path (void *ctx,
940 const char **directory,
941 const char **basename)
945 if (path == NULL || *path == '\0') {
950 return NOTMUCH_STATUS_SUCCESS;
953 /* Find the last slash (not counting a trailing slash), if any. */
955 slash = path + strlen (path) - 1;
957 /* First, skip trailing slashes. */
958 while (slash != path) {
965 /* Then, find a slash. */
966 while (slash != path) {
976 /* Finally, skip multiple slashes. */
977 while (slash != path) {
986 *directory = talloc_strdup (ctx, "");
991 *directory = talloc_strndup (ctx, path, slash - path + 1);
994 return NOTMUCH_STATUS_SUCCESS;
998 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1000 unsigned int *directory_id)
1002 notmuch_directory_t *directory;
1003 notmuch_status_t status;
1007 return NOTMUCH_STATUS_SUCCESS;
1010 directory = _notmuch_directory_create (notmuch, path, &status);
1016 *directory_id = _notmuch_directory_get_document_id (directory);
1018 notmuch_directory_destroy (directory);
1020 return NOTMUCH_STATUS_SUCCESS;
1024 _notmuch_database_get_directory_path (void *ctx,
1025 notmuch_database_t *notmuch,
1026 unsigned int doc_id)
1028 Xapian::Document document;
1030 document = find_document_for_doc_id (notmuch, doc_id);
1032 return talloc_strdup (ctx, document.get_data ().c_str ());
1035 /* Given a legal 'filename' for the database, (either relative to
1036 * database path or absolute with initial components identical to
1037 * database path), return a new string (with 'ctx' as the talloc
1038 * owner) suitable for use as a direntry term value.
1040 * The necessary directory documents will be created in the database
1044 _notmuch_database_filename_to_direntry (void *ctx,
1045 notmuch_database_t *notmuch,
1046 const char *filename,
1049 const char *relative, *directory, *basename;
1050 Xapian::docid directory_id;
1051 notmuch_status_t status;
1053 relative = _notmuch_database_relative_path (notmuch, filename);
1055 status = _notmuch_database_split_path (ctx, relative,
1056 &directory, &basename);
1060 status = _notmuch_database_find_directory_id (notmuch, directory,
1065 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1067 return NOTMUCH_STATUS_SUCCESS;
1070 /* Given a legal 'path' for the database, return the relative path.
1072 * The return value will be a pointer to the originl path contents,
1073 * and will be either the original string (if 'path' was relative) or
1074 * a portion of the string (if path was absolute and begins with the
1078 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1081 const char *db_path, *relative;
1082 unsigned int db_path_len;
1084 db_path = notmuch_database_get_path (notmuch);
1085 db_path_len = strlen (db_path);
1089 if (*relative == '/') {
1090 while (*relative == '/' && *(relative+1) == '/')
1093 if (strncmp (relative, db_path, db_path_len) == 0)
1095 relative += db_path_len;
1096 while (*relative == '/')
1104 notmuch_directory_t *
1105 notmuch_database_get_directory (notmuch_database_t *notmuch,
1108 notmuch_status_t status;
1110 return _notmuch_directory_create (notmuch, path, &status);
1113 /* Find the thread ID to which the message with 'message_id' belongs.
1115 * Returns NULL if no message with message ID 'message_id' is in the
1118 * Otherwise, returns a newly talloced string belonging to 'ctx'.
1121 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1123 const char *message_id)
1125 notmuch_message_t *message;
1126 const char *ret = NULL;
1128 message = notmuch_database_find_message (notmuch, message_id);
1129 if (message == NULL)
1132 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1136 notmuch_message_destroy (message);
1141 static notmuch_status_t
1142 _merge_threads (notmuch_database_t *notmuch,
1143 const char *winner_thread_id,
1144 const char *loser_thread_id)
1146 Xapian::PostingIterator loser, loser_end;
1147 notmuch_message_t *message = NULL;
1148 notmuch_private_status_t private_status;
1149 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1151 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1153 for ( ; loser != loser_end; loser++) {
1154 message = _notmuch_message_create (notmuch, notmuch,
1155 *loser, &private_status);
1156 if (message == NULL) {
1157 ret = COERCE_STATUS (private_status,
1158 "Cannot find document for doc_id from query");
1162 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1163 _notmuch_message_add_term (message, "thread", winner_thread_id);
1164 _notmuch_message_sync (message);
1166 notmuch_message_destroy (message);
1172 notmuch_message_destroy (message);
1178 _my_talloc_free_for_g_hash (void *ptr)
1183 static notmuch_status_t
1184 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1185 notmuch_message_t *message,
1186 notmuch_message_file_t *message_file,
1187 const char **thread_id)
1189 GHashTable *parents = NULL;
1190 const char *refs, *in_reply_to, *in_reply_to_message_id;
1191 GList *l, *keys = NULL;
1192 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1194 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1195 _my_talloc_free_for_g_hash, NULL);
1197 refs = notmuch_message_file_get_header (message_file, "references");
1198 parse_references (message, notmuch_message_get_message_id (message),
1201 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1202 parse_references (message, notmuch_message_get_message_id (message),
1203 parents, in_reply_to);
1205 /* Carefully avoid adding any self-referential in-reply-to term. */
1206 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1207 if (in_reply_to_message_id &&
1208 strcmp (in_reply_to_message_id,
1209 notmuch_message_get_message_id (message)))
1211 _notmuch_message_add_term (message, "replyto",
1212 _parse_message_id (message, in_reply_to, NULL));
1215 keys = g_hash_table_get_keys (parents);
1216 for (l = keys; l; l = l->next) {
1217 char *parent_message_id;
1218 const char *parent_thread_id;
1220 parent_message_id = (char *) l->data;
1221 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1225 if (parent_thread_id == NULL) {
1226 _notmuch_message_add_term (message, "reference",
1229 if (*thread_id == NULL) {
1230 *thread_id = talloc_strdup (message, parent_thread_id);
1231 _notmuch_message_add_term (message, "thread", *thread_id);
1232 } else if (strcmp (*thread_id, parent_thread_id)) {
1233 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1244 g_hash_table_unref (parents);
1249 static notmuch_status_t
1250 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1251 notmuch_message_t *message,
1252 const char **thread_id)
1254 const char *message_id = notmuch_message_get_message_id (message);
1255 Xapian::PostingIterator child, children_end;
1256 notmuch_message_t *child_message = NULL;
1257 const char *child_thread_id;
1258 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1259 notmuch_private_status_t private_status;
1261 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1263 for ( ; child != children_end; child++) {
1265 child_message = _notmuch_message_create (message, notmuch,
1266 *child, &private_status);
1267 if (child_message == NULL) {
1268 ret = COERCE_STATUS (private_status,
1269 "Cannot find document for doc_id from query");
1273 child_thread_id = notmuch_message_get_thread_id (child_message);
1274 if (*thread_id == NULL) {
1275 *thread_id = talloc_strdup (message, child_thread_id);
1276 _notmuch_message_add_term (message, "thread", *thread_id);
1277 } else if (strcmp (*thread_id, child_thread_id)) {
1278 _notmuch_message_remove_term (child_message, "reference",
1280 _notmuch_message_sync (child_message);
1281 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1286 notmuch_message_destroy (child_message);
1287 child_message = NULL;
1292 notmuch_message_destroy (child_message);
1298 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1300 /* 16 bytes (+ terminator) for hexadecimal representation of
1301 * a 64-bit integer. */
1302 static char thread_id[17];
1303 Xapian::WritableDatabase *db;
1305 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1307 notmuch->last_thread_id++;
1309 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1311 db->set_metadata ("last_thread_id", thread_id);
1316 /* Given a (mostly empty) 'message' and its corresponding
1317 * 'message_file' link it to existing threads in the database.
1319 * We first look at 'message_file' and its link-relevant headers
1320 * (References and In-Reply-To) for message IDs. We also look in the
1321 * database for existing message that reference 'message'. In either
1322 * case, we will assign to the current message the first thread_id
1323 * found (through either parent or child). We will also merge any
1324 * existing, distinct threads where this message belongs to both,
1325 * (which is not uncommon when mesages are processed out of order).
1327 * Finally, if not thread ID has been found through parent or child,
1328 * we call _notmuch_message_generate_thread_id to generate a new
1329 * generates a new thread ID if the message doesn't connect to any
1332 static notmuch_status_t
1333 _notmuch_database_link_message (notmuch_database_t *notmuch,
1334 notmuch_message_t *message,
1335 notmuch_message_file_t *message_file)
1337 notmuch_status_t status;
1338 const char *thread_id = NULL;
1340 status = _notmuch_database_link_message_to_parents (notmuch, message,
1346 status = _notmuch_database_link_message_to_children (notmuch, message,
1351 /* If not part of any existing thread, generate a new thread ID. */
1352 if (thread_id == NULL) {
1353 thread_id = _notmuch_database_generate_thread_id (notmuch);
1355 _notmuch_message_add_term (message, "thread", thread_id);
1358 return NOTMUCH_STATUS_SUCCESS;
1362 notmuch_database_add_message (notmuch_database_t *notmuch,
1363 const char *filename,
1364 notmuch_message_t **message_ret)
1366 notmuch_message_file_t *message_file;
1367 notmuch_message_t *message = NULL;
1368 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1369 notmuch_private_status_t private_status;
1371 const char *date, *header;
1372 const char *from, *to, *subject;
1373 char *message_id = NULL;
1376 *message_ret = NULL;
1378 ret = _notmuch_database_ensure_writable (notmuch);
1382 message_file = notmuch_message_file_open (filename);
1383 if (message_file == NULL)
1384 return NOTMUCH_STATUS_FILE_ERROR;
1386 notmuch_message_file_restrict_headers (message_file,
1397 /* Before we do any real work, (especially before doing a
1398 * potential SHA-1 computation on the entire file's contents),
1399 * let's make sure that what we're looking at looks like an
1400 * actual email message.
1402 from = notmuch_message_file_get_header (message_file, "from");
1403 subject = notmuch_message_file_get_header (message_file, "subject");
1404 to = notmuch_message_file_get_header (message_file, "to");
1406 if ((from == NULL || *from == '\0') &&
1407 (subject == NULL || *subject == '\0') &&
1408 (to == NULL || *to == '\0'))
1410 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1414 /* Now that we're sure it's mail, the first order of business
1415 * is to find a message ID (or else create one ourselves). */
1417 header = notmuch_message_file_get_header (message_file, "message-id");
1418 if (header && *header != '\0') {
1419 message_id = _parse_message_id (message_file, header, NULL);
1421 /* So the header value isn't RFC-compliant, but it's
1422 * better than no message-id at all. */
1423 if (message_id == NULL)
1424 message_id = talloc_strdup (message_file, header);
1426 /* Reject a Message ID that's too long. */
1427 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1428 talloc_free (message_id);
1433 if (message_id == NULL ) {
1434 /* No message-id at all, let's generate one by taking a
1435 * hash over the file's contents. */
1436 char *sha1 = notmuch_sha1_of_file (filename);
1438 /* If that failed too, something is really wrong. Give up. */
1440 ret = NOTMUCH_STATUS_FILE_ERROR;
1444 message_id = talloc_asprintf (message_file,
1445 "notmuch-sha1-%s", sha1);
1449 /* Now that we have a message ID, we get a message object,
1450 * (which may or may not reference an existing document in the
1453 message = _notmuch_message_create_for_message_id (notmuch,
1457 talloc_free (message_id);
1459 if (message == NULL) {
1460 ret = COERCE_STATUS (private_status,
1461 "Unexpected status value from _notmuch_message_create_for_message_id");
1465 _notmuch_message_add_filename (message, filename);
1467 /* Is this a newly created message object? */
1468 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1469 _notmuch_message_add_term (message, "type", "mail");
1471 ret = _notmuch_database_link_message (notmuch, message,
1476 date = notmuch_message_file_get_header (message_file, "date");
1477 _notmuch_message_set_date (message, date);
1479 _notmuch_message_index_file (message, filename);
1481 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1484 _notmuch_message_sync (message);
1485 } catch (const Xapian::Error &error) {
1486 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1487 error.get_description().c_str());
1488 notmuch->exception_reported = TRUE;
1489 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1495 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1496 *message_ret = message;
1498 notmuch_message_destroy (message);
1502 notmuch_message_file_close (message_file);
1508 notmuch_database_remove_message (notmuch_database_t *notmuch,
1509 const char *filename)
1511 Xapian::WritableDatabase *db;
1512 void *local = talloc_new (notmuch);
1513 const char *prefix = _find_prefix ("file-direntry");
1514 char *direntry, *term;
1515 Xapian::PostingIterator i, end;
1516 Xapian::Document document;
1517 notmuch_status_t status;
1519 status = _notmuch_database_ensure_writable (notmuch);
1523 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1525 status = _notmuch_database_filename_to_direntry (local, notmuch,
1526 filename, &direntry);
1530 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1532 find_doc_ids_for_term (notmuch, term, &i, &end);
1534 for ( ; i != end; i++) {
1535 Xapian::TermIterator j;
1537 document = find_document_for_doc_id (notmuch, *i);
1539 document.remove_term (term);
1541 j = document.termlist_begin ();
1544 /* Was this the last file-direntry in the message? */
1545 if (j == document.termlist_end () ||
1546 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1548 db->delete_document (document.get_docid ());
1549 status = NOTMUCH_STATUS_SUCCESS;
1551 db->replace_document (document.get_docid (), document);
1552 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1556 talloc_free (local);
1562 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1563 Xapian::TermIterator &end)
1565 const char *prefix = _find_prefix ("tag");
1566 notmuch_tags_t *tags;
1569 /* Currently this iteration is written with the assumption that
1570 * "tag" has a single-character prefix. */
1571 assert (strlen (prefix) == 1);
1573 tags = _notmuch_tags_create (ctx);
1574 if (unlikely (tags == NULL))
1582 if (tag.empty () || tag[0] != *prefix)
1585 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1590 _notmuch_tags_prepare_iterator (tags);
1596 notmuch_database_get_all_tags (notmuch_database_t *db)
1598 Xapian::TermIterator i, end;
1599 i = db->xapian_db->allterms_begin();
1600 end = db->xapian_db->allterms_end();
1601 return _notmuch_convert_tags(db, i, end);