]> git.notmuchmail.org Git - notmuch/blob - database.cc
77b2eff22973073aa511c2d0c0baa31d20190e31
[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 "database-private.h"
22
23 #include <iostream>
24
25 #include <xapian.h>
26
27 #include <glib.h> /* g_strdup_printf, g_free, GPtrArray, GHashTable */
28
29 using namespace std;
30
31 /* "128 bits of thread-id ought to be enough for anybody" */
32 #define NOTMUCH_THREAD_ID_BITS   128
33 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
34 typedef struct _thread_id {
35     char str[NOTMUCH_THREAD_ID_DIGITS + 1];
36 } thread_id_t;
37
38 static void
39 thread_id_generate (thread_id_t *thread_id)
40 {
41     static int seeded = 0;
42     FILE *dev_random;
43     uint32_t value;
44     char *s;
45     int i;
46
47     if (! seeded) {
48         dev_random = fopen ("/dev/random", "r");
49         if (dev_random == NULL) {
50             srand (time (NULL));
51         } else {
52             fread ((void *) &value, sizeof (value), 1, dev_random);
53             srand (value);
54             fclose (dev_random);
55         }
56         seeded = 1;
57     }
58
59     s = thread_id->str;
60     for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
61         value = rand ();
62         sprintf (s, "%08x", value);
63         s += 8;
64     }
65 }
66
67 static void
68 add_term (Xapian::Document doc,
69           const char *prefix_name,
70           const char *value)
71 {
72     const char *prefix;
73     char *term;
74
75     if (value == NULL)
76         return;
77
78     prefix = _find_prefix (prefix_name);
79
80     term = g_strdup_printf ("%s%s", prefix, value);
81
82     if (strlen (term) <= NOTMUCH_TERM_MAX)
83         doc.add_term (term);
84
85     g_free (term);
86 }
87
88 static void
89 find_messages_by_term (Xapian::Database *db,
90                        const char *prefix_name,
91                        const char *value,
92                        Xapian::PostingIterator *begin,
93                        Xapian::PostingIterator *end)
94 {
95     Xapian::PostingIterator i;
96     char *term;
97
98     term = g_strdup_printf ("%s%s", _find_prefix (prefix_name), value);
99
100     *begin = db->postlist_begin (term);
101
102     if (end)
103         *end = db->postlist_end (term);
104
105     free (term);
106 }
107
108 Xapian::Document
109 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
110 {
111     return db->get_document (docid);
112 }
113
114 static void
115 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
116 {
117     string value_string;
118     const char *value, *id, *comma;
119
120     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
121     value = value_string.c_str();
122     if (strlen (value)) {
123         id = value;
124         while (*id) {
125             comma = strchr (id, ',');
126             if (comma == NULL)
127                 comma = id + strlen (id);
128             g_hash_table_insert (thread_ids,
129                                  strndup (id, comma - id), NULL);
130             id = comma;
131             if (*id)
132                 id++;
133         }
134     }
135 }
136
137 notmuch_message_t *
138 notmuch_database_find_message (notmuch_database_t *notmuch,
139                                const char *message_id)
140 {
141     Xapian::PostingIterator i, end;
142
143     find_messages_by_term (notmuch->xapian_db,
144                            "msgid", message_id, &i, &end);
145
146     if (i == end)
147         return NULL;
148
149     return _notmuch_message_create (notmuch, notmuch, *i);
150 }
151
152 /* Return one or more thread_ids, (as a GPtrArray of strings), for the
153  * given message based on looking into the database for any messages
154  * referenced in parents, and also for any messages in the database
155  * referencing message_id.
156  *
157  * Caller should free all strings in the array and the array itself,
158  * (g_ptr_array_free) when done. */
159 static GPtrArray *
160 find_thread_ids (notmuch_database_t *notmuch,
161                  GPtrArray *parents,
162                  const char *message_id)
163 {
164     Xapian::WritableDatabase *db = notmuch->xapian_db;
165     Xapian::PostingIterator child, children_end;
166     Xapian::Document doc;
167     GHashTable *thread_ids;
168     GList *keys, *l;
169     unsigned int i;
170     const char *parent_message_id;
171     GPtrArray *result;
172
173     thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
174                                         free, NULL);
175
176     find_messages_by_term (db, "ref", message_id, &child, &children_end);
177     for ( ; child != children_end; child++) {
178         doc = find_message_by_docid (db, *child);
179         insert_thread_id (thread_ids, doc);
180     }
181
182     for (i = 0; i < parents->len; i++) {
183         notmuch_message_t *parent;
184         notmuch_thread_ids_t *ids;
185
186         parent_message_id = (char *) g_ptr_array_index (parents, i);
187         parent = notmuch_database_find_message (notmuch, parent_message_id);
188         if (parent == NULL)
189             continue;
190
191         for (ids = notmuch_message_get_thread_ids (parent);
192              notmuch_thread_ids_has_more (ids);
193              notmuch_thread_ids_advance (ids))
194         {
195             const char *id;
196
197             id = notmuch_thread_ids_get (ids);
198             g_hash_table_insert (thread_ids, strdup (id), NULL);
199         }
200
201         notmuch_message_destroy (parent);
202     }
203
204     result = g_ptr_array_new ();
205
206     keys = g_hash_table_get_keys (thread_ids);
207     for (l = keys; l; l = l->next) {
208         char *id = (char *) l->data;
209         g_ptr_array_add (result, id);
210     }
211     g_list_free (keys);
212
213     /* We're done with the hash table, but we've taken the pointers to
214      * the allocated strings and put them into our result array, so
215      * tell the hash not to free them on its way out. */
216     g_hash_table_steal_all (thread_ids);
217     g_hash_table_unref (thread_ids);
218
219     return result;
220 }
221
222 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
223  * a (potentially nested) parenthesized sequence with '\' used to
224  * escape any character (including parentheses).
225  *
226  * If the sequence to be skipped continues to the end of the string,
227  * then 'str' will be left pointing at the final terminating '\0'
228  * character.
229  */
230 static void
231 skip_space_and_comments (const char **str)
232 {
233     const char *s;
234
235     s = *str;
236     while (*s && (isspace (*s) || *s == '(')) {
237         while (*s && isspace (*s))
238             s++;
239         if (*s == '(') {
240             int nesting = 1;
241             s++;
242             while (*s && nesting) {
243                 if (*s == '(')
244                     nesting++;
245                 else if (*s == ')')
246                     nesting--;
247                 else if (*s == '\\')
248                     if (*(s+1))
249                         s++;
250                 s++;
251             }
252         }
253     }
254
255     *str = s;
256 }
257
258 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
259  * comments, and the '<' and '>' delimeters.
260  *
261  * If not NULL, then *next will be made to point to the first character
262  * not parsed, (possibly pointing to the final '\0' terminator.
263  *
264  * Returns a newly allocated string which the caller should free()
265  * when done with it.
266  *
267  * Returns NULL if there is any error parsing the message-id. */
268 static char *
269 parse_message_id (const char *message_id, const char **next)
270 {
271     const char *s, *end;
272     char *result;
273
274     if (message_id == NULL)
275         return NULL;
276
277     s = message_id;
278
279     skip_space_and_comments (&s);
280
281     /* Skip any unstructured text as well. */
282     while (*s && *s != '<')
283         s++;
284
285     if (*s == '<') {
286         s++;
287     } else {
288         if (next)
289             *next = s;
290         return NULL;
291     }
292
293     skip_space_and_comments (&s);
294
295     end = s;
296     while (*end && *end != '>')
297         end++;
298     if (next) {
299         if (*end)
300             *next = end + 1;
301         else
302             *next = end;
303     }
304
305     if (end > s && *end == '>')
306         end--;
307     if (end <= s)
308         return NULL;
309
310     result = strndup (s, end - s + 1);
311
312     /* Finally, collapse any whitespace that is within the message-id
313      * itself. */
314     {
315         char *r;
316         int len;
317
318         for (r = result, len = strlen (r); *r; r++, len--)
319             if (*r == ' ' || *r == '\t')
320                 memmove (r, r+1, len);
321     }
322
323     return result;
324 }
325
326 /* Parse a References header value, putting a copy of each referenced
327  * message-id into 'array'. */
328 static void
329 parse_references (GPtrArray *array,
330                   const char *refs)
331 {
332     char *ref;
333
334     if (refs == NULL)
335         return;
336
337     while (*refs) {
338         ref = parse_message_id (refs, &refs);
339
340         if (ref)
341             g_ptr_array_add (array, ref);
342     }
343 }
344
345 char *
346 notmuch_database_default_path (void)
347 {
348     if (getenv ("NOTMUCH_BASE"))
349         return strdup (getenv ("NOTMUCH_BASE"));
350
351     return g_strdup_printf ("%s/mail", getenv ("HOME"));
352 }
353
354 notmuch_database_t *
355 notmuch_database_create (const char *path)
356 {
357     notmuch_database_t *notmuch = NULL;
358     char *notmuch_path = NULL;
359     struct stat st;
360     int err;
361     char *local_path = NULL;
362
363     if (path == NULL)
364         path = local_path = notmuch_database_default_path ();
365
366     err = stat (path, &st);
367     if (err) {
368         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
369                  path, strerror (errno));
370         goto DONE;
371     }
372
373     if (! S_ISDIR (st.st_mode)) {
374         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
375                  path);
376         goto DONE;
377     }
378
379     notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
380
381     err = mkdir (notmuch_path, 0755);
382
383     if (err) {
384         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
385                  notmuch_path, strerror (errno));
386         goto DONE;
387     }
388
389     notmuch = notmuch_database_open (path);
390
391   DONE:
392     if (notmuch_path)
393         free (notmuch_path);
394     if (local_path)
395         free (local_path);
396
397     return notmuch;
398 }
399
400 notmuch_database_t *
401 notmuch_database_open (const char *path)
402 {
403     notmuch_database_t *notmuch = NULL;
404     char *notmuch_path = NULL, *xapian_path = NULL;
405     struct stat st;
406     int err;
407     char *local_path = NULL;
408
409     if (path == NULL)
410         path = local_path = notmuch_database_default_path ();
411
412     notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
413
414     err = stat (notmuch_path, &st);
415     if (err) {
416         fprintf (stderr, "Error opening database at %s: %s\n",
417                  notmuch_path, strerror (errno));
418         goto DONE;
419     }
420
421     xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
422
423     notmuch = talloc (NULL, notmuch_database_t);
424     notmuch->path = talloc_strdup (notmuch, path);
425
426     try {
427         notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
428                                                            Xapian::DB_CREATE_OR_OPEN);
429         notmuch->query_parser = new Xapian::QueryParser;
430         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
431         notmuch->query_parser->set_database (*notmuch->xapian_db);
432     } catch (const Xapian::Error &error) {
433         fprintf (stderr, "A Xapian exception occurred: %s\n",
434                  error.get_msg().c_str());
435     }
436     
437   DONE:
438     if (local_path)
439         free (local_path);
440     if (notmuch_path)
441         free (notmuch_path);
442     if (xapian_path)
443         free (xapian_path);
444
445     return notmuch;
446 }
447
448 void
449 notmuch_database_close (notmuch_database_t *notmuch)
450 {
451     delete notmuch->query_parser;
452     delete notmuch->xapian_db;
453     talloc_free (notmuch);
454 }
455
456 const char *
457 notmuch_database_get_path (notmuch_database_t *notmuch)
458 {
459     return notmuch->path;
460 }
461
462 notmuch_status_t
463 notmuch_database_add_message (notmuch_database_t *notmuch,
464                               const char *filename)
465 {
466     Xapian::WritableDatabase *db = notmuch->xapian_db;
467     Xapian::Document doc;
468     notmuch_message_file_t *message;
469
470     GPtrArray *parents, *thread_ids;
471
472     const char *refs, *in_reply_to, *date, *header;
473     const char *from, *to, *subject;
474     char *message_id;
475
476     time_t time_value;
477     unsigned int i;
478
479     message = notmuch_message_file_open (filename);
480
481     notmuch_message_file_restrict_headers (message,
482                                            "date",
483                                            "from",
484                                            "in-reply-to",
485                                            "message-id",
486                                            "references",
487                                            "subject",
488                                            (char *) NULL);
489
490     try {
491         doc.set_data (filename);
492
493         add_term (doc, "type", "mail");
494
495         parents = g_ptr_array_new ();
496
497         refs = notmuch_message_file_get_header (message, "references");
498         parse_references (parents, refs);
499
500         in_reply_to = notmuch_message_file_get_header (message, "in-reply-to");
501         parse_references (parents, in_reply_to);
502
503         for (i = 0; i < parents->len; i++)
504             add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
505
506         header = notmuch_message_file_get_header (message, "message-id");
507         if (header) {
508             message_id = parse_message_id (header, NULL);
509             /* So the header value isn't RFC-compliant, but it's
510              * better than no message-id at all. */
511             if (message_id == NULL)
512                 message_id = xstrdup (header);
513         } else {
514             /* XXX: Should generate a message_id here, (such as a SHA1
515              * sum of the message itself) */
516             message_id = NULL;
517         }
518
519         thread_ids = find_thread_ids (notmuch, parents, message_id);
520
521         for (i = 0; i < parents->len; i++)
522             g_free (g_ptr_array_index (parents, i));
523         g_ptr_array_free (parents, TRUE);
524         if (message_id) {
525             add_term (doc, "msgid", message_id);
526             doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
527         }
528
529         if (thread_ids->len) {
530             unsigned int i;
531             GString *thread_id;
532             char *id;
533
534             for (i = 0; i < thread_ids->len; i++) {
535                 id = (char *) thread_ids->pdata[i];
536                 add_term (doc, "thread", id);
537                 if (i == 0)
538                     thread_id = g_string_new (id);
539                 else
540                     g_string_append_printf (thread_id, ",%s", id);
541
542                 free (id);
543             }
544             doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
545             g_string_free (thread_id, TRUE);
546         } else if (message_id) {
547             /* If not part of any existing thread, generate a new thread_id. */
548             thread_id_t thread_id;
549
550             thread_id_generate (&thread_id);
551             add_term (doc, "thread", thread_id.str);
552             doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
553         }
554
555         g_ptr_array_free (thread_ids, TRUE);
556
557         free (message_id);
558
559         date = notmuch_message_file_get_header (message, "date");
560         time_value = notmuch_parse_date (date, NULL);
561
562         doc.add_value (NOTMUCH_VALUE_DATE,
563                        Xapian::sortable_serialise (time_value));
564
565         from = notmuch_message_file_get_header (message, "from");
566         subject = notmuch_message_file_get_header (message, "subject");
567         to = notmuch_message_file_get_header (message, "to");
568
569         if (from == NULL &&
570             subject == NULL &&
571             to == NULL)
572         {
573             notmuch_message_file_close (message);
574             return NOTMUCH_STATUS_FILE_NOT_EMAIL;
575         } else {
576             db->add_document (doc);
577         }
578     } catch (const Xapian::Error &error) {
579         fprintf (stderr, "A Xapian exception occurred: %s.\n",
580                  error.get_msg().c_str());
581         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
582     }
583
584     notmuch_message_file_close (message);
585
586     return NOTMUCH_STATUS_SUCCESS;
587 }