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 * parent: The document ID of the parent directory document.
91 * Top-level directories will have a parent value of 0.
93 * and has a single value:
95 * TIMESTAMP: The mtime of the directory (at last scan)
98 /* With these prefix values we follow the conventions published here:
100 * http://xapian.org/docs/omega/termprefixes.html
102 * as much as makes sense. Note that I took some liberty in matching
103 * the reserved prefix values to notmuch concepts, (for example, 'G'
104 * is documented as "newsGroup (or similar entity - e.g. a web forum
105 * name)", for which I think the thread is the closest analogue in
106 * notmuch. This in spite of the fact that we will eventually be
107 * storing mailing-list messages where 'G' for "mailing list name"
108 * might be even a closer analogue. I'm treating the single-character
109 * prefixes preferentially for core notmuch concepts (which will be
110 * nearly universal to all mail messages).
113 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
115 { "reference", "XREFERENCE" },
116 { "replyto", "XREPLYTO" },
117 { "directory", "XDIRECTORY" },
118 { "parent", "XPARENT" },
121 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
127 prefix_t PROBABILISTIC_PREFIX[]= {
130 { "attachment", "XATTACHMENT" },
131 { "subject", "XSUBJECT"}
135 _internal_error (const char *format, ...)
139 va_start (va_args, format);
141 fprintf (stderr, "Internal error: ");
142 vfprintf (stderr, format, va_args);
150 _find_prefix (const char *name)
154 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
155 if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
156 return BOOLEAN_PREFIX_INTERNAL[i].prefix;
159 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
160 if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
161 return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
164 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
165 if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
166 return PROBABILISTIC_PREFIX[i].prefix;
169 INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
175 notmuch_status_to_string (notmuch_status_t status)
178 case NOTMUCH_STATUS_SUCCESS:
179 return "No error occurred";
180 case NOTMUCH_STATUS_OUT_OF_MEMORY:
181 return "Out of memory";
182 case NOTMUCH_STATUS_READONLY_DATABASE:
183 return "The database is read-only";
184 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
185 return "A Xapian exception occurred";
186 case NOTMUCH_STATUS_FILE_ERROR:
187 return "Something went wrong trying to read or write a file";
188 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
189 return "File is not an email";
190 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
191 return "Message ID is identical to a message in database";
192 case NOTMUCH_STATUS_NULL_POINTER:
193 return "Erroneous NULL pointer";
194 case NOTMUCH_STATUS_TAG_TOO_LONG:
195 return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
196 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
197 return "Unbalanced number of calls to notmuch_message_freeze/thaw";
199 case NOTMUCH_STATUS_LAST_STATUS:
200 return "Unknown error status value";
205 find_doc_ids (notmuch_database_t *notmuch,
206 const char *prefix_name,
208 Xapian::PostingIterator *begin,
209 Xapian::PostingIterator *end)
211 Xapian::PostingIterator i;
214 term = talloc_asprintf (notmuch, "%s%s",
215 _find_prefix (prefix_name), value);
217 *begin = notmuch->xapian_db->postlist_begin (term);
219 *end = notmuch->xapian_db->postlist_end (term);
224 static notmuch_private_status_t
225 find_unique_doc_id (notmuch_database_t *notmuch,
226 const char *prefix_name,
228 unsigned int *doc_id)
230 Xapian::PostingIterator i, end;
232 find_doc_ids (notmuch, prefix_name, value, &i, &end);
236 return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
239 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
243 static Xapian::Document
244 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
246 return notmuch->xapian_db->get_document (doc_id);
249 static notmuch_private_status_t
250 find_unique_document (notmuch_database_t *notmuch,
251 const char *prefix_name,
253 Xapian::Document *document,
254 unsigned int *doc_id)
256 notmuch_private_status_t status;
258 status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
261 *document = Xapian::Document ();
265 *document = find_document_for_doc_id (notmuch, *doc_id);
266 return NOTMUCH_PRIVATE_STATUS_SUCCESS;
270 notmuch_database_find_message (notmuch_database_t *notmuch,
271 const char *message_id)
273 notmuch_private_status_t status;
276 status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
278 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
281 return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
284 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
285 * a (potentially nested) parenthesized sequence with '\' used to
286 * escape any character (including parentheses).
288 * If the sequence to be skipped continues to the end of the string,
289 * then 'str' will be left pointing at the final terminating '\0'
293 skip_space_and_comments (const char **str)
298 while (*s && (isspace (*s) || *s == '(')) {
299 while (*s && isspace (*s))
304 while (*s && nesting) {
307 } else if (*s == ')') {
309 } else if (*s == '\\') {
321 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
322 * comments, and the '<' and '>' delimeters.
324 * If not NULL, then *next will be made to point to the first character
325 * not parsed, (possibly pointing to the final '\0' terminator.
327 * Returns a newly talloc'ed string belonging to 'ctx'.
329 * Returns NULL if there is any error parsing the message-id. */
331 _parse_message_id (void *ctx, const char *message_id, const char **next)
336 if (message_id == NULL || *message_id == '\0')
341 skip_space_and_comments (&s);
343 /* Skip any unstructured text as well. */
344 while (*s && *s != '<')
355 skip_space_and_comments (&s);
358 while (*end && *end != '>')
367 if (end > s && *end == '>')
372 result = talloc_strndup (ctx, s, end - s + 1);
374 /* Finally, collapse any whitespace that is within the message-id
380 for (r = result, len = strlen (r); *r; r++, len--)
381 if (*r == ' ' || *r == '\t')
382 memmove (r, r+1, len);
388 /* Parse a References header value, putting a (talloc'ed under 'ctx')
389 * copy of each referenced message-id into 'hash'.
391 * We explicitly avoid including any reference identical to
392 * 'message_id' in the result (to avoid mass confusion when a single
393 * message references itself cyclically---and yes, mail messages are
394 * not infrequent in the wild that do this---don't ask me why).
397 parse_references (void *ctx,
398 const char *message_id,
404 if (refs == NULL || *refs == '\0')
408 ref = _parse_message_id (ctx, refs, &refs);
410 if (ref && strcmp (ref, message_id))
411 g_hash_table_insert (hash, ref, NULL);
416 notmuch_database_create (const char *path)
418 notmuch_database_t *notmuch = NULL;
419 char *notmuch_path = NULL;
424 fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
428 err = stat (path, &st);
430 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
431 path, strerror (errno));
435 if (! S_ISDIR (st.st_mode)) {
436 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
441 notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
443 err = mkdir (notmuch_path, 0755);
446 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
447 notmuch_path, strerror (errno));
451 notmuch = notmuch_database_open (path,
452 NOTMUCH_DATABASE_MODE_READ_WRITE);
456 talloc_free (notmuch_path);
462 notmuch_database_open (const char *path,
463 notmuch_database_mode_t mode)
465 notmuch_database_t *notmuch = NULL;
466 char *notmuch_path = NULL, *xapian_path = NULL;
471 if (asprintf (¬much_path, "%s/%s", path, ".notmuch") == -1) {
473 fprintf (stderr, "Out of memory\n");
477 err = stat (notmuch_path, &st);
479 fprintf (stderr, "Error opening database at %s: %s\n",
480 notmuch_path, strerror (errno));
484 if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
486 fprintf (stderr, "Out of memory\n");
490 notmuch = talloc (NULL, notmuch_database_t);
491 notmuch->exception_reported = FALSE;
492 notmuch->path = talloc_strdup (notmuch, path);
494 if (notmuch->path[strlen (notmuch->path) - 1] == '/')
495 notmuch->path[strlen (notmuch->path) - 1] = '\0';
497 notmuch->mode = mode;
499 if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
500 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
501 Xapian::DB_CREATE_OR_OPEN);
503 notmuch->xapian_db = new Xapian::Database (xapian_path);
505 notmuch->query_parser = new Xapian::QueryParser;
506 notmuch->term_gen = new Xapian::TermGenerator;
507 notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
508 notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
510 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
511 notmuch->query_parser->set_database (*notmuch->xapian_db);
512 notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
513 notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
514 notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
516 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
517 prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
518 notmuch->query_parser->add_boolean_prefix (prefix->name,
522 for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
523 prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
524 notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
526 } catch (const Xapian::Error &error) {
527 fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
528 error.get_msg().c_str());
542 notmuch_database_close (notmuch_database_t *notmuch)
545 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
546 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
547 } catch (const Xapian::Error &error) {
548 if (! notmuch->exception_reported) {
549 fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
550 error.get_msg().c_str());
554 delete notmuch->term_gen;
555 delete notmuch->query_parser;
556 delete notmuch->xapian_db;
557 delete notmuch->value_range_processor;
558 talloc_free (notmuch);
562 notmuch_database_get_path (notmuch_database_t *notmuch)
564 return notmuch->path;
567 static notmuch_private_status_t
568 find_directory_document (notmuch_database_t *notmuch, const char *db_path,
569 Xapian::Document *doc, unsigned int *doc_id)
571 return find_unique_document (notmuch, "directory", db_path, doc, doc_id);
574 /* We allow the user to use arbitrarily long paths for directories. But
575 * we have a term-length limit. So if we exceed that, we'll use the
576 * SHA-1 of the path for the database term.
578 * Note: This function may return the original value of 'path'. If it
579 * does not, then the caller is responsible to free() the returned
583 directory_db_path (const char *path)
585 int term_len = strlen (_find_prefix ("directory")) + strlen (path);
587 if (term_len > NOTMUCH_TERM_MAX)
588 return notmuch_sha1_of_string (path);
594 _find_parent_id (notmuch_database_t *notmuch,
596 Xapian::docid *parent_id)
598 const char *slash, *parent_db_path;
600 notmuch_private_status_t private_status;
601 notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
603 if (path == NULL || *path == '\0') {
605 return NOTMUCH_STATUS_SUCCESS;
608 /* Find the last slash (not counting a trailing slash), if any. */
610 slash = path + strlen (path) - 1;
612 /* First, skip trailing slashes. */
613 while (slash != path) {
620 /* Then, find a slash. */
621 while (slash != path) {
628 /* Finally, skip multiple slashes. */
629 while (slash != path) {
637 parent_path = talloc_strdup (notmuch, "");
639 parent_path = talloc_strndup (notmuch, path, slash - path + 1);
641 parent_db_path = directory_db_path (parent_path);
643 private_status = find_unique_doc_id (notmuch, "directory",
644 parent_db_path, parent_id);
645 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
646 status = notmuch_database_set_directory_mtime (notmuch,
650 private_status = find_unique_doc_id (notmuch, "directory",
651 parent_db_path, parent_id);
652 status = COERCE_STATUS (private_status, "_find_parent_id");
655 if (parent_db_path != parent_path)
656 free ((char *) parent_db_path);
658 talloc_free (parent_path);
663 /* Given a legal 'path' for the database, return the relative path.
665 * The return value will be a pointer to the originl path contents,
666 * and will be either the original string (if 'path' was relative) or
667 * a portion of the string (if path was absolute and begins with the
671 _notmuch_database_relative_path (notmuch_database_t *notmuch,
674 const char *db_path, *relative;
675 unsigned int db_path_len;
677 db_path = notmuch_database_get_path (notmuch);
678 db_path_len = strlen (db_path);
682 if (*relative == '/') {
683 while (*relative == '/' && *(relative+1) == '/')
686 if (strncmp (relative, db_path, db_path_len) == 0)
688 relative += db_path_len;
689 while (*relative == '/')
698 notmuch_database_set_directory_mtime (notmuch_database_t *notmuch,
702 Xapian::Document doc;
703 Xapian::WritableDatabase *db;
705 notmuch_private_status_t status;
706 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
707 const char *db_path = NULL;
708 Xapian::docid parent_id;
710 if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
711 fprintf (stderr, "Attempted to update a read-only database.\n");
712 return NOTMUCH_STATUS_READONLY_DATABASE;
715 path = _notmuch_database_relative_path (notmuch, path);
717 db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
718 db_path = directory_db_path (path);
721 status = find_directory_document (notmuch, db_path, &doc, &doc_id);
723 doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
724 Xapian::sortable_serialise (mtime));
726 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
727 char *term = talloc_asprintf (NULL, "%s%s",
728 _find_prefix ("directory"), db_path);
732 status = _find_parent_id (notmuch, path, &parent_id);
736 term = talloc_asprintf (NULL, "%s%u",
737 _find_prefix ("parent"),
742 db->add_document (doc);
744 db->replace_document (doc_id, doc);
747 } catch (const Xapian::Error &error) {
748 fprintf (stderr, "A Xapian exception occurred setting directory mtime: %s.\n",
749 error.get_msg().c_str());
750 notmuch->exception_reported = TRUE;
751 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
755 free ((char *) db_path);
761 notmuch_database_get_directory_mtime (notmuch_database_t *notmuch,
764 Xapian::Document doc;
766 notmuch_private_status_t status;
767 const char *db_path = NULL;
770 db_path = directory_db_path (path);
773 status = find_directory_document (notmuch, db_path, &doc, &doc_id);
775 if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
778 ret = Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
779 } catch (Xapian::Error &error) {
786 free ((char *) db_path);
791 /* Find the thread ID to which the message with 'message_id' belongs.
793 * Returns NULL if no message with message ID 'message_id' is in the
796 * Otherwise, returns a newly talloced string belonging to 'ctx'.
799 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
801 const char *message_id)
803 notmuch_message_t *message;
804 const char *ret = NULL;
806 message = notmuch_database_find_message (notmuch, message_id);
810 ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
814 notmuch_message_destroy (message);
819 static notmuch_status_t
820 _merge_threads (notmuch_database_t *notmuch,
821 const char *winner_thread_id,
822 const char *loser_thread_id)
824 Xapian::PostingIterator loser, loser_end;
825 notmuch_message_t *message = NULL;
826 notmuch_private_status_t private_status;
827 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
829 find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
831 for ( ; loser != loser_end; loser++) {
832 message = _notmuch_message_create (notmuch, notmuch,
833 *loser, &private_status);
834 if (message == NULL) {
835 ret = COERCE_STATUS (private_status,
836 "Cannot find document for doc_id from query");
840 _notmuch_message_remove_term (message, "thread", loser_thread_id);
841 _notmuch_message_add_term (message, "thread", winner_thread_id);
842 _notmuch_message_sync (message);
844 notmuch_message_destroy (message);
850 notmuch_message_destroy (message);
856 _my_talloc_free_for_g_hash (void *ptr)
861 static notmuch_status_t
862 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
863 notmuch_message_t *message,
864 notmuch_message_file_t *message_file,
865 const char **thread_id)
867 GHashTable *parents = NULL;
868 const char *refs, *in_reply_to, *in_reply_to_message_id;
869 GList *l, *keys = NULL;
870 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
872 parents = g_hash_table_new_full (g_str_hash, g_str_equal,
873 _my_talloc_free_for_g_hash, NULL);
875 refs = notmuch_message_file_get_header (message_file, "references");
876 parse_references (message, notmuch_message_get_message_id (message),
879 in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
880 parse_references (message, notmuch_message_get_message_id (message),
881 parents, in_reply_to);
883 /* Carefully avoid adding any self-referential in-reply-to term. */
884 in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
885 if (in_reply_to_message_id &&
886 strcmp (in_reply_to_message_id,
887 notmuch_message_get_message_id (message)))
889 _notmuch_message_add_term (message, "replyto",
890 _parse_message_id (message, in_reply_to, NULL));
893 keys = g_hash_table_get_keys (parents);
894 for (l = keys; l; l = l->next) {
895 char *parent_message_id;
896 const char *parent_thread_id;
898 parent_message_id = (char *) l->data;
899 parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
903 if (parent_thread_id == NULL) {
904 _notmuch_message_add_term (message, "reference",
907 if (*thread_id == NULL) {
908 *thread_id = talloc_strdup (message, parent_thread_id);
909 _notmuch_message_add_term (message, "thread", *thread_id);
910 } else if (strcmp (*thread_id, parent_thread_id)) {
911 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
922 g_hash_table_unref (parents);
927 static notmuch_status_t
928 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
929 notmuch_message_t *message,
930 const char **thread_id)
932 const char *message_id = notmuch_message_get_message_id (message);
933 Xapian::PostingIterator child, children_end;
934 notmuch_message_t *child_message = NULL;
935 const char *child_thread_id;
936 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
937 notmuch_private_status_t private_status;
939 find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
941 for ( ; child != children_end; child++) {
943 child_message = _notmuch_message_create (message, notmuch,
944 *child, &private_status);
945 if (child_message == NULL) {
946 ret = COERCE_STATUS (private_status,
947 "Cannot find document for doc_id from query");
951 child_thread_id = notmuch_message_get_thread_id (child_message);
952 if (*thread_id == NULL) {
953 *thread_id = talloc_strdup (message, child_thread_id);
954 _notmuch_message_add_term (message, "thread", *thread_id);
955 } else if (strcmp (*thread_id, child_thread_id)) {
956 _notmuch_message_remove_term (child_message, "reference",
958 _notmuch_message_sync (child_message);
959 ret = _merge_threads (notmuch, *thread_id, child_thread_id);
964 notmuch_message_destroy (child_message);
965 child_message = NULL;
970 notmuch_message_destroy (child_message);
975 /* Given a (mostly empty) 'message' and its corresponding
976 * 'message_file' link it to existing threads in the database.
978 * We first look at 'message_file' and its link-relevant headers
979 * (References and In-Reply-To) for message IDs. We also look in the
980 * database for existing message that reference 'message'.
982 * The end result is to call _notmuch_message_ensure_thread_id which
983 * generates a new thread ID if the message doesn't connect to any
986 static notmuch_status_t
987 _notmuch_database_link_message (notmuch_database_t *notmuch,
988 notmuch_message_t *message,
989 notmuch_message_file_t *message_file)
991 notmuch_status_t status;
992 const char *thread_id = NULL;
994 status = _notmuch_database_link_message_to_parents (notmuch, message,
1000 status = _notmuch_database_link_message_to_children (notmuch, message,
1005 if (thread_id == NULL)
1006 _notmuch_message_ensure_thread_id (message);
1008 return NOTMUCH_STATUS_SUCCESS;
1012 notmuch_database_add_message (notmuch_database_t *notmuch,
1013 const char *filename,
1014 notmuch_message_t **message_ret)
1016 notmuch_message_file_t *message_file;
1017 notmuch_message_t *message = NULL;
1018 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1019 notmuch_private_status_t private_status;
1021 const char *date, *header;
1022 const char *from, *to, *subject;
1023 char *message_id = NULL;
1026 *message_ret = NULL;
1028 message_file = notmuch_message_file_open (filename);
1029 if (message_file == NULL) {
1030 ret = NOTMUCH_STATUS_FILE_ERROR;
1034 notmuch_message_file_restrict_headers (message_file,
1045 /* Before we do any real work, (especially before doing a
1046 * potential SHA-1 computation on the entire file's contents),
1047 * let's make sure that what we're looking at looks like an
1048 * actual email message.
1050 from = notmuch_message_file_get_header (message_file, "from");
1051 subject = notmuch_message_file_get_header (message_file, "subject");
1052 to = notmuch_message_file_get_header (message_file, "to");
1054 if ((from == NULL || *from == '\0') &&
1055 (subject == NULL || *subject == '\0') &&
1056 (to == NULL || *to == '\0'))
1058 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1062 /* Now that we're sure it's mail, the first order of business
1063 * is to find a message ID (or else create one ourselves). */
1065 header = notmuch_message_file_get_header (message_file, "message-id");
1066 if (header && *header != '\0') {
1067 message_id = _parse_message_id (message_file, header, NULL);
1069 /* So the header value isn't RFC-compliant, but it's
1070 * better than no message-id at all. */
1071 if (message_id == NULL)
1072 message_id = talloc_strdup (message_file, header);
1074 /* Reject a Message ID that's too long. */
1075 if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1076 talloc_free (message_id);
1081 if (message_id == NULL ) {
1082 /* No message-id at all, let's generate one by taking a
1083 * hash over the file's contents. */
1084 char *sha1 = notmuch_sha1_of_file (filename);
1086 /* If that failed too, something is really wrong. Give up. */
1088 ret = NOTMUCH_STATUS_FILE_ERROR;
1092 message_id = talloc_asprintf (message_file,
1093 "notmuch-sha1-%s", sha1);
1097 /* Now that we have a message ID, we get a message object,
1098 * (which may or may not reference an existing document in the
1101 message = _notmuch_message_create_for_message_id (notmuch,
1105 talloc_free (message_id);
1107 if (message == NULL) {
1108 ret = COERCE_STATUS (private_status,
1109 "Unexpected status value from _notmuch_message_create_for_message_id");
1113 /* Is this a newly created message object? */
1114 if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1115 _notmuch_message_set_filename (message, filename);
1116 _notmuch_message_add_term (message, "type", "mail");
1118 ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1122 ret = _notmuch_database_link_message (notmuch, message, message_file);
1126 date = notmuch_message_file_get_header (message_file, "date");
1127 _notmuch_message_set_date (message, date);
1129 _notmuch_message_index_file (message, filename);
1131 _notmuch_message_sync (message);
1132 } catch (const Xapian::Error &error) {
1133 fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1134 error.get_description().c_str());
1135 notmuch->exception_reported = TRUE;
1136 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1142 if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1143 *message_ret = message;
1145 notmuch_message_destroy (message);
1149 notmuch_message_file_close (message_file);
1155 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1156 Xapian::TermIterator &end)
1158 const char *prefix = _find_prefix ("tag");
1159 notmuch_tags_t *tags;
1162 /* Currently this iteration is written with the assumption that
1163 * "tag" has a single-character prefix. */
1164 assert (strlen (prefix) == 1);
1166 tags = _notmuch_tags_create (ctx);
1167 if (unlikely (tags == NULL))
1175 if (tag.empty () || tag[0] != *prefix)
1178 _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1183 _notmuch_tags_prepare_iterator (tags);
1189 notmuch_database_get_all_tags (notmuch_database_t *db)
1191 Xapian::TermIterator i, end;
1192 i = db->xapian_db->allterms_begin();
1193 end = db->xapian_db->allterms_end();
1194 return _notmuch_convert_tags(db, i, end);