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