]> git.notmuchmail.org Git - notmuch/blob - database.cc
Implement 'notmuch dump'.
[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 /* Similarly, these value numbers are also chosen to be sup
71  * compatible. */
72
73 typedef enum {
74     NOTMUCH_VALUE_MESSAGE_ID = 0,
75     NOTMUCH_VALUE_THREAD = 1,
76     NOTMUCH_VALUE_DATE = 2
77 } notmuch_value_t;
78
79 static const char *
80 find_prefix (const char *name)
81 {
82     unsigned int i;
83
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;
87
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;
91
92     return "";
93 }
94
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];
100 } thread_id_t;
101
102 static void
103 thread_id_generate (thread_id_t *thread_id)
104 {
105     static int seeded = 0;
106     FILE *dev_random;
107     uint32_t value;
108     char *s;
109     int i;
110
111     if (! seeded) {
112         dev_random = fopen ("/dev/random", "r");
113         if (dev_random == NULL) {
114             srand (time (NULL));
115         } else {
116             fread ((void *) &value, sizeof (value), 1, dev_random);
117             srand (value);
118             fclose (dev_random);
119         }
120         seeded = 1;
121     }
122
123     s = thread_id->str;
124     for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
125         value = rand ();
126         sprintf (s, "%08x", value);
127         s += 8;
128     }
129 }
130
131 static void
132 add_term (Xapian::Document doc,
133           const char *prefix_name,
134           const char *value)
135 {
136     const char *prefix;
137     char *term;
138
139     if (value == NULL)
140         return;
141
142     prefix = find_prefix (prefix_name);
143
144     term = g_strdup_printf ("%s%s", prefix, value);
145
146     if (strlen (term) <= NOTMUCH_MAX_TERM)
147         doc.add_term (term);
148
149     g_free (term);
150 }
151
152 static void
153 find_messages_by_term (Xapian::Database *db,
154                        const char *prefix_name,
155                        const char *value,
156                        Xapian::PostingIterator *begin,
157                        Xapian::PostingIterator *end)
158 {
159     Xapian::PostingIterator i;
160     char *term;
161
162     term = g_strdup_printf ("%s%s", find_prefix (prefix_name), value);
163
164     *begin = db->postlist_begin (term);
165
166     if (end)
167         *end = db->postlist_end (term);
168
169     free (term);
170 }
171
172 Xapian::Document
173 find_message_by_docid (Xapian::Database *db, Xapian::docid docid)
174 {
175     return db->get_document (docid);
176 }
177
178 Xapian::Document
179 find_message_by_message_id (Xapian::Database *db, const char *message_id)
180 {
181     Xapian::PostingIterator i, end;
182
183     find_messages_by_term (db, "msgid", message_id, &i, &end);
184
185     if (i != end)
186         return find_message_by_docid (db, *i);
187     else
188         return Xapian::Document ();
189 }
190
191 static void
192 insert_thread_id (GHashTable *thread_ids, Xapian::Document doc)
193 {
194     string value_string;
195     const char *value, *id, *comma;
196
197     value_string = doc.get_value (NOTMUCH_VALUE_THREAD);
198     value = value_string.c_str();
199     if (strlen (value)) {
200         id = value;
201         while (*id) {
202             comma = strchr (id, ',');
203             if (comma == NULL)
204                 comma = id + strlen (id);
205             g_hash_table_insert (thread_ids,
206                                  strndup (id, comma - id), NULL);
207             id = comma;
208             if (*id)
209                 id++;
210         }
211     }
212 }
213
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.
218  *
219  * Caller should free all strings in the array and the array itself,
220  * (g_ptr_array_free) when done. */
221 static GPtrArray *
222 find_thread_ids (Xapian::Database *db,
223                  GPtrArray *parents,
224                  const char *message_id)
225 {
226     Xapian::PostingIterator child, children_end;
227     Xapian::Document doc;
228     GHashTable *thread_ids;
229     GList *keys, *l;
230     unsigned int i;
231     const char *parent_message_id;
232     GPtrArray *result;
233
234     thread_ids = g_hash_table_new_full (g_str_hash, g_str_equal,
235                                         free, NULL);
236
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);
241     }
242
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);
247     }
248
249     result = g_ptr_array_new ();
250
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);
255     }
256     g_list_free (keys);
257
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);
263
264     return result;
265 }
266
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).
270  *
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'
273  * character.
274  */
275 static void
276 skip_space_and_comments (const char **str)
277 {
278     const char *s;
279
280     s = *str;
281     while (*s && (isspace (*s) || *s == '(')) {
282         while (*s && isspace (*s))
283             s++;
284         if (*s == '(') {
285             int nesting = 1;
286             s++;
287             while (*s && nesting) {
288                 if (*s == '(')
289                     nesting++;
290                 else if (*s == ')')
291                     nesting--;
292                 else if (*s == '\\')
293                     if (*(s+1))
294                         s++;
295                 s++;
296             }
297         }
298     }
299
300     *str = s;
301 }
302
303 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
304  * comments, and the '<' and '>' delimeters.
305  *
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.
308  *
309  * Returns a newly allocated string which the caller should free()
310  * when done with it.
311  *
312  * Returns NULL if there is any error parsing the message-id. */
313 static char *
314 parse_message_id (const char *message_id, const char **next)
315 {
316     const char *s, *end;
317
318     if (message_id == NULL)
319         return NULL;
320
321     s = message_id;
322
323     skip_space_and_comments (&s);
324
325     /* Skip any unstructured text as well. */
326     while (*s && *s != '<')
327         s++;
328
329     if (*s == '<') {
330         s++;
331     } else {
332         if (next)
333             *next = s;
334         return NULL;
335     }
336
337     skip_space_and_comments (&s);
338
339     end = s;
340     while (*end && *end != '>')
341         end++;
342     if (next) {
343         if (*end)
344             *next = end + 1;
345         else
346             *next = end;
347     }
348
349     if (end > s && *end == '>')
350         end--;
351     if (end > s)
352         return strndup (s, end - s + 1);
353     else
354         return NULL;
355 }
356
357 /* Parse a References header value, putting a copy of each referenced
358  * message-id into 'array'. */
359 static void
360 parse_references (GPtrArray *array,
361                   const char *refs)
362 {
363     char *ref;
364
365     if (refs == NULL)
366         return;
367
368     while (*refs) {
369         ref = parse_message_id (refs, &refs);
370
371         if (ref)
372             g_ptr_array_add (array, ref);
373     }
374 }
375
376 char *
377 notmuch_database_default_path (void)
378 {
379     if (getenv ("NOTMUCH_BASE"))
380         return strdup (getenv ("NOTMUCH_BASE"));
381
382     return g_strdup_printf ("%s/mail", getenv ("HOME"));
383 }
384
385 notmuch_database_t *
386 notmuch_database_create (const char *path)
387 {
388     notmuch_database_t *notmuch = NULL;
389     char *notmuch_path = NULL;
390     struct stat st;
391     int err;
392     char *local_path = NULL;
393
394     if (path == NULL)
395         path = local_path = notmuch_database_default_path ();
396
397     err = stat (path, &st);
398     if (err) {
399         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
400                  path, strerror (errno));
401         goto DONE;
402     }
403
404     if (! S_ISDIR (st.st_mode)) {
405         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
406                  path);
407         goto DONE;
408     }
409
410     notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
411
412     err = mkdir (notmuch_path, 0755);
413
414     if (err) {
415         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
416                  notmuch_path, strerror (errno));
417         goto DONE;
418     }
419
420     notmuch = notmuch_database_open (path);
421
422   DONE:
423     if (notmuch_path)
424         free (notmuch_path);
425     if (local_path)
426         free (local_path);
427
428     return notmuch;
429 }
430
431 notmuch_database_t *
432 notmuch_database_open (const char *path)
433 {
434     notmuch_database_t *notmuch = NULL;
435     char *notmuch_path = NULL, *xapian_path = NULL;
436     struct stat st;
437     int err;
438     char *local_path = NULL;
439
440     if (path == NULL)
441         path = local_path = notmuch_database_default_path ();
442
443     notmuch_path = g_strdup_printf ("%s/%s", path, ".notmuch");
444
445     err = stat (notmuch_path, &st);
446     if (err) {
447         fprintf (stderr, "Error opening database at %s: %s\n",
448                  notmuch_path, strerror (errno));
449         goto DONE;
450     }
451
452     xapian_path = g_strdup_printf ("%s/%s", notmuch_path, "xapian");
453
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);
458
459     try {
460         Xapian::PostingIterator i;
461         notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
462                                                            Xapian::DB_CREATE_OR_OPEN);
463     } catch (const Xapian::Error &error) {
464         fprintf (stderr, "A Xapian exception occurred: %s\n",
465                  error.get_msg().c_str());
466     }
467     
468   DONE:
469     if (local_path)
470         free (local_path);
471     if (notmuch_path)
472         free (notmuch_path);
473     if (xapian_path)
474         free (xapian_path);
475
476     return notmuch;
477 }
478
479 void
480 notmuch_database_close (notmuch_database_t *notmuch)
481 {
482     delete notmuch->xapian_db;
483     free (notmuch->path);
484     free (notmuch);
485 }
486
487 const char *
488 notmuch_database_get_path (notmuch_database_t *notmuch)
489 {
490     return notmuch->path;
491 }
492
493 notmuch_status_t
494 notmuch_database_add_message (notmuch_database_t *notmuch,
495                               const char *filename)
496 {
497     Xapian::WritableDatabase *db = notmuch->xapian_db;
498     Xapian::Document doc;
499     notmuch_message_file_t *message;
500
501     GPtrArray *parents, *thread_ids;
502
503     const char *refs, *in_reply_to, *date, *header;
504     const char *from, *to, *subject;
505     char *message_id;
506
507     time_t time_value;
508     unsigned int i;
509
510     message = notmuch_message_file_open (filename);
511
512     notmuch_message_file_restrict_headers (message,
513                                            "date",
514                                            "from",
515                                            "in-reply-to",
516                                            "message-id",
517                                            "references",
518                                            "subject",
519                                            (char *) NULL);
520
521     try {
522         doc = Xapian::Document ();
523
524         doc.set_data (filename);
525
526         parents = g_ptr_array_new ();
527
528         refs = notmuch_message_file_get_header (message, "references");
529         parse_references (parents, refs);
530
531         in_reply_to = notmuch_message_file_get_header (message, "in-reply-to");
532         parse_references (parents, in_reply_to);
533
534         for (i = 0; i < parents->len; i++)
535             add_term (doc, "ref", (char *) g_ptr_array_index (parents, i));
536
537         header = notmuch_message_file_get_header (message, "message-id");
538         if (header) {
539             message_id = parse_message_id (header, NULL);
540             /* So the header value isn't RFC-compliant, but it's
541              * better than no message-id at all. */
542             if (message_id == NULL)
543                 message_id = xstrdup (header);
544         } else {
545             /* XXX: Should generate a message_id here, (such as a SHA1
546              * sum of the message itself) */
547             message_id = NULL;
548         }
549
550         thread_ids = find_thread_ids (db, parents, message_id);
551
552         for (i = 0; i < parents->len; i++)
553             g_free (g_ptr_array_index (parents, i));
554         g_ptr_array_free (parents, TRUE);
555         if (message_id) {
556             add_term (doc, "msgid", message_id);
557             doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
558         }
559
560         if (thread_ids->len) {
561             unsigned int i;
562             GString *thread_id;
563             char *id;
564
565             for (i = 0; i < thread_ids->len; i++) {
566                 id = (char *) thread_ids->pdata[i];
567                 add_term (doc, "thread", id);
568                 if (i == 0)
569                     thread_id = g_string_new (id);
570                 else
571                     g_string_append_printf (thread_id, ",%s", id);
572
573                 free (id);
574             }
575             doc.add_value (NOTMUCH_VALUE_THREAD, thread_id->str);
576             g_string_free (thread_id, TRUE);
577         } else if (message_id) {
578             /* If not part of any existing thread, generate a new thread_id. */
579             thread_id_t thread_id;
580
581             thread_id_generate (&thread_id);
582             add_term (doc, "thread", thread_id.str);
583             doc.add_value (NOTMUCH_VALUE_THREAD, thread_id.str);
584         }
585
586         g_ptr_array_free (thread_ids, TRUE);
587
588         free (message_id);
589
590         date = notmuch_message_file_get_header (message, "date");
591         time_value = notmuch_parse_date (date, NULL);
592
593         doc.add_value (NOTMUCH_VALUE_DATE,
594                        Xapian::sortable_serialise (time_value));
595
596         from = notmuch_message_file_get_header (message, "from");
597         subject = notmuch_message_file_get_header (message, "subject");
598         to = notmuch_message_file_get_header (message, "to");
599
600         if (from == NULL &&
601             subject == NULL &&
602             to == NULL)
603         {
604             notmuch_message_file_close (message);
605             return NOTMUCH_STATUS_FILE_NOT_EMAIL;
606         } else {
607             db->add_document (doc);
608         }
609     } catch (const Xapian::Error &error) {
610         fprintf (stderr, "A Xapian exception occurred: %s.\n",
611                  error.get_msg().c_str());
612         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
613     }
614
615     notmuch_message_file_close (message);
616
617     return NOTMUCH_STATUS_SUCCESS;
618 }