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