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[] = {
154 prefix_t PROBABILISTIC_PREFIX[]= {
157 { "attachment", "XATTACHMENT" },
158 { "subject", "XSUBJECT"}
162 _internal_error (const char *format, ...)
166 va_start (va_args, format);
168 fprintf (stderr, "Internal error: ");
169 vfprintf (stderr, format, va_args);
177 _find_prefix (const char *name)
181 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
182 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
183 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
186 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
187 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
188 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
191 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
192 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
193 return PROBABILISTIC_PREFIX[i].prefix;
196 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
202 notmuch_status_to_string (notmuch_status_t status)
205 case NOTMUCH_STATUS_SUCCESS:
206 return "No error occurred";
207 case NOTMUCH_STATUS_OUT_OF_MEMORY:
208 return "Out of memory";
209 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
210 return "Attempt to write to a read-only database";
211 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
212 return "A Xapian exception occurred";
213 case NOTMUCH_STATUS_FILE_ERROR:
214 return "Something went wrong trying to read or write a file";
215 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
216 return "File is not an email";
217 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
218 return "Message ID is identical to a message in database";
219 case NOTMUCH_STATUS_NULL_POINTER:
220 return "Erroneous NULL pointer";
221 case NOTMUCH_STATUS_TAG_TOO_LONG:
222 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
223 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
224 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
226 case NOTMUCH_STATUS_LAST_STATUS:
227 return "Unknown error status value";
232 find_doc_ids_for_term (notmuch_database_t *notmuch,
234 Xapian::PostingIterator *begin,
235 Xapian::PostingIterator *end)
237 *begin = notmuch->xapian_db->postlist_begin (term);
239 *end = notmuch->xapian_db->postlist_end (term);
243 find_doc_ids (notmuch_database_t *notmuch,
244 const char *prefix_name,
246 Xapian::PostingIterator *begin,
247 Xapian::PostingIterator *end)
251 term = talloc_asprintf (notmuch, "%s%s",
252 _find_prefix (prefix_name), value);
254 find_doc_ids_for_term (notmuch, term, begin, end);
259 notmuch_private_status_t
260 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
261 const char *prefix_name,
263 unsigned int *doc_id)
265 Xapian::PostingIterator i, end;
267 find_doc_ids (notmuch, prefix_name, value, &i, &end);
271 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
276 #if DEBUG_DATABASE_SANITY
280 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
284 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
287 static Xapian::Document
288 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
290 return notmuch->xapian_db->get_document (doc_id);
294 notmuch_database_find_message (notmuch_database_t *notmuch,
295 const char *message_id)
297 notmuch_private_status_t status;
300 status = _notmuch_database_find_unique_doc_id (notmuch, "id",
301 message_id, &doc_id);
303 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
306 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
309 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
310 * a (potentially nested) parenthesized sequence with '\' used to
311 * escape any character (including parentheses).
313 * If the sequence to be skipped continues to the end of the string,
314 * then 'str' will be left pointing at the final terminating '\0'
318 skip_space_and_comments (const char **str)
323 while (*s && (isspace (*s) || *s == '(')) {
324 while (*s && isspace (*s))
329 while (*s && nesting) {
332 } else if (*s == ')') {
334 } else if (*s == '\\') {
346 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
347 * comments, and the '<' and '>' delimeters.
349 * If not NULL, then *next will be made to point to the first character
350 * not parsed, (possibly pointing to the final '\0' terminator.
352 * Returns a newly talloc'ed string belonging to 'ctx'.
354 * Returns NULL if there is any error parsing the message-id. */
356 _parse_message_id (void *ctx, const char *message_id, const char **next)
361 if (message_id == NULL || *message_id == '\0')
366 skip_space_and_comments (&s);
368 /* Skip any unstructured text as well. */
369 while (*s && *s != '<')
380 skip_space_and_comments (&s);
383 while (*end && *end != '>')
392 if (end > s && *end == '>')
397 result = talloc_strndup (ctx, s, end - s + 1);
399 /* Finally, collapse any whitespace that is within the message-id
405 for (r = result, len = strlen (r); *r; r++, len--)
406 if (*r == ' ' || *r == '\t')
407 memmove (r, r+1, len);
413 /* Parse a References header value, putting a (talloc'ed under 'ctx')
414 * copy of each referenced message-id into 'hash'.
416 * We explicitly avoid including any reference identical to
417 * 'message_id' in the result (to avoid mass confusion when a single
418 * message references itself cyclically---and yes, mail messages are
419 * not infrequent in the wild that do this---don't ask me why).
422 parse_references (void *ctx,
423 const char *message_id,
429 if (refs == NULL || *refs == '\0')
433 ref = _parse_message_id (ctx, refs, &refs);
435 if (ref && strcmp (ref, message_id))
436 g_hash_table_insert (hash, ref, NULL);
441 notmuch_database_create (const char *path)
443 notmuch_database_t *notmuch = NULL;
444 char *notmuch_path = NULL;
449 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
453 err = stat (path, &st);
455 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
456 path, strerror (errno));
460 if (! S_ISDIR (st.st_mode)) {
461 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
466 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
468 err = mkdir (notmuch_path, 0755);
471 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
472 notmuch_path, strerror (errno));
476 notmuch = notmuch_database_open (path,
477 NOTMUCH_DATABASE_MODE_READ_WRITE);
478 notmuch_database_upgrade (notmuch, NULL, NULL);
482 talloc_free (notmuch_path);
488 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
490 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
491 fprintf (stderr, "Cannot write to a read-only database.\n");
492 return NOTMUCH_STATUS_READ_ONLY_DATABASE;
495 return NOTMUCH_STATUS_SUCCESS;
499 notmuch_database_open (const char *path,
500 notmuch_database_mode_t mode)
502 notmuch_database_t *notmuch = NULL;
503 char *notmuch_path = NULL, *xapian_path = NULL;
506 unsigned int i, version;
508 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
510 fprintf (stderr, "Out of memory\n");
514 err = stat (notmuch_path, &st);
516 fprintf (stderr, "Error opening database at %s: %s\n",
517 notmuch_path, strerror (errno));
521 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
523 fprintf (stderr, "Out of memory\n");
527 notmuch = talloc (NULL, notmuch_database_t);
528 notmuch->exception_reported = FALSE;
529 notmuch->path = talloc_strdup (notmuch, path);
531 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
532 notmuch->path[strlen (notmuch->path) - 1] = '\0';
534 notmuch->needs_upgrade = FALSE;
535 notmuch->mode = mode;
537 string last_thread_id;
539 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
540 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
541 Xapian::DB_CREATE_OR_OPEN);
542 version = notmuch_database_get_version (notmuch);
544 if (version > NOTMUCH_DATABASE_VERSION) {
546 "Error: Notmuch database at %s\n"
547 " has a newer database format version (%u) than supported by this\n"
548 " version of notmuch (%u). Refusing to open this database in\n"
549 " read-write mode.\n",
550 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
551 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
552 notmuch_database_close (notmuch);
557 if (version < NOTMUCH_DATABASE_VERSION)
558 notmuch->needs_upgrade = TRUE;
560 notmuch->xapian_db = new Xapian::Database (xapian_path);
561 version = notmuch_database_get_version (notmuch);
562 if (version > NOTMUCH_DATABASE_VERSION)
565 "Warning: Notmuch database at %s\n"
566 " has a newer database format version (%u) than supported by this\n"
567 " version of notmuch (%u). Some operations may behave incorrectly,\n"
568 " (but the database will not be harmed since it is being opened\n"
569 " in read-only mode).\n",
570 notmuch_path, version, NOTMUCH_DATABASE_VERSION);
574 last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
575 if (last_thread_id.empty ()) {
576 notmuch->last_thread_id = 0;
581 str = last_thread_id.c_str ();
582 notmuch->last_thread_id = strtoull (str, &end, 16);
584 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
587 notmuch->query_parser = new Xapian::QueryParser;
588 notmuch->term_gen = new Xapian::TermGenerator;
589 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
590 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
592 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
593 notmuch->query_parser->set_database (*notmuch->xapian_db);
594 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
595 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
596 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
598 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
599 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
600 notmuch->query_parser->add_boolean_prefix (prefix->name,
604 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
605 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
606 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
608 } catch (const Xapian::Error &error) {
609 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
610 error.get_msg().c_str());
624 notmuch_database_close (notmuch_database_t *notmuch)
627 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
628 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
629 } catch (const Xapian::Error &error) {
630 if (! notmuch->exception_reported) {
631 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
632 error.get_msg().c_str());
636 delete notmuch->term_gen;
637 delete notmuch->query_parser;
638 delete notmuch->xapian_db;
639 delete notmuch->value_range_processor;
640 talloc_free (notmuch);
644 notmuch_database_get_path (notmuch_database_t *notmuch)
646 return notmuch->path;
650 notmuch_database_get_version (notmuch_database_t *notmuch)
652 unsigned int version;
653 string version_string;
657 version_string = notmuch->xapian_db->get_metadata ("version");
658 if (version_string.empty ())
661 str = version_string.c_str ();
662 if (str == NULL || *str == '\0')
665 version = strtoul (str, &end, 10);
667 INTERNAL_ERROR ("Malformed database version: %s", str);
673 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
675 return notmuch->needs_upgrade;
678 static volatile sig_atomic_t do_progress_notify = 0;
681 handle_sigalrm (unused (int signal))
683 do_progress_notify = 1;
686 /* Upgrade the current database.
688 * After opening a database in read-write mode, the client should
689 * check if an upgrade is needed (notmuch_database_needs_upgrade) and
690 * if so, upgrade with this function before making any modifications.
692 * The optional progress_notify callback can be used by the caller to
693 * provide progress indication to the user. If non-NULL it will be
694 * called periodically with 'count' as the number of messages upgraded
695 * so far and 'total' the overall number of messages that will be
699 notmuch_database_upgrade (notmuch_database_t *notmuch,
700 void (*progress_notify) (void *closure,
704 Xapian::WritableDatabase *db;
705 struct sigaction action;
706 struct itimerval timerval;
707 notmuch_bool_t timer_is_active = FALSE;
708 unsigned int version;
709 notmuch_status_t status;
710 unsigned int count = 0, total = 0;
712 status = _notmuch_database_ensure_writable (notmuch);
716 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
718 version = notmuch_database_get_version (notmuch);
720 if (version >= NOTMUCH_DATABASE_VERSION)
721 return NOTMUCH_STATUS_SUCCESS;
723 if (progress_notify) {
724 /* Setup our handler for SIGALRM */
725 memset (&action, 0, sizeof (struct sigaction));
726 action.sa_handler = handle_sigalrm;
727 sigemptyset (&action.sa_mask);
728 action.sa_flags = SA_RESTART;
729 sigaction (SIGALRM, &action, NULL);
731 /* Then start a timer to send SIGALRM once per second. */
732 timerval.it_interval.tv_sec = 1;
733 timerval.it_interval.tv_usec = 0;
734 timerval.it_value.tv_sec = 1;
735 timerval.it_value.tv_usec = 0;
736 setitimer (ITIMER_REAL, &timerval, NULL);
738 timer_is_active = TRUE;
741 /* Before version 1, each message document had its filename in the
742 * data field. Copy that into the new format by calling
743 * notmuch_message_add_filename.
746 notmuch_query_t *query = notmuch_query_create (notmuch, "");
747 notmuch_messages_t *messages;
748 notmuch_message_t *message;
750 Xapian::TermIterator t, t_end;
752 total = notmuch_query_count_messages (query);
754 for (messages = notmuch_query_search_messages (query);
755 notmuch_messages_valid (messages);
756 notmuch_messages_move_to_next (messages))
758 if (do_progress_notify) {
759 progress_notify (closure, (double) count / total);
760 do_progress_notify = 0;
763 message = notmuch_messages_get (messages);
765 filename = _notmuch_message_talloc_copy_data (message);
766 if (filename && *filename != '\0') {
767 _notmuch_message_add_filename (message, filename);
768 _notmuch_message_sync (message);
770 talloc_free (filename);
772 notmuch_message_destroy (message);
777 notmuch_query_destroy (query);
779 /* Also, before version 1 we stored directory timestamps in
780 * XTIMESTAMP documents instead of the current XDIRECTORY
781 * documents. So copy those as well. */
783 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
785 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
789 Xapian::PostingIterator p, p_end;
790 std::string term = *t;
792 p_end = notmuch->xapian_db->postlist_end (term);
794 for (p = notmuch->xapian_db->postlist_begin (term);
798 Xapian::Document document;
800 notmuch_directory_t *directory;
802 if (do_progress_notify) {
803 progress_notify (closure, (double) count / total);
804 do_progress_notify = 0;
807 document = find_document_for_doc_id (notmuch, *p);
808 mtime = Xapian::sortable_unserialise (
809 document.get_value (NOTMUCH_VALUE_TIMESTAMP));
811 directory = notmuch_database_get_directory (notmuch,
813 notmuch_directory_set_mtime (directory, mtime);
814 notmuch_directory_destroy (directory);
819 db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
822 /* Now that the upgrade is complete we can remove the old data
823 * and documents that are no longer needed. */
825 notmuch_query_t *query = notmuch_query_create (notmuch, "");
826 notmuch_messages_t *messages;
827 notmuch_message_t *message;
830 for (messages = notmuch_query_search_messages (query);
831 notmuch_messages_valid (messages);
832 notmuch_messages_move_to_next (messages))
834 if (do_progress_notify) {
835 progress_notify (closure, (double) count / total);
836 do_progress_notify = 0;
839 message = notmuch_messages_get (messages);
841 filename = _notmuch_message_talloc_copy_data (message);
842 if (filename && *filename != '\0') {
843 _notmuch_message_clear_data (message);
844 _notmuch_message_sync (message);
846 talloc_free (filename);
848 notmuch_message_destroy (message);
851 notmuch_query_destroy (query);
855 Xapian::TermIterator t, t_end;
857 t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
859 for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
863 Xapian::PostingIterator p, p_end;
864 std::string term = *t;
866 p_end = notmuch->xapian_db->postlist_end (term);
868 for (p = notmuch->xapian_db->postlist_begin (term);
872 if (do_progress_notify) {
873 progress_notify (closure, (double) count / total);
874 do_progress_notify = 0;
877 db->delete_document (*p);
882 if (timer_is_active) {
883 /* Now stop the timer. */
884 timerval.it_interval.tv_sec = 0;
885 timerval.it_interval.tv_usec = 0;
886 timerval.it_value.tv_sec = 0;
887 timerval.it_value.tv_usec = 0;
888 setitimer (ITIMER_REAL, &timerval, NULL);
890 /* And disable the signal handler. */
891 action.sa_handler = SIG_IGN;
892 sigaction (SIGALRM, &action, NULL);
895 return NOTMUCH_STATUS_SUCCESS;
898 /* We allow the user to use arbitrarily long paths for directories. But
899 * we have a term-length limit. So if we exceed that, we'll use the
900 * SHA-1 of the path for the database term.
902 * Note: This function may return the original value of 'path'. If it
903 * does not, then the caller is responsible to free() the returned
907 _notmuch_database_get_directory_db_path (const char *path)
909 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
911 if (term_len > NOTMUCH_TERM_MAX)
912 return notmuch_sha1_of_string (path);
917 /* Given a path, split it into two parts: the directory part is all
918 * components except for the last, and the basename is that last
919 * component. Getting the return-value for either part is optional
920 * (the caller can pass NULL).
922 * The original 'path' can represent either a regular file or a
923 * directory---the splitting will be carried out in the same way in
924 * either case. Trailing slashes on 'path' will be ignored, and any
925 * cases of multiple '/' characters appearing in series will be
926 * treated as a single '/'.
928 * Allocation (if any) will have 'ctx' as the talloc owner. But
929 * pointers will be returned within the original path string whenever
932 * Note: If 'path' is non-empty and contains no non-trailing slash,
933 * (that is, consists of a filename with no parent directory), then
934 * the directory returned will be an empty string. However, if 'path'
935 * is an empty string, then both directory and basename will be
939 _notmuch_database_split_path (void *ctx,
941 const char **directory,
942 const char **basename)
946 if (path == NULL || *path == '\0') {
951 return NOTMUCH_STATUS_SUCCESS;
954 /* Find the last slash (not counting a trailing slash), if any. */
956 slash = path + strlen (path) - 1;
958 /* First, skip trailing slashes. */
959 while (slash != path) {
966 /* Then, find a slash. */
967 while (slash != path) {
977 /* Finally, skip multiple slashes. */
978 while (slash != path) {
987 *directory = talloc_strdup (ctx, "");
992 *directory = talloc_strndup (ctx, path, slash - path + 1);
995 return NOTMUCH_STATUS_SUCCESS;
999 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1001 unsigned int *directory_id)
1003 notmuch_directory_t *directory;
1004 notmuch_status_t status;
1008 return NOTMUCH_STATUS_SUCCESS;
1011 directory = _notmuch_directory_create (notmuch, path, &status);
1017 *directory_id = _notmuch_directory_get_document_id (directory);
1019 notmuch_directory_destroy (directory);
1021 return NOTMUCH_STATUS_SUCCESS;
1025 _notmuch_database_get_directory_path (void *ctx,
1026 notmuch_database_t *notmuch,
1027 unsigned int doc_id)
1029 Xapian::Document document;
1031 document = find_document_for_doc_id (notmuch, doc_id);
1033 return talloc_strdup (ctx, document.get_data ().c_str ());
1036 /* Given a legal 'filename' for the database, (either relative to
1037 * database path or absolute with initial components identical to
1038 * database path), return a new string (with 'ctx' as the talloc
1039 * owner) suitable for use as a direntry term value.
1041 * The necessary directory documents will be created in the database
1045 _notmuch_database_filename_to_direntry (void *ctx,
1046 notmuch_database_t *notmuch,
1047 const char *filename,
1050 const char *relative, *directory, *basename;
1051 Xapian::docid directory_id;
1052 notmuch_status_t status;
1054 relative = _notmuch_database_relative_path (notmuch, filename);
1056 status = _notmuch_database_split_path (ctx, relative,
1057 &directory, &basename);
1061 status = _notmuch_database_find_directory_id (notmuch, directory,
1066 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1068 return NOTMUCH_STATUS_SUCCESS;
1071 /* Given a legal 'path' for the database, return the relative path.
1073 * The return value will be a pointer to the originl path contents,
1074 * and will be either the original string (if 'path' was relative) or
1075 * a portion of the string (if path was absolute and begins with the
1079 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1082 const char *db_path, *relative;
1083 unsigned int db_path_len;
1085 db_path = notmuch_database_get_path (notmuch);
1086 db_path_len = strlen (db_path);
1090 if (*relative == '/') {
1091 while (*relative == '/' && *(relative+1) == '/')
1094 if (strncmp (relative, db_path, db_path_len) == 0)
1096 relative += db_path_len;
1097 while (*relative == '/')
1105 notmuch_directory_t *
1106 notmuch_database_get_directory (notmuch_database_t *notmuch,
1109 notmuch_status_t status;
1111 return _notmuch_directory_create (notmuch, path, &status);
1115 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1117 /* 16 bytes (+ terminator) for hexadecimal representation of
1118 * a 64-bit integer. */
1119 static char thread_id[17];
1120 Xapian::WritableDatabase *db;
1122 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1124 notmuch->last_thread_id++;
1126 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1128 db->set_metadata ("last_thread_id", thread_id);
1134 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1136 return talloc_asprintf (ctx, "thread_id_%s", message_id);
1139 /* Find the thread ID to which the message with 'message_id' belongs.
1141 * Always returns a newly talloced string belonging to 'ctx'.
1143 * Note: If there is no message in the database with the given
1144 * 'message_id' then a new thread_id will be allocated for this
1145 * message and stored in the database metadata, (where this same
1146 * thread ID can be looked up if the message is added to the database
1150 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1152 const char *message_id)
1154 notmuch_message_t *message;
1155 string thread_id_string;
1156 const char *thread_id;
1158 Xapian::WritableDatabase *db;
1160 message = notmuch_database_find_message (notmuch, message_id);
1163 thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1165 notmuch_message_destroy (message);
1170 /* Message has not been seen yet.
1172 * We may have seen a reference to it already, in which case, we
1173 * can return the thread ID stored in the metadata. Otherwise, we
1174 * generate a new thread ID and store it there.
1176 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1177 metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1178 thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1180 if (thread_id_string.empty()) {
1181 thread_id = _notmuch_database_generate_thread_id (notmuch);
1182 db->set_metadata (metadata_key, thread_id);
1184 thread_id = thread_id_string.c_str();
1187 talloc_free (metadata_key);
1192 static notmuch_status_t
1193 _merge_threads (notmuch_database_t *notmuch,
1194 const char *winner_thread_id,
1195 const char *loser_thread_id)
1197 Xapian::PostingIterator loser, loser_end;
1198 notmuch_message_t *message = NULL;
1199 notmuch_private_status_t private_status;
1200 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1202 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1204 for ( ; loser != loser_end; loser++) {
1205 message = _notmuch_message_create (notmuch, notmuch,
1206 *loser, &private_status);
1207 if (message == NULL) {
1208 ret = COERCE_STATUS (private_status,
1209 "Cannot find document for doc_id from query");
1213 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1214 _notmuch_message_add_term (message, "thread", winner_thread_id);
1215 _notmuch_message_sync (message);
1217 notmuch_message_destroy (message);
1223 notmuch_message_destroy (message);
1229 _my_talloc_free_for_g_hash (void *ptr)
1234 static notmuch_status_t
1235 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1236 notmuch_message_t *message,
1237 notmuch_message_file_t *message_file,
1238 const char **thread_id)
1240 GHashTable *parents = NULL;
1241 const char *refs, *in_reply_to, *in_reply_to_message_id;
1242 GList *l, *keys = NULL;
1243 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1245 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1246 _my_talloc_free_for_g_hash, NULL);
1248 refs = notmuch_message_file_get_header (message_file, "references");
1249 parse_references (message, notmuch_message_get_message_id (message),
1252 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1253 parse_references (message, notmuch_message_get_message_id (message),
1254 parents, in_reply_to);
1256 /* Carefully avoid adding any self-referential in-reply-to term. */
1257 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1258 if (in_reply_to_message_id &&
1259 strcmp (in_reply_to_message_id,
1260 notmuch_message_get_message_id (message)))
1262 _notmuch_message_add_term (message, "replyto",
1263 _parse_message_id (message, in_reply_to, NULL));
1266 keys = g_hash_table_get_keys (parents);
1267 for (l = keys; l; l = l->next) {
1268 char *parent_message_id;
1269 const char *parent_thread_id;
1271 parent_message_id = (char *) l->data;
1272 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1276 if (parent_thread_id == NULL) {
1277 _notmuch_message_add_term (message, "reference",
1280 if (*thread_id == NULL) {
1281 *thread_id = talloc_strdup (message, parent_thread_id);
1282 _notmuch_message_add_term (message, "thread", *thread_id);
1283 } else if (strcmp (*thread_id, parent_thread_id)) {
1284 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1295 g_hash_table_unref (parents);
1300 static notmuch_status_t
1301 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1302 notmuch_message_t *message,
1303 const char **thread_id)
1305 const char *message_id = notmuch_message_get_message_id (message);
1306 Xapian::PostingIterator child, children_end;
1307 notmuch_message_t *child_message = NULL;
1308 const char *child_thread_id;
1309 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1310 notmuch_private_status_t private_status;
1312 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1314 for ( ; child != children_end; child++) {
1316 child_message = _notmuch_message_create (message, notmuch,
1317 *child, &private_status);
1318 if (child_message == NULL) {
1319 ret = COERCE_STATUS (private_status,
1320 "Cannot find document for doc_id from query");
1324 child_thread_id = notmuch_message_get_thread_id (child_message);
1325 if (*thread_id == NULL) {
1326 *thread_id = talloc_strdup (message, child_thread_id);
1327 _notmuch_message_add_term (message, "thread", *thread_id);
1328 } else if (strcmp (*thread_id, child_thread_id)) {
1329 _notmuch_message_remove_term (child_message, "reference",
1331 _notmuch_message_sync (child_message);
1332 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1337 notmuch_message_destroy (child_message);
1338 child_message = NULL;
1343 notmuch_message_destroy (child_message);
1348 /* Given a (mostly empty) 'message' and its corresponding
1349 * 'message_file' link it to existing threads in the database.
1351 * We first look at 'message_file' and its link-relevant headers
1352 * (References and In-Reply-To) for message IDs. We also look in the
1353 * database for existing message that reference 'message'. In either
1354 * case, we will assign to the current message the first thread_id
1355 * found (through either parent or child). We will also merge any
1356 * existing, distinct threads where this message belongs to both,
1357 * (which is not uncommon when mesages are processed out of order).
1359 * Finally, if not thread ID has been found through parent or child,
1360 * we call _notmuch_message_generate_thread_id to generate a new
1361 * generates a new thread ID if the message doesn't connect to any
1364 static notmuch_status_t
1365 _notmuch_database_link_message (notmuch_database_t *notmuch,
1366 notmuch_message_t *message,
1367 notmuch_message_file_t *message_file)
1369 notmuch_status_t status;
1370 const char *thread_id = NULL;
1371 char *metadata_key = _get_metadata_thread_id_key (message,
1372 notmuch_message_get_message_id (message));
1373 /* Check if we have already seen related messages to this one.
1374 * If we have then use the thread_id that we stored at that time.
1376 string stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1377 if (!stored_id.empty()) {
1378 Xapian::WritableDatabase *db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1379 db->set_metadata (metadata_key, "");
1380 thread_id = stored_id.c_str();
1381 _notmuch_message_add_term (message, "thread", thread_id);
1383 talloc_free (metadata_key);
1385 status = _notmuch_database_link_message_to_parents (notmuch, message,
1391 status = _notmuch_database_link_message_to_children (notmuch, message,
1396 /* If not part of any existing thread, generate a new thread ID. */
1397 if (thread_id == NULL) {
1398 thread_id = _notmuch_database_generate_thread_id (notmuch);
1400 _notmuch_message_add_term (message, "thread", thread_id);
1403 return NOTMUCH_STATUS_SUCCESS;
1407 notmuch_database_add_message (notmuch_database_t *notmuch,
1408 const char *filename,
1409 notmuch_message_t **message_ret)
1411 notmuch_message_file_t *message_file;
1412 notmuch_message_t *message = NULL;
1413 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1414 notmuch_private_status_t private_status;
1416 const char *date, *header;
1417 const char *from, *to, *subject;
1418 char *message_id = NULL;
1421 *message_ret = NULL;
1423 ret = _notmuch_database_ensure_writable (notmuch);
1427 message_file = notmuch_message_file_open (filename);
1428 if (message_file == NULL)
1429 return NOTMUCH_STATUS_FILE_ERROR;
1431 notmuch_message_file_restrict_headers (message_file,
1442 /* Before we do any real work, (especially before doing a
1443 * potential SHA-1 computation on the entire file's contents),
1444 * let's make sure that what we're looking at looks like an
1445 * actual email message.
1447 from = notmuch_message_file_get_header (message_file, "from");
1448 subject = notmuch_message_file_get_header (message_file, "subject");
1449 to = notmuch_message_file_get_header (message_file, "to");
1451 if ((from == NULL || *from == '\0') &&
1452 (subject == NULL || *subject == '\0') &&
1453 (to == NULL || *to == '\0'))
1455 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1459 /* Now that we're sure it's mail, the first order of business
1460 * is to find a message ID (or else create one ourselves). */
1462 header = notmuch_message_file_get_header (message_file, "message-id");
1463 if (header && *header != '\0') {
1464 message_id = _parse_message_id (message_file, header, NULL);
1466 /* So the header value isn't RFC-compliant, but it's
1467 * better than no message-id at all. */
1468 if (message_id == NULL)
1469 message_id = talloc_strdup (message_file, header);
1471 /* Reject a Message ID that's too long. */
1472 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1473 talloc_free (message_id);
1478 if (message_id == NULL ) {
1479 /* No message-id at all, let's generate one by taking a
1480 * hash over the file's contents. */
1481 char *sha1 = notmuch_sha1_of_file (filename);
1483 /* If that failed too, something is really wrong. Give up. */
1485 ret = NOTMUCH_STATUS_FILE_ERROR;
1489 message_id = talloc_asprintf (message_file,
1490 "notmuch-sha1-%s", sha1);
1494 /* Now that we have a message ID, we get a message object,
1495 * (which may or may not reference an existing document in the
1498 message = _notmuch_message_create_for_message_id (notmuch,
1502 talloc_free (message_id);
1504 if (message == NULL) {
1505 ret = COERCE_STATUS (private_status,
1506 "Unexpected status value from _notmuch_message_create_for_message_id");
1510 _notmuch_message_add_filename (message, filename);
1512 /* Is this a newly created message object? */
1513 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1514 _notmuch_message_add_term (message, "type", "mail");
1516 ret = _notmuch_database_link_message (notmuch, message,
1521 date = notmuch_message_file_get_header (message_file, "date");
1522 _notmuch_message_set_date (message, date);
1524 _notmuch_message_index_file (message, filename);
1526 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1529 _notmuch_message_sync (message);
1530 } catch (const Xapian::Error &error) {
1531 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1532 error.get_description().c_str());
1533 notmuch->exception_reported = TRUE;
1534 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1540 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1541 *message_ret = message;
1543 notmuch_message_destroy (message);
1547 notmuch_message_file_close (message_file);
1553 notmuch_database_remove_message (notmuch_database_t *notmuch,
1554 const char *filename)
1556 Xapian::WritableDatabase *db;
1557 void *local = talloc_new (notmuch);
1558 const char *prefix = _find_prefix ("file-direntry");
1559 char *direntry, *term;
1560 Xapian::PostingIterator i, end;
1561 Xapian::Document document;
1562 notmuch_status_t status;
1564 status = _notmuch_database_ensure_writable (notmuch);
1568 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1570 status = _notmuch_database_filename_to_direntry (local, notmuch,
1571 filename, &direntry);
1575 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1577 find_doc_ids_for_term (notmuch, term, &i, &end);
1579 for ( ; i != end; i++) {
1580 Xapian::TermIterator j;
1582 document = find_document_for_doc_id (notmuch, *i);
1584 document.remove_term (term);
1586 j = document.termlist_begin ();
1589 /* Was this the last file-direntry in the message? */
1590 if (j == document.termlist_end () ||
1591 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1593 db->delete_document (document.get_docid ());
1594 status = NOTMUCH_STATUS_SUCCESS;
1596 db->replace_document (document.get_docid (), document);
1597 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1601 talloc_free (local);
1607 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1608 Xapian::TermIterator &end)
1610 const char *prefix = _find_prefix ("tag");
1611 notmuch_tags_t *tags;
1614 /* Currently this iteration is written with the assumption that
1615 * "tag" has a single-character prefix. */
1616 assert (strlen (prefix) == 1);
1618 tags = _notmuch_tags_create (ctx);
1619 if (unlikely (tags == NULL))
1627 if (tag.empty () || tag[0] != *prefix)
1630 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1635 _notmuch_tags_prepare_iterator (tags);
1641 notmuch_database_get_all_tags (notmuch_database_t *db)
1643 Xapian::TermIterator i, end;
1644 i = db->xapian_db->allterms_begin();
1645 end = db->xapian_db->allterms_end();
1646 return _notmuch_convert_tags(db, i, end);