]> git.notmuchmail.org Git - notmuch/blob - database.cc
notmuch: Start actually adding messages to the index.
[notmuch] / database.cc
1 /* database.cc - The database interfaces of the notmuch mail library
2  *
3  * Copyright © 2009 Carl Worth
4  *
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.
9  *
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.
14  *
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/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-private.h"
22
23 #include <stdio.h>
24 #include <errno.h>
25 #include <time.h>
26 #include <unistd.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/time.h>
30
31 #include <iostream>
32
33 #include <gmime/gmime.h>
34
35 #include <xapian.h>
36
37 using namespace std;
38
39 struct _notmuch_database {
40     char *path;
41     Xapian::WritableDatabase *xapian_db;
42     Xapian::TermGenerator *term_gen;
43 };
44
45 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
46
47 /* Xapian complains if we provide a term longer than this. */
48 #define NOTMUCH_MAX_TERM 245
49
50 /* These prefix values are specifically chosen to be compatible
51  * with sup, (http://sup.rubyforge.org), written by
52  * William Morgan <wmorgan-sup@masanjin.net>, and released
53  * under the GNU GPL v2.
54  */
55
56 typedef struct {
57     const char *name;
58     const char *prefix;
59 } prefix_t;
60
61 prefix_t NORMAL_PREFIX[] = {
62     { "subject", "S" },
63     { "body", "B" },
64     { "from_name", "FN" },
65     { "to_name", "TN" },
66     { "name", "N" },
67     { "attachment", "A" }
68 };
69
70 prefix_t BOOLEAN_PREFIX[] = {
71     { "type", "K" },
72     { "from_email", "FE" },
73     { "to_email", "TE" },
74     { "email", "E" },
75     { "date", "D" },
76     { "label", "L" },
77     { "source_id", "I" },
78     { "attachment_extension", "O" },
79     { "msgid", "Q" },
80     { "thread", "H" },
81     { "ref", "R" }
82 };
83
84 /* Similarly, these value numbers are also chosen to be sup
85  * compatible. */
86
87 typedef enum {
88     NOTMUCH_VALUE_MESSAGE_ID = 0,
89     NOTMUCH_VALUE_THREAD = 1,
90     NOTMUCH_VALUE_DATE = 2
91 } notmuch_value_t;
92
93 static const char *
94 find_prefix (const char *name)
95 {
96     unsigned int i;
97
98     for (i = 0; i < ARRAY_SIZE (NORMAL_PREFIX); i++)
99         if (strcmp (name, NORMAL_PREFIX[i].name) == 0)
100             return NORMAL_PREFIX[i].prefix;
101
102     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX); i++)
103         if (strcmp (name, BOOLEAN_PREFIX[i].name) == 0)
104             return BOOLEAN_PREFIX[i].prefix;
105
106     return "";
107 }
108
109 /* "128 bits of thread-id ought to be enough for anybody" */
110 #define NOTMUCH_THREAD_ID_BITS   128
111 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
112 typedef struct _thread_id {
113     char str[NOTMUCH_THREAD_ID_DIGITS + 1];
114 } thread_id_t;
115
116 static void
117 thread_id_generate (thread_id_t *thread_id)
118 {
119     static int seeded = 0;
120     FILE *dev_random;
121     uint32_t value;
122     char *s;
123     int i;
124
125     if (! seeded) {
126         dev_random = fopen ("/dev/random", "r");
127         if (dev_random == NULL) {
128             srand (time (NULL));
129         } else {
130             fread ((void *) &value, sizeof (value), 1, dev_random);
131             srand (value);
132             fclose (dev_random);
133         }
134         seeded = 1;
135     }
136
137     s = thread_id->str;
138     for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
139         value = rand ();
140         sprintf (s, "%08x", value);
141         s += 8;
142     }
143 }
144
145 static void
146 add_term (Xapian::Document doc,
147           const char *prefix_name,
148           const char *value)
149 {
150     const char *prefix;
151     char *term;
152
153     if (value == NULL)
154         return;
155
156     prefix = find_prefix (prefix_name);
157
158     term = g_strdup_printf ("%s%s", prefix, value);
159
160     if (strlen (term) <= NOTMUCH_MAX_TERM)
161         doc.add_term (term);
162
163     g_free (term);
164 }
165
166 static void
167 find_messages_by_term (Xapian::Database *db,
168                        const char *prefix_name,
169                        const char *value,
170                        Xapian::PostingIterator *begin,
171                        Xapian::PostingIterator *end)
172 {
173     Xapian::PostingIterator i;
174     char *term;
175
176     term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
177
178     *begin = db->postlist_begin (term);
179
180     if (end)
181         *end = db->postlist_end (term);
182
183     free (term);
184 }
185
186 Xapian::Document
187 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
188 {
189     return db->get_document (docid);
190 }
191
192 Xapian::Document
193 find_message_by_message_id (Xapian::Database *db, const char *message_id)
194 {
195     Xapian::PostingIterator i, end;
196
197     find_messages_by_term (db, "msgid", message_id, &i, &end);
198
199     if (i != end)
200         return find_message_by_docid (db, *i);
201     else
202         return Xapian::Document ();
203 }
204
205 static void
206 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
207 {
208     string value_string;
209     const char *value, *id, *comma;
210
211     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
212     value = value_string.c_str();
213     if (strlen (value)) {
214         id = value;
215         while (*id) {
216             comma = strchr (id, ',');
217             if (comma == NULL)
218                 comma = id + strlen (id);
219             g_hash_table_insert (thread_ids,
220                                  strndup (id, comma - id), NULL);
221             id = comma;
222             if (*id)
223                 id++;
224         }
225     }
226 }
227
228 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
229  * given message based on looking into the database for any messages
230  * referenced in parents, and also for any messages in the database
231  * referencing message_id.
232  *
233  * Caller should free all strings in the array and the array itself,
234  * (g_ptr_array_free) when done. */
235 static GPtrArray *
236 find_thread_ids (Xapian::Database *db,
237                  GPtrArray *parents,
238                  const char *message_id)
239 {
240     Xapian::PostingIterator child, children_end;
241     Xapian::Document doc;
242     GHashTable *thread_ids;
243     GList *keys, *l;
244     unsigned int i;
245     const char *parent_message_id;
246     GPtrArray *result;
247
248     thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
249                                         free, NULL);
250
251     find_messages_by_term (db, "ref", message_id, &child, &children_end);
252     for ( ; child != children_end; child++) {
253         doc = find_message_by_docid (db, *child);
254         insert_thread_id (thread_ids, doc);
255     }
256
257     for (i = 0; i < parents->len; i++) {
258         parent_message_id = (char *) g_ptr_array_index (parents, i);
259         doc = find_message_by_message_id (db, parent_message_id);
260         insert_thread_id (thread_ids, doc);
261     }
262
263     result = g_ptr_array_new ();
264
265     keys = g_hash_table_get_keys (thread_ids);
266     for (l = keys; l; l = l->next) {
267         char *id = (char *) l->data;
268         g_ptr_array_add (result, id);
269     }
270     g_list_free (keys);
271
272     /* We're done with the hash table, but we've taken the pointers to
273      * the allocated strings and put them into our result array, so
274      * tell the hash not to free them on its way out. */
275     g_hash_table_steal_all (thread_ids);
276     g_hash_table_unref (thread_ids);
277
278     return result;
279 }
280
281 /* Add a term for each message-id in the References header of the
282  * message. */
283 static void
284 parse_references (GPtrArray *array,
285                   const char *refs_str)
286 {
287     GMimeReferences *refs, *r;
288     const char *message_id;
289
290     if (refs_str == NULL)
291         return;
292
293     refs = g_mime_references_decode (refs_str);
294
295     for (r = refs; r; r = r->next) {
296         message_id = g_mime_references_get_message_id (r);
297         g_ptr_array_add (array, g_strdup (message_id));
298     }
299
300     g_mime_references_free (refs);
301 }
302
303 notmuch_database_t *
304 notmuch_database_create (const char *path)
305 {
306     char *notmuch_path;
307     struct stat st;
308     int err;
309
310     err = stat (path, &st);
311     if (err) {
312         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
313                  path, strerror (errno));
314         return NULL;
315     }
316
317     if (! S_ISDIR (st.st_mode)) {
318         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
319                  path);
320         return NULL;
321     }
322
323     notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
324
325     err = mkdir (notmuch_path, 0755);
326
327     if (err) {
328         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
329                  notmuch_path, strerror (errno));
330         free (notmuch_path);
331         return NULL;
332     }
333
334     free (notmuch_path);
335
336     return notmuch_database_open (path);
337 }
338
339 notmuch_database_t *
340 notmuch_database_open (const char *path)
341 {
342     notmuch_database_t *notmuch;
343     char *notmuch_path, *xapian_path;
344     struct stat st;
345     int err;
346
347     g_mime_init (0);
348
349     notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
350
351     err = stat (notmuch_path, &st);
352     if (err) {
353         fprintf (stderr, "Error: Cannot stat %s: %s\n",
354                  notmuch_path, strerror (err));
355         free (notmuch_path);
356         return NULL;
357     }
358
359     xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
360     free (notmuch_path);
361
362     /* C++ is so nasty in requiring these casts. I'm almost tempted to
363      * write a C wrapper for Xapian... */
364     notmuch = (notmuch_database_t *) xmalloc (sizeof (notmuch_database_t));
365     notmuch->path = xstrdup (path);
366
367     try {
368         notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
369                                                            Xapian::DB_CREATE_OR_OPEN);
370     } catch (const Xapian::Error &error) {
371         fprintf (stderr, "A Xapian exception occurred: %s\n",
372                  error.get_msg().c_str());
373     }
374     
375     free (xapian_path);
376
377     return notmuch;
378 }
379
380 void
381 notmuch_database_close (notmuch_database_t *notmuch)
382 {
383     delete notmuch->xapian_db;
384     free (notmuch->path);
385     free (notmuch);
386 }
387
388 const char *
389 notmuch_database_get_path (notmuch_database_t *notmuch)
390 {
391     return notmuch->path;
392 }
393
394 notmuch_status_t
395 notmuch_database_add_message (notmuch_database_t *notmuch,
396                               const char *filename)
397 {
398     Xapian::WritableDatabase *db = notmuch->xapian_db;
399     Xapian::Document doc;
400
401     GMimeStream *stream;
402     GMimeParser *parser;
403     GMimeMessage *message;
404     GPtrArray *parents, *thread_ids;
405
406     FILE *file;
407
408     const char *refs, *in_reply_to;
409     const char *message_id;
410
411     time_t time;
412     unsigned int i;
413
414     file = fopen (filename, "r");
415     if (! file) {
416         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
417         exit (1);
418     }
419
420     stream = g_mime_stream_file_new (file);
421
422     parser = g_mime_parser_new_with_stream (stream);
423
424     message = g_mime_parser_construct_message (parser);
425
426     try {
427         doc = Xapian::Document ();
428
429         doc.set_data (filename);
430
431         parents = g_ptr_array_new ();
432
433         refs = g_mime_object_get_header (GMIME_OBJECT (message), "references");
434         parse_references (parents, refs);
435
436         in_reply_to = g_mime_object_get_header (GMIME_OBJECT (message),
437                                                 "in-reply-to");
438         parse_references (parents, in_reply_to);
439         for (i = 0; i < parents->len; i++)
440             add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
441
442         message_id = g_mime_message_get_message_id (message);
443
444         thread_ids = find_thread_ids (db, parents, message_id);
445
446         for (i = 0; i < parents->len; i++)
447             g_free (g_ptr_array_index (parents, i));
448         g_ptr_array_free (parents, TRUE);
449         if (message_id) {
450             add_term (doc, "msgid", message_id);
451             doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
452         }
453
454         if (thread_ids->len) {
455             unsigned int i;
456             GString *thread_id;
457             char *id;
458
459             for (i = 0; i < thread_ids->len; i++) {
460                 id = (char *) thread_ids->pdata[i];
461                 add_term (doc, "thread", id);
462                 if (i == 0)
463                     thread_id = g_string_new (id);
464                 else
465                     g_string_append_printf (thread_id, ",%s", id);
466
467                 free (id);
468             }
469             g_ptr_array_free (thread_ids, TRUE);
470             doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
471             g_string_free (thread_id, TRUE);
472         } else if (message_id) {
473             /* If not part of any existing thread, generate a new thread_id. */
474             thread_id_t thread_id;
475
476             thread_id_generate (&thread_id);
477             add_term (doc, "thread", thread_id.str);
478             doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
479         }
480
481         g_mime_message_get_date (message, &time, NULL);
482         doc.add_value (NOTMUCH_VALUE_DATE, Xapian::sortable_serialise (time));
483
484         db->add_document (doc);
485     } catch (const Xapian::Error &error) {
486         fprintf (stderr, "A Xapian exception occurred: %s.\n",
487                  error.get_msg().c_str());
488         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
489     }
490
491     g_object_unref (message);
492     g_object_unref (parser);
493     g_object_unref (stream);
494
495     return NOTMUCH_STATUS_SUCCESS;
496 }