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" },
70 /* Similarly, these value numbers are also chosen to be sup
74 NOTMUCH_VALUE_MESSAGE_ID = 0,
75 NOTMUCH_VALUE_THREAD = 1,
76 NOTMUCH_VALUE_DATE = 2
80 find_prefix (const char *name)
84 for (i = 0; i < ARRAY_SIZE (NORMAL_PREFIX); i++)
85 if (strcmp (name, NORMAL_PREFIX[i].name) == 0)
86 return NORMAL_PREFIX[i].prefix;
88 for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX); i++)
89 if (strcmp (name, BOOLEAN_PREFIX[i].name) == 0)
90 return BOOLEAN_PREFIX[i].prefix;
95 /* "128 bits of thread-id ought to be enough for anybody" */
96 #define NOTMUCH_THREAD_ID_BITS 128
97 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
98 typedef struct _thread_id {
99 char str[NOTMUCH_THREAD_ID_DIGITS + 1];
103 thread_id_generate (thread_id_t *thread_id)
105 static int seeded = 0;
112 dev_random = fopen ("/dev/random", "r");
113 if (dev_random == NULL) {
116 fread ((void *) &value, sizeof (value), 1, dev_random);
124 for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
126 sprintf (s, "%08x", value);
132 add_term (Xapian::Document doc,
133 const char *prefix_name,
142 prefix = find_prefix (prefix_name);
144 term = g_strdup_printf ("%s%s", prefix, value);
146 if (strlen (term) <= NOTMUCH_MAX_TERM)
153 find_messages_by_term (Xapian::Database *db,
154 const char *prefix_name,
156 Xapian::PostingIterator *begin,
157 Xapian::PostingIterator *end)
159 Xapian::PostingIterator i;
162 term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
164 *begin = db->postlist_begin (term);
167 *end = db->postlist_end (term);
173 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
175 return db->get_document (docid);
179 find_message_by_message_id (Xapian::Database *db, const char *message_id)
181 Xapian::PostingIterator i, end;
183 find_messages_by_term (db, "msgid", message_id, &i, &end);
186 return find_message_by_docid (db, *i);
188 return Xapian::Document ();
192 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
195 const char *value, *id, *comma;
197 value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
198 value = value_string.c_str();
199 if (strlen (value)) {
202 comma = strchr (id, ',');
204 comma = id + strlen (id);
205 g_hash_table_insert (thread_ids,
206 strndup (id, comma - id), NULL);
214 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
215 * given message based on looking into the database for any messages
216 * referenced in parents, and also for any messages in the database
217 * referencing message_id.
219 * Caller should free all strings in the array and the array itself,
220 * (g_ptr_array_free) when done. */
222 find_thread_ids (Xapian::Database *db,
224 const char *message_id)
226 Xapian::PostingIterator child, children_end;
227 Xapian::Document doc;
228 GHashTable *thread_ids;
231 const char *parent_message_id;
234 thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
237 find_messages_by_term (db, "ref", message_id, &child, &children_end);
238 for ( ; child != children_end; child++) {
239 doc = find_message_by_docid (db, *child);
240 insert_thread_id (thread_ids, doc);
243 for (i = 0; i < parents->len; i++) {
244 parent_message_id = (char *) g_ptr_array_index (parents, i);
245 doc = find_message_by_message_id (db, parent_message_id);
246 insert_thread_id (thread_ids, doc);
249 result = g_ptr_array_new ();
251 keys = g_hash_table_get_keys (thread_ids);
252 for (l = keys; l; l = l->next) {
253 char *id = (char *) l->data;
254 g_ptr_array_add (result, id);
258 /* We're done with the hash table, but we've taken the pointers to
259 * the allocated strings and put them into our result array, so
260 * tell the hash not to free them on its way out. */
261 g_hash_table_steal_all (thread_ids);
262 g_hash_table_unref (thread_ids);
267 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
268 * a (potentially nested) parenthesized sequence with '\' used to
269 * escape any character (including parentheses).
271 * If the sequence to be skipped continues to the end of the string,
272 * then 'str' will be left pointing at the final terminating '\0'
276 skip_space_and_comments (const char **str)
281 while (*s && (isspace (*s) || *s == '(')) {
282 while (*s && isspace (*s))
287 while (*s && nesting) {
303 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
304 * comments, and the '<' and '>' delimeters.
306 * If not NULL, then *next will be made to point to the first character
307 * not parsed, (possibly pointing to the final '\0' terminator.
309 * Returns a newly allocated string which the caller should free()
312 * Returns NULL if there is any error parsing the message-id. */
314 parse_message_id (const char *message_id, const char **next)
318 if (message_id == NULL)
323 skip_space_and_comments (&s);
325 /* Skip any unstructured text as well. */
326 while (*s && *s != '<')
337 skip_space_and_comments (&s);
340 while (*end && *end != '>')
349 if (end > s && *end == '>')
352 return strndup (s, end - s + 1);
357 /* Parse a References header value, putting a copy of each referenced
358 * message-id into 'array'. */
360 parse_references (GPtrArray *array,
369 ref = parse_message_id (refs, &refs);
372 g_ptr_array_add (array, ref);
377 notmuch_database_default_path (void)
379 if (getenv ("NOTMUCH_BASE"))
380 return strdup (getenv ("NOTMUCH_BASE"));
382 return g_strdup_printf ("%s/mail", getenv ("HOME"));
386 notmuch_database_create (const char *path)
388 notmuch_database_t *notmuch = NULL;
389 char *notmuch_path = NULL;
392 char *local_path = NULL;
395 path = local_path = notmuch_database_default_path ();
397 err = stat (path, &st);
399 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
400 path, strerror (errno));
404 if (! S_ISDIR (st.st_mode)) {
405 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
410 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
412 err = mkdir (notmuch_path, 0755);
415 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
416 notmuch_path, strerror (errno));
420 notmuch = notmuch_database_open (path);
432 notmuch_database_open (const char *path)
434 notmuch_database_t *notmuch = NULL;
435 char *notmuch_path = NULL, *xapian_path = NULL;
438 char *local_path = NULL;
441 path = local_path = notmuch_database_default_path ();
443 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
445 err = stat (notmuch_path, &st);
447 fprintf (stderr, "Error opening database at %s: %s\n",
448 notmuch_path, strerror (errno));
452 xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
454 /* C++ is so nasty in requiring these casts. I'm almost tempted to
455 * write a C wrapper for Xapian... */
456 notmuch = (notmuch_database_t *) xmalloc (sizeof (notmuch_database_t));
457 notmuch->path = xstrdup (path);
460 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
461 Xapian::DB_CREATE_OR_OPEN);
462 } catch (const Xapian::Error &error) {
463 fprintf (stderr, "A Xapian exception occurred: %s\n",
464 error.get_msg().c_str());
479 notmuch_database_close (notmuch_database_t *notmuch)
481 delete notmuch->xapian_db;
482 free (notmuch->path);
487 notmuch_database_get_path (notmuch_database_t *notmuch)
489 return notmuch->path;
493 notmuch_database_add_message (notmuch_database_t *notmuch,
494 const char *filename)
496 Xapian::WritableDatabase *db = notmuch->xapian_db;
497 Xapian::Document doc;
498 notmuch_message_file_t *message;
500 GPtrArray *parents, *thread_ids;
502 const char *refs, *in_reply_to, *date, *header;
503 const char *from, *to, *subject;
509 message = notmuch_message_file_open (filename);
511 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 /* XXX: Should generate a message_id here, (such as a SHA1
545 * sum of the message itself) */
549 thread_ids = find_thread_ids (db, parents, message_id);
551 for (i = 0; i < parents->len; i++)
552 g_free (g_ptr_array_index (parents, i));
553 g_ptr_array_free (parents, TRUE);
555 add_term (doc, "msgid", message_id);
556 doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
559 if (thread_ids->len) {
564 for (i = 0; i < thread_ids->len; i++) {
565 id = (char *) thread_ids->pdata[i];
566 add_term (doc, "thread", id);
568 thread_id = g_string_new (id);
570 g_string_append_printf (thread_id, ",%s", id);
574 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
575 g_string_free (thread_id, TRUE);
576 } else if (message_id) {
577 /* If not part of any existing thread, generate a new thread_id. */
578 thread_id_t thread_id;
580 thread_id_generate (&thread_id);
581 add_term (doc, "thread", thread_id.str);
582 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
585 g_ptr_array_free (thread_ids, TRUE);
589 date = notmuch_message_file_get_header (message, "date");
590 time_value = notmuch_parse_date (date, NULL);
592 doc.add_value (NOTMUCH_VALUE_DATE,
593 Xapian::sortable_serialise (time_value));
595 from = notmuch_message_file_get_header (message, "from");
596 subject = notmuch_message_file_get_header (message, "subject");
597 to = notmuch_message_file_get_header (message, "to");
603 notmuch_message_file_close (message);
604 return NOTMUCH_STATUS_FILE_NOT_EMAIL;
606 db->add_document (doc);
608 } catch (const Xapian::Error &error) {
609 fprintf (stderr, "A Xapian exception occurred: %s.\n",
610 error.get_msg().c_str());
611 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
614 notmuch_message_file_close (message);
616 return NOTMUCH_STATUS_SUCCESS;