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