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