]> git.notmuchmail.org Git - notmuch/blob - database.cc
notmuch dump: Fix the sorting of results.
[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 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
32
33 /* Xapian complains if we provide a term longer than this. */
34 #define NOTMUCH_MAX_TERM 245
35
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.
40  */
41
42 typedef struct {
43     const char *name;
44     const char *prefix;
45 } prefix_t;
46
47 prefix_t NORMAL_PREFIX[] = {
48     { "subject", "S" },
49     { "body", "B" },
50     { "from_name", "FN" },
51     { "to_name", "TN" },
52     { "name", "N" },
53     { "attachment", "A" }
54 };
55
56 prefix_t BOOLEAN_PREFIX[] = {
57     { "type", "K" },
58     { "from_email", "FE" },
59     { "to_email", "TE" },
60     { "email", "E" },
61     { "date", "D" },
62     { "label", "L" },
63     { "source_id", "I" },
64     { "attachment_extension", "O" },
65     { "msgid", "Q" },
66     { "thread", "H" },
67     { "ref", "R" }
68 };
69
70 static const char *
71 find_prefix (const char *name)
72 {
73     unsigned int i;
74
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;
78
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;
82
83     return "";
84 }
85
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];
91 } thread_id_t;
92
93 static void
94 thread_id_generate (thread_id_t *thread_id)
95 {
96     static int seeded = 0;
97     FILE *dev_random;
98     uint32_t value;
99     char *s;
100     int i;
101
102     if (! seeded) {
103         dev_random = fopen ("/dev/random", "r");
104         if (dev_random == NULL) {
105             srand (time (NULL));
106         } else {
107             fread ((void *) &value, sizeof (value), 1, dev_random);
108             srand (value);
109             fclose (dev_random);
110         }
111         seeded = 1;
112     }
113
114     s = thread_id->str;
115     for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
116         value = rand ();
117         sprintf (s, "%08x", value);
118         s += 8;
119     }
120 }
121
122 static void
123 add_term (Xapian::Document doc,
124           const char *prefix_name,
125           const char *value)
126 {
127     const char *prefix;
128     char *term;
129
130     if (value == NULL)
131         return;
132
133     prefix = find_prefix (prefix_name);
134
135     term = g_strdup_printf ("%s%s", prefix, value);
136
137     if (strlen (term) <= NOTMUCH_MAX_TERM)
138         doc.add_term (term);
139
140     g_free (term);
141 }
142
143 static void
144 find_messages_by_term (Xapian::Database *db,
145                        const char *prefix_name,
146                        const char *value,
147                        Xapian::PostingIterator *begin,
148                        Xapian::PostingIterator *end)
149 {
150     Xapian::PostingIterator i;
151     char *term;
152
153     term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
154
155     *begin = db->postlist_begin (term);
156
157     if (end)
158         *end = db->postlist_end (term);
159
160     free (term);
161 }
162
163 Xapian::Document
164 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
165 {
166     return db->get_document (docid);
167 }
168
169 Xapian::Document
170 find_message_by_message_id (Xapian::Database *db, const char *message_id)
171 {
172     Xapian::PostingIterator i, end;
173
174     find_messages_by_term (db, "msgid", message_id, &i, &end);
175
176     if (i != end)
177         return find_message_by_docid (db, *i);
178     else
179         return Xapian::Document ();
180 }
181
182 static void
183 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
184 {
185     string value_string;
186     const char *value, *id, *comma;
187
188     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
189     value = value_string.c_str();
190     if (strlen (value)) {
191         id = value;
192         while (*id) {
193             comma = strchr (id, ',');
194             if (comma == NULL)
195                 comma = id + strlen (id);
196             g_hash_table_insert (thread_ids,
197                                  strndup (id, comma - id), NULL);
198             id = comma;
199             if (*id)
200                 id++;
201         }
202     }
203 }
204
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.
209  *
210  * Caller should free all strings in the array and the array itself,
211  * (g_ptr_array_free) when done. */
212 static GPtrArray *
213 find_thread_ids (Xapian::Database *db,
214                  GPtrArray *parents,
215                  const char *message_id)
216 {
217     Xapian::PostingIterator child, children_end;
218     Xapian::Document doc;
219     GHashTable *thread_ids;
220     GList *keys, *l;
221     unsigned int i;
222     const char *parent_message_id;
223     GPtrArray *result;
224
225     thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
226                                         free, NULL);
227
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);
232     }
233
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);
238     }
239
240     result = g_ptr_array_new ();
241
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);
246     }
247     g_list_free (keys);
248
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);
254
255     return result;
256 }
257
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).
261  *
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'
264  * character.
265  */
266 static void
267 skip_space_and_comments (const char **str)
268 {
269     const char *s;
270
271     s = *str;
272     while (*s && (isspace (*s) || *s == '(')) {
273         while (*s && isspace (*s))
274             s++;
275         if (*s == '(') {
276             int nesting = 1;
277             s++;
278             while (*s && nesting) {
279                 if (*s == '(')
280                     nesting++;
281                 else if (*s == ')')
282                     nesting--;
283                 else if (*s == '\\')
284                     if (*(s+1))
285                         s++;
286                 s++;
287             }
288         }
289     }
290
291     *str = s;
292 }
293
294 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
295  * comments, and the '<' and '>' delimeters.
296  *
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.
299  *
300  * Returns a newly allocated string which the caller should free()
301  * when done with it.
302  *
303  * Returns NULL if there is any error parsing the message-id. */
304 static char *
305 parse_message_id (const char *message_id, const char **next)
306 {
307     const char *s, *end;
308
309     if (message_id == NULL)
310         return NULL;
311
312     s = message_id;
313
314     skip_space_and_comments (&s);
315
316     /* Skip any unstructured text as well. */
317     while (*s && *s != '<')
318         s++;
319
320     if (*s == '<') {
321         s++;
322     } else {
323         if (next)
324             *next = s;
325         return NULL;
326     }
327
328     skip_space_and_comments (&s);
329
330     end = s;
331     while (*end && *end != '>')
332         end++;
333     if (next) {
334         if (*end)
335             *next = end + 1;
336         else
337             *next = end;
338     }
339
340     if (end > s && *end == '>')
341         end--;
342     if (end > s)
343         return strndup (s, end - s + 1);
344     else
345         return NULL;
346 }
347
348 /* Parse a References header value, putting a copy of each referenced
349  * message-id into 'array'. */
350 static void
351 parse_references (GPtrArray *array,
352                   const char *refs)
353 {
354     char *ref;
355
356     if (refs == NULL)
357         return;
358
359     while (*refs) {
360         ref = parse_message_id (refs, &refs);
361
362         if (ref)
363             g_ptr_array_add (array, ref);
364     }
365 }
366
367 char *
368 notmuch_database_default_path (void)
369 {
370     if (getenv ("NOTMUCH_BASE"))
371         return strdup (getenv ("NOTMUCH_BASE"));
372
373     return g_strdup_printf ("%s/mail", getenv ("HOME"));
374 }
375
376 notmuch_database_t *
377 notmuch_database_create (const char *path)
378 {
379     notmuch_database_t *notmuch = NULL;
380     char *notmuch_path = NULL;
381     struct stat st;
382     int err;
383     char *local_path = NULL;
384
385     if (path == NULL)
386         path = local_path = notmuch_database_default_path ();
387
388     err = stat (path, &st);
389     if (err) {
390         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
391                  path, strerror (errno));
392         goto DONE;
393     }
394
395     if (! S_ISDIR (st.st_mode)) {
396         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
397                  path);
398         goto DONE;
399     }
400
401     notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
402
403     err = mkdir (notmuch_path, 0755);
404
405     if (err) {
406         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
407                  notmuch_path, strerror (errno));
408         goto DONE;
409     }
410
411     notmuch = notmuch_database_open (path);
412
413   DONE:
414     if (notmuch_path)
415         free (notmuch_path);
416     if (local_path)
417         free (local_path);
418
419     return notmuch;
420 }
421
422 notmuch_database_t *
423 notmuch_database_open (const char *path)
424 {
425     notmuch_database_t *notmuch = NULL;
426     char *notmuch_path = NULL, *xapian_path = NULL;
427     struct stat st;
428     int err;
429     char *local_path = NULL;
430
431     if (path == NULL)
432         path = local_path = notmuch_database_default_path ();
433
434     notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
435
436     err = stat (notmuch_path, &st);
437     if (err) {
438         fprintf (stderr, "Error opening database at %s: %s\n",
439                  notmuch_path, strerror (errno));
440         goto DONE;
441     }
442
443     xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
444
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);
449
450     try {
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());
459     }
460     
461   DONE:
462     if (local_path)
463         free (local_path);
464     if (notmuch_path)
465         free (notmuch_path);
466     if (xapian_path)
467         free (xapian_path);
468
469     return notmuch;
470 }
471
472 void
473 notmuch_database_close (notmuch_database_t *notmuch)
474 {
475     delete notmuch->query_parser;
476     delete notmuch->xapian_db;
477     free (notmuch->path);
478     free (notmuch);
479 }
480
481 const char *
482 notmuch_database_get_path (notmuch_database_t *notmuch)
483 {
484     return notmuch->path;
485 }
486
487 notmuch_status_t
488 notmuch_database_add_message (notmuch_database_t *notmuch,
489                               const char *filename)
490 {
491     Xapian::WritableDatabase *db = notmuch->xapian_db;
492     Xapian::Document doc;
493     notmuch_message_file_t *message;
494
495     GPtrArray *parents, *thread_ids;
496
497     const char *refs, *in_reply_to, *date, *header;
498     const char *from, *to, *subject;
499     char *message_id;
500
501     time_t time_value;
502     unsigned int i;
503
504     message = notmuch_message_file_open (filename);
505
506     notmuch_message_file_restrict_headers (message,
507                                            "date",
508                                            "from",
509                                            "in-reply-to",
510                                            "message-id",
511                                            "references",
512                                            "subject",
513                                            (char *) NULL);
514
515     try {
516         doc.set_data (filename);
517
518         add_term (doc, "type", "mail");
519
520         parents = g_ptr_array_new ();
521
522         refs = notmuch_message_file_get_header (message, "references");
523         parse_references (parents, refs);
524
525         in_reply_to = notmuch_message_file_get_header (message, "in-reply-to");
526         parse_references (parents, in_reply_to);
527
528         for (i = 0; i < parents->len; i++)
529             add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
530
531         header = notmuch_message_file_get_header (message, "message-id");
532         if (header) {
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);
538         } else {
539             /* XXX: Should generate a message_id here, (such as a SHA1
540              * sum of the message itself) */
541             message_id = NULL;
542         }
543
544         thread_ids = find_thread_ids (db, parents, message_id);
545
546         for (i = 0; i < parents->len; i++)
547             g_free (g_ptr_array_index (parents, i));
548         g_ptr_array_free (parents, TRUE);
549         if (message_id) {
550             add_term (doc, "msgid", message_id);
551             doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
552         }
553
554         if (thread_ids->len) {
555             unsigned int i;
556             GString *thread_id;
557             char *id;
558
559             for (i = 0; i < thread_ids->len; i++) {
560                 id = (char *) thread_ids->pdata[i];
561                 add_term (doc, "thread", id);
562                 if (i == 0)
563                     thread_id = g_string_new (id);
564                 else
565                     g_string_append_printf (thread_id, ",%s", id);
566
567                 free (id);
568             }
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;
574
575             thread_id_generate (&thread_id);
576             add_term (doc, "thread", thread_id.str);
577             doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
578         }
579
580         g_ptr_array_free (thread_ids, TRUE);
581
582         free (message_id);
583
584         date = notmuch_message_file_get_header (message, "date");
585         time_value = notmuch_parse_date (date, NULL);
586
587         doc.add_value (NOTMUCH_VALUE_DATE,
588                        Xapian::sortable_serialise (time_value));
589
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");
593
594         if (from == NULL &&
595             subject == NULL &&
596             to == NULL)
597         {
598             notmuch_message_file_close (message);
599             return NOTMUCH_STATUS_FILE_NOT_EMAIL;
600         } else {
601             db->add_document (doc);
602         }
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;
607     }
608
609     notmuch_message_file_close (message);
610
611     return NOTMUCH_STATUS_SUCCESS;
612 }