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_strdup_printf, g_free, GPtrArray, GHashTable */
32 notmuch_status_to_string (notmuch_status_t status)
35 case NOTMUCH_STATUS_SUCCESS:
36 return "No error occurred";
37 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
38 return "A Xapian exception occurred";
39 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
40 return "File is not an email";
41 case NOTMUCH_STATUS_NULL_POINTER:
42 return "Erroneous NULL pointer";
43 case NOTMUCH_STATUS_TAG_TOO_LONG:
44 return "Tag value is too long";
46 case NOTMUCH_STATUS_LAST_STATUS:
47 return "Unknown error status value";
51 /* "128 bits of thread-id ought to be enough for anybody" */
52 #define NOTMUCH_THREAD_ID_BITS 128
53 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
54 typedef struct _thread_id {
55 char str[NOTMUCH_THREAD_ID_DIGITS + 1];
59 thread_id_generate (thread_id_t *thread_id)
61 static int seeded = 0;
68 dev_random = fopen ("/dev/random", "r");
69 if (dev_random == NULL) {
72 fread ((void *) &value, sizeof (value), 1, dev_random);
80 for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
82 sprintf (s, "%08x", value);
87 /* XXX: We should drop this function and convert all callers to call
88 * _notmuch_message_add_term instead. */
90 add_term (Xapian::Document doc,
91 const char *prefix_name,
100 prefix = _find_prefix (prefix_name);
102 term = g_strdup_printf ("%s%s", prefix, value);
104 if (strlen (term) <= NOTMUCH_TERM_MAX)
111 find_messages_by_term (Xapian::Database *db,
112 const char *prefix_name,
114 Xapian::PostingIterator *begin,
115 Xapian::PostingIterator *end)
117 Xapian::PostingIterator i;
120 term = g_strdup_printf ("%s%s", _find_prefix (prefix_name), value);
122 *begin = db->postlist_begin (term);
125 *end = db->postlist_end (term);
131 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
133 return db->get_document (docid);
137 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
140 const char *value, *id, *comma;
142 value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
143 value = value_string.c_str();
144 if (strlen (value)) {
147 comma = strchr (id, ',');
149 comma = id + strlen (id);
150 g_hash_table_insert (thread_ids,
151 strndup (id, comma - id), NULL);
160 notmuch_database_find_message (notmuch_database_t *notmuch,
161 const char *message_id)
163 Xapian::PostingIterator i, end;
165 find_messages_by_term (notmuch->xapian_db,
166 "msgid", message_id, &i, &end);
171 return _notmuch_message_create (notmuch, notmuch, *i);
174 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
175 * given message based on looking into the database for any messages
176 * referenced in parents, and also for any messages in the database
177 * referencing message_id.
179 * Caller should free all strings in the array and the array itself,
180 * (g_ptr_array_free) when done. */
182 find_thread_ids (notmuch_database_t *notmuch,
184 const char *message_id)
186 Xapian::WritableDatabase *db = notmuch->xapian_db;
187 Xapian::PostingIterator child, children_end;
188 Xapian::Document doc;
189 GHashTable *thread_ids;
192 const char *parent_message_id;
195 thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
198 find_messages_by_term (db, "ref", message_id, &child, &children_end);
199 for ( ; child != children_end; child++) {
200 doc = find_message_by_docid (db, *child);
201 insert_thread_id (thread_ids, doc);
204 for (i = 0; i < parents->len; i++) {
205 notmuch_message_t *parent;
206 notmuch_thread_ids_t *ids;
208 parent_message_id = (char *) g_ptr_array_index (parents, i);
209 parent = notmuch_database_find_message (notmuch, parent_message_id);
213 for (ids = notmuch_message_get_thread_ids (parent);
214 notmuch_thread_ids_has_more (ids);
215 notmuch_thread_ids_advance (ids))
219 id = notmuch_thread_ids_get (ids);
220 g_hash_table_insert (thread_ids, strdup (id), NULL);
223 notmuch_message_destroy (parent);
226 result = g_ptr_array_new ();
228 keys = g_hash_table_get_keys (thread_ids);
229 for (l = keys; l; l = l->next) {
230 char *id = (char *) l->data;
231 g_ptr_array_add (result, id);
235 /* We're done with the hash table, but we've taken the pointers to
236 * the allocated strings and put them into our result array, so
237 * tell the hash not to free them on its way out. */
238 g_hash_table_steal_all (thread_ids);
239 g_hash_table_unref (thread_ids);
244 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
245 * a (potentially nested) parenthesized sequence with '\' used to
246 * escape any character (including parentheses).
248 * If the sequence to be skipped continues to the end of the string,
249 * then 'str' will be left pointing at the final terminating '\0'
253 skip_space_and_comments (const char **str)
258 while (*s && (isspace (*s) || *s == '(')) {
259 while (*s && isspace (*s))
264 while (*s && nesting) {
280 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
281 * comments, and the '<' and '>' delimeters.
283 * If not NULL, then *next will be made to point to the first character
284 * not parsed, (possibly pointing to the final '\0' terminator.
286 * Returns a newly allocated string which the caller should free()
289 * Returns NULL if there is any error parsing the message-id. */
291 parse_message_id (const char *message_id, const char **next)
296 if (message_id == NULL)
301 skip_space_and_comments (&s);
303 /* Skip any unstructured text as well. */
304 while (*s && *s != '<')
315 skip_space_and_comments (&s);
318 while (*end && *end != '>')
327 if (end > s && *end == '>')
332 result = strndup (s, end - s + 1);
334 /* Finally, collapse any whitespace that is within the message-id
340 for (r = result, len = strlen (r); *r; r++, len--)
341 if (*r == ' ' || *r == '\t')
342 memmove (r, r+1, len);
348 /* Parse a References header value, putting a copy of each referenced
349 * message-id into 'array'. */
351 parse_references (GPtrArray *array,
360 ref = parse_message_id (refs, &refs);
363 g_ptr_array_add (array, ref);
368 notmuch_database_default_path (void)
370 if (getenv ("NOTMUCH_BASE"))
371 return strdup (getenv ("NOTMUCH_BASE"));
373 return g_strdup_printf ("%s/mail", getenv ("HOME"));
377 notmuch_database_create (const char *path)
379 notmuch_database_t *notmuch = NULL;
380 char *notmuch_path = NULL;
383 char *local_path = NULL;
386 path = local_path = notmuch_database_default_path ();
388 err = stat (path, &st);
390 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
391 path, strerror (errno));
395 if (! S_ISDIR (st.st_mode)) {
396 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
401 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
403 err = mkdir (notmuch_path, 0755);
406 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
407 notmuch_path, strerror (errno));
411 notmuch = notmuch_database_open (path);
423 notmuch_database_open (const char *path)
425 notmuch_database_t *notmuch = NULL;
426 char *notmuch_path = NULL, *xapian_path = NULL;
429 char *local_path = NULL;
432 path = local_path = notmuch_database_default_path ();
434 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
436 err = stat (notmuch_path, &st);
438 fprintf (stderr, "Error opening database at %s: %s\n",
439 notmuch_path, strerror (errno));
443 xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
445 notmuch = talloc (NULL, notmuch_database_t);
446 notmuch->path = talloc_strdup (notmuch, path);
449 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
450 Xapian::DB_CREATE_OR_OPEN);
451 notmuch->query_parser = new Xapian::QueryParser;
452 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
453 notmuch->query_parser->set_database (*notmuch->xapian_db);
454 } catch (const Xapian::Error &error) {
455 fprintf (stderr, "A Xapian exception occurred: %s\n",
456 error.get_msg().c_str());
471 notmuch_database_close (notmuch_database_t *notmuch)
473 delete notmuch->query_parser;
474 delete notmuch->xapian_db;
475 talloc_free (notmuch);
479 notmuch_database_get_path (notmuch_database_t *notmuch)
481 return notmuch->path;
485 notmuch_database_add_message (notmuch_database_t *notmuch,
486 const char *filename)
488 Xapian::WritableDatabase *db = notmuch->xapian_db;
489 Xapian::Document doc;
490 notmuch_message_file_t *message;
492 GPtrArray *parents, *thread_ids;
494 const char *refs, *in_reply_to, *date, *header;
495 const char *from, *to, *subject;
501 message = notmuch_message_file_open (filename);
503 notmuch_message_file_restrict_headers (message,
513 doc.set_data (filename);
515 add_term (doc, "type", "mail");
517 parents = g_ptr_array_new ();
519 refs = notmuch_message_file_get_header (message, "references");
520 parse_references (parents, refs);
522 in_reply_to = notmuch_message_file_get_header (message, "in-reply-to");
523 parse_references (parents, in_reply_to);
525 for (i = 0; i < parents->len; i++)
526 add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
528 header = notmuch_message_file_get_header (message, "message-id");
530 message_id = parse_message_id (header, NULL);
531 /* So the header value isn't RFC-compliant, but it's
532 * better than no message-id at all. */
533 if (message_id == NULL)
534 message_id = xstrdup (header);
536 /* XXX: Should generate a message_id here, (such as a SHA1
537 * sum of the message itself) */
541 thread_ids = find_thread_ids (notmuch, parents, message_id);
543 for (i = 0; i < parents->len; i++)
544 g_free (g_ptr_array_index (parents, i));
545 g_ptr_array_free (parents, TRUE);
547 add_term (doc, "msgid", message_id);
548 doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
551 if (thread_ids->len) {
556 for (i = 0; i < thread_ids->len; i++) {
557 id = (char *) thread_ids->pdata[i];
558 add_term (doc, "thread", id);
560 thread_id = g_string_new (id);
562 g_string_append_printf (thread_id, ",%s", id);
566 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
567 g_string_free (thread_id, TRUE);
568 } else if (message_id) {
569 /* If not part of any existing thread, generate a new thread_id. */
570 thread_id_t thread_id;
572 thread_id_generate (&thread_id);
573 add_term (doc, "thread", thread_id.str);
574 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
577 g_ptr_array_free (thread_ids, TRUE);
581 date = notmuch_message_file_get_header (message, "date");
582 time_value = notmuch_parse_date (date, NULL);
584 doc.add_value (NOTMUCH_VALUE_DATE,
585 Xapian::sortable_serialise (time_value));
587 from = notmuch_message_file_get_header (message, "from");
588 subject = notmuch_message_file_get_header (message, "subject");
589 to = notmuch_message_file_get_header (message, "to");
595 notmuch_message_file_close (message);
596 return NOTMUCH_STATUS_FILE_NOT_EMAIL;
598 db->add_document (doc);
600 } catch (const Xapian::Error &error) {
601 fprintf (stderr, "A Xapian exception occurred: %s.\n",
602 error.get_msg().c_str());
603 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
606 notmuch_message_file_close (message);
608 return NOTMUCH_STATUS_SUCCESS;