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_ERROR:
40 return "Something went wrong trying to read or write a file";
41 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
42 return "File is not an email";
43 case NOTMUCH_STATUS_NULL_POINTER:
44 return "Erroneous NULL pointer";
45 case NOTMUCH_STATUS_TAG_TOO_LONG:
46 return "Tag value is too long";
48 case NOTMUCH_STATUS_LAST_STATUS:
49 return "Unknown error status value";
53 /* "128 bits of thread-id ought to be enough for anybody" */
54 #define NOTMUCH_THREAD_ID_BITS 128
55 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
56 typedef struct _thread_id {
57 char str[NOTMUCH_THREAD_ID_DIGITS + 1];
61 thread_id_generate (thread_id_t *thread_id)
63 static int seeded = 0;
70 dev_random = fopen ("/dev/random", "r");
71 if (dev_random == NULL) {
74 fread ((void *) &value, sizeof (value), 1, dev_random);
82 for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
84 sprintf (s, "%08x", value);
89 /* XXX: We should drop this function and convert all callers to call
90 * _notmuch_message_add_term instead. */
92 add_term (Xapian::Document doc,
93 const char *prefix_name,
102 prefix = _find_prefix (prefix_name);
104 term = g_strdup_printf ("%s%s", prefix, value);
106 if (strlen (term) <= NOTMUCH_TERM_MAX)
113 find_messages_by_term (Xapian::Database *db,
114 const char *prefix_name,
116 Xapian::PostingIterator *begin,
117 Xapian::PostingIterator *end)
119 Xapian::PostingIterator i;
122 term = g_strdup_printf ("%s%s", _find_prefix (prefix_name), value);
124 *begin = db->postlist_begin (term);
127 *end = db->postlist_end (term);
133 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
135 return db->get_document (docid);
139 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
142 const char *value, *id, *comma;
144 value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
145 value = value_string.c_str();
146 if (strlen (value)) {
149 comma = strchr (id, ',');
151 comma = id + strlen (id);
152 g_hash_table_insert (thread_ids,
153 strndup (id, comma - id), NULL);
162 notmuch_database_find_message (notmuch_database_t *notmuch,
163 const char *message_id)
165 Xapian::PostingIterator i, end;
167 find_messages_by_term (notmuch->xapian_db,
168 "msgid", message_id, &i, &end);
173 return _notmuch_message_create (notmuch, notmuch, *i);
176 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
177 * given message based on looking into the database for any messages
178 * referenced in parents, and also for any messages in the database
179 * referencing message_id.
181 * Caller should free all strings in the array and the array itself,
182 * (g_ptr_array_free) when done. */
184 find_thread_ids (notmuch_database_t *notmuch,
186 const char *message_id)
188 Xapian::WritableDatabase *db = notmuch->xapian_db;
189 Xapian::PostingIterator child, children_end;
190 Xapian::Document doc;
191 GHashTable *thread_ids;
194 const char *parent_message_id;
197 thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
200 find_messages_by_term (db, "ref", message_id, &child, &children_end);
201 for ( ; child != children_end; child++) {
202 doc = find_message_by_docid (db, *child);
203 insert_thread_id (thread_ids, doc);
206 for (i = 0; i < parents->len; i++) {
207 notmuch_message_t *parent;
208 notmuch_thread_ids_t *ids;
210 parent_message_id = (char *) g_ptr_array_index (parents, i);
211 parent = notmuch_database_find_message (notmuch, parent_message_id);
215 for (ids = notmuch_message_get_thread_ids (parent);
216 notmuch_thread_ids_has_more (ids);
217 notmuch_thread_ids_advance (ids))
221 id = notmuch_thread_ids_get (ids);
222 g_hash_table_insert (thread_ids, strdup (id), NULL);
225 notmuch_message_destroy (parent);
228 result = g_ptr_array_new ();
230 keys = g_hash_table_get_keys (thread_ids);
231 for (l = keys; l; l = l->next) {
232 char *id = (char *) l->data;
233 g_ptr_array_add (result, id);
237 /* We're done with the hash table, but we've taken the pointers to
238 * the allocated strings and put them into our result array, so
239 * tell the hash not to free them on its way out. */
240 g_hash_table_steal_all (thread_ids);
241 g_hash_table_unref (thread_ids);
246 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
247 * a (potentially nested) parenthesized sequence with '\' used to
248 * escape any character (including parentheses).
250 * If the sequence to be skipped continues to the end of the string,
251 * then 'str' will be left pointing at the final terminating '\0'
255 skip_space_and_comments (const char **str)
260 while (*s && (isspace (*s) || *s == '(')) {
261 while (*s && isspace (*s))
266 while (*s && nesting) {
282 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
283 * comments, and the '<' and '>' delimeters.
285 * If not NULL, then *next will be made to point to the first character
286 * not parsed, (possibly pointing to the final '\0' terminator.
288 * Returns a newly allocated string which the caller should free()
291 * Returns NULL if there is any error parsing the message-id. */
293 parse_message_id (const char *message_id, const char **next)
298 if (message_id == NULL)
303 skip_space_and_comments (&s);
305 /* Skip any unstructured text as well. */
306 while (*s && *s != '<')
317 skip_space_and_comments (&s);
320 while (*end && *end != '>')
329 if (end > s && *end == '>')
334 result = strndup (s, end - s + 1);
336 /* Finally, collapse any whitespace that is within the message-id
342 for (r = result, len = strlen (r); *r; r++, len--)
343 if (*r == ' ' || *r == '\t')
344 memmove (r, r+1, len);
350 /* Parse a References header value, putting a copy of each referenced
351 * message-id into 'array'. */
353 parse_references (GPtrArray *array,
362 ref = parse_message_id (refs, &refs);
365 g_ptr_array_add (array, ref);
370 notmuch_database_default_path (void)
372 if (getenv ("NOTMUCH_BASE"))
373 return strdup (getenv ("NOTMUCH_BASE"));
375 return g_strdup_printf ("%s/mail", getenv ("HOME"));
379 notmuch_database_create (const char *path)
381 notmuch_database_t *notmuch = NULL;
382 char *notmuch_path = NULL;
385 char *local_path = NULL;
388 path = local_path = notmuch_database_default_path ();
390 err = stat (path, &st);
392 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
393 path, strerror (errno));
397 if (! S_ISDIR (st.st_mode)) {
398 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
403 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
405 err = mkdir (notmuch_path, 0755);
408 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
409 notmuch_path, strerror (errno));
413 notmuch = notmuch_database_open (path);
425 notmuch_database_open (const char *path)
427 notmuch_database_t *notmuch = NULL;
428 char *notmuch_path = NULL, *xapian_path = NULL;
431 char *local_path = NULL;
434 path = local_path = notmuch_database_default_path ();
436 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
438 err = stat (notmuch_path, &st);
440 fprintf (stderr, "Error opening database at %s: %s\n",
441 notmuch_path, strerror (errno));
445 xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
447 notmuch = talloc (NULL, notmuch_database_t);
448 notmuch->path = talloc_strdup (notmuch, path);
451 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
452 Xapian::DB_CREATE_OR_OPEN);
453 notmuch->query_parser = new Xapian::QueryParser;
454 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
455 notmuch->query_parser->set_database (*notmuch->xapian_db);
456 } catch (const Xapian::Error &error) {
457 fprintf (stderr, "A Xapian exception occurred: %s\n",
458 error.get_msg().c_str());
473 notmuch_database_close (notmuch_database_t *notmuch)
475 delete notmuch->query_parser;
476 delete notmuch->xapian_db;
477 talloc_free (notmuch);
481 notmuch_database_get_path (notmuch_database_t *notmuch)
483 return notmuch->path;
487 notmuch_database_add_message (notmuch_database_t *notmuch,
488 const char *filename)
490 Xapian::WritableDatabase *db = notmuch->xapian_db;
491 Xapian::Document doc;
492 notmuch_message_file_t *message;
493 notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
495 GPtrArray *parents, *thread_ids;
497 const char *refs, *in_reply_to, *date, *header;
498 const char *from, *to, *subject;
504 message = notmuch_message_file_open (filename);
505 if (message == NULL) {
506 ret = NOTMUCH_STATUS_FILE_ERROR;
510 notmuch_message_file_restrict_headers (message,
521 doc.set_data (filename);
523 add_term (doc, "type", "mail");
525 parents = g_ptr_array_new ();
527 refs = notmuch_message_file_get_header (message, "references");
528 parse_references (parents, refs);
530 in_reply_to = notmuch_message_file_get_header (message, "in-reply-to");
531 parse_references (parents, in_reply_to);
533 for (i = 0; i < parents->len; i++)
534 add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
536 header = notmuch_message_file_get_header (message, "message-id");
538 message_id = parse_message_id (header, NULL);
539 /* So the header value isn't RFC-compliant, but it's
540 * better than no message-id at all. */
541 if (message_id == NULL)
542 message_id = xstrdup (header);
544 /* No message-id at all, let's generate one by taking a
545 * hash over the file's contents. */
546 char *sha1 = notmuch_sha1_of_file (filename);
548 /* If that failed too, something is really wrong. Give up. */
550 ret = NOTMUCH_STATUS_FILE_ERROR;
554 message_id = g_strdup_printf ("notmuch-sha1-%s", sha1);
558 thread_ids = find_thread_ids (notmuch, parents, message_id);
560 for (i = 0; i < parents->len; i++)
561 g_free (g_ptr_array_index (parents, i));
562 g_ptr_array_free (parents, TRUE);
564 add_term (doc, "msgid", message_id);
565 doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
569 if (thread_ids->len) {
574 for (i = 0; i < thread_ids->len; i++) {
575 id = (char *) thread_ids->pdata[i];
576 add_term (doc, "thread", id);
578 thread_id = g_string_new (id);
580 g_string_append_printf (thread_id, ",%s", id);
584 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
585 g_string_free (thread_id, TRUE);
587 /* If not part of any existing thread, generate a new thread_id. */
588 thread_id_t thread_id;
590 thread_id_generate (&thread_id);
591 add_term (doc, "thread", thread_id.str);
592 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
595 g_ptr_array_free (thread_ids, TRUE);
597 date = notmuch_message_file_get_header (message, "date");
598 time_value = notmuch_parse_date (date, NULL);
600 doc.add_value (NOTMUCH_VALUE_DATE,
601 Xapian::sortable_serialise (time_value));
603 from = notmuch_message_file_get_header (message, "from");
604 subject = notmuch_message_file_get_header (message, "subject");
605 to = notmuch_message_file_get_header (message, "to");
611 ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
614 db->add_document (doc);
616 } catch (const Xapian::Error &error) {
617 fprintf (stderr, "A Xapian exception occurred: %s.\n",
618 error.get_msg().c_str());
619 ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
625 notmuch_message_file_close (message);