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 "notmuch-private.h"
27 #include <glib.h> /* g_strdup_printf, g_free, GHashTable */
31 struct _notmuch_database {
33 Xapian::WritableDatabase *xapian_db;
34 Xapian::TermGenerator *term_gen;
37 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
39 /* Xapian complains if we provide a term longer than this. */
40 #define NOTMUCH_MAX_TERM 245
42 /* These prefix values are specifically chosen to be compatible
43 * with sup, (http://sup.rubyforge.org), written by
44 * William Morgan <wmorgan-sup@masanjin.net>, and released
45 * under the GNU GPL v2.
53 prefix_t NORMAL_PREFIX[] = {
56 { "from_name", "FN" },
62 prefix_t BOOLEAN_PREFIX[] = {
64 { "from_email", "FE" },
70 { "attachment_extension", "O" },
76 /* Similarly, these value numbers are also chosen to be sup
80 NOTMUCH_VALUE_MESSAGE_ID = 0,
81 NOTMUCH_VALUE_THREAD = 1,
82 NOTMUCH_VALUE_DATE = 2
86 find_prefix (const char *name)
90 for (i = 0; i < ARRAY_SIZE (NORMAL_PREFIX); i++)
91 if (strcmp (name, NORMAL_PREFIX[i].name) == 0)
92 return NORMAL_PREFIX[i].prefix;
94 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX); i++)
95 if (strcmp (name, BOOLEAN_PREFIX[i].name) == 0)
96 return BOOLEAN_PREFIX[i].prefix;
101 /* "128 bits of thread-id ought to be enough for anybody" */
102 #define NOTMUCH_THREAD_ID_BITS 128
103 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
104 typedef struct _thread_id {
105 char str[NOTMUCH_THREAD_ID_DIGITS + 1];
109 thread_id_generate (thread_id_t *thread_id)
111 static int seeded = 0;
118 dev_random = fopen ("/dev/random", "r");
119 if (dev_random == NULL) {
122 fread ((void *) &value, sizeof (value), 1, dev_random);
130 for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
132 sprintf (s, "%08x", value);
138 add_term (Xapian::Document doc,
139 const char *prefix_name,
148 prefix = find_prefix (prefix_name);
150 term = g_strdup_printf ("%s%s", prefix, value);
152 if (strlen (term) <= NOTMUCH_MAX_TERM)
159 find_messages_by_term (Xapian::Database *db,
160 const char *prefix_name,
162 Xapian::PostingIterator *begin,
163 Xapian::PostingIterator *end)
165 Xapian::PostingIterator i;
168 term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
170 *begin = db->postlist_begin (term);
173 *end = db->postlist_end (term);
179 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
181 return db->get_document (docid);
185 find_message_by_message_id (Xapian::Database *db, const char *message_id)
187 Xapian::PostingIterator i, end;
189 find_messages_by_term (db, "msgid", message_id, &i, &end);
192 return find_message_by_docid (db, *i);
194 return Xapian::Document ();
198 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
201 const char *value, *id, *comma;
203 value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
204 value = value_string.c_str();
205 if (strlen (value)) {
208 comma = strchr (id, ',');
210 comma = id + strlen (id);
211 g_hash_table_insert (thread_ids,
212 strndup (id, comma - id), NULL);
220 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
221 * given message based on looking into the database for any messages
222 * referenced in parents, and also for any messages in the database
223 * referencing message_id.
225 * Caller should free all strings in the array and the array itself,
226 * (g_ptr_array_free) when done. */
228 find_thread_ids (Xapian::Database *db,
230 const char *message_id)
232 Xapian::PostingIterator child, children_end;
233 Xapian::Document doc;
234 GHashTable *thread_ids;
237 const char *parent_message_id;
240 thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
243 find_messages_by_term (db, "ref", message_id, &child, &children_end);
244 for ( ; child != children_end; child++) {
245 doc = find_message_by_docid (db, *child);
246 insert_thread_id (thread_ids, doc);
249 for (i = 0; i < parents->len; i++) {
250 parent_message_id = (char *) g_ptr_array_index (parents, i);
251 doc = find_message_by_message_id (db, parent_message_id);
252 insert_thread_id (thread_ids, doc);
255 result = g_ptr_array_new ();
257 keys = g_hash_table_get_keys (thread_ids);
258 for (l = keys; l; l = l->next) {
259 char *id = (char *) l->data;
260 g_ptr_array_add (result, id);
264 /* We're done with the hash table, but we've taken the pointers to
265 * the allocated strings and put them into our result array, so
266 * tell the hash not to free them on its way out. */
267 g_hash_table_steal_all (thread_ids);
268 g_hash_table_unref (thread_ids);
273 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
274 * a (potentially nested) parenthesized sequence with '\' used to
275 * escape any character (including parentheses).
277 * If the sequence to be skipped continues to the end of the string,
278 * then 'str' will be left pointing at the final terminating '\0'
282 skip_space_and_comments (const char **str)
287 while (*s && (isspace (*s) || *s == '(')) {
288 while (*s && isspace (*s))
293 while (*s && nesting) {
309 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
310 * comments, and the '<' and '>' delimeters.
312 * If not NULL, then *next will be made to point to the first character
313 * not parsed, (possibly pointing to the final '\0' terminator.
315 * Returns a newly allocated string which the caller should free()
318 * Returns NULL if there is any error parsing the message-id. */
320 parse_message_id (const char *message_id, const char **next)
324 if (message_id == NULL)
329 skip_space_and_comments (&s);
331 /* Skip any unstructured text as well. */
332 while (*s && *s != '<')
343 skip_space_and_comments (&s);
346 while (*end && *end != '>')
355 if (end > s && *end == '>')
358 return strndup (s, end - s + 1);
363 /* Parse a References header value, putting a copy of each referenced
364 * message-id into 'array'. */
366 parse_references (GPtrArray *array,
375 ref = parse_message_id (refs, &refs);
378 g_ptr_array_add (array, ref);
383 notmuch_database_default_path (void)
385 if (getenv ("NOTMUCH_BASE"))
386 return strdup (getenv ("NOTMUCH_BASE"));
388 return g_strdup_printf ("%s/mail", getenv ("HOME"));
392 notmuch_database_create (const char *path)
394 notmuch_database_t *notmuch = NULL;
395 char *notmuch_path = NULL;
398 char *local_path = NULL;
401 path = local_path = notmuch_database_default_path ();
403 err = stat (path, &st);
405 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
406 path, strerror (errno));
410 if (! S_ISDIR (st.st_mode)) {
411 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
416 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
418 err = mkdir (notmuch_path, 0755);
421 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
422 notmuch_path, strerror (errno));
426 notmuch = notmuch_database_open (path);
438 notmuch_database_open (const char *path)
440 notmuch_database_t *notmuch = NULL;
441 char *notmuch_path = NULL, *xapian_path = NULL;
444 char *local_path = NULL;
447 path = local_path = notmuch_database_default_path ();
449 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
451 err = stat (notmuch_path, &st);
453 fprintf (stderr, "Error: Cannot stat %s: %s\n",
454 notmuch_path, strerror (err));
458 xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
460 /* C++ is so nasty in requiring these casts. I'm almost tempted to
461 * write a C wrapper for Xapian... */
462 notmuch = (notmuch_database_t *) xmalloc (sizeof (notmuch_database_t));
463 notmuch->path = xstrdup (path);
466 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
467 Xapian::DB_CREATE_OR_OPEN);
468 } catch (const Xapian::Error &error) {
469 fprintf (stderr, "A Xapian exception occurred: %s\n",
470 error.get_msg().c_str());
485 notmuch_database_close (notmuch_database_t *notmuch)
487 delete notmuch->xapian_db;
488 free (notmuch->path);
493 notmuch_database_get_path (notmuch_database_t *notmuch)
495 return notmuch->path;
499 notmuch_database_add_message (notmuch_database_t *notmuch,
500 const char *filename)
502 Xapian::WritableDatabase *db = notmuch->xapian_db;
503 Xapian::Document doc;
504 notmuch_message_t *message;
506 GPtrArray *parents, *thread_ids;
508 const char *refs, *in_reply_to, *date, *header;
509 const char *from, *to, *subject;
515 message = notmuch_message_open (filename);
517 notmuch_message_restrict_headers (message,
527 doc = Xapian::Document ();
529 doc.set_data (filename);
531 parents = g_ptr_array_new ();
533 refs = notmuch_message_get_header (message, "references");
534 parse_references (parents, refs);
536 in_reply_to = notmuch_message_get_header (message, "in-reply-to");
537 parse_references (parents, in_reply_to);
539 for (i = 0; i < parents->len; i++)
540 add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
542 header = notmuch_message_get_header (message, "message-id");
544 message_id = parse_message_id (header, NULL);
545 /* So the header value isn't RFC-compliant, but it's
546 * better than no message-id at all. */
547 if (message_id == NULL)
548 message_id = xstrdup (header);
550 /* XXX: Should generate a message_id here, (such as a SHA1
551 * sum of the message itself) */
555 thread_ids = find_thread_ids (db, parents, message_id);
557 for (i = 0; i < parents->len; i++)
558 g_free (g_ptr_array_index (parents, i));
559 g_ptr_array_free (parents, TRUE);
561 add_term (doc, "msgid", message_id);
562 doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
565 if (thread_ids->len) {
570 for (i = 0; i < thread_ids->len; i++) {
571 id = (char *) thread_ids->pdata[i];
572 add_term (doc, "thread", id);
574 thread_id = g_string_new (id);
576 g_string_append_printf (thread_id, ",%s", id);
580 g_ptr_array_free (thread_ids, TRUE);
581 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
582 g_string_free (thread_id, TRUE);
583 } else if (message_id) {
584 /* If not part of any existing thread, generate a new thread_id. */
585 thread_id_t thread_id;
587 thread_id_generate (&thread_id);
588 add_term (doc, "thread", thread_id.str);
589 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
594 date = notmuch_message_get_header (message, "date");
595 time_value = notmuch_parse_date (date, NULL);
597 doc.add_value (NOTMUCH_VALUE_DATE,
598 Xapian::sortable_serialise (time_value));
600 from = notmuch_message_get_header (message, "from");
601 subject = notmuch_message_get_header (message, "subject");
602 to = notmuch_message_get_header (message, "to");
608 notmuch_message_close (message);
609 return NOTMUCH_STATUS_FILE_NOT_EMAIL;
611 db->add_document (doc);
613 } catch (const Xapian::Error &error) {
614 fprintf (stderr, "A Xapian exception occurred: %s.\n",
615 error.get_msg().c_str());
616 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
619 notmuch_message_close (message);
621 return NOTMUCH_STATUS_SUCCESS;