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