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 */
31 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
33 /* Xapian complains if we provide a term longer than this. */
34 #define NOTMUCH_MAX_TERM 245
36 /* These prefix values are specifically chosen to be compatible
37 * with sup, (http://sup.rubyforge.org), written by
38 * William Morgan <wmorgan-sup@masanjin.net>, and released
39 * under the GNU GPL v2.
47 prefix_t NORMAL_PREFIX[] = {
50 { "from_name", "FN" },
56 prefix_t BOOLEAN_PREFIX[] = {
58 { "from_email", "FE" },
64 { "attachment_extension", "O" },
71 find_prefix (const char *name)
75 for (i = 0; i < ARRAY_SIZE (NORMAL_PREFIX); i++)
76 if (strcmp (name, NORMAL_PREFIX[i].name) == 0)
77 return NORMAL_PREFIX[i].prefix;
79 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX); i++)
80 if (strcmp (name, BOOLEAN_PREFIX[i].name) == 0)
81 return BOOLEAN_PREFIX[i].prefix;
86 /* "128 bits of thread-id ought to be enough for anybody" */
87 #define NOTMUCH_THREAD_ID_BITS 128
88 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
89 typedef struct _thread_id {
90 char str[NOTMUCH_THREAD_ID_DIGITS + 1];
94 thread_id_generate (thread_id_t *thread_id)
96 static int seeded = 0;
103 dev_random = fopen ("/dev/random", "r");
104 if (dev_random == NULL) {
107 fread ((void *) &value, sizeof (value), 1, dev_random);
115 for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
117 sprintf (s, "%08x", value);
123 add_term (Xapian::Document doc,
124 const char *prefix_name,
133 prefix = find_prefix (prefix_name);
135 term = g_strdup_printf ("%s%s", prefix, value);
137 if (strlen (term) <= NOTMUCH_MAX_TERM)
144 find_messages_by_term (Xapian::Database *db,
145 const char *prefix_name,
147 Xapian::PostingIterator *begin,
148 Xapian::PostingIterator *end)
150 Xapian::PostingIterator i;
153 term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
155 *begin = db->postlist_begin (term);
158 *end = db->postlist_end (term);
164 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
166 return db->get_document (docid);
170 find_message_by_message_id (Xapian::Database *db, const char *message_id)
172 Xapian::PostingIterator i, end;
174 find_messages_by_term (db, "msgid", message_id, &i, &end);
177 return find_message_by_docid (db, *i);
179 return Xapian::Document ();
183 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
186 const char *value, *id, *comma;
188 value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
189 value = value_string.c_str();
190 if (strlen (value)) {
193 comma = strchr (id, ',');
195 comma = id + strlen (id);
196 g_hash_table_insert (thread_ids,
197 strndup (id, comma - id), NULL);
205 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
206 * given message based on looking into the database for any messages
207 * referenced in parents, and also for any messages in the database
208 * referencing message_id.
210 * Caller should free all strings in the array and the array itself,
211 * (g_ptr_array_free) when done. */
213 find_thread_ids (Xapian::Database *db,
215 const char *message_id)
217 Xapian::PostingIterator child, children_end;
218 Xapian::Document doc;
219 GHashTable *thread_ids;
222 const char *parent_message_id;
225 thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
228 find_messages_by_term (db, "ref", message_id, &child, &children_end);
229 for ( ; child != children_end; child++) {
230 doc = find_message_by_docid (db, *child);
231 insert_thread_id (thread_ids, doc);
234 for (i = 0; i < parents->len; i++) {
235 parent_message_id = (char *) g_ptr_array_index (parents, i);
236 doc = find_message_by_message_id (db, parent_message_id);
237 insert_thread_id (thread_ids, doc);
240 result = g_ptr_array_new ();
242 keys = g_hash_table_get_keys (thread_ids);
243 for (l = keys; l; l = l->next) {
244 char *id = (char *) l->data;
245 g_ptr_array_add (result, id);
249 /* We're done with the hash table, but we've taken the pointers to
250 * the allocated strings and put them into our result array, so
251 * tell the hash not to free them on its way out. */
252 g_hash_table_steal_all (thread_ids);
253 g_hash_table_unref (thread_ids);
258 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
259 * a (potentially nested) parenthesized sequence with '\' used to
260 * escape any character (including parentheses).
262 * If the sequence to be skipped continues to the end of the string,
263 * then 'str' will be left pointing at the final terminating '\0'
267 skip_space_and_comments (const char **str)
272 while (*s && (isspace (*s) || *s == '(')) {
273 while (*s && isspace (*s))
278 while (*s && nesting) {
294 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
295 * comments, and the '<' and '>' delimeters.
297 * If not NULL, then *next will be made to point to the first character
298 * not parsed, (possibly pointing to the final '\0' terminator.
300 * Returns a newly allocated string which the caller should free()
303 * Returns NULL if there is any error parsing the message-id. */
305 parse_message_id (const char *message_id, const char **next)
309 if (message_id == NULL)
314 skip_space_and_comments (&s);
316 /* Skip any unstructured text as well. */
317 while (*s && *s != '<')
328 skip_space_and_comments (&s);
331 while (*end && *end != '>')
340 if (end > s && *end == '>')
343 return strndup (s, end - s + 1);
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 /* C++ is so nasty in requiring these casts. I'm almost tempted to
446 * write a C wrapper for Xapian... */
447 notmuch = (notmuch_database_t *) xmalloc (sizeof (notmuch_database_t));
448 notmuch->path = xstrdup (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 free (notmuch->path);
482 notmuch_database_get_path (notmuch_database_t *notmuch)
484 return notmuch->path;
488 notmuch_database_add_message (notmuch_database_t *notmuch,
489 const char *filename)
491 Xapian::WritableDatabase *db = notmuch->xapian_db;
492 Xapian::Document doc;
493 notmuch_message_file_t *message;
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);
506 notmuch_message_file_restrict_headers (message,
516 doc.set_data (filename);
518 add_term (doc, "type", "mail");
520 parents = g_ptr_array_new ();
522 refs = notmuch_message_file_get_header (message, "references");
523 parse_references (parents, refs);
525 in_reply_to = notmuch_message_file_get_header (message, "in-reply-to");
526 parse_references (parents, in_reply_to);
528 for (i = 0; i < parents->len; i++)
529 add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
531 header = notmuch_message_file_get_header (message, "message-id");
533 message_id = parse_message_id (header, NULL);
534 /* So the header value isn't RFC-compliant, but it's
535 * better than no message-id at all. */
536 if (message_id == NULL)
537 message_id = xstrdup (header);
539 /* XXX: Should generate a message_id here, (such as a SHA1
540 * sum of the message itself) */
544 thread_ids = find_thread_ids (db, parents, message_id);
546 for (i = 0; i < parents->len; i++)
547 g_free (g_ptr_array_index (parents, i));
548 g_ptr_array_free (parents, TRUE);
550 add_term (doc, "msgid", message_id);
551 doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
554 if (thread_ids->len) {
559 for (i = 0; i < thread_ids->len; i++) {
560 id = (char *) thread_ids->pdata[i];
561 add_term (doc, "thread", id);
563 thread_id = g_string_new (id);
565 g_string_append_printf (thread_id, ",%s", id);
569 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
570 g_string_free (thread_id, TRUE);
571 } else if (message_id) {
572 /* If not part of any existing thread, generate a new thread_id. */
573 thread_id_t thread_id;
575 thread_id_generate (&thread_id);
576 add_term (doc, "thread", thread_id.str);
577 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
580 g_ptr_array_free (thread_ids, TRUE);
584 date = notmuch_message_file_get_header (message, "date");
585 time_value = notmuch_parse_date (date, NULL);
587 doc.add_value (NOTMUCH_VALUE_DATE,
588 Xapian::sortable_serialise (time_value));
590 from = notmuch_message_file_get_header (message, "from");
591 subject = notmuch_message_file_get_header (message, "subject");
592 to = notmuch_message_file_get_header (message, "to");
598 notmuch_message_file_close (message);
599 return NOTMUCH_STATUS_FILE_NOT_EMAIL;
601 db->add_document (doc);
603 } catch (const Xapian::Error &error) {
604 fprintf (stderr, "A Xapian exception occurred: %s.\n",
605 error.get_msg().c_str());
606 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
609 notmuch_message_file_close (message);
611 return NOTMUCH_STATUS_SUCCESS;