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)
310 if (message_id == NULL)
315 skip_space_and_comments (&s);
317 /* Skip any unstructured text as well. */
318 while (*s && *s != '<')
329 skip_space_and_comments (&s);
332 while (*end && *end != '>')
341 if (end > s && *end == '>')
346 result = strndup (s, end - s + 1);
348 /* Finally, collapse any whitespace that is within the message-id
354 for (r = result, len = strlen (r); *r; r++, len--)
355 if (*r == ' ' || *r == '\t')
356 memmove (r, r+1, len);
362 /* Parse a References header value, putting a copy of each referenced
363 * message-id into 'array'. */
365 parse_references (GPtrArray *array,
374 ref = parse_message_id (refs, &refs);
377 g_ptr_array_add (array, ref);
382 notmuch_database_default_path (void)
384 if (getenv ("NOTMUCH_BASE"))
385 return strdup (getenv ("NOTMUCH_BASE"));
387 return g_strdup_printf ("%s/mail", getenv ("HOME"));
391 notmuch_database_create (const char *path)
393 notmuch_database_t *notmuch = NULL;
394 char *notmuch_path = NULL;
397 char *local_path = NULL;
400 path = local_path = notmuch_database_default_path ();
402 err = stat (path, &st);
404 fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
405 path, strerror (errno));
409 if (! S_ISDIR (st.st_mode)) {
410 fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
415 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
417 err = mkdir (notmuch_path, 0755);
420 fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
421 notmuch_path, strerror (errno));
425 notmuch = notmuch_database_open (path);
437 notmuch_database_open (const char *path)
439 notmuch_database_t *notmuch = NULL;
440 char *notmuch_path = NULL, *xapian_path = NULL;
443 char *local_path = NULL;
446 path = local_path = notmuch_database_default_path ();
448 notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
450 err = stat (notmuch_path, &st);
452 fprintf (stderr, "Error opening database at %s: %s\n",
453 notmuch_path, strerror (errno));
457 xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
459 notmuch = talloc (NULL, notmuch_database_t);
460 notmuch->path = talloc_strdup (notmuch, path);
463 notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
464 Xapian::DB_CREATE_OR_OPEN);
465 notmuch->query_parser = new Xapian::QueryParser;
466 notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
467 notmuch->query_parser->set_database (*notmuch->xapian_db);
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->query_parser;
488 delete notmuch->xapian_db;
489 talloc_free (notmuch);
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_file_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_file_open (filename);
517 notmuch_message_file_restrict_headers (message,
527 doc.set_data (filename);
529 add_term (doc, "type", "mail");
531 parents = g_ptr_array_new ();
533 refs = notmuch_message_file_get_header (message, "references");
534 parse_references (parents, refs);
536 in_reply_to = notmuch_message_file_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_file_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 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
581 g_string_free (thread_id, TRUE);
582 } else if (message_id) {
583 /* If not part of any existing thread, generate a new thread_id. */
584 thread_id_t thread_id;
586 thread_id_generate (&thread_id);
587 add_term (doc, "thread", thread_id.str);
588 doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
591 g_ptr_array_free (thread_ids, TRUE);
595 date = notmuch_message_file_get_header (message, "date");
596 time_value = notmuch_parse_date (date, NULL);
598 doc.add_value (NOTMUCH_VALUE_DATE,
599 Xapian::sortable_serialise (time_value));
601 from = notmuch_message_file_get_header (message, "from");
602 subject = notmuch_message_file_get_header (message, "subject");
603 to = notmuch_message_file_get_header (message, "to");
609 notmuch_message_file_close (message);
610 return NOTMUCH_STATUS_FILE_NOT_EMAIL;
612 db->add_document (doc);
614 } catch (const Xapian::Error &error) {
615 fprintf (stderr, "A Xapian exception occurred: %s.\n",
616 error.get_msg().c_str());
617 return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
620 notmuch_message_file_close (message);
622 return NOTMUCH_STATUS_SUCCESS;