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 * A mail document also has two values:
68 * TIMESTAMP: The time_t value corresponding to the message's
71 * MESSAGE_ID: The unique ID of the mail mess (see "id" above)
73 * In addition, terms from the content of the message are added with
74 * "from", "to", "attachment", and "subject" prefixes for use by the
75 * user in searching. But the database doesn't really care itself
78 * Finally, the data portion of a mail document contains the path name
79 * of the mail message (relative to the database path).
83 * A directory document is used by a client of the notmuch library to
84 * maintain data necessary to allow for efficient polling of mail
87 * The directory document contains the following terms:
89 * directory: The directory path (relative to the database path)
90 * Or the SHA1 sum of the directory path (if the
91 * path itself is too long to fit in a Xapian
94 * parent: The document ID of the parent directory document.
95 * Top-level directories will have a parent value of 0.
97 * and has a single value:
99 * TIMESTAMP: The mtime of the directory (at last scan)
101 * The data portion of a directory document contains the path of the
102 * directory (relative to the datbase path).
105 /* With these prefix values we follow the conventions published here:
107 * http://xapian.org/docs/omega/termprefixes.html
109 * as much as makes sense. Note that I took some liberty in matching
110 * the reserved prefix values to notmuch concepts, (for example, 'G'
111 * is documented as "newsGroup (or similar entity - e.g. a web forum
112 * name)", for which I think the thread is the closest analogue in
113 * notmuch. This in spite of the fact that we will eventually be
114 * storing mailing-list messages where 'G' for "mailing list name"
115 * might be even a closer analogue. I'm treating the single-character
116 * prefixes preferentially for core notmuch concepts (which will be
117 * nearly universal to all mail messages).
120 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
122 { "reference", "XREFERENCE" },
123 { "replyto", "XREPLYTO" },
124 { "directory", "XDIRECTORY" },
125 { "parent", "XPARENT" },
128 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
134 prefix_t PROBABILISTIC_PREFIX[]= {
137 { "attachment", "XATTACHMENT" },
138 { "subject", "XSUBJECT"}
142 _internal_error (const char *format, ...)
146 va_start (va_args, format);
148 fprintf (stderr, "Internal error: ");
149 vfprintf (stderr, format, va_args);
157 _find_prefix (const char *name)
161 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
162 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
163 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
166 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
167 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
168 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
171 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
172 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
173 return PROBABILISTIC_PREFIX[i].prefix;
176 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
182 notmuch_status_to_string (notmuch_status_t status)
185 case NOTMUCH_STATUS_SUCCESS:
186 return "No error occurred";
187 case NOTMUCH_STATUS_OUT_OF_MEMORY:
188 return "Out of memory";
189 case NOTMUCH_STATUS_READONLY_DATABASE:
190 return "The database is read-only";
191 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
192 return "A Xapian exception occurred";
193 case NOTMUCH_STATUS_FILE_ERROR:
194 return "Something went wrong trying to read or write a file";
195 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
196 return "File is not an email";
197 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
198 return "Message ID is identical to a message in database";
199 case NOTMUCH_STATUS_NULL_POINTER:
200 return "Erroneous NULL pointer";
201 case NOTMUCH_STATUS_TAG_TOO_LONG:
202 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
203 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
204 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
206 case NOTMUCH_STATUS_LAST_STATUS:
207 return "Unknown error status value";
212 find_doc_ids (notmuch_database_t *notmuch,
213 const char *prefix_name,
215 Xapian::PostingIterator *begin,
216 Xapian::PostingIterator *end)
218 Xapian::PostingIterator i;
221 term = talloc_asprintf (notmuch, "%s%s",
222 _find_prefix (prefix_name), value);
224 *begin = notmuch->xapian_db->postlist_begin (term);
226 *end = notmuch->xapian_db->postlist_end (term);
231 static notmuch_private_status_t
232 find_unique_doc_id (notmuch_database_t *notmuch,
233 const char *prefix_name,
235 unsigned int *doc_id)
237 Xapian::PostingIterator i, end;
239 find_doc_ids (notmuch, prefix_name, value, &i, &end);
243 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
246 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
250 static Xapian::Document
251 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
253 return notmuch->xapian_db->get_document (doc_id);
256 static notmuch_private_status_t
257 find_unique_document (notmuch_database_t *notmuch,
258 const char *prefix_name,
260 Xapian::Document *document,
261 unsigned int *doc_id)
263 notmuch_private_status_t status;
265 status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
268 *document = Xapian::Document ();
272 *document = find_document_for_doc_id (notmuch, *doc_id);
273 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
277 notmuch_database_find_message (notmuch_database_t *notmuch,
278 const char *message_id)
280 notmuch_private_status_t status;
283 status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
285 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
288 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
291 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
292 * a (potentially nested) parenthesized sequence with '\' used to
293 * escape any character (including parentheses).
295 * If the sequence to be skipped continues to the end of the string,
296 * then 'str' will be left pointing at the final terminating '\0'
300 skip_space_and_comments (const char **str)
305 while (*s && (isspace (*s) || *s == '(')) {
306 while (*s && isspace (*s))
311 while (*s && nesting) {
314 } else if (*s == ')') {
316 } else if (*s == '\\') {
328 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
329 * comments, and the '<' and '>' delimeters.
331 * If not NULL, then *next will be made to point to the first character
332 * not parsed, (possibly pointing to the final '\0' terminator.
334 * Returns a newly talloc'ed string belonging to 'ctx'.
336 * Returns NULL if there is any error parsing the message-id. */
338 _parse_message_id (void *ctx, const char *message_id, const char **next)
343 if (message_id == NULL || *message_id == '\0')
348 skip_space_and_comments (&s);
350 /* Skip any unstructured text as well. */
351 while (*s && *s != '<')
362 skip_space_and_comments (&s);
365 while (*end && *end != '>')
374 if (end > s && *end == '>')
379 result = talloc_strndup (ctx, s, end - s + 1);
381 /* Finally, collapse any whitespace that is within the message-id
387 for (r = result, len = strlen (r); *r; r++, len--)
388 if (*r == ' ' || *r == '\t')
389 memmove (r, r+1, len);
395 /* Parse a References header value, putting a (talloc'ed under 'ctx')
396 * copy of each referenced message-id into 'hash'.
398 * We explicitly avoid including any reference identical to
399 * 'message_id' in the result (to avoid mass confusion when a single
400 * message references itself cyclically---and yes, mail messages are
401 * not infrequent in the wild that do this---don't ask me why).
404 parse_references (void *ctx,
405 const char *message_id,
411 if (refs == NULL || *refs == '\0')
415 ref = _parse_message_id (ctx, refs, &refs);
417 if (ref && strcmp (ref, message_id))
418 g_hash_table_insert (hash, ref, NULL);
423 notmuch_database_create (const char *path)
425 notmuch_database_t *notmuch = NULL;
426 char *notmuch_path = NULL;
431 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
435 err = stat (path, &st);
437 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
438 path, strerror (errno));
442 if (! S_ISDIR (st.st_mode)) {
443 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
448 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
450 err = mkdir (notmuch_path, 0755);
453 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
454 notmuch_path, strerror (errno));
458 notmuch = notmuch_database_open (path,
459 NOTMUCH_DATABASE_MODE_READ_WRITE);
463 talloc_free (notmuch_path);
469 notmuch_database_open (const char *path,
470 notmuch_database_mode_t mode)
472 notmuch_database_t *notmuch = NULL;
473 char *notmuch_path = NULL, *xapian_path = NULL;
478 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
480 fprintf (stderr, "Out of memory\n");
484 err = stat (notmuch_path, &st);
486 fprintf (stderr, "Error opening database at %s: %s\n",
487 notmuch_path, strerror (errno));
491 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
493 fprintf (stderr, "Out of memory\n");
497 notmuch = talloc (NULL, notmuch_database_t);
498 notmuch->exception_reported = FALSE;
499 notmuch->path = talloc_strdup (notmuch, path);
501 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
502 notmuch->path[strlen (notmuch->path) - 1] = '\0';
504 notmuch->mode = mode;
506 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
507 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
508 Xapian::DB_CREATE_OR_OPEN);
510 notmuch->xapian_db = new Xapian::Database (xapian_path);
512 notmuch->query_parser = new Xapian::QueryParser;
513 notmuch->term_gen = new Xapian::TermGenerator;
514 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
515 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
517 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
518 notmuch->query_parser->set_database (*notmuch->xapian_db);
519 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
520 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
521 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
523 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
524 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
525 notmuch->query_parser->add_boolean_prefix (prefix->name,
529 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
530 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
531 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
533 } catch (const Xapian::Error &error) {
534 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
535 error.get_msg().c_str());
549 notmuch_database_close (notmuch_database_t *notmuch)
552 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
553 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
554 } catch (const Xapian::Error &error) {
555 if (! notmuch->exception_reported) {
556 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
557 error.get_msg().c_str());
561 delete notmuch->term_gen;
562 delete notmuch->query_parser;
563 delete notmuch->xapian_db;
564 delete notmuch->value_range_processor;
565 talloc_free (notmuch);
569 notmuch_database_get_path (notmuch_database_t *notmuch)
571 return notmuch->path;
574 static notmuch_private_status_t
575 find_directory_document (notmuch_database_t *notmuch, const char *db_path,
576 Xapian::Document *doc, unsigned int *doc_id)
578 return find_unique_document (notmuch, "directory", db_path, doc, doc_id);
581 /* We allow the user to use arbitrarily long paths for directories. But
582 * we have a term-length limit. So if we exceed that, we'll use the
583 * SHA-1 of the path for the database term.
585 * Note: This function may return the original value of 'path'. If it
586 * does not, then the caller is responsible to free() the returned
590 directory_db_path (const char *path)
592 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
594 if (term_len > NOTMUCH_TERM_MAX)
595 return notmuch_sha1_of_string (path);
600 /* Given a path, split it into two parts: the directory part is all
601 * components except for the last, and the basename is that last
602 * component. Getting the return-value for either part is optional
603 * (the caller can pass NULL).
605 * The original 'path' can represent either a regular file or a
606 * directory---the splitting will be carried out in the same way in
607 * either case. Trailing slashes on 'path' will be ignored, and any
608 * cases of multiple '/' characters appearing in series will be
609 * treated as a single '/'.
611 * Allocation (if any) will have 'ctx' as the talloc owner. But
612 * pointers will be returned within the original path string whenever
615 * Note: If 'path' is non-empty and contains no non-trailing slash,
616 * (that is, consists of a filename with no parent directory), then
617 * the directory returned will be an empty string. However, if 'path'
618 * is an empty string, then both directory and basename will be
622 _notmuch_database_split_path (void *ctx,
624 const char **directory,
625 const char **basename)
629 if (path == NULL || *path == '\0') {
634 return NOTMUCH_STATUS_SUCCESS;
637 /* Find the last slash (not counting a trailing slash), if any. */
639 slash = path + strlen (path) - 1;
641 /* First, skip trailing slashes. */
642 while (slash != path) {
649 /* Then, find a slash. */
650 while (slash != path) {
660 /* Finally, skip multiple slashes. */
661 while (slash != path) {
670 *directory = talloc_strdup (ctx, "");
675 *directory = talloc_strndup (ctx, path, slash - path + 1);
678 return NOTMUCH_STATUS_SUCCESS;
682 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
684 unsigned int *directory_id)
686 notmuch_private_status_t private_status;
687 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
692 return NOTMUCH_STATUS_SUCCESS;
695 db_path = directory_db_path (path);
697 private_status = find_unique_doc_id (notmuch, "directory",
698 db_path, directory_id);
699 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
700 status = notmuch_database_set_directory_mtime (notmuch,
705 private_status = find_unique_doc_id (notmuch, "directory",
706 db_path, directory_id);
707 status = COERCE_STATUS (private_status, "_find_directory_id");
712 free ((char *) db_path);
720 /* Given a legal 'path' for the database, return the relative path.
722 * The return value will be a pointer to the originl path contents,
723 * and will be either the original string (if 'path' was relative) or
724 * a portion of the string (if path was absolute and begins with the
728 _notmuch_database_relative_path (notmuch_database_t *notmuch,
731 const char *db_path, *relative;
732 unsigned int db_path_len;
734 db_path = notmuch_database_get_path (notmuch);
735 db_path_len = strlen (db_path);
739 if (*relative == '/') {
740 while (*relative == '/' && *(relative+1) == '/')
743 if (strncmp (relative, db_path, db_path_len) == 0)
745 relative += db_path_len;
746 while (*relative == '/')
755 notmuch_database_set_directory_mtime (notmuch_database_t *notmuch,
759 Xapian::Document doc;
760 Xapian::WritableDatabase *db;
762 notmuch_private_status_t status;
763 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
764 const char *parent, *db_path = NULL;
765 unsigned int parent_id;
766 void *local = talloc_new (notmuch);
768 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
769 fprintf (stderr, "Attempted to update a read-only database.\n");
770 return NOTMUCH_STATUS_READONLY_DATABASE;
773 path = _notmuch_database_relative_path (notmuch, path);
775 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
776 db_path = directory_db_path (path);
779 status = find_directory_document (notmuch, db_path, &doc, &doc_id);
781 doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
782 Xapian::sortable_serialise (mtime));
784 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
785 char *term = talloc_asprintf (local, "%s%s",
786 _find_prefix ("directory"), db_path);
791 _notmuch_database_split_path (local, path, &parent, NULL);
793 _notmuch_database_find_directory_id (notmuch, parent, &parent_id);
795 term = talloc_asprintf (local, "%s%u",
796 _find_prefix ("parent"),
800 db->add_document (doc);
802 db->replace_document (doc_id, doc);
805 } catch (const Xapian::Error &error) {
806 fprintf (stderr, "A Xapian exception occurred setting directory mtime: %s.\n",
807 error.get_msg().c_str());
808 notmuch->exception_reported = TRUE;
809 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
813 free ((char *) db_path);
819 notmuch_database_get_directory_mtime (notmuch_database_t *notmuch,
822 Xapian::Document doc;
824 notmuch_private_status_t status;
825 const char *db_path = NULL;
827 void *local = talloc_new (notmuch);
829 db_path = directory_db_path (path);
832 status = find_directory_document (notmuch, db_path, &doc, &doc_id);
834 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
837 ret = Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
838 } catch (Xapian::Error &error) {
845 free ((char *) db_path);
852 /* Find the thread ID to which the message with 'message_id' belongs.
854 * Returns NULL if no message with message ID 'message_id' is in the
857 * Otherwise, returns a newly talloced string belonging to 'ctx'.
860 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
862 const char *message_id)
864 notmuch_message_t *message;
865 const char *ret = NULL;
867 message = notmuch_database_find_message (notmuch, message_id);
871 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
875 notmuch_message_destroy (message);
880 static notmuch_status_t
881 _merge_threads (notmuch_database_t *notmuch,
882 const char *winner_thread_id,
883 const char *loser_thread_id)
885 Xapian::PostingIterator loser, loser_end;
886 notmuch_message_t *message = NULL;
887 notmuch_private_status_t private_status;
888 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
890 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
892 for ( ; loser != loser_end; loser++) {
893 message = _notmuch_message_create (notmuch, notmuch,
894 *loser, &private_status);
895 if (message == NULL) {
896 ret = COERCE_STATUS (private_status,
897 "Cannot find document for doc_id from query");
901 _notmuch_message_remove_term (message, "thread", loser_thread_id);
902 _notmuch_message_add_term (message, "thread", winner_thread_id);
903 _notmuch_message_sync (message);
905 notmuch_message_destroy (message);
911 notmuch_message_destroy (message);
917 _my_talloc_free_for_g_hash (void *ptr)
922 static notmuch_status_t
923 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
924 notmuch_message_t *message,
925 notmuch_message_file_t *message_file,
926 const char **thread_id)
928 GHashTable *parents = NULL;
929 const char *refs, *in_reply_to, *in_reply_to_message_id;
930 GList *l, *keys = NULL;
931 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
933 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
934 _my_talloc_free_for_g_hash, NULL);
936 refs = notmuch_message_file_get_header (message_file, "references");
937 parse_references (message, notmuch_message_get_message_id (message),
940 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
941 parse_references (message, notmuch_message_get_message_id (message),
942 parents, in_reply_to);
944 /* Carefully avoid adding any self-referential in-reply-to term. */
945 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
946 if (in_reply_to_message_id &&
947 strcmp (in_reply_to_message_id,
948 notmuch_message_get_message_id (message)))
950 _notmuch_message_add_term (message, "replyto",
951 _parse_message_id (message, in_reply_to, NULL));
954 keys = g_hash_table_get_keys (parents);
955 for (l = keys; l; l = l->next) {
956 char *parent_message_id;
957 const char *parent_thread_id;
959 parent_message_id = (char *) l->data;
960 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
964 if (parent_thread_id == NULL) {
965 _notmuch_message_add_term (message, "reference",
968 if (*thread_id == NULL) {
969 *thread_id = talloc_strdup (message, parent_thread_id);
970 _notmuch_message_add_term (message, "thread", *thread_id);
971 } else if (strcmp (*thread_id, parent_thread_id)) {
972 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
983 g_hash_table_unref (parents);
988 static notmuch_status_t
989 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
990 notmuch_message_t *message,
991 const char **thread_id)
993 const char *message_id = notmuch_message_get_message_id (message);
994 Xapian::PostingIterator child, children_end;
995 notmuch_message_t *child_message = NULL;
996 const char *child_thread_id;
997 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
998 notmuch_private_status_t private_status;
1000 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1002 for ( ; child != children_end; child++) {
1004 child_message = _notmuch_message_create (message, notmuch,
1005 *child, &private_status);
1006 if (child_message == NULL) {
1007 ret = COERCE_STATUS (private_status,
1008 "Cannot find document for doc_id from query");
1012 child_thread_id = notmuch_message_get_thread_id (child_message);
1013 if (*thread_id == NULL) {
1014 *thread_id = talloc_strdup (message, child_thread_id);
1015 _notmuch_message_add_term (message, "thread", *thread_id);
1016 } else if (strcmp (*thread_id, child_thread_id)) {
1017 _notmuch_message_remove_term (child_message, "reference",
1019 _notmuch_message_sync (child_message);
1020 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1025 notmuch_message_destroy (child_message);
1026 child_message = NULL;
1031 notmuch_message_destroy (child_message);
1036 /* Given a (mostly empty) 'message' and its corresponding
1037 * 'message_file' link it to existing threads in the database.
1039 * We first look at 'message_file' and its link-relevant headers
1040 * (References and In-Reply-To) for message IDs. We also look in the
1041 * database for existing message that reference 'message'.
1043 * The end result is to call _notmuch_message_ensure_thread_id which
1044 * generates a new thread ID if the message doesn't connect to any
1047 static notmuch_status_t
1048 _notmuch_database_link_message (notmuch_database_t *notmuch,
1049 notmuch_message_t *message,
1050 notmuch_message_file_t *message_file)
1052 notmuch_status_t status;
1053 const char *thread_id = NULL;
1055 status = _notmuch_database_link_message_to_parents (notmuch, message,
1061 status = _notmuch_database_link_message_to_children (notmuch, message,
1066 if (thread_id == NULL)
1067 _notmuch_message_ensure_thread_id (message);
1069 return NOTMUCH_STATUS_SUCCESS;
1073 notmuch_database_add_message (notmuch_database_t *notmuch,
1074 const char *filename,
1075 notmuch_message_t **message_ret)
1077 notmuch_message_file_t *message_file;
1078 notmuch_message_t *message = NULL;
1079 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1080 notmuch_private_status_t private_status;
1082 const char *date, *header;
1083 const char *from, *to, *subject;
1084 char *message_id = NULL;
1087 *message_ret = NULL;
1089 message_file = notmuch_message_file_open (filename);
1090 if (message_file == NULL) {
1091 ret = NOTMUCH_STATUS_FILE_ERROR;
1095 notmuch_message_file_restrict_headers (message_file,
1106 /* Before we do any real work, (especially before doing a
1107 * potential SHA-1 computation on the entire file's contents),
1108 * let's make sure that what we're looking at looks like an
1109 * actual email message.
1111 from = notmuch_message_file_get_header (message_file, "from");
1112 subject = notmuch_message_file_get_header (message_file, "subject");
1113 to = notmuch_message_file_get_header (message_file, "to");
1115 if ((from == NULL || *from == '\0') &&
1116 (subject == NULL || *subject == '\0') &&
1117 (to == NULL || *to == '\0'))
1119 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1123 /* Now that we're sure it's mail, the first order of business
1124 * is to find a message ID (or else create one ourselves). */
1126 header = notmuch_message_file_get_header (message_file, "message-id");
1127 if (header && *header != '\0') {
1128 message_id = _parse_message_id (message_file, header, NULL);
1130 /* So the header value isn't RFC-compliant, but it's
1131 * better than no message-id at all. */
1132 if (message_id == NULL)
1133 message_id = talloc_strdup (message_file, header);
1135 /* Reject a Message ID that's too long. */
1136 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1137 talloc_free (message_id);
1142 if (message_id == NULL ) {
1143 /* No message-id at all, let's generate one by taking a
1144 * hash over the file's contents. */
1145 char *sha1 = notmuch_sha1_of_file (filename);
1147 /* If that failed too, something is really wrong. Give up. */
1149 ret = NOTMUCH_STATUS_FILE_ERROR;
1153 message_id = talloc_asprintf (message_file,
1154 "notmuch-sha1-%s", sha1);
1158 /* Now that we have a message ID, we get a message object,
1159 * (which may or may not reference an existing document in the
1162 message = _notmuch_message_create_for_message_id (notmuch,
1166 talloc_free (message_id);
1168 if (message == NULL) {
1169 ret = COERCE_STATUS (private_status,
1170 "Unexpected status value from _notmuch_message_create_for_message_id");
1174 /* Is this a newly created message object? */
1175 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1176 _notmuch_message_set_filename (message, filename);
1177 _notmuch_message_add_term (message, "type", "mail");
1179 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1183 ret = _notmuch_database_link_message (notmuch, message, message_file);
1187 date = notmuch_message_file_get_header (message_file, "date");
1188 _notmuch_message_set_date (message, date);
1190 _notmuch_message_index_file (message, filename);
1192 _notmuch_message_sync (message);
1193 } catch (const Xapian::Error &error) {
1194 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1195 error.get_description().c_str());
1196 notmuch->exception_reported = TRUE;
1197 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1203 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1204 *message_ret = message;
1206 notmuch_message_destroy (message);
1210 notmuch_message_file_close (message_file);
1216 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1217 Xapian::TermIterator &end)
1219 const char *prefix = _find_prefix ("tag");
1220 notmuch_tags_t *tags;
1223 /* Currently this iteration is written with the assumption that
1224 * "tag" has a single-character prefix. */
1225 assert (strlen (prefix) == 1);
1227 tags = _notmuch_tags_create (ctx);
1228 if (unlikely (tags == NULL))
1236 if (tag.empty () || tag[0] != *prefix)
1239 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1244 _notmuch_tags_prepare_iterator (tags);
1250 notmuch_database_get_all_tags (notmuch_database_t *db)
1252 Xapian::TermIterator i, end;
1253 i = db->xapian_db->allterms_begin();
1254 end = db->xapian_db->allterms_end();
1255 return _notmuch_convert_tags(db, i, end);