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);
1114 /* Find the thread ID to which the message with 'message_id' belongs.
1116 * Returns NULL if no message with message ID 'message_id' is in the
1119 * Otherwise, returns a newly talloced string belonging to 'ctx'.
1122 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1124 const char *message_id)
1126 notmuch_message_t *message;
1127 const char *ret = NULL;
1129 message = notmuch_database_find_message (notmuch, message_id);
1130 if (message == NULL)
1133 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1137 notmuch_message_destroy (message);
1142 static notmuch_status_t
1143 _merge_threads (notmuch_database_t *notmuch,
1144 const char *winner_thread_id,
1145 const char *loser_thread_id)
1147 Xapian::PostingIterator loser, loser_end;
1148 notmuch_message_t *message = NULL;
1149 notmuch_private_status_t private_status;
1150 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1152 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1154 for ( ; loser != loser_end; loser++) {
1155 message = _notmuch_message_create (notmuch, notmuch,
1156 *loser, &private_status);
1157 if (message == NULL) {
1158 ret = COERCE_STATUS (private_status,
1159 "Cannot find document for doc_id from query");
1163 _notmuch_message_remove_term (message, "thread", loser_thread_id);
1164 _notmuch_message_add_term (message, "thread", winner_thread_id);
1165 _notmuch_message_sync (message);
1167 notmuch_message_destroy (message);
1173 notmuch_message_destroy (message);
1179 _my_talloc_free_for_g_hash (void *ptr)
1184 static notmuch_status_t
1185 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1186 notmuch_message_t *message,
1187 notmuch_message_file_t *message_file,
1188 const char **thread_id)
1190 GHashTable *parents = NULL;
1191 const char *refs, *in_reply_to, *in_reply_to_message_id;
1192 GList *l, *keys = NULL;
1193 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1195 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1196 _my_talloc_free_for_g_hash, NULL);
1198 refs = notmuch_message_file_get_header (message_file, "references");
1199 parse_references (message, notmuch_message_get_message_id (message),
1202 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1203 parse_references (message, notmuch_message_get_message_id (message),
1204 parents, in_reply_to);
1206 /* Carefully avoid adding any self-referential in-reply-to term. */
1207 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1208 if (in_reply_to_message_id &&
1209 strcmp (in_reply_to_message_id,
1210 notmuch_message_get_message_id (message)))
1212 _notmuch_message_add_term (message, "replyto",
1213 _parse_message_id (message, in_reply_to, NULL));
1216 keys = g_hash_table_get_keys (parents);
1217 for (l = keys; l; l = l->next) {
1218 char *parent_message_id;
1219 const char *parent_thread_id;
1221 parent_message_id = (char *) l->data;
1222 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1226 if (parent_thread_id == NULL) {
1227 _notmuch_message_add_term (message, "reference",
1230 if (*thread_id == NULL) {
1231 *thread_id = talloc_strdup (message, parent_thread_id);
1232 _notmuch_message_add_term (message, "thread", *thread_id);
1233 } else if (strcmp (*thread_id, parent_thread_id)) {
1234 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1245 g_hash_table_unref (parents);
1250 static notmuch_status_t
1251 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1252 notmuch_message_t *message,
1253 const char **thread_id)
1255 const char *message_id = notmuch_message_get_message_id (message);
1256 Xapian::PostingIterator child, children_end;
1257 notmuch_message_t *child_message = NULL;
1258 const char *child_thread_id;
1259 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1260 notmuch_private_status_t private_status;
1262 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1264 for ( ; child != children_end; child++) {
1266 child_message = _notmuch_message_create (message, notmuch,
1267 *child, &private_status);
1268 if (child_message == NULL) {
1269 ret = COERCE_STATUS (private_status,
1270 "Cannot find document for doc_id from query");
1274 child_thread_id = notmuch_message_get_thread_id (child_message);
1275 if (*thread_id == NULL) {
1276 *thread_id = talloc_strdup (message, child_thread_id);
1277 _notmuch_message_add_term (message, "thread", *thread_id);
1278 } else if (strcmp (*thread_id, child_thread_id)) {
1279 _notmuch_message_remove_term (child_message, "reference",
1281 _notmuch_message_sync (child_message);
1282 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1287 notmuch_message_destroy (child_message);
1288 child_message = NULL;
1293 notmuch_message_destroy (child_message);
1299 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1301 /* 16 bytes (+ terminator) for hexadecimal representation of
1302 * a 64-bit integer. */
1303 static char thread_id[17];
1304 Xapian::WritableDatabase *db;
1306 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1308 notmuch->last_thread_id++;
1310 sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1312 db->set_metadata ("last_thread_id", thread_id);
1317 /* Given a (mostly empty) 'message' and its corresponding
1318 * 'message_file' link it to existing threads in the database.
1320 * We first look at 'message_file' and its link-relevant headers
1321 * (References and In-Reply-To) for message IDs. We also look in the
1322 * database for existing message that reference 'message'. In either
1323 * case, we will assign to the current message the first thread_id
1324 * found (through either parent or child). We will also merge any
1325 * existing, distinct threads where this message belongs to both,
1326 * (which is not uncommon when mesages are processed out of order).
1328 * Finally, if not thread ID has been found through parent or child,
1329 * we call _notmuch_message_generate_thread_id to generate a new
1330 * generates a new thread ID if the message doesn't connect to any
1333 static notmuch_status_t
1334 _notmuch_database_link_message (notmuch_database_t *notmuch,
1335 notmuch_message_t *message,
1336 notmuch_message_file_t *message_file)
1338 notmuch_status_t status;
1339 const char *thread_id = NULL;
1341 status = _notmuch_database_link_message_to_parents (notmuch, message,
1347 status = _notmuch_database_link_message_to_children (notmuch, message,
1352 /* If not part of any existing thread, generate a new thread ID. */
1353 if (thread_id == NULL) {
1354 thread_id = _notmuch_database_generate_thread_id (notmuch);
1356 _notmuch_message_add_term (message, "thread", thread_id);
1359 return NOTMUCH_STATUS_SUCCESS;
1363 notmuch_database_add_message (notmuch_database_t *notmuch,
1364 const char *filename,
1365 notmuch_message_t **message_ret)
1367 notmuch_message_file_t *message_file;
1368 notmuch_message_t *message = NULL;
1369 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1370 notmuch_private_status_t private_status;
1372 const char *date, *header;
1373 const char *from, *to, *subject;
1374 char *message_id = NULL;
1377 *message_ret = NULL;
1379 ret = _notmuch_database_ensure_writable (notmuch);
1383 message_file = notmuch_message_file_open (filename);
1384 if (message_file == NULL)
1385 return NOTMUCH_STATUS_FILE_ERROR;
1387 notmuch_message_file_restrict_headers (message_file,
1398 /* Before we do any real work, (especially before doing a
1399 * potential SHA-1 computation on the entire file's contents),
1400 * let's make sure that what we're looking at looks like an
1401 * actual email message.
1403 from = notmuch_message_file_get_header (message_file, "from");
1404 subject = notmuch_message_file_get_header (message_file, "subject");
1405 to = notmuch_message_file_get_header (message_file, "to");
1407 if ((from == NULL || *from == '\0') &&
1408 (subject == NULL || *subject == '\0') &&
1409 (to == NULL || *to == '\0'))
1411 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1415 /* Now that we're sure it's mail, the first order of business
1416 * is to find a message ID (or else create one ourselves). */
1418 header = notmuch_message_file_get_header (message_file, "message-id");
1419 if (header && *header != '\0') {
1420 message_id = _parse_message_id (message_file, header, NULL);
1422 /* So the header value isn't RFC-compliant, but it's
1423 * better than no message-id at all. */
1424 if (message_id == NULL)
1425 message_id = talloc_strdup (message_file, header);
1427 /* Reject a Message ID that's too long. */
1428 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1429 talloc_free (message_id);
1434 if (message_id == NULL ) {
1435 /* No message-id at all, let's generate one by taking a
1436 * hash over the file's contents. */
1437 char *sha1 = notmuch_sha1_of_file (filename);
1439 /* If that failed too, something is really wrong. Give up. */
1441 ret = NOTMUCH_STATUS_FILE_ERROR;
1445 message_id = talloc_asprintf (message_file,
1446 "notmuch-sha1-%s", sha1);
1450 /* Now that we have a message ID, we get a message object,
1451 * (which may or may not reference an existing document in the
1454 message = _notmuch_message_create_for_message_id (notmuch,
1458 talloc_free (message_id);
1460 if (message == NULL) {
1461 ret = COERCE_STATUS (private_status,
1462 "Unexpected status value from _notmuch_message_create_for_message_id");
1466 _notmuch_message_add_filename (message, filename);
1468 /* Is this a newly created message object? */
1469 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1470 _notmuch_message_add_term (message, "type", "mail");
1472 ret = _notmuch_database_link_message (notmuch, message,
1477 date = notmuch_message_file_get_header (message_file, "date");
1478 _notmuch_message_set_date (message, date);
1480 _notmuch_message_index_file (message, filename);
1482 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1485 _notmuch_message_sync (message);
1486 } catch (const Xapian::Error &error) {
1487 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1488 error.get_description().c_str());
1489 notmuch->exception_reported = TRUE;
1490 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1496 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1497 *message_ret = message;
1499 notmuch_message_destroy (message);
1503 notmuch_message_file_close (message_file);
1509 notmuch_database_remove_message (notmuch_database_t *notmuch,
1510 const char *filename)
1512 Xapian::WritableDatabase *db;
1513 void *local = talloc_new (notmuch);
1514 const char *prefix = _find_prefix ("file-direntry");
1515 char *direntry, *term;
1516 Xapian::PostingIterator i, end;
1517 Xapian::Document document;
1518 notmuch_status_t status;
1520 status = _notmuch_database_ensure_writable (notmuch);
1524 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1526 status = _notmuch_database_filename_to_direntry (local, notmuch,
1527 filename, &direntry);
1531 term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1533 find_doc_ids_for_term (notmuch, term, &i, &end);
1535 for ( ; i != end; i++) {
1536 Xapian::TermIterator j;
1538 document = find_document_for_doc_id (notmuch, *i);
1540 document.remove_term (term);
1542 j = document.termlist_begin ();
1545 /* Was this the last file-direntry in the message? */
1546 if (j == document.termlist_end () ||
1547 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1549 db->delete_document (document.get_docid ());
1550 status = NOTMUCH_STATUS_SUCCESS;
1552 db->replace_document (document.get_docid (), document);
1553 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1557 talloc_free (local);
1563 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1564 Xapian::TermIterator &end)
1566 const char *prefix = _find_prefix ("tag");
1567 notmuch_tags_t *tags;
1570 /* Currently this iteration is written with the assumption that
1571 * "tag" has a single-character prefix. */
1572 assert (strlen (prefix) == 1);
1574 tags = _notmuch_tags_create (ctx);
1575 if (unlikely (tags == NULL))
1583 if (tag.empty () || tag[0] != *prefix)
1586 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1591 _notmuch_tags_prepare_iterator (tags);
1597 notmuch_database_get_all_tags (notmuch_database_t *db)
1599 Xapian::TermIterator i, end;
1600 i = db->xapian_db->allterms_begin();
1601 end = db->xapian_db->allterms_end();
1602 return _notmuch_convert_tags(db, i, end);