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"
27 #include <glib.h> /* g_free, GPtrArray, GHashTable */
31 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
38 /* Here's the current schema for our database:
40 * We currently have two different types of documents: mail and directory.
44 * A mail document is associated with a particular email message file
45 * on disk. It is indexed with the following prefixed terms which the
46 * database uses to construct threads, etc.:
48 * Single terms of given prefix:
52 * id: Unique ID of mail, (from Message-ID header or generated
53 * as "notmuch-sha1-<sha1_sum_of_entire_file>.
55 * thread: The ID of the thread to which the mail belongs
57 * replyto: The ID from the In-Reply-To header of the mail (if any).
59 * Multiple terms of given prefix:
61 * reference: All message IDs from In-Reply-To and Re ferences
62 * headers in the message.
64 * tag: Any tags associated with this message by the user.
66 * direntry: A colon-separated pair of values (INTEGER:STRING),
67 * where INTEGER is the document ID of a directory
68 * document, and STRING is the name of a file within
69 * that directory for this mail message.
71 * A mail document also has two values:
73 * TIMESTAMP: The time_t value corresponding to the message's
76 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
78 * In addition, terms from the content of the message are added with
79 * "from", "to", "attachment", and "subject" prefixes for use by the
80 * user in searching. But the database doesn't really care itself
83 * The data portion of a mail document is empty.
87 * A directory document is used by a client of the notmuch library to
88 * maintain data necessary to allow for efficient polling of mail
91 * The directory document contains the following terms:
93 * directory: The directory path (relative to the database path)
94 * Or the SHA1 sum of the directory path (if the
95 * path itself is too long to fit in a Xapian
98 * parent: The document ID of the parent directory document.
99 * Top-level directories will have a parent value of 0.
101 * and has a single value:
103 * TIMESTAMP: The mtime of the directory (at last scan)
105 * The data portion of a directory document contains the path of the
106 * directory (relative to the datbase path).
109 /* With these prefix values we follow the conventions published here:
111 * http://xapian.org/docs/omega/termprefixes.html
113 * as much as makes sense. Note that I took some liberty in matching
114 * the reserved prefix values to notmuch concepts, (for example, 'G'
115 * is documented as "newsGroup (or similar entity - e.g. a web forum
116 * name)", for which I think the thread is the closest analogue in
117 * notmuch. This in spite of the fact that we will eventually be
118 * storing mailing-list messages where 'G' for "mailing list name"
119 * might be even a closer analogue. I'm treating the single-character
120 * prefixes preferentially for core notmuch concepts (which will be
121 * nearly universal to all mail messages).
124 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
126 { "reference", "XREFERENCE" },
127 { "replyto", "XREPLYTO" },
128 { "directory", "XDIRECTORY" },
129 { "direntry", "XDIRENTRY" },
130 { "parent", "XPARENT" },
133 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
139 prefix_t PROBABILISTIC_PREFIX[]= {
142 { "attachment", "XATTACHMENT" },
143 { "subject", "XSUBJECT"}
147 _internal_error (const char *format, ...)
151 va_start (va_args, format);
153 fprintf (stderr, "Internal error: ");
154 vfprintf (stderr, format, va_args);
162 _find_prefix (const char *name)
166 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
167 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
168 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
171 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
172 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
173 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
176 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
177 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
178 return PROBABILISTIC_PREFIX[i].prefix;
181 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
187 notmuch_status_to_string (notmuch_status_t status)
190 case NOTMUCH_STATUS_SUCCESS:
191 return "No error occurred";
192 case NOTMUCH_STATUS_OUT_OF_MEMORY:
193 return "Out of memory";
194 case NOTMUCH_STATUS_READONLY_DATABASE:
195 return "The database is read-only";
196 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
197 return "A Xapian exception occurred";
198 case NOTMUCH_STATUS_FILE_ERROR:
199 return "Something went wrong trying to read or write a file";
200 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
201 return "File is not an email";
202 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
203 return "Message ID is identical to a message in database";
204 case NOTMUCH_STATUS_NULL_POINTER:
205 return "Erroneous NULL pointer";
206 case NOTMUCH_STATUS_TAG_TOO_LONG:
207 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
208 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
209 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
211 case NOTMUCH_STATUS_LAST_STATUS:
212 return "Unknown error status value";
217 find_doc_ids_for_term (notmuch_database_t *notmuch,
219 Xapian::PostingIterator *begin,
220 Xapian::PostingIterator *end)
222 *begin = notmuch->xapian_db->postlist_begin (term);
224 *end = notmuch->xapian_db->postlist_end (term);
228 find_doc_ids (notmuch_database_t *notmuch,
229 const char *prefix_name,
231 Xapian::PostingIterator *begin,
232 Xapian::PostingIterator *end)
236 term = talloc_asprintf (notmuch, "%s%s",
237 _find_prefix (prefix_name), value);
239 find_doc_ids_for_term (notmuch, term, begin, end);
244 static notmuch_private_status_t
245 find_unique_doc_id (notmuch_database_t *notmuch,
246 const char *prefix_name,
248 unsigned int *doc_id)
250 Xapian::PostingIterator i, end;
252 find_doc_ids (notmuch, prefix_name, value, &i, &end);
256 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
261 #if DEBUG_DATABASE_SANITY
265 INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
269 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
272 static Xapian::Document
273 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
275 return notmuch->xapian_db->get_document (doc_id);
278 static notmuch_private_status_t
279 find_unique_document (notmuch_database_t *notmuch,
280 const char *prefix_name,
282 Xapian::Document *document,
283 unsigned int *doc_id)
285 notmuch_private_status_t status;
287 status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
290 *document = Xapian::Document ();
294 *document = find_document_for_doc_id (notmuch, *doc_id);
295 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
299 notmuch_database_find_message (notmuch_database_t *notmuch,
300 const char *message_id)
302 notmuch_private_status_t status;
305 status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
307 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
310 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
313 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
314 * a (potentially nested) parenthesized sequence with '\' used to
315 * escape any character (including parentheses).
317 * If the sequence to be skipped continues to the end of the string,
318 * then 'str' will be left pointing at the final terminating '\0'
322 skip_space_and_comments (const char **str)
327 while (*s && (isspace (*s) || *s == '(')) {
328 while (*s && isspace (*s))
333 while (*s && nesting) {
336 } else if (*s == ')') {
338 } else if (*s == '\\') {
350 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
351 * comments, and the '<' and '>' delimeters.
353 * If not NULL, then *next will be made to point to the first character
354 * not parsed, (possibly pointing to the final '\0' terminator.
356 * Returns a newly talloc'ed string belonging to 'ctx'.
358 * Returns NULL if there is any error parsing the message-id. */
360 _parse_message_id (void *ctx, const char *message_id, const char **next)
365 if (message_id == NULL || *message_id == '\0')
370 skip_space_and_comments (&s);
372 /* Skip any unstructured text as well. */
373 while (*s && *s != '<')
384 skip_space_and_comments (&s);
387 while (*end && *end != '>')
396 if (end > s && *end == '>')
401 result = talloc_strndup (ctx, s, end - s + 1);
403 /* Finally, collapse any whitespace that is within the message-id
409 for (r = result, len = strlen (r); *r; r++, len--)
410 if (*r == ' ' || *r == '\t')
411 memmove (r, r+1, len);
417 /* Parse a References header value, putting a (talloc'ed under 'ctx')
418 * copy of each referenced message-id into 'hash'.
420 * We explicitly avoid including any reference identical to
421 * 'message_id' in the result (to avoid mass confusion when a single
422 * message references itself cyclically---and yes, mail messages are
423 * not infrequent in the wild that do this---don't ask me why).
426 parse_references (void *ctx,
427 const char *message_id,
433 if (refs == NULL || *refs == '\0')
437 ref = _parse_message_id (ctx, refs, &refs);
439 if (ref && strcmp (ref, message_id))
440 g_hash_table_insert (hash, ref, NULL);
445 notmuch_database_create (const char *path)
447 notmuch_database_t *notmuch = NULL;
448 char *notmuch_path = NULL;
453 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
457 err = stat (path, &st);
459 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
460 path, strerror (errno));
464 if (! S_ISDIR (st.st_mode)) {
465 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
470 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
472 err = mkdir (notmuch_path, 0755);
475 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
476 notmuch_path, strerror (errno));
480 notmuch = notmuch_database_open (path,
481 NOTMUCH_DATABASE_MODE_READ_WRITE);
485 talloc_free (notmuch_path);
491 notmuch_database_open (const char *path,
492 notmuch_database_mode_t mode)
494 notmuch_database_t *notmuch = NULL;
495 char *notmuch_path = NULL, *xapian_path = NULL;
500 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
502 fprintf (stderr, "Out of memory\n");
506 err = stat (notmuch_path, &st);
508 fprintf (stderr, "Error opening database at %s: %s\n",
509 notmuch_path, strerror (errno));
513 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
515 fprintf (stderr, "Out of memory\n");
519 notmuch = talloc (NULL, notmuch_database_t);
520 notmuch->exception_reported = FALSE;
521 notmuch->path = talloc_strdup (notmuch, path);
523 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
524 notmuch->path[strlen (notmuch->path) - 1] = '\0';
526 notmuch->mode = mode;
528 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
529 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
530 Xapian::DB_CREATE_OR_OPEN);
532 notmuch->xapian_db = new Xapian::Database (xapian_path);
534 notmuch->query_parser = new Xapian::QueryParser;
535 notmuch->term_gen = new Xapian::TermGenerator;
536 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
537 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
539 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
540 notmuch->query_parser->set_database (*notmuch->xapian_db);
541 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
542 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
543 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
545 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
546 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
547 notmuch->query_parser->add_boolean_prefix (prefix->name,
551 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
552 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
553 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
555 } catch (const Xapian::Error &error) {
556 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
557 error.get_msg().c_str());
571 notmuch_database_close (notmuch_database_t *notmuch)
574 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
575 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
576 } catch (const Xapian::Error &error) {
577 if (! notmuch->exception_reported) {
578 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
579 error.get_msg().c_str());
583 delete notmuch->term_gen;
584 delete notmuch->query_parser;
585 delete notmuch->xapian_db;
586 delete notmuch->value_range_processor;
587 talloc_free (notmuch);
591 notmuch_database_get_path (notmuch_database_t *notmuch)
593 return notmuch->path;
596 static notmuch_private_status_t
597 find_directory_document (notmuch_database_t *notmuch, const char *db_path,
598 Xapian::Document *doc, unsigned int *doc_id)
600 return find_unique_document (notmuch, "directory", db_path, doc, doc_id);
603 /* We allow the user to use arbitrarily long paths for directories. But
604 * we have a term-length limit. So if we exceed that, we'll use the
605 * SHA-1 of the path for the database term.
607 * Note: This function may return the original value of 'path'. If it
608 * does not, then the caller is responsible to free() the returned
612 directory_db_path (const char *path)
614 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
616 if (term_len > NOTMUCH_TERM_MAX)
617 return notmuch_sha1_of_string (path);
622 /* Given a path, split it into two parts: the directory part is all
623 * components except for the last, and the basename is that last
624 * component. Getting the return-value for either part is optional
625 * (the caller can pass NULL).
627 * The original 'path' can represent either a regular file or a
628 * directory---the splitting will be carried out in the same way in
629 * either case. Trailing slashes on 'path' will be ignored, and any
630 * cases of multiple '/' characters appearing in series will be
631 * treated as a single '/'.
633 * Allocation (if any) will have 'ctx' as the talloc owner. But
634 * pointers will be returned within the original path string whenever
637 * Note: If 'path' is non-empty and contains no non-trailing slash,
638 * (that is, consists of a filename with no parent directory), then
639 * the directory returned will be an empty string. However, if 'path'
640 * is an empty string, then both directory and basename will be
644 _notmuch_database_split_path (void *ctx,
646 const char **directory,
647 const char **basename)
651 if (path == NULL || *path == '\0') {
656 return NOTMUCH_STATUS_SUCCESS;
659 /* Find the last slash (not counting a trailing slash), if any. */
661 slash = path + strlen (path) - 1;
663 /* First, skip trailing slashes. */
664 while (slash != path) {
671 /* Then, find a slash. */
672 while (slash != path) {
682 /* Finally, skip multiple slashes. */
683 while (slash != path) {
692 *directory = talloc_strdup (ctx, "");
697 *directory = talloc_strndup (ctx, path, slash - path + 1);
700 return NOTMUCH_STATUS_SUCCESS;
704 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
706 unsigned int *directory_id)
708 notmuch_private_status_t private_status;
709 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
714 return NOTMUCH_STATUS_SUCCESS;
717 db_path = directory_db_path (path);
719 private_status = find_unique_doc_id (notmuch, "directory",
720 db_path, directory_id);
721 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
722 status = notmuch_database_set_directory_mtime (notmuch,
727 private_status = find_unique_doc_id (notmuch, "directory",
728 db_path, directory_id);
729 status = COERCE_STATUS (private_status, "_find_directory_id");
734 free ((char *) db_path);
743 _notmuch_database_get_directory_path (void *ctx,
744 notmuch_database_t *notmuch,
747 Xapian::Document document;
749 document = find_document_for_doc_id (notmuch, doc_id);
751 return talloc_strdup (ctx, document.get_data ().c_str ());
754 /* Given a legal 'filename' for the database, (either relative to
755 * database path or absolute with initial components identical to
756 * database path), return a new string (with 'ctx' as the talloc
757 * owner) suitable for use as a direntry term value.
760 _notmuch_database_filename_to_direntry (void *ctx,
761 notmuch_database_t *notmuch,
762 const char *filename,
765 const char *relative, *directory, *basename;
766 Xapian::docid directory_id;
767 notmuch_status_t status;
769 relative = _notmuch_database_relative_path (notmuch, filename);
771 status = _notmuch_database_split_path (ctx, relative,
772 &directory, &basename);
776 status = _notmuch_database_find_directory_id (notmuch, directory,
781 *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
783 return NOTMUCH_STATUS_SUCCESS;
786 /* Given a legal 'path' for the database, return the relative path.
788 * The return value will be a pointer to the originl path contents,
789 * and will be either the original string (if 'path' was relative) or
790 * a portion of the string (if path was absolute and begins with the
794 _notmuch_database_relative_path (notmuch_database_t *notmuch,
797 const char *db_path, *relative;
798 unsigned int db_path_len;
800 db_path = notmuch_database_get_path (notmuch);
801 db_path_len = strlen (db_path);
805 if (*relative == '/') {
806 while (*relative == '/' && *(relative+1) == '/')
809 if (strncmp (relative, db_path, db_path_len) == 0)
811 relative += db_path_len;
812 while (*relative == '/')
821 notmuch_database_set_directory_mtime (notmuch_database_t *notmuch,
825 Xapian::Document doc;
826 Xapian::WritableDatabase *db;
828 notmuch_private_status_t status;
829 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
830 const char *parent, *db_path = NULL;
831 unsigned int parent_id;
832 void *local = talloc_new (notmuch);
834 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
835 fprintf (stderr, "Attempted to update a read-only database.\n");
836 return NOTMUCH_STATUS_READONLY_DATABASE;
839 path = _notmuch_database_relative_path (notmuch, path);
841 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
842 db_path = directory_db_path (path);
845 status = find_directory_document (notmuch, db_path, &doc, &doc_id);
847 doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
848 Xapian::sortable_serialise (mtime));
850 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
851 char *term = talloc_asprintf (local, "%s%s",
852 _find_prefix ("directory"), db_path);
857 _notmuch_database_split_path (local, path, &parent, NULL);
859 _notmuch_database_find_directory_id (notmuch, parent, &parent_id);
861 term = talloc_asprintf (local, "%s%u",
862 _find_prefix ("parent"),
866 db->add_document (doc);
868 db->replace_document (doc_id, doc);
871 } catch (const Xapian::Error &error) {
872 fprintf (stderr, "A Xapian exception occurred setting directory mtime: %s.\n",
873 error.get_msg().c_str());
874 notmuch->exception_reported = TRUE;
875 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
879 free ((char *) db_path);
887 notmuch_database_get_directory_mtime (notmuch_database_t *notmuch,
890 Xapian::Document doc;
892 notmuch_private_status_t status;
893 const char *db_path = NULL;
896 db_path = directory_db_path (path);
899 status = find_directory_document (notmuch, db_path, &doc, &doc_id);
901 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
904 ret = Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
905 } catch (Xapian::Error &error) {
912 free ((char *) db_path);
917 /* Find the thread ID to which the message with 'message_id' belongs.
919 * Returns NULL if no message with message ID 'message_id' is in the
922 * Otherwise, returns a newly talloced string belonging to 'ctx'.
925 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
927 const char *message_id)
929 notmuch_message_t *message;
930 const char *ret = NULL;
932 message = notmuch_database_find_message (notmuch, message_id);
936 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
940 notmuch_message_destroy (message);
945 static notmuch_status_t
946 _merge_threads (notmuch_database_t *notmuch,
947 const char *winner_thread_id,
948 const char *loser_thread_id)
950 Xapian::PostingIterator loser, loser_end;
951 notmuch_message_t *message = NULL;
952 notmuch_private_status_t private_status;
953 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
955 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
957 for ( ; loser != loser_end; loser++) {
958 message = _notmuch_message_create (notmuch, notmuch,
959 *loser, &private_status);
960 if (message == NULL) {
961 ret = COERCE_STATUS (private_status,
962 "Cannot find document for doc_id from query");
966 _notmuch_message_remove_term (message, "thread", loser_thread_id);
967 _notmuch_message_add_term (message, "thread", winner_thread_id);
968 _notmuch_message_sync (message);
970 notmuch_message_destroy (message);
976 notmuch_message_destroy (message);
982 _my_talloc_free_for_g_hash (void *ptr)
987 static notmuch_status_t
988 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
989 notmuch_message_t *message,
990 notmuch_message_file_t *message_file,
991 const char **thread_id)
993 GHashTable *parents = NULL;
994 const char *refs, *in_reply_to, *in_reply_to_message_id;
995 GList *l, *keys = NULL;
996 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
998 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
999 _my_talloc_free_for_g_hash, NULL);
1001 refs = notmuch_message_file_get_header (message_file, "references");
1002 parse_references (message, notmuch_message_get_message_id (message),
1005 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1006 parse_references (message, notmuch_message_get_message_id (message),
1007 parents, in_reply_to);
1009 /* Carefully avoid adding any self-referential in-reply-to term. */
1010 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1011 if (in_reply_to_message_id &&
1012 strcmp (in_reply_to_message_id,
1013 notmuch_message_get_message_id (message)))
1015 _notmuch_message_add_term (message, "replyto",
1016 _parse_message_id (message, in_reply_to, NULL));
1019 keys = g_hash_table_get_keys (parents);
1020 for (l = keys; l; l = l->next) {
1021 char *parent_message_id;
1022 const char *parent_thread_id;
1024 parent_message_id = (char *) l->data;
1025 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1029 if (parent_thread_id == NULL) {
1030 _notmuch_message_add_term (message, "reference",
1033 if (*thread_id == NULL) {
1034 *thread_id = talloc_strdup (message, parent_thread_id);
1035 _notmuch_message_add_term (message, "thread", *thread_id);
1036 } else if (strcmp (*thread_id, parent_thread_id)) {
1037 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1048 g_hash_table_unref (parents);
1053 static notmuch_status_t
1054 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1055 notmuch_message_t *message,
1056 const char **thread_id)
1058 const char *message_id = notmuch_message_get_message_id (message);
1059 Xapian::PostingIterator child, children_end;
1060 notmuch_message_t *child_message = NULL;
1061 const char *child_thread_id;
1062 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1063 notmuch_private_status_t private_status;
1065 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1067 for ( ; child != children_end; child++) {
1069 child_message = _notmuch_message_create (message, notmuch,
1070 *child, &private_status);
1071 if (child_message == NULL) {
1072 ret = COERCE_STATUS (private_status,
1073 "Cannot find document for doc_id from query");
1077 child_thread_id = notmuch_message_get_thread_id (child_message);
1078 if (*thread_id == NULL) {
1079 *thread_id = talloc_strdup (message, child_thread_id);
1080 _notmuch_message_add_term (message, "thread", *thread_id);
1081 } else if (strcmp (*thread_id, child_thread_id)) {
1082 _notmuch_message_remove_term (child_message, "reference",
1084 _notmuch_message_sync (child_message);
1085 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1090 notmuch_message_destroy (child_message);
1091 child_message = NULL;
1096 notmuch_message_destroy (child_message);
1101 /* Given a (mostly empty) 'message' and its corresponding
1102 * 'message_file' link it to existing threads in the database.
1104 * We first look at 'message_file' and its link-relevant headers
1105 * (References and In-Reply-To) for message IDs. We also look in the
1106 * database for existing message that reference 'message'.
1108 * The end result is to call _notmuch_message_ensure_thread_id which
1109 * generates a new thread ID if the message doesn't connect to any
1112 static notmuch_status_t
1113 _notmuch_database_link_message (notmuch_database_t *notmuch,
1114 notmuch_message_t *message,
1115 notmuch_message_file_t *message_file)
1117 notmuch_status_t status;
1118 const char *thread_id = NULL;
1120 status = _notmuch_database_link_message_to_parents (notmuch, message,
1126 status = _notmuch_database_link_message_to_children (notmuch, message,
1131 if (thread_id == NULL)
1132 _notmuch_message_ensure_thread_id (message);
1134 return NOTMUCH_STATUS_SUCCESS;
1138 notmuch_database_add_message (notmuch_database_t *notmuch,
1139 const char *filename,
1140 notmuch_message_t **message_ret)
1142 notmuch_message_file_t *message_file;
1143 notmuch_message_t *message = NULL;
1144 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1145 notmuch_private_status_t private_status;
1147 const char *date, *header;
1148 const char *from, *to, *subject;
1149 char *message_id = NULL;
1152 *message_ret = NULL;
1154 message_file = notmuch_message_file_open (filename);
1155 if (message_file == NULL) {
1156 ret = NOTMUCH_STATUS_FILE_ERROR;
1160 notmuch_message_file_restrict_headers (message_file,
1171 /* Before we do any real work, (especially before doing a
1172 * potential SHA-1 computation on the entire file's contents),
1173 * let's make sure that what we're looking at looks like an
1174 * actual email message.
1176 from = notmuch_message_file_get_header (message_file, "from");
1177 subject = notmuch_message_file_get_header (message_file, "subject");
1178 to = notmuch_message_file_get_header (message_file, "to");
1180 if ((from == NULL || *from == '\0') &&
1181 (subject == NULL || *subject == '\0') &&
1182 (to == NULL || *to == '\0'))
1184 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1188 /* Now that we're sure it's mail, the first order of business
1189 * is to find a message ID (or else create one ourselves). */
1191 header = notmuch_message_file_get_header (message_file, "message-id");
1192 if (header && *header != '\0') {
1193 message_id = _parse_message_id (message_file, header, NULL);
1195 /* So the header value isn't RFC-compliant, but it's
1196 * better than no message-id at all. */
1197 if (message_id == NULL)
1198 message_id = talloc_strdup (message_file, header);
1200 /* Reject a Message ID that's too long. */
1201 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1202 talloc_free (message_id);
1207 if (message_id == NULL ) {
1208 /* No message-id at all, let's generate one by taking a
1209 * hash over the file's contents. */
1210 char *sha1 = notmuch_sha1_of_file (filename);
1212 /* If that failed too, something is really wrong. Give up. */
1214 ret = NOTMUCH_STATUS_FILE_ERROR;
1218 message_id = talloc_asprintf (message_file,
1219 "notmuch-sha1-%s", sha1);
1223 /* Now that we have a message ID, we get a message object,
1224 * (which may or may not reference an existing document in the
1227 message = _notmuch_message_create_for_message_id (notmuch,
1231 talloc_free (message_id);
1233 if (message == NULL) {
1234 ret = COERCE_STATUS (private_status,
1235 "Unexpected status value from _notmuch_message_create_for_message_id");
1239 _notmuch_message_add_filename (message, filename);
1241 /* Is this a newly created message object? */
1242 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1243 _notmuch_message_add_term (message, "type", "mail");
1245 ret = _notmuch_database_link_message (notmuch, message,
1250 date = notmuch_message_file_get_header (message_file, "date");
1251 _notmuch_message_set_date (message, date);
1253 _notmuch_message_index_file (message, filename);
1255 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1258 _notmuch_message_sync (message);
1259 } catch (const Xapian::Error &error) {
1260 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1261 error.get_description().c_str());
1262 notmuch->exception_reported = TRUE;
1263 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1269 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1270 *message_ret = message;
1272 notmuch_message_destroy (message);
1276 notmuch_message_file_close (message_file);
1282 notmuch_database_remove_message (notmuch_database_t *notmuch,
1283 const char *filename)
1285 Xapian::WritableDatabase *db;
1286 void *local = talloc_new (notmuch);
1287 const char *direntry_prefix = _find_prefix ("direntry");
1288 char *direntry, *term;
1289 Xapian::PostingIterator i, end;
1290 Xapian::Document document;
1291 notmuch_status_t status;
1293 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
1294 fprintf (stderr, "Attempted to update a read-only database.\n");
1295 return NOTMUCH_STATUS_READONLY_DATABASE;
1298 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1300 status = _notmuch_database_filename_to_direntry (local, notmuch,
1301 filename, &direntry);
1305 term = talloc_asprintf (notmuch, "%s%s", direntry_prefix, direntry);
1307 find_doc_ids_for_term (notmuch, term, &i, &end);
1309 for ( ; i != end; i++) {
1310 Xapian::TermIterator j;
1312 document = find_document_for_doc_id (notmuch, *i);
1314 document.remove_term (term);
1316 j = document.termlist_begin ();
1317 j.skip_to (direntry_prefix);
1319 /* Was this the last direntry in the message? */
1320 if (j == document.termlist_end () ||
1321 strncmp ((*j).c_str (), direntry_prefix, strlen (direntry_prefix)))
1323 db->delete_document (document.get_docid ());
1325 db->replace_document (document.get_docid (), document);
1329 talloc_free (local);
1331 return NOTMUCH_STATUS_SUCCESS;
1335 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1336 Xapian::TermIterator &end)
1338 const char *prefix = _find_prefix ("tag");
1339 notmuch_tags_t *tags;
1342 /* Currently this iteration is written with the assumption that
1343 * "tag" has a single-character prefix. */
1344 assert (strlen (prefix) == 1);
1346 tags = _notmuch_tags_create (ctx);
1347 if (unlikely (tags == NULL))
1355 if (tag.empty () || tag[0] != *prefix)
1358 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1363 _notmuch_tags_prepare_iterator (tags);
1369 notmuch_database_get_all_tags (notmuch_database_t *db)
1371 Xapian::TermIterator i, end;
1372 i = db->xapian_db->allterms_begin();
1373 end = db->xapian_db->allterms_end();
1374 return _notmuch_convert_tags(db, i, end);