]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib: construct compactor within try block to catch any exceptions
[notmuch] / lib / 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 #include "parse-time-vrp.h"
23
24 #include <iostream>
25
26 #include <sys/time.h>
27 #include <sys/stat.h>
28 #include <signal.h>
29 #include <ftw.h>
30
31 #include <glib.h> /* g_free, GPtrArray, GHashTable */
32 #include <glib-object.h> /* g_type_init */
33
34 #include <gmime/gmime.h> /* g_mime_init */
35
36 using namespace std;
37
38 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
39
40 typedef struct {
41     const char *name;
42     const char *prefix;
43 } prefix_t;
44
45 #define NOTMUCH_DATABASE_VERSION 1
46
47 #define STRINGIFY(s) _SUB_STRINGIFY(s)
48 #define _SUB_STRINGIFY(s) #s
49
50 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
51  *
52  * We currently have two different types of documents (mail and
53  * directory) and also some metadata.
54  *
55  * Mail document
56  * -------------
57  * A mail document is associated with a particular email message file
58  * on disk. It is indexed with the following prefixed terms which the
59  * database uses to construct threads, etc.:
60  *
61  *    Single terms of given prefix:
62  *
63  *      type:   mail
64  *
65  *      id:     Unique ID of mail. This is from the Message-ID header
66  *              if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
67  *              If it's present and too long, then we use
68  *              "notmuch-sha1-<sha1_sum_of_message_id>".
69  *              If this header is not present, we use
70  *              "notmuch-sha1-<sha1_sum_of_entire_file>".
71  *
72  *      thread: The ID of the thread to which the mail belongs
73  *
74  *      replyto: The ID from the In-Reply-To header of the mail (if any).
75  *
76  *    Multiple terms of given prefix:
77  *
78  *      reference: All message IDs from In-Reply-To and References
79  *                 headers in the message.
80  *
81  *      tag:       Any tags associated with this message by the user.
82  *
83  *      file-direntry:  A colon-separated pair of values
84  *                      (INTEGER:STRING), where INTEGER is the
85  *                      document ID of a directory document, and
86  *                      STRING is the name of a file within that
87  *                      directory for this mail message.
88  *
89  *    A mail document also has four values:
90  *
91  *      TIMESTAMP:      The time_t value corresponding to the message's
92  *                      Date header.
93  *
94  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
95  *
96  *      FROM:           The value of the "From" header
97  *
98  *      SUBJECT:        The value of the "Subject" header
99  *
100  * In addition, terms from the content of the message are added with
101  * "from", "to", "attachment", and "subject" prefixes for use by the
102  * user in searching. Similarly, terms from the path of the mail
103  * message are added with a "folder" prefix. But the database doesn't
104  * really care itself about any of these.
105  *
106  * The data portion of a mail document is empty.
107  *
108  * Directory document
109  * ------------------
110  * A directory document is used by a client of the notmuch library to
111  * maintain data necessary to allow for efficient polling of mail
112  * directories.
113  *
114  * All directory documents contain one term:
115  *
116  *      directory:      The directory path (relative to the database path)
117  *                      Or the SHA1 sum of the directory path (if the
118  *                      path itself is too long to fit in a Xapian
119  *                      term).
120  *
121  * And all directory documents for directories other than top-level
122  * directories also contain the following term:
123  *
124  *      directory-direntry: A colon-separated pair of values
125  *                          (INTEGER:STRING), where INTEGER is the
126  *                          document ID of the parent directory
127  *                          document, and STRING is the name of this
128  *                          directory within that parent.
129  *
130  * All directory documents have a single value:
131  *
132  *      TIMESTAMP:      The mtime of the directory (at last scan)
133  *
134  * The data portion of a directory document contains the path of the
135  * directory (relative to the database path).
136  *
137  * Database metadata
138  * -----------------
139  * Xapian allows us to store arbitrary name-value pairs as
140  * "metadata". We currently use the following metadata names with the
141  * given meanings:
142  *
143  *      version         The database schema version, (which is distinct
144  *                      from both the notmuch package version (see
145  *                      notmuch --version) and the libnotmuch library
146  *                      version. The version is stored as an base-10
147  *                      ASCII integer. The initial database version
148  *                      was 1, (though a schema existed before that
149  *                      were no "version" database value existed at
150  *                      all). Successive versions are allocated as
151  *                      changes are made to the database (such as by
152  *                      indexing new fields).
153  *
154  *      last_thread_id  The last thread ID generated. This is stored
155  *                      as a 16-byte hexadecimal ASCII representation
156  *                      of a 64-bit unsigned integer. The first ID
157  *                      generated is 1 and the value will be
158  *                      incremented for each thread ID.
159  *
160  *      thread_id_*     A pre-allocated thread ID for a particular
161  *                      message. This is actually an arbitrarily large
162  *                      family of metadata name. Any particular name is
163  *                      formed by concatenating "thread_id_" with a message
164  *                      ID (or the SHA1 sum of a message ID if it is very
165  *                      long---see description of 'id' in the mail
166  *                      document). The value stored is a thread ID.
167  *
168  *                      These thread ID metadata values are stored
169  *                      whenever a message references a parent message
170  *                      that does not yet exist in the database. A
171  *                      thread ID will be allocated and stored, and if
172  *                      the message is later added, the stored thread
173  *                      ID will be used (and the metadata value will
174  *                      be cleared).
175  *
176  *                      Even before a message is added, it's
177  *                      pre-allocated thread ID is useful so that all
178  *                      descendant messages that reference this common
179  *                      parent can be recognized as belonging to the
180  *                      same thread.
181  */
182
183 /* With these prefix values we follow the conventions published here:
184  *
185  * http://xapian.org/docs/omega/termprefixes.html
186  *
187  * as much as makes sense. Note that I took some liberty in matching
188  * the reserved prefix values to notmuch concepts, (for example, 'G'
189  * is documented as "newsGroup (or similar entity - e.g. a web forum
190  * name)", for which I think the thread is the closest analogue in
191  * notmuch. This in spite of the fact that we will eventually be
192  * storing mailing-list messages where 'G' for "mailing list name"
193  * might be even a closer analogue. I'm treating the single-character
194  * prefixes preferentially for core notmuch concepts (which will be
195  * nearly universal to all mail messages).
196  */
197
198 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
199     { "type",                   "T" },
200     { "reference",              "XREFERENCE" },
201     { "replyto",                "XREPLYTO" },
202     { "directory",              "XDIRECTORY" },
203     { "file-direntry",          "XFDIRENTRY" },
204     { "directory-direntry",     "XDDIRENTRY" },
205 };
206
207 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
208     { "thread",                 "G" },
209     { "tag",                    "K" },
210     { "is",                     "K" },
211     { "id",                     "Q" }
212 };
213
214 static prefix_t PROBABILISTIC_PREFIX[]= {
215     { "from",                   "XFROM" },
216     { "to",                     "XTO" },
217     { "attachment",             "XATTACHMENT" },
218     { "subject",                "XSUBJECT"},
219     { "folder",                 "XFOLDER"}
220 };
221
222 const char *
223 _find_prefix (const char *name)
224 {
225     unsigned int i;
226
227     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
228         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
229             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
230     }
231
232     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
233         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
234             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
235     }
236
237     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
238         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
239             return PROBABILISTIC_PREFIX[i].prefix;
240     }
241
242     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
243
244     return "";
245 }
246
247 const char *
248 notmuch_status_to_string (notmuch_status_t status)
249 {
250     switch (status) {
251     case NOTMUCH_STATUS_SUCCESS:
252         return "No error occurred";
253     case NOTMUCH_STATUS_OUT_OF_MEMORY:
254         return "Out of memory";
255     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
256         return "Attempt to write to a read-only database";
257     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
258         return "A Xapian exception occurred";
259     case NOTMUCH_STATUS_FILE_ERROR:
260         return "Something went wrong trying to read or write a file";
261     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
262         return "File is not an email";
263     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
264         return "Message ID is identical to a message in database";
265     case NOTMUCH_STATUS_NULL_POINTER:
266         return "Erroneous NULL pointer";
267     case NOTMUCH_STATUS_TAG_TOO_LONG:
268         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
269     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
270         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
271     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
272         return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
273     case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
274         return "Unsupported operation";
275     default:
276     case NOTMUCH_STATUS_LAST_STATUS:
277         return "Unknown error status value";
278     }
279 }
280
281 static void
282 find_doc_ids_for_term (notmuch_database_t *notmuch,
283                        const char *term,
284                        Xapian::PostingIterator *begin,
285                        Xapian::PostingIterator *end)
286 {
287     *begin = notmuch->xapian_db->postlist_begin (term);
288
289     *end = notmuch->xapian_db->postlist_end (term);
290 }
291
292 static void
293 find_doc_ids (notmuch_database_t *notmuch,
294               const char *prefix_name,
295               const char *value,
296               Xapian::PostingIterator *begin,
297               Xapian::PostingIterator *end)
298 {
299     char *term;
300
301     term = talloc_asprintf (notmuch, "%s%s",
302                             _find_prefix (prefix_name), value);
303
304     find_doc_ids_for_term (notmuch, term, begin, end);
305
306     talloc_free (term);
307 }
308
309 notmuch_private_status_t
310 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
311                                       const char *prefix_name,
312                                       const char *value,
313                                       unsigned int *doc_id)
314 {
315     Xapian::PostingIterator i, end;
316
317     find_doc_ids (notmuch, prefix_name, value, &i, &end);
318
319     if (i == end) {
320         *doc_id = 0;
321         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
322     }
323
324     *doc_id = *i;
325
326 #if DEBUG_DATABASE_SANITY
327     i++;
328
329     if (i != end)
330         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
331                         prefix_name, value);
332 #endif
333
334     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
335 }
336
337 static Xapian::Document
338 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
339 {
340     return notmuch->xapian_db->get_document (doc_id);
341 }
342
343 /* Generate a compressed version of 'message_id' of the form:
344  *
345  *      notmuch-sha1-<sha1_sum_of_message_id>
346  */
347 static char *
348 _message_id_compressed (void *ctx, const char *message_id)
349 {
350     char *sha1, *compressed;
351
352     sha1 = notmuch_sha1_of_string (message_id);
353
354     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
355     free (sha1);
356
357     return compressed;
358 }
359
360 notmuch_status_t
361 notmuch_database_find_message (notmuch_database_t *notmuch,
362                                const char *message_id,
363                                notmuch_message_t **message_ret)
364 {
365     notmuch_private_status_t status;
366     unsigned int doc_id;
367
368     if (message_ret == NULL)
369         return NOTMUCH_STATUS_NULL_POINTER;
370
371     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
372         message_id = _message_id_compressed (notmuch, message_id);
373
374     try {
375         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
376                                                        message_id, &doc_id);
377
378         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
379             *message_ret = NULL;
380         else {
381             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
382                                                     NULL);
383             if (*message_ret == NULL)
384                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
385         }
386
387         return NOTMUCH_STATUS_SUCCESS;
388     } catch (const Xapian::Error &error) {
389         fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
390                  error.get_msg().c_str());
391         notmuch->exception_reported = TRUE;
392         *message_ret = NULL;
393         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
394     }
395 }
396
397 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
398  * a (potentially nested) parenthesized sequence with '\' used to
399  * escape any character (including parentheses).
400  *
401  * If the sequence to be skipped continues to the end of the string,
402  * then 'str' will be left pointing at the final terminating '\0'
403  * character.
404  */
405 static void
406 skip_space_and_comments (const char **str)
407 {
408     const char *s;
409
410     s = *str;
411     while (*s && (isspace (*s) || *s == '(')) {
412         while (*s && isspace (*s))
413             s++;
414         if (*s == '(') {
415             int nesting = 1;
416             s++;
417             while (*s && nesting) {
418                 if (*s == '(') {
419                     nesting++;
420                 } else if (*s == ')') {
421                     nesting--;
422                 } else if (*s == '\\') {
423                     if (*(s+1))
424                         s++;
425                 }
426                 s++;
427             }
428         }
429     }
430
431     *str = s;
432 }
433
434 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
435  * comments, and the '<' and '>' delimiters.
436  *
437  * If not NULL, then *next will be made to point to the first character
438  * not parsed, (possibly pointing to the final '\0' terminator.
439  *
440  * Returns a newly talloc'ed string belonging to 'ctx'.
441  *
442  * Returns NULL if there is any error parsing the message-id. */
443 static char *
444 _parse_message_id (void *ctx, const char *message_id, const char **next)
445 {
446     const char *s, *end;
447     char *result;
448
449     if (message_id == NULL || *message_id == '\0')
450         return NULL;
451
452     s = message_id;
453
454     skip_space_and_comments (&s);
455
456     /* Skip any unstructured text as well. */
457     while (*s && *s != '<')
458         s++;
459
460     if (*s == '<') {
461         s++;
462     } else {
463         if (next)
464             *next = s;
465         return NULL;
466     }
467
468     skip_space_and_comments (&s);
469
470     end = s;
471     while (*end && *end != '>')
472         end++;
473     if (next) {
474         if (*end)
475             *next = end + 1;
476         else
477             *next = end;
478     }
479
480     if (end > s && *end == '>')
481         end--;
482     if (end <= s)
483         return NULL;
484
485     result = talloc_strndup (ctx, s, end - s + 1);
486
487     /* Finally, collapse any whitespace that is within the message-id
488      * itself. */
489     {
490         char *r;
491         int len;
492
493         for (r = result, len = strlen (r); *r; r++, len--)
494             if (*r == ' ' || *r == '\t')
495                 memmove (r, r+1, len);
496     }
497
498     return result;
499 }
500
501 /* Parse a References header value, putting a (talloc'ed under 'ctx')
502  * copy of each referenced message-id into 'hash'.
503  *
504  * We explicitly avoid including any reference identical to
505  * 'message_id' in the result (to avoid mass confusion when a single
506  * message references itself cyclically---and yes, mail messages are
507  * not infrequent in the wild that do this---don't ask me why).
508  *
509  * Return the last reference parsed, if it is not equal to message_id.
510  */
511 static char *
512 parse_references (void *ctx,
513                   const char *message_id,
514                   GHashTable *hash,
515                   const char *refs)
516 {
517     char *ref;
518
519     if (refs == NULL || *refs == '\0')
520         return NULL;
521
522     while (*refs) {
523         ref = _parse_message_id (ctx, refs, &refs);
524
525         if (ref && strcmp (ref, message_id))
526             g_hash_table_insert (hash, ref, NULL);
527     }
528
529     /* The return value of this function is used to add a parent
530      * reference to the database.  We should avoid making a message
531      * its own parent, thus the following check.
532      */
533
534     if (ref && strcmp(ref, message_id)) {
535         return ref;
536     } else {
537         return NULL;
538     }
539 }
540
541 notmuch_status_t
542 notmuch_database_create (const char *path, notmuch_database_t **database)
543 {
544     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
545     notmuch_database_t *notmuch = NULL;
546     char *notmuch_path = NULL;
547     struct stat st;
548     int err;
549
550     if (path == NULL) {
551         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
552         status = NOTMUCH_STATUS_NULL_POINTER;
553         goto DONE;
554     }
555
556     err = stat (path, &st);
557     if (err) {
558         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
559                  path, strerror (errno));
560         status = NOTMUCH_STATUS_FILE_ERROR;
561         goto DONE;
562     }
563
564     if (! S_ISDIR (st.st_mode)) {
565         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
566                  path);
567         status = NOTMUCH_STATUS_FILE_ERROR;
568         goto DONE;
569     }
570
571     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
572
573     err = mkdir (notmuch_path, 0755);
574
575     if (err) {
576         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
577                  notmuch_path, strerror (errno));
578         status = NOTMUCH_STATUS_FILE_ERROR;
579         goto DONE;
580     }
581
582     status = notmuch_database_open (path,
583                                     NOTMUCH_DATABASE_MODE_READ_WRITE,
584                                     &notmuch);
585     if (status)
586         goto DONE;
587     status = notmuch_database_upgrade (notmuch, NULL, NULL);
588     if (status) {
589         notmuch_database_close(notmuch);
590         notmuch = NULL;
591     }
592
593   DONE:
594     if (notmuch_path)
595         talloc_free (notmuch_path);
596
597     if (database)
598         *database = notmuch;
599     else
600         talloc_free (notmuch);
601     return status;
602 }
603
604 notmuch_status_t
605 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
606 {
607     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
608         fprintf (stderr, "Cannot write to a read-only database.\n");
609         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
610     }
611
612     return NOTMUCH_STATUS_SUCCESS;
613 }
614
615 notmuch_status_t
616 notmuch_database_open (const char *path,
617                        notmuch_database_mode_t mode,
618                        notmuch_database_t **database)
619 {
620     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
621     void *local = talloc_new (NULL);
622     notmuch_database_t *notmuch = NULL;
623     char *notmuch_path, *xapian_path;
624     struct stat st;
625     int err;
626     unsigned int i, version;
627     static int initialized = 0;
628
629     if (path == NULL) {
630         fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
631         status = NOTMUCH_STATUS_NULL_POINTER;
632         goto DONE;
633     }
634
635     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
636         fprintf (stderr, "Out of memory\n");
637         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
638         goto DONE;
639     }
640
641     err = stat (notmuch_path, &st);
642     if (err) {
643         fprintf (stderr, "Error opening database at %s: %s\n",
644                  notmuch_path, strerror (errno));
645         status = NOTMUCH_STATUS_FILE_ERROR;
646         goto DONE;
647     }
648
649     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
650         fprintf (stderr, "Out of memory\n");
651         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
652         goto DONE;
653     }
654
655     /* Initialize the GLib type system and threads */
656 #if !GLIB_CHECK_VERSION(2, 35, 1)
657     g_type_init ();
658 #endif
659
660     /* Initialize gmime */
661     if (! initialized) {
662         g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
663         initialized = 1;
664     }
665
666     notmuch = talloc_zero (NULL, notmuch_database_t);
667     notmuch->exception_reported = FALSE;
668     notmuch->path = talloc_strdup (notmuch, path);
669
670     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
671         notmuch->path[strlen (notmuch->path) - 1] = '\0';
672
673     notmuch->needs_upgrade = FALSE;
674     notmuch->mode = mode;
675     notmuch->atomic_nesting = 0;
676     try {
677         string last_thread_id;
678
679         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
680             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
681                                                                Xapian::DB_CREATE_OR_OPEN);
682             version = notmuch_database_get_version (notmuch);
683
684             if (version > NOTMUCH_DATABASE_VERSION) {
685                 fprintf (stderr,
686                          "Error: Notmuch database at %s\n"
687                          "       has a newer database format version (%u) than supported by this\n"
688                          "       version of notmuch (%u). Refusing to open this database in\n"
689                          "       read-write mode.\n",
690                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
691                 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
692                 notmuch_database_destroy (notmuch);
693                 notmuch = NULL;
694                 status = NOTMUCH_STATUS_FILE_ERROR;
695                 goto DONE;
696             }
697
698             if (version < NOTMUCH_DATABASE_VERSION)
699                 notmuch->needs_upgrade = TRUE;
700         } else {
701             notmuch->xapian_db = new Xapian::Database (xapian_path);
702             version = notmuch_database_get_version (notmuch);
703             if (version > NOTMUCH_DATABASE_VERSION)
704             {
705                 fprintf (stderr,
706                          "Warning: Notmuch database at %s\n"
707                          "         has a newer database format version (%u) than supported by this\n"
708                          "         version of notmuch (%u). Some operations may behave incorrectly,\n"
709                          "         (but the database will not be harmed since it is being opened\n"
710                          "         in read-only mode).\n",
711                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
712             }
713         }
714
715         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
716         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
717         if (last_thread_id.empty ()) {
718             notmuch->last_thread_id = 0;
719         } else {
720             const char *str;
721             char *end;
722
723             str = last_thread_id.c_str ();
724             notmuch->last_thread_id = strtoull (str, &end, 16);
725             if (*end != '\0')
726                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
727         }
728
729         notmuch->query_parser = new Xapian::QueryParser;
730         notmuch->term_gen = new Xapian::TermGenerator;
731         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
732         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
733         notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
734
735         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
736         notmuch->query_parser->set_database (*notmuch->xapian_db);
737         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
738         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
739         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
740         notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
741
742         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
743             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
744             notmuch->query_parser->add_boolean_prefix (prefix->name,
745                                                        prefix->prefix);
746         }
747
748         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
749             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
750             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
751         }
752     } catch (const Xapian::Error &error) {
753         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
754                  error.get_msg().c_str());
755         notmuch_database_destroy (notmuch);
756         notmuch = NULL;
757         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
758     }
759
760   DONE:
761     talloc_free (local);
762
763     if (database)
764         *database = notmuch;
765     else
766         talloc_free (notmuch);
767     return status;
768 }
769
770 void
771 notmuch_database_close (notmuch_database_t *notmuch)
772 {
773     try {
774         if (notmuch->xapian_db != NULL &&
775             notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
776             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
777     } catch (const Xapian::Error &error) {
778         if (! notmuch->exception_reported) {
779             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
780                      error.get_msg().c_str());
781         }
782     }
783
784     /* Many Xapian objects (and thus notmuch objects) hold references to
785      * the database, so merely deleting the database may not suffice to
786      * close it.  Thus, we explicitly close it here. */
787     if (notmuch->xapian_db != NULL) {
788         try {
789             notmuch->xapian_db->close();
790         } catch (const Xapian::Error &error) {
791             /* do nothing */
792         }
793     }
794
795     delete notmuch->term_gen;
796     notmuch->term_gen = NULL;
797     delete notmuch->query_parser;
798     notmuch->query_parser = NULL;
799     delete notmuch->xapian_db;
800     notmuch->xapian_db = NULL;
801     delete notmuch->value_range_processor;
802     notmuch->value_range_processor = NULL;
803     delete notmuch->date_range_processor;
804     notmuch->date_range_processor = NULL;
805 }
806
807 #if HAVE_XAPIAN_COMPACT
808 static int unlink_cb (const char *path,
809                       unused (const struct stat *sb),
810                       unused (int type),
811                       unused (struct FTW *ftw))
812 {
813     return remove(path);
814 }
815
816 static int rmtree (const char *path)
817 {
818     return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
819 }
820
821 class NotmuchCompactor : public Xapian::Compactor
822 {
823     notmuch_compact_status_cb_t status_cb;
824
825 public:
826     NotmuchCompactor(notmuch_compact_status_cb_t cb) : status_cb(cb) { }
827
828     virtual void
829     set_status (const std::string &table, const std::string &status)
830     {
831         char* msg;
832
833         if (status_cb == NULL)
834             return;
835
836         if (status.length() == 0)
837             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
838         else
839             msg = talloc_asprintf (NULL, "     %s", status.c_str());
840
841         if (msg == NULL) {
842             return;
843         }
844
845         status_cb(msg);
846         talloc_free(msg);
847     }
848 };
849
850 /* Compacts the given database, optionally saving the original database
851  * in backup_path. Additionally, a callback function can be provided to
852  * give the user feedback on the progress of the (likely long-lived)
853  * compaction process.
854  *
855  * The backup path must point to a directory on the same volume as the
856  * original database. Passing a NULL backup_path will result in the
857  * uncompacted database being deleted after compaction has finished.
858  * Note that the database write lock will be held during the
859  * compaction process to protect data integrity.
860  */
861 notmuch_status_t
862 notmuch_database_compact (const char* path,
863                           const char* backup_path,
864                           notmuch_compact_status_cb_t status_cb)
865 {
866     void *local = talloc_new (NULL);
867     char *notmuch_path, *xapian_path, *compact_xapian_path;
868     char *old_xapian_path = NULL;
869     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
870     notmuch_database_t *notmuch = NULL;
871     struct stat statbuf;
872
873     ret = notmuch_database_open(path, NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch);
874     if (ret) {
875         goto DONE;
876     }
877
878     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
879         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
880         goto DONE;
881     }
882
883     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
884         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
885         goto DONE;
886     }
887
888     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
889         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
890         goto DONE;
891     }
892
893     if (backup_path != NULL) {
894         if (! (old_xapian_path = talloc_asprintf (local, "%s/xapian.old", backup_path))) {
895             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
896             goto DONE;
897         }
898
899         if (stat(old_xapian_path, &statbuf) != -1) {
900             fprintf (stderr, "Backup path already exists: %s\n", old_xapian_path);
901             ret = NOTMUCH_STATUS_FILE_ERROR;
902             goto DONE;
903         }
904         if (errno != ENOENT) {
905             fprintf (stderr, "Unknown error while stat()ing backup path: %s\n",
906                      strerror(errno));
907             goto DONE;
908         }
909     }
910
911     try {
912         NotmuchCompactor compactor(status_cb);
913
914         compactor.set_renumber(false);
915         compactor.add_source(xapian_path);
916         compactor.set_destdir(compact_xapian_path);
917         compactor.compact();
918     } catch (Xapian::InvalidArgumentError e) {
919         fprintf (stderr, "Error while compacting: %s\n", e.get_msg().c_str());
920         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
921         goto DONE;
922     }
923
924     if (old_xapian_path != NULL) {
925         if (rename(xapian_path, old_xapian_path)) {
926             fprintf (stderr, "Error moving old database out of the way\n");
927             ret = NOTMUCH_STATUS_FILE_ERROR;
928             goto DONE;
929         }
930     } else {
931         rmtree(xapian_path);
932     }
933
934     if (rename(compact_xapian_path, xapian_path)) {
935         fprintf (stderr, "Error moving compacted database\n");
936         ret = NOTMUCH_STATUS_FILE_ERROR;
937         goto DONE;
938     }
939
940     notmuch_database_close(notmuch);
941
942 DONE:
943     talloc_free(local);
944     return ret;
945 }
946 #else
947 notmuch_status_t
948 notmuch_database_compact (unused (const char* path),
949                           unused (const char* backup_path),
950                           unused (notmuch_compact_status_cb_t status_cb))
951 {
952     fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
953     return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
954 }
955 #endif
956
957 void
958 notmuch_database_destroy (notmuch_database_t *notmuch)
959 {
960     notmuch_database_close (notmuch);
961     talloc_free (notmuch);
962 }
963
964 const char *
965 notmuch_database_get_path (notmuch_database_t *notmuch)
966 {
967     return notmuch->path;
968 }
969
970 unsigned int
971 notmuch_database_get_version (notmuch_database_t *notmuch)
972 {
973     unsigned int version;
974     string version_string;
975     const char *str;
976     char *end;
977
978     version_string = notmuch->xapian_db->get_metadata ("version");
979     if (version_string.empty ())
980         return 0;
981
982     str = version_string.c_str ();
983     if (str == NULL || *str == '\0')
984         return 0;
985
986     version = strtoul (str, &end, 10);
987     if (*end != '\0')
988         INTERNAL_ERROR ("Malformed database version: %s", str);
989
990     return version;
991 }
992
993 notmuch_bool_t
994 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
995 {
996     return notmuch->needs_upgrade;
997 }
998
999 static volatile sig_atomic_t do_progress_notify = 0;
1000
1001 static void
1002 handle_sigalrm (unused (int signal))
1003 {
1004     do_progress_notify = 1;
1005 }
1006
1007 /* Upgrade the current database.
1008  *
1009  * After opening a database in read-write mode, the client should
1010  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1011  * if so, upgrade with this function before making any modifications.
1012  *
1013  * The optional progress_notify callback can be used by the caller to
1014  * provide progress indication to the user. If non-NULL it will be
1015  * called periodically with 'count' as the number of messages upgraded
1016  * so far and 'total' the overall number of messages that will be
1017  * converted.
1018  */
1019 notmuch_status_t
1020 notmuch_database_upgrade (notmuch_database_t *notmuch,
1021                           void (*progress_notify) (void *closure,
1022                                                    double progress),
1023                           void *closure)
1024 {
1025     Xapian::WritableDatabase *db;
1026     struct sigaction action;
1027     struct itimerval timerval;
1028     notmuch_bool_t timer_is_active = FALSE;
1029     unsigned int version;
1030     notmuch_status_t status;
1031     unsigned int count = 0, total = 0;
1032
1033     status = _notmuch_database_ensure_writable (notmuch);
1034     if (status)
1035         return status;
1036
1037     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1038
1039     version = notmuch_database_get_version (notmuch);
1040
1041     if (version >= NOTMUCH_DATABASE_VERSION)
1042         return NOTMUCH_STATUS_SUCCESS;
1043
1044     if (progress_notify) {
1045         /* Setup our handler for SIGALRM */
1046         memset (&action, 0, sizeof (struct sigaction));
1047         action.sa_handler = handle_sigalrm;
1048         sigemptyset (&action.sa_mask);
1049         action.sa_flags = SA_RESTART;
1050         sigaction (SIGALRM, &action, NULL);
1051
1052         /* Then start a timer to send SIGALRM once per second. */
1053         timerval.it_interval.tv_sec = 1;
1054         timerval.it_interval.tv_usec = 0;
1055         timerval.it_value.tv_sec = 1;
1056         timerval.it_value.tv_usec = 0;
1057         setitimer (ITIMER_REAL, &timerval, NULL);
1058
1059         timer_is_active = TRUE;
1060     }
1061
1062     /* Before version 1, each message document had its filename in the
1063      * data field. Copy that into the new format by calling
1064      * notmuch_message_add_filename.
1065      */
1066     if (version < 1) {
1067         notmuch_query_t *query = notmuch_query_create (notmuch, "");
1068         notmuch_messages_t *messages;
1069         notmuch_message_t *message;
1070         char *filename;
1071         Xapian::TermIterator t, t_end;
1072
1073         total = notmuch_query_count_messages (query);
1074
1075         for (messages = notmuch_query_search_messages (query);
1076              notmuch_messages_valid (messages);
1077              notmuch_messages_move_to_next (messages))
1078         {
1079             if (do_progress_notify) {
1080                 progress_notify (closure, (double) count / total);
1081                 do_progress_notify = 0;
1082             }
1083
1084             message = notmuch_messages_get (messages);
1085
1086             filename = _notmuch_message_talloc_copy_data (message);
1087             if (filename && *filename != '\0') {
1088                 _notmuch_message_add_filename (message, filename);
1089                 _notmuch_message_sync (message);
1090             }
1091             talloc_free (filename);
1092
1093             notmuch_message_destroy (message);
1094
1095             count++;
1096         }
1097
1098         notmuch_query_destroy (query);
1099
1100         /* Also, before version 1 we stored directory timestamps in
1101          * XTIMESTAMP documents instead of the current XDIRECTORY
1102          * documents. So copy those as well. */
1103
1104         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1105
1106         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1107              t != t_end;
1108              t++)
1109         {
1110             Xapian::PostingIterator p, p_end;
1111             std::string term = *t;
1112
1113             p_end = notmuch->xapian_db->postlist_end (term);
1114
1115             for (p = notmuch->xapian_db->postlist_begin (term);
1116                  p != p_end;
1117                  p++)
1118             {
1119                 Xapian::Document document;
1120                 time_t mtime;
1121                 notmuch_directory_t *directory;
1122
1123                 if (do_progress_notify) {
1124                     progress_notify (closure, (double) count / total);
1125                     do_progress_notify = 0;
1126                 }
1127
1128                 document = find_document_for_doc_id (notmuch, *p);
1129                 mtime = Xapian::sortable_unserialise (
1130                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1131
1132                 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1133                                                        NOTMUCH_FIND_CREATE, &status);
1134                 notmuch_directory_set_mtime (directory, mtime);
1135                 notmuch_directory_destroy (directory);
1136             }
1137         }
1138     }
1139
1140     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1141     db->flush ();
1142
1143     /* Now that the upgrade is complete we can remove the old data
1144      * and documents that are no longer needed. */
1145     if (version < 1) {
1146         notmuch_query_t *query = notmuch_query_create (notmuch, "");
1147         notmuch_messages_t *messages;
1148         notmuch_message_t *message;
1149         char *filename;
1150
1151         for (messages = notmuch_query_search_messages (query);
1152              notmuch_messages_valid (messages);
1153              notmuch_messages_move_to_next (messages))
1154         {
1155             if (do_progress_notify) {
1156                 progress_notify (closure, (double) count / total);
1157                 do_progress_notify = 0;
1158             }
1159
1160             message = notmuch_messages_get (messages);
1161
1162             filename = _notmuch_message_talloc_copy_data (message);
1163             if (filename && *filename != '\0') {
1164                 _notmuch_message_clear_data (message);
1165                 _notmuch_message_sync (message);
1166             }
1167             talloc_free (filename);
1168
1169             notmuch_message_destroy (message);
1170         }
1171
1172         notmuch_query_destroy (query);
1173     }
1174
1175     if (version < 1) {
1176         Xapian::TermIterator t, t_end;
1177
1178         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1179
1180         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1181              t != t_end;
1182              t++)
1183         {
1184             Xapian::PostingIterator p, p_end;
1185             std::string term = *t;
1186
1187             p_end = notmuch->xapian_db->postlist_end (term);
1188
1189             for (p = notmuch->xapian_db->postlist_begin (term);
1190                  p != p_end;
1191                  p++)
1192             {
1193                 if (do_progress_notify) {
1194                     progress_notify (closure, (double) count / total);
1195                     do_progress_notify = 0;
1196                 }
1197
1198                 db->delete_document (*p);
1199             }
1200         }
1201     }
1202
1203     if (timer_is_active) {
1204         /* Now stop the timer. */
1205         timerval.it_interval.tv_sec = 0;
1206         timerval.it_interval.tv_usec = 0;
1207         timerval.it_value.tv_sec = 0;
1208         timerval.it_value.tv_usec = 0;
1209         setitimer (ITIMER_REAL, &timerval, NULL);
1210
1211         /* And disable the signal handler. */
1212         action.sa_handler = SIG_IGN;
1213         sigaction (SIGALRM, &action, NULL);
1214     }
1215
1216     return NOTMUCH_STATUS_SUCCESS;
1217 }
1218
1219 notmuch_status_t
1220 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1221 {
1222     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1223         notmuch->atomic_nesting > 0)
1224         goto DONE;
1225
1226     try {
1227         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1228     } catch (const Xapian::Error &error) {
1229         fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1230                  error.get_msg().c_str());
1231         notmuch->exception_reported = TRUE;
1232         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1233     }
1234
1235 DONE:
1236     notmuch->atomic_nesting++;
1237     return NOTMUCH_STATUS_SUCCESS;
1238 }
1239
1240 notmuch_status_t
1241 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1242 {
1243     Xapian::WritableDatabase *db;
1244
1245     if (notmuch->atomic_nesting == 0)
1246         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1247
1248     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1249         notmuch->atomic_nesting > 1)
1250         goto DONE;
1251
1252     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1253     try {
1254         db->commit_transaction ();
1255
1256         /* This is a hack for testing.  Xapian never flushes on a
1257          * non-flushed commit, even if the flush threshold is 1.
1258          * However, we rely on flushing to test atomicity. */
1259         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1260         if (thresh && atoi (thresh) == 1)
1261             db->flush ();
1262     } catch (const Xapian::Error &error) {
1263         fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1264                  error.get_msg().c_str());
1265         notmuch->exception_reported = TRUE;
1266         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1267     }
1268
1269 DONE:
1270     notmuch->atomic_nesting--;
1271     return NOTMUCH_STATUS_SUCCESS;
1272 }
1273
1274 /* We allow the user to use arbitrarily long paths for directories. But
1275  * we have a term-length limit. So if we exceed that, we'll use the
1276  * SHA-1 of the path for the database term.
1277  *
1278  * Note: This function may return the original value of 'path'. If it
1279  * does not, then the caller is responsible to free() the returned
1280  * value.
1281  */
1282 const char *
1283 _notmuch_database_get_directory_db_path (const char *path)
1284 {
1285     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1286
1287     if (term_len > NOTMUCH_TERM_MAX)
1288         return notmuch_sha1_of_string (path);
1289     else
1290         return path;
1291 }
1292
1293 /* Given a path, split it into two parts: the directory part is all
1294  * components except for the last, and the basename is that last
1295  * component. Getting the return-value for either part is optional
1296  * (the caller can pass NULL).
1297  *
1298  * The original 'path' can represent either a regular file or a
1299  * directory---the splitting will be carried out in the same way in
1300  * either case. Trailing slashes on 'path' will be ignored, and any
1301  * cases of multiple '/' characters appearing in series will be
1302  * treated as a single '/'.
1303  *
1304  * Allocation (if any) will have 'ctx' as the talloc owner. But
1305  * pointers will be returned within the original path string whenever
1306  * possible.
1307  *
1308  * Note: If 'path' is non-empty and contains no non-trailing slash,
1309  * (that is, consists of a filename with no parent directory), then
1310  * the directory returned will be an empty string. However, if 'path'
1311  * is an empty string, then both directory and basename will be
1312  * returned as NULL.
1313  */
1314 notmuch_status_t
1315 _notmuch_database_split_path (void *ctx,
1316                               const char *path,
1317                               const char **directory,
1318                               const char **basename)
1319 {
1320     const char *slash;
1321
1322     if (path == NULL || *path == '\0') {
1323         if (directory)
1324             *directory = NULL;
1325         if (basename)
1326             *basename = NULL;
1327         return NOTMUCH_STATUS_SUCCESS;
1328     }
1329
1330     /* Find the last slash (not counting a trailing slash), if any. */
1331
1332     slash = path + strlen (path) - 1;
1333
1334     /* First, skip trailing slashes. */
1335     while (slash != path) {
1336         if (*slash != '/')
1337             break;
1338
1339         --slash;
1340     }
1341
1342     /* Then, find a slash. */
1343     while (slash != path) {
1344         if (*slash == '/')
1345             break;
1346
1347         if (basename)
1348             *basename = slash;
1349
1350         --slash;
1351     }
1352
1353     /* Finally, skip multiple slashes. */
1354     while (slash != path) {
1355         if (*slash != '/')
1356             break;
1357
1358         --slash;
1359     }
1360
1361     if (slash == path) {
1362         if (directory)
1363             *directory = talloc_strdup (ctx, "");
1364         if (basename)
1365             *basename = path;
1366     } else {
1367         if (directory)
1368             *directory = talloc_strndup (ctx, path, slash - path + 1);
1369     }
1370
1371     return NOTMUCH_STATUS_SUCCESS;
1372 }
1373
1374 /* Find the document ID of the specified directory.
1375  *
1376  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1377  * created if one does not exist for 'path'.  Otherwise, if the
1378  * directory document does not exist, this sets *directory_id to
1379  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1380  */
1381 notmuch_status_t
1382 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1383                                      const char *path,
1384                                      notmuch_find_flags_t flags,
1385                                      unsigned int *directory_id)
1386 {
1387     notmuch_directory_t *directory;
1388     notmuch_status_t status;
1389
1390     if (path == NULL) {
1391         *directory_id = 0;
1392         return NOTMUCH_STATUS_SUCCESS;
1393     }
1394
1395     directory = _notmuch_directory_create (notmuch, path, flags, &status);
1396     if (status || !directory) {
1397         *directory_id = -1;
1398         return status;
1399     }
1400
1401     *directory_id = _notmuch_directory_get_document_id (directory);
1402
1403     notmuch_directory_destroy (directory);
1404
1405     return NOTMUCH_STATUS_SUCCESS;
1406 }
1407
1408 const char *
1409 _notmuch_database_get_directory_path (void *ctx,
1410                                       notmuch_database_t *notmuch,
1411                                       unsigned int doc_id)
1412 {
1413     Xapian::Document document;
1414
1415     document = find_document_for_doc_id (notmuch, doc_id);
1416
1417     return talloc_strdup (ctx, document.get_data ().c_str ());
1418 }
1419
1420 /* Given a legal 'filename' for the database, (either relative to
1421  * database path or absolute with initial components identical to
1422  * database path), return a new string (with 'ctx' as the talloc
1423  * owner) suitable for use as a direntry term value.
1424  *
1425  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1426  * will be created in the database as needed.  Otherwise, if the
1427  * necessary directory documents do not exist, this sets
1428  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1429  */
1430 notmuch_status_t
1431 _notmuch_database_filename_to_direntry (void *ctx,
1432                                         notmuch_database_t *notmuch,
1433                                         const char *filename,
1434                                         notmuch_find_flags_t flags,
1435                                         char **direntry)
1436 {
1437     const char *relative, *directory, *basename;
1438     Xapian::docid directory_id;
1439     notmuch_status_t status;
1440
1441     relative = _notmuch_database_relative_path (notmuch, filename);
1442
1443     status = _notmuch_database_split_path (ctx, relative,
1444                                            &directory, &basename);
1445     if (status)
1446         return status;
1447
1448     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1449                                                   &directory_id);
1450     if (status || directory_id == (unsigned int)-1) {
1451         *direntry = NULL;
1452         return status;
1453     }
1454
1455     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1456
1457     return NOTMUCH_STATUS_SUCCESS;
1458 }
1459
1460 /* Given a legal 'path' for the database, return the relative path.
1461  *
1462  * The return value will be a pointer to the original path contents,
1463  * and will be either the original string (if 'path' was relative) or
1464  * a portion of the string (if path was absolute and begins with the
1465  * database path).
1466  */
1467 const char *
1468 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1469                                  const char *path)
1470 {
1471     const char *db_path, *relative;
1472     unsigned int db_path_len;
1473
1474     db_path = notmuch_database_get_path (notmuch);
1475     db_path_len = strlen (db_path);
1476
1477     relative = path;
1478
1479     if (*relative == '/') {
1480         while (*relative == '/' && *(relative+1) == '/')
1481             relative++;
1482
1483         if (strncmp (relative, db_path, db_path_len) == 0)
1484         {
1485             relative += db_path_len;
1486             while (*relative == '/')
1487                 relative++;
1488         }
1489     }
1490
1491     return relative;
1492 }
1493
1494 notmuch_status_t
1495 notmuch_database_get_directory (notmuch_database_t *notmuch,
1496                                 const char *path,
1497                                 notmuch_directory_t **directory)
1498 {
1499     notmuch_status_t status;
1500
1501     if (directory == NULL)
1502         return NOTMUCH_STATUS_NULL_POINTER;
1503     *directory = NULL;
1504
1505     try {
1506         *directory = _notmuch_directory_create (notmuch, path,
1507                                                 NOTMUCH_FIND_LOOKUP, &status);
1508     } catch (const Xapian::Error &error) {
1509         fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1510                  error.get_msg().c_str());
1511         notmuch->exception_reported = TRUE;
1512         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1513     }
1514     return status;
1515 }
1516
1517 /* Allocate a document ID that satisfies the following criteria:
1518  *
1519  * 1. The ID does not exist for any document in the Xapian database
1520  *
1521  * 2. The ID was not previously returned from this function
1522  *
1523  * 3. The ID is the smallest integer satisfying (1) and (2)
1524  *
1525  * This function will trigger an internal error if these constraints
1526  * cannot all be satisfied, (that is, the pool of available document
1527  * IDs has been exhausted).
1528  */
1529 unsigned int
1530 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1531 {
1532     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1533
1534     notmuch->last_doc_id++;
1535
1536     if (notmuch->last_doc_id == 0)
1537         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");        
1538
1539     return notmuch->last_doc_id;
1540 }
1541
1542 static const char *
1543 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1544 {
1545     /* 16 bytes (+ terminator) for hexadecimal representation of
1546      * a 64-bit integer. */
1547     static char thread_id[17];
1548     Xapian::WritableDatabase *db;
1549
1550     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1551
1552     notmuch->last_thread_id++;
1553
1554     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1555
1556     db->set_metadata ("last_thread_id", thread_id);
1557
1558     return thread_id;
1559 }
1560
1561 static char *
1562 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1563 {
1564     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1565         message_id = _message_id_compressed (ctx, message_id);
1566
1567     return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1568                             message_id);
1569 }
1570
1571 /* Find the thread ID to which the message with 'message_id' belongs.
1572  *
1573  * Note: 'thread_id_ret' must not be NULL!
1574  * On success '*thread_id_ret' is set to a newly talloced string belonging to
1575  * 'ctx'.
1576  *
1577  * Note: If there is no message in the database with the given
1578  * 'message_id' then a new thread_id will be allocated for this
1579  * message and stored in the database metadata, (where this same
1580  * thread ID can be looked up if the message is added to the database
1581  * later).
1582  */
1583 static notmuch_status_t
1584 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1585                                   void *ctx,
1586                                   const char *message_id,
1587                                   const char **thread_id_ret)
1588 {
1589     notmuch_status_t status;
1590     notmuch_message_t *message;
1591     string thread_id_string;
1592     char *metadata_key;
1593     Xapian::WritableDatabase *db;
1594
1595     status = notmuch_database_find_message (notmuch, message_id, &message);
1596
1597     if (status)
1598         return status;
1599
1600     if (message) {
1601         *thread_id_ret = talloc_steal (ctx,
1602                                        notmuch_message_get_thread_id (message));
1603
1604         notmuch_message_destroy (message);
1605
1606         return NOTMUCH_STATUS_SUCCESS;
1607     }
1608
1609     /* Message has not been seen yet.
1610      *
1611      * We may have seen a reference to it already, in which case, we
1612      * can return the thread ID stored in the metadata. Otherwise, we
1613      * generate a new thread ID and store it there.
1614      */
1615     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1616     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1617     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1618
1619     if (thread_id_string.empty()) {
1620         *thread_id_ret = talloc_strdup (ctx,
1621                                         _notmuch_database_generate_thread_id (notmuch));
1622         db->set_metadata (metadata_key, *thread_id_ret);
1623     } else {
1624         *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1625     }
1626
1627     talloc_free (metadata_key);
1628
1629     return NOTMUCH_STATUS_SUCCESS;
1630 }
1631
1632 static notmuch_status_t
1633 _merge_threads (notmuch_database_t *notmuch,
1634                 const char *winner_thread_id,
1635                 const char *loser_thread_id)
1636 {
1637     Xapian::PostingIterator loser, loser_end;
1638     notmuch_message_t *message = NULL;
1639     notmuch_private_status_t private_status;
1640     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1641
1642     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1643
1644     for ( ; loser != loser_end; loser++) {
1645         message = _notmuch_message_create (notmuch, notmuch,
1646                                            *loser, &private_status);
1647         if (message == NULL) {
1648             ret = COERCE_STATUS (private_status,
1649                                  "Cannot find document for doc_id from query");
1650             goto DONE;
1651         }
1652
1653         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1654         _notmuch_message_add_term (message, "thread", winner_thread_id);
1655         _notmuch_message_sync (message);
1656
1657         notmuch_message_destroy (message);
1658         message = NULL;
1659     }
1660
1661   DONE:
1662     if (message)
1663         notmuch_message_destroy (message);
1664
1665     return ret;
1666 }
1667
1668 static void
1669 _my_talloc_free_for_g_hash (void *ptr)
1670 {
1671     talloc_free (ptr);
1672 }
1673
1674 static notmuch_status_t
1675 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1676                                            notmuch_message_t *message,
1677                                            notmuch_message_file_t *message_file,
1678                                            const char **thread_id)
1679 {
1680     GHashTable *parents = NULL;
1681     const char *refs, *in_reply_to, *in_reply_to_message_id;
1682     const char *last_ref_message_id, *this_message_id;
1683     GList *l, *keys = NULL;
1684     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1685
1686     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1687                                      _my_talloc_free_for_g_hash, NULL);
1688     this_message_id = notmuch_message_get_message_id (message);
1689
1690     refs = notmuch_message_file_get_header (message_file, "references");
1691     last_ref_message_id = parse_references (message,
1692                                             this_message_id,
1693                                             parents, refs);
1694
1695     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1696     in_reply_to_message_id = parse_references (message,
1697                                                this_message_id,
1698                                                parents, in_reply_to);
1699
1700     /* For the parent of this message, use the last message ID of the
1701      * References header, if available.  If not, fall back to the
1702      * first message ID in the In-Reply-To header. */
1703     if (last_ref_message_id) {
1704         _notmuch_message_add_term (message, "replyto",
1705                                    last_ref_message_id);
1706     } else if (in_reply_to_message_id) {
1707         _notmuch_message_add_term (message, "replyto",
1708                              in_reply_to_message_id);
1709     }
1710
1711     keys = g_hash_table_get_keys (parents);
1712     for (l = keys; l; l = l->next) {
1713         char *parent_message_id;
1714         const char *parent_thread_id = NULL;
1715
1716         parent_message_id = (char *) l->data;
1717
1718         _notmuch_message_add_term (message, "reference",
1719                                    parent_message_id);
1720
1721         ret = _resolve_message_id_to_thread_id (notmuch,
1722                                                 message,
1723                                                 parent_message_id,
1724                                                 &parent_thread_id);
1725         if (ret)
1726             goto DONE;
1727
1728         if (*thread_id == NULL) {
1729             *thread_id = talloc_strdup (message, parent_thread_id);
1730             _notmuch_message_add_term (message, "thread", *thread_id);
1731         } else if (strcmp (*thread_id, parent_thread_id)) {
1732             ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1733             if (ret)
1734                 goto DONE;
1735         }
1736     }
1737
1738   DONE:
1739     if (keys)
1740         g_list_free (keys);
1741     if (parents)
1742         g_hash_table_unref (parents);
1743
1744     return ret;
1745 }
1746
1747 static notmuch_status_t
1748 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1749                                             notmuch_message_t *message,
1750                                             const char **thread_id)
1751 {
1752     const char *message_id = notmuch_message_get_message_id (message);
1753     Xapian::PostingIterator child, children_end;
1754     notmuch_message_t *child_message = NULL;
1755     const char *child_thread_id;
1756     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1757     notmuch_private_status_t private_status;
1758
1759     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1760
1761     for ( ; child != children_end; child++) {
1762
1763         child_message = _notmuch_message_create (message, notmuch,
1764                                                  *child, &private_status);
1765         if (child_message == NULL) {
1766             ret = COERCE_STATUS (private_status,
1767                                  "Cannot find document for doc_id from query");
1768             goto DONE;
1769         }
1770
1771         child_thread_id = notmuch_message_get_thread_id (child_message);
1772         if (*thread_id == NULL) {
1773             *thread_id = talloc_strdup (message, child_thread_id);
1774             _notmuch_message_add_term (message, "thread", *thread_id);
1775         } else if (strcmp (*thread_id, child_thread_id)) {
1776             _notmuch_message_remove_term (child_message, "reference",
1777                                           message_id);
1778             _notmuch_message_sync (child_message);
1779             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1780             if (ret)
1781                 goto DONE;
1782         }
1783
1784         notmuch_message_destroy (child_message);
1785         child_message = NULL;
1786     }
1787
1788   DONE:
1789     if (child_message)
1790         notmuch_message_destroy (child_message);
1791
1792     return ret;
1793 }
1794
1795 /* Given a (mostly empty) 'message' and its corresponding
1796  * 'message_file' link it to existing threads in the database.
1797  *
1798  * The first check is in the metadata of the database to see if we
1799  * have pre-allocated a thread_id in advance for this message, (which
1800  * would have happened if a message was previously added that
1801  * referenced this one).
1802  *
1803  * Second, we look at 'message_file' and its link-relevant headers
1804  * (References and In-Reply-To) for message IDs.
1805  *
1806  * Finally, we look in the database for existing message that
1807  * reference 'message'.
1808  *
1809  * In all cases, we assign to the current message the first thread_id
1810  * found (through either parent or child). We will also merge any
1811  * existing, distinct threads where this message belongs to both,
1812  * (which is not uncommon when messages are processed out of order).
1813  *
1814  * Finally, if no thread ID has been found through parent or child, we
1815  * call _notmuch_message_generate_thread_id to generate a new thread
1816  * ID. This should only happen for new, top-level messages, (no
1817  * References or In-Reply-To header in this message, and no previously
1818  * added message refers to this message).
1819  */
1820 static notmuch_status_t
1821 _notmuch_database_link_message (notmuch_database_t *notmuch,
1822                                 notmuch_message_t *message,
1823                                 notmuch_message_file_t *message_file)
1824 {
1825     notmuch_status_t status;
1826     const char *message_id, *thread_id = NULL;
1827     char *metadata_key;
1828     string stored_id;
1829
1830     message_id = notmuch_message_get_message_id (message);
1831     metadata_key = _get_metadata_thread_id_key (message, message_id);
1832
1833     /* Check if we have already seen related messages to this one.
1834      * If we have then use the thread_id that we stored at that time.
1835      */
1836     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1837     if (! stored_id.empty()) {
1838         Xapian::WritableDatabase *db;
1839
1840         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1841
1842         /* Clear the metadata for this message ID. We don't need it
1843          * anymore. */
1844         db->set_metadata (metadata_key, "");
1845         thread_id = stored_id.c_str();
1846
1847         _notmuch_message_add_term (message, "thread", thread_id);
1848     }
1849     talloc_free (metadata_key);
1850
1851     status = _notmuch_database_link_message_to_parents (notmuch, message,
1852                                                         message_file,
1853                                                         &thread_id);
1854     if (status)
1855         return status;
1856
1857     status = _notmuch_database_link_message_to_children (notmuch, message,
1858                                                          &thread_id);
1859     if (status)
1860         return status;
1861
1862     /* If not part of any existing thread, generate a new thread ID. */
1863     if (thread_id == NULL) {
1864         thread_id = _notmuch_database_generate_thread_id (notmuch);
1865
1866         _notmuch_message_add_term (message, "thread", thread_id);
1867     }
1868
1869     return NOTMUCH_STATUS_SUCCESS;
1870 }
1871
1872 notmuch_status_t
1873 notmuch_database_add_message (notmuch_database_t *notmuch,
1874                               const char *filename,
1875                               notmuch_message_t **message_ret)
1876 {
1877     notmuch_message_file_t *message_file;
1878     notmuch_message_t *message = NULL;
1879     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1880     notmuch_private_status_t private_status;
1881
1882     const char *date, *header;
1883     const char *from, *to, *subject;
1884     char *message_id = NULL;
1885
1886     if (message_ret)
1887         *message_ret = NULL;
1888
1889     ret = _notmuch_database_ensure_writable (notmuch);
1890     if (ret)
1891         return ret;
1892
1893     message_file = notmuch_message_file_open (filename);
1894     if (message_file == NULL)
1895         return NOTMUCH_STATUS_FILE_ERROR;
1896
1897     /* Adding a message may change many documents.  Do this all
1898      * atomically. */
1899     ret = notmuch_database_begin_atomic (notmuch);
1900     if (ret)
1901         goto DONE;
1902
1903     notmuch_message_file_restrict_headers (message_file,
1904                                            "date",
1905                                            "from",
1906                                            "in-reply-to",
1907                                            "message-id",
1908                                            "references",
1909                                            "subject",
1910                                            "to",
1911                                            (char *) NULL);
1912
1913     try {
1914         /* Before we do any real work, (especially before doing a
1915          * potential SHA-1 computation on the entire file's contents),
1916          * let's make sure that what we're looking at looks like an
1917          * actual email message.
1918          */
1919         from = notmuch_message_file_get_header (message_file, "from");
1920         subject = notmuch_message_file_get_header (message_file, "subject");
1921         to = notmuch_message_file_get_header (message_file, "to");
1922
1923         if ((from == NULL || *from == '\0') &&
1924             (subject == NULL || *subject == '\0') &&
1925             (to == NULL || *to == '\0'))
1926         {
1927             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1928             goto DONE;
1929         }
1930
1931         /* Now that we're sure it's mail, the first order of business
1932          * is to find a message ID (or else create one ourselves). */
1933
1934         header = notmuch_message_file_get_header (message_file, "message-id");
1935         if (header && *header != '\0') {
1936             message_id = _parse_message_id (message_file, header, NULL);
1937
1938             /* So the header value isn't RFC-compliant, but it's
1939              * better than no message-id at all. */
1940             if (message_id == NULL)
1941                 message_id = talloc_strdup (message_file, header);
1942
1943             /* If a message ID is too long, substitute its sha1 instead. */
1944             if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1945                 char *compressed = _message_id_compressed (message_file,
1946                                                            message_id);
1947                 talloc_free (message_id);
1948                 message_id = compressed;
1949             }
1950         }
1951
1952         if (message_id == NULL ) {
1953             /* No message-id at all, let's generate one by taking a
1954              * hash over the file's contents. */
1955             char *sha1 = notmuch_sha1_of_file (filename);
1956
1957             /* If that failed too, something is really wrong. Give up. */
1958             if (sha1 == NULL) {
1959                 ret = NOTMUCH_STATUS_FILE_ERROR;
1960                 goto DONE;
1961             }
1962
1963             message_id = talloc_asprintf (message_file,
1964                                           "notmuch-sha1-%s", sha1);
1965             free (sha1);
1966         }
1967
1968         /* Now that we have a message ID, we get a message object,
1969          * (which may or may not reference an existing document in the
1970          * database). */
1971
1972         message = _notmuch_message_create_for_message_id (notmuch,
1973                                                           message_id,
1974                                                           &private_status);
1975
1976         talloc_free (message_id);
1977
1978         if (message == NULL) {
1979             ret = COERCE_STATUS (private_status,
1980                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1981             goto DONE;
1982         }
1983
1984         _notmuch_message_add_filename (message, filename);
1985
1986         /* Is this a newly created message object? */
1987         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1988             _notmuch_message_add_term (message, "type", "mail");
1989
1990             ret = _notmuch_database_link_message (notmuch, message,
1991                                                   message_file);
1992             if (ret)
1993                 goto DONE;
1994
1995             date = notmuch_message_file_get_header (message_file, "date");
1996             _notmuch_message_set_header_values (message, date, from, subject);
1997
1998             ret = _notmuch_message_index_file (message, filename);
1999             if (ret)
2000                 goto DONE;
2001         } else {
2002             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2003         }
2004
2005         _notmuch_message_sync (message);
2006     } catch (const Xapian::Error &error) {
2007         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2008                  error.get_msg().c_str());
2009         notmuch->exception_reported = TRUE;
2010         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2011         goto DONE;
2012     }
2013
2014   DONE:
2015     if (message) {
2016         if ((ret == NOTMUCH_STATUS_SUCCESS ||
2017              ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2018             *message_ret = message;
2019         else
2020             notmuch_message_destroy (message);
2021     }
2022
2023     if (message_file)
2024         notmuch_message_file_close (message_file);
2025
2026     ret2 = notmuch_database_end_atomic (notmuch);
2027     if ((ret == NOTMUCH_STATUS_SUCCESS ||
2028          ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2029         ret2 != NOTMUCH_STATUS_SUCCESS)
2030         ret = ret2;
2031
2032     return ret;
2033 }
2034
2035 notmuch_status_t
2036 notmuch_database_remove_message (notmuch_database_t *notmuch,
2037                                  const char *filename)
2038 {
2039     notmuch_status_t status;
2040     notmuch_message_t *message;
2041
2042     status = notmuch_database_find_message_by_filename (notmuch, filename,
2043                                                         &message);
2044
2045     if (status == NOTMUCH_STATUS_SUCCESS && message) {
2046             status = _notmuch_message_remove_filename (message, filename);
2047             if (status == NOTMUCH_STATUS_SUCCESS)
2048                 _notmuch_message_delete (message);
2049             else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2050                 _notmuch_message_sync (message);
2051
2052             notmuch_message_destroy (message);
2053     }
2054
2055     return status;
2056 }
2057
2058 notmuch_status_t
2059 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2060                                            const char *filename,
2061                                            notmuch_message_t **message_ret)
2062 {
2063     void *local;
2064     const char *prefix = _find_prefix ("file-direntry");
2065     char *direntry, *term;
2066     Xapian::PostingIterator i, end;
2067     notmuch_status_t status;
2068
2069     if (message_ret == NULL)
2070         return NOTMUCH_STATUS_NULL_POINTER;
2071
2072     /* return NULL on any failure */
2073     *message_ret = NULL;
2074
2075     local = talloc_new (notmuch);
2076
2077     try {
2078         status = _notmuch_database_filename_to_direntry (
2079             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2080         if (status || !direntry)
2081             goto DONE;
2082
2083         term = talloc_asprintf (local, "%s%s", prefix, direntry);
2084
2085         find_doc_ids_for_term (notmuch, term, &i, &end);
2086
2087         if (i != end) {
2088             notmuch_private_status_t private_status;
2089
2090             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2091                                                     &private_status);
2092             if (*message_ret == NULL)
2093                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2094         }
2095     } catch (const Xapian::Error &error) {
2096         fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2097                  error.get_msg().c_str());
2098         notmuch->exception_reported = TRUE;
2099         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2100     }
2101
2102   DONE:
2103     talloc_free (local);
2104
2105     if (status && *message_ret) {
2106         notmuch_message_destroy (*message_ret);
2107         *message_ret = NULL;
2108     }
2109     return status;
2110 }
2111
2112 notmuch_string_list_t *
2113 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2114                                          Xapian::TermIterator &end,
2115                                          const char *prefix)
2116 {
2117     int prefix_len = strlen (prefix);
2118     notmuch_string_list_t *list;
2119
2120     list = _notmuch_string_list_create (ctx);
2121     if (unlikely (list == NULL))
2122         return NULL;
2123
2124     for (i.skip_to (prefix); i != end; i++) {
2125         /* Terminate loop at first term without desired prefix. */
2126         if (strncmp ((*i).c_str (), prefix, prefix_len))
2127             break;
2128
2129         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2130     }
2131
2132     return list;
2133 }
2134
2135 notmuch_tags_t *
2136 notmuch_database_get_all_tags (notmuch_database_t *db)
2137 {
2138     Xapian::TermIterator i, end;
2139     notmuch_string_list_t *tags;
2140
2141     try {
2142         i = db->xapian_db->allterms_begin();
2143         end = db->xapian_db->allterms_end();
2144         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2145                                                         _find_prefix ("tag"));
2146         _notmuch_string_list_sort (tags);
2147         return _notmuch_tags_create (db, tags);
2148     } catch (const Xapian::Error &error) {
2149         fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2150                  error.get_msg().c_str());
2151         db->exception_reported = TRUE;
2152         return NULL;
2153     }
2154 }