]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
Merge branch 'release'
[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     case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
417         return "Crypto protocol missing, malformed, or unintelligible";
418     case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
419         return "Crypto engine initialization failure";
420     case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
421         return "Unknown crypto protocol";
422     default:
423     case NOTMUCH_STATUS_LAST_STATUS:
424         return "Unknown error status value";
425     }
426 }
427
428 void
429 _notmuch_database_log (notmuch_database_t *notmuch,
430                       const char *format,
431                       ...)
432 {
433     va_list va_args;
434
435     va_start (va_args, format);
436
437     if (notmuch->status_string)
438         talloc_free (notmuch->status_string);
439
440     notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
441     va_end (va_args);
442 }
443
444 void
445 _notmuch_database_log_append (notmuch_database_t *notmuch,
446                       const char *format,
447                       ...)
448 {
449     va_list va_args;
450
451     va_start (va_args, format);
452
453     if (notmuch->status_string)
454         notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
455     else
456         notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
457
458     va_end (va_args);
459 }
460
461 static void
462 find_doc_ids_for_term (notmuch_database_t *notmuch,
463                        const char *term,
464                        Xapian::PostingIterator *begin,
465                        Xapian::PostingIterator *end)
466 {
467     *begin = notmuch->xapian_db->postlist_begin (term);
468
469     *end = notmuch->xapian_db->postlist_end (term);
470 }
471
472 void
473 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
474                                 const char *prefix_name,
475                                 const char *value,
476                                 Xapian::PostingIterator *begin,
477                                 Xapian::PostingIterator *end)
478 {
479     char *term;
480
481     term = talloc_asprintf (notmuch, "%s%s",
482                             _find_prefix (prefix_name), value);
483
484     find_doc_ids_for_term (notmuch, term, begin, end);
485
486     talloc_free (term);
487 }
488
489 notmuch_private_status_t
490 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
491                                       const char *prefix_name,
492                                       const char *value,
493                                       unsigned int *doc_id)
494 {
495     Xapian::PostingIterator i, end;
496
497     _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
498
499     if (i == end) {
500         *doc_id = 0;
501         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
502     }
503
504     *doc_id = *i;
505
506 #if DEBUG_DATABASE_SANITY
507     i++;
508
509     if (i != end)
510         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
511                         prefix_name, value);
512 #endif
513
514     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
515 }
516
517 static Xapian::Document
518 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
519 {
520     return notmuch->xapian_db->get_document (doc_id);
521 }
522
523 /* Generate a compressed version of 'message_id' of the form:
524  *
525  *      notmuch-sha1-<sha1_sum_of_message_id>
526  */
527 char *
528 _notmuch_message_id_compressed (void *ctx, const char *message_id)
529 {
530     char *sha1, *compressed;
531
532     sha1 = _notmuch_sha1_of_string (message_id);
533
534     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
535     free (sha1);
536
537     return compressed;
538 }
539
540 notmuch_status_t
541 notmuch_database_find_message (notmuch_database_t *notmuch,
542                                const char *message_id,
543                                notmuch_message_t **message_ret)
544 {
545     notmuch_private_status_t status;
546     unsigned int doc_id;
547
548     if (message_ret == NULL)
549         return NOTMUCH_STATUS_NULL_POINTER;
550
551     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
552         message_id = _notmuch_message_id_compressed (notmuch, message_id);
553
554     try {
555         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
556                                                        message_id, &doc_id);
557
558         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
559             *message_ret = NULL;
560         else {
561             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
562                                                     NULL);
563             if (*message_ret == NULL)
564                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
565         }
566
567         return NOTMUCH_STATUS_SUCCESS;
568     } catch (const Xapian::Error &error) {
569         _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
570                  error.get_msg().c_str());
571         notmuch->exception_reported = true;
572         *message_ret = NULL;
573         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
574     }
575 }
576
577 notmuch_status_t
578 notmuch_database_create (const char *path, notmuch_database_t **database)
579 {
580     char *status_string = NULL;
581     notmuch_status_t status;
582
583     status = notmuch_database_create_verbose (path, database,
584                                               &status_string);
585
586     if (status_string) {
587         fputs (status_string, stderr);
588         free (status_string);
589     }
590
591     return status;
592 }
593
594 notmuch_status_t
595 notmuch_database_create_verbose (const char *path,
596                                  notmuch_database_t **database,
597                                  char **status_string)
598 {
599     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
600     notmuch_database_t *notmuch = NULL;
601     char *notmuch_path = NULL;
602     char *message = NULL;
603     struct stat st;
604     int err;
605
606     if (path == NULL) {
607         message = strdup ("Error: Cannot create a database for a NULL path.\n");
608         status = NOTMUCH_STATUS_NULL_POINTER;
609         goto DONE;
610     }
611
612     if (path[0] != '/') {
613         message = strdup ("Error: Database path must be absolute.\n");
614         status = NOTMUCH_STATUS_PATH_ERROR;
615         goto DONE;
616     }
617
618     err = stat (path, &st);
619     if (err) {
620         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
621                                 path, strerror (errno)));
622         status = NOTMUCH_STATUS_FILE_ERROR;
623         goto DONE;
624     }
625
626     if (! S_ISDIR (st.st_mode)) {
627         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
628                                  "Not a directory.\n",
629                                  path));
630         status = NOTMUCH_STATUS_FILE_ERROR;
631         goto DONE;
632     }
633
634     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
635
636     err = mkdir (notmuch_path, 0755);
637
638     if (err) {
639         IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
640                                  notmuch_path, strerror (errno)));
641         status = NOTMUCH_STATUS_FILE_ERROR;
642         goto DONE;
643     }
644
645     status = notmuch_database_open_verbose (path,
646                                             NOTMUCH_DATABASE_MODE_READ_WRITE,
647                                             &notmuch, &message);
648     if (status)
649         goto DONE;
650
651     /* Upgrade doesn't add these feature to existing databases, but
652      * new databases have them. */
653     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
654     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
655
656     status = notmuch_database_upgrade (notmuch, NULL, NULL);
657     if (status) {
658         notmuch_database_close(notmuch);
659         notmuch = NULL;
660     }
661
662   DONE:
663     if (notmuch_path)
664         talloc_free (notmuch_path);
665
666     if (message) {
667         if (status_string)
668             *status_string = message;
669         else
670             free (message);
671     }
672     if (database)
673         *database = notmuch;
674     else
675         talloc_free (notmuch);
676     return status;
677 }
678
679 notmuch_status_t
680 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
681 {
682     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
683         _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
684         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
685     }
686
687     return NOTMUCH_STATUS_SUCCESS;
688 }
689
690 /* Allocate a revision number for the next change. */
691 unsigned long
692 _notmuch_database_new_revision (notmuch_database_t *notmuch)
693 {
694     unsigned long new_revision = notmuch->revision + 1;
695
696     /* If we're in an atomic section, hold off on updating the
697      * committed revision number until we commit the atomic section.
698      */
699     if (notmuch->atomic_nesting)
700         notmuch->atomic_dirty = true;
701     else
702         notmuch->revision = new_revision;
703
704     return new_revision;
705 }
706
707 /* Parse a database features string from the given database version.
708  * Returns the feature bit set.
709  *
710  * For version < 3, this ignores the features string and returns a
711  * hard-coded set of features.
712  *
713  * If there are unrecognized features that are required to open the
714  * database in mode (which should be 'r' or 'w'), return a
715  * comma-separated list of unrecognized but required features in
716  * *incompat_out suitable for presenting to the user.  *incompat_out
717  * will be allocated from ctx.
718  */
719 static _notmuch_features
720 _parse_features (const void *ctx, const char *features, unsigned int version,
721                  char mode, char **incompat_out)
722 {
723     _notmuch_features res = static_cast<_notmuch_features>(0);
724     unsigned int namelen, i;
725     size_t llen = 0;
726     const char *flags;
727
728     /* Prior to database version 3, features were implied by the
729      * version number. */
730     if (version == 0)
731         return NOTMUCH_FEATURES_V0;
732     else if (version == 1)
733         return NOTMUCH_FEATURES_V1;
734     else if (version == 2)
735         return NOTMUCH_FEATURES_V2;
736
737     /* Parse the features string */
738     while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
739         flags = strchr (features, '\t');
740         if (! flags || flags > features + llen)
741             continue;
742         namelen = flags - features;
743
744         for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
745             if (strlen (feature_names[i].name) == namelen &&
746                 strncmp (feature_names[i].name, features, namelen) == 0) {
747                 res |= feature_names[i].value;
748                 break;
749             }
750         }
751
752         if (i == ARRAY_SIZE (feature_names) && incompat_out) {
753             /* Unrecognized feature */
754             const char *have = strchr (flags, mode);
755             if (have && have < features + llen) {
756                 /* This feature is required to access this database in
757                  * 'mode', but we don't understand it. */
758                 if (! *incompat_out)
759                     *incompat_out = talloc_strdup (ctx, "");
760                 *incompat_out = talloc_asprintf_append_buffer (
761                     *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
762                     namelen, features);
763             }
764         }
765     }
766
767     return res;
768 }
769
770 static char *
771 _print_features (const void *ctx, unsigned int features)
772 {
773     unsigned int i;
774     char *res = talloc_strdup (ctx, "");
775
776     for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
777         if (features & feature_names[i].value)
778             res = talloc_asprintf_append_buffer (
779                 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
780
781     return res;
782 }
783
784 notmuch_status_t
785 notmuch_database_open (const char *path,
786                        notmuch_database_mode_t mode,
787                        notmuch_database_t **database)
788 {
789     char *status_string = NULL;
790     notmuch_status_t status;
791
792     status = notmuch_database_open_verbose (path, mode, database,
793                                            &status_string);
794
795     if (status_string) {
796         fputs (status_string, stderr);
797         free (status_string);
798     }
799
800     return status;
801 }
802
803 notmuch_status_t
804 notmuch_database_open_verbose (const char *path,
805                                notmuch_database_mode_t mode,
806                                notmuch_database_t **database,
807                                char **status_string)
808 {
809     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
810     void *local = talloc_new (NULL);
811     notmuch_database_t *notmuch = NULL;
812     char *notmuch_path, *xapian_path, *incompat_features;
813     char *message = NULL;
814     struct stat st;
815     int err;
816     unsigned int i, version;
817     static int initialized = 0;
818
819     if (path == NULL) {
820         message = strdup ("Error: Cannot open a database for a NULL path.\n");
821         status = NOTMUCH_STATUS_NULL_POINTER;
822         goto DONE;
823     }
824
825     if (path[0] != '/') {
826         message = strdup ("Error: Database path must be absolute.\n");
827         status = NOTMUCH_STATUS_PATH_ERROR;
828         goto DONE;
829     }
830
831     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
832         message = strdup ("Out of memory\n");
833         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
834         goto DONE;
835     }
836
837     err = stat (notmuch_path, &st);
838     if (err) {
839         IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
840                                  notmuch_path, strerror (errno)));
841         status = NOTMUCH_STATUS_FILE_ERROR;
842         goto DONE;
843     }
844
845     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
846         message = strdup ("Out of memory\n");
847         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
848         goto DONE;
849     }
850
851     /* Initialize the GLib type system and threads */
852 #if !GLIB_CHECK_VERSION(2, 35, 1)
853     g_type_init ();
854 #endif
855
856     /* Initialize gmime */
857     if (! initialized) {
858         g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
859         initialized = 1;
860     }
861
862     notmuch = talloc_zero (NULL, notmuch_database_t);
863     notmuch->exception_reported = false;
864     notmuch->status_string = NULL;
865     notmuch->path = talloc_strdup (notmuch, path);
866
867     strip_trailing(notmuch->path, '/');
868
869     notmuch->mode = mode;
870     notmuch->atomic_nesting = 0;
871     notmuch->view = 1;
872     try {
873         string last_thread_id;
874         string last_mod;
875
876         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
877             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
878                                                                DB_ACTION);
879         } else {
880             notmuch->xapian_db = new Xapian::Database (xapian_path);
881         }
882
883         /* Check version.  As of database version 3, we represent
884          * changes in terms of features, so assume a version bump
885          * means a dramatically incompatible change. */
886         version = notmuch_database_get_version (notmuch);
887         if (version > NOTMUCH_DATABASE_VERSION) {
888             IGNORE_RESULT (asprintf (&message,
889                       "Error: Notmuch database at %s\n"
890                       "       has a newer database format version (%u) than supported by this\n"
891                       "       version of notmuch (%u).\n",
892                                      notmuch_path, version, NOTMUCH_DATABASE_VERSION));
893             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
894             notmuch_database_destroy (notmuch);
895             notmuch = NULL;
896             status = NOTMUCH_STATUS_FILE_ERROR;
897             goto DONE;
898         }
899
900         /* Check features. */
901         incompat_features = NULL;
902         notmuch->features = _parse_features (
903             local, notmuch->xapian_db->get_metadata ("features").c_str (),
904             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
905             &incompat_features);
906         if (incompat_features) {
907             IGNORE_RESULT (asprintf (&message,
908                 "Error: Notmuch database at %s\n"
909                 "       requires features (%s)\n"
910                 "       not supported by this version of notmuch.\n",
911                                      notmuch_path, incompat_features));
912             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
913             notmuch_database_destroy (notmuch);
914             notmuch = NULL;
915             status = NOTMUCH_STATUS_FILE_ERROR;
916             goto DONE;
917         }
918
919         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
920         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
921         if (last_thread_id.empty ()) {
922             notmuch->last_thread_id = 0;
923         } else {
924             const char *str;
925             char *end;
926
927             str = last_thread_id.c_str ();
928             notmuch->last_thread_id = strtoull (str, &end, 16);
929             if (*end != '\0')
930                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
931         }
932
933         /* Get current highest revision number. */
934         last_mod = notmuch->xapian_db->get_value_upper_bound (
935             NOTMUCH_VALUE_LAST_MOD);
936         if (last_mod.empty ())
937             notmuch->revision = 0;
938         else
939             notmuch->revision = Xapian::sortable_unserialise (last_mod);
940         notmuch->uuid = talloc_strdup (
941             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
942
943         notmuch->query_parser = new Xapian::QueryParser;
944         notmuch->term_gen = new Xapian::TermGenerator;
945         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
946         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
947         notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
948         notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
949
950         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
951         notmuch->query_parser->set_database (*notmuch->xapian_db);
952         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
953         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
954         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
955         notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
956         notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
957
958         for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
959             const prefix_t *prefix = &prefix_table[i];
960             if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
961                 _setup_query_field (prefix, notmuch);
962             }
963         }
964     } catch (const Xapian::Error &error) {
965         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
966                                  error.get_msg().c_str()));
967         notmuch_database_destroy (notmuch);
968         notmuch = NULL;
969         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
970     }
971
972   DONE:
973     talloc_free (local);
974
975     if (message) {
976         if (status_string)
977             *status_string = message;
978         else
979             free (message);
980     }
981
982     if (database)
983         *database = notmuch;
984     else
985         talloc_free (notmuch);
986     return status;
987 }
988
989 notmuch_status_t
990 notmuch_database_close (notmuch_database_t *notmuch)
991 {
992     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
993
994     /* Many Xapian objects (and thus notmuch objects) hold references to
995      * the database, so merely deleting the database may not suffice to
996      * close it.  Thus, we explicitly close it here. */
997     if (notmuch->xapian_db != NULL) {
998         try {
999             /* If there's an outstanding transaction, it's unclear if
1000              * closing the Xapian database commits everything up to
1001              * that transaction, or may discard committed (but
1002              * unflushed) transactions.  To be certain, explicitly
1003              * cancel any outstanding transaction before closing. */
1004             if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1005                 notmuch->atomic_nesting)
1006                 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1007                     ->cancel_transaction ();
1008
1009             /* Close the database.  This implicitly flushes
1010              * outstanding changes. */
1011             notmuch->xapian_db->close();
1012         } catch (const Xapian::Error &error) {
1013             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1014             if (! notmuch->exception_reported) {
1015                 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1016                          error.get_msg().c_str());
1017             }
1018         }
1019     }
1020
1021     delete notmuch->term_gen;
1022     notmuch->term_gen = NULL;
1023     delete notmuch->query_parser;
1024     notmuch->query_parser = NULL;
1025     delete notmuch->xapian_db;
1026     notmuch->xapian_db = NULL;
1027     delete notmuch->value_range_processor;
1028     notmuch->value_range_processor = NULL;
1029     delete notmuch->date_range_processor;
1030     notmuch->date_range_processor = NULL;
1031     delete notmuch->last_mod_range_processor;
1032     notmuch->last_mod_range_processor = NULL;
1033
1034     return status;
1035 }
1036
1037 notmuch_status_t
1038 _notmuch_database_reopen (notmuch_database_t *notmuch)
1039 {
1040     if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1041         return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1042
1043     try {
1044         notmuch->xapian_db->reopen ();
1045     } catch (const Xapian::Error &error) {
1046         if (! notmuch->exception_reported) {
1047             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1048                                    error.get_msg ().c_str ());
1049             notmuch->exception_reported = true;
1050         }
1051         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1052     }
1053
1054     notmuch->view++;
1055
1056     return NOTMUCH_STATUS_SUCCESS;
1057 }
1058
1059 static int
1060 unlink_cb (const char *path,
1061            unused (const struct stat *sb),
1062            unused (int type),
1063            unused (struct FTW *ftw))
1064 {
1065     return remove (path);
1066 }
1067
1068 static int
1069 rmtree (const char *path)
1070 {
1071     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1072 }
1073
1074 class NotmuchCompactor : public Xapian::Compactor
1075 {
1076     notmuch_compact_status_cb_t status_cb;
1077     void *status_closure;
1078
1079 public:
1080     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1081         status_cb (cb), status_closure (closure) { }
1082
1083     virtual void
1084     set_status (const std::string &table, const std::string &status)
1085     {
1086         char *msg;
1087
1088         if (status_cb == NULL)
1089             return;
1090
1091         if (status.length () == 0)
1092             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1093         else
1094             msg = talloc_asprintf (NULL, "     %s", status.c_str());
1095
1096         if (msg == NULL) {
1097             return;
1098         }
1099
1100         status_cb (msg, status_closure);
1101         talloc_free (msg);
1102     }
1103 };
1104
1105 /* Compacts the given database, optionally saving the original database
1106  * in backup_path. Additionally, a callback function can be provided to
1107  * give the user feedback on the progress of the (likely long-lived)
1108  * compaction process.
1109  *
1110  * The backup path must point to a directory on the same volume as the
1111  * original database. Passing a NULL backup_path will result in the
1112  * uncompacted database being deleted after compaction has finished.
1113  * Note that the database write lock will be held during the
1114  * compaction process to protect data integrity.
1115  */
1116 notmuch_status_t
1117 notmuch_database_compact (const char *path,
1118                           const char *backup_path,
1119                           notmuch_compact_status_cb_t status_cb,
1120                           void *closure)
1121 {
1122     void *local;
1123     char *notmuch_path, *xapian_path, *compact_xapian_path;
1124     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1125     notmuch_database_t *notmuch = NULL;
1126     struct stat statbuf;
1127     bool keep_backup;
1128     char *message = NULL;
1129
1130     local = talloc_new (NULL);
1131     if (! local)
1132         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1133
1134     ret = notmuch_database_open_verbose (path,
1135                                          NOTMUCH_DATABASE_MODE_READ_WRITE,
1136                                          &notmuch,
1137                                          &message);
1138     if (ret) {
1139         if (status_cb) status_cb (message, closure);
1140         goto DONE;
1141     }
1142
1143     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1144         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1145         goto DONE;
1146     }
1147
1148     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1149         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1150         goto DONE;
1151     }
1152
1153     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1154         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1155         goto DONE;
1156     }
1157
1158     if (backup_path == NULL) {
1159         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1160             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1161             goto DONE;
1162         }
1163         keep_backup = false;
1164     }
1165     else {
1166         keep_backup = true;
1167     }
1168
1169     if (stat (backup_path, &statbuf) != -1) {
1170         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1171         ret = NOTMUCH_STATUS_FILE_ERROR;
1172         goto DONE;
1173     }
1174     if (errno != ENOENT) {
1175         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1176                  strerror (errno));
1177         ret = NOTMUCH_STATUS_FILE_ERROR;
1178         goto DONE;
1179     }
1180
1181     /* Unconditionally attempt to remove old work-in-progress database (if
1182      * any). This is "protected" by database lock. If this fails due to write
1183      * errors (etc), the following code will fail and provide error message.
1184      */
1185     (void) rmtree (compact_xapian_path);
1186
1187     try {
1188         NotmuchCompactor compactor (status_cb, closure);
1189
1190         compactor.set_renumber (false);
1191         compactor.add_source (xapian_path);
1192         compactor.set_destdir (compact_xapian_path);
1193         compactor.compact ();
1194     } catch (const Xapian::Error &error) {
1195         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1196         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1197         goto DONE;
1198     }
1199
1200     if (rename (xapian_path, backup_path)) {
1201         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1202                  xapian_path, backup_path, strerror (errno));
1203         ret = NOTMUCH_STATUS_FILE_ERROR;
1204         goto DONE;
1205     }
1206
1207     if (rename (compact_xapian_path, xapian_path)) {
1208         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1209                  compact_xapian_path, xapian_path, strerror (errno));
1210         ret = NOTMUCH_STATUS_FILE_ERROR;
1211         goto DONE;
1212     }
1213
1214     if (! keep_backup) {
1215         if (rmtree (backup_path)) {
1216             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1217                      backup_path, strerror (errno));
1218             ret = NOTMUCH_STATUS_FILE_ERROR;
1219             goto DONE;
1220         }
1221     }
1222
1223   DONE:
1224     if (notmuch) {
1225         notmuch_status_t ret2;
1226
1227         const char *str = notmuch_database_status_string (notmuch);
1228         if (status_cb && str)
1229             status_cb (str, closure);
1230
1231         ret2 = notmuch_database_destroy (notmuch);
1232
1233         /* don't clobber previous error status */
1234         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1235             ret = ret2;
1236     }
1237
1238     talloc_free (local);
1239
1240     return ret;
1241 }
1242
1243 notmuch_status_t
1244 notmuch_database_destroy (notmuch_database_t *notmuch)
1245 {
1246     notmuch_status_t status;
1247
1248     status = notmuch_database_close (notmuch);
1249     talloc_free (notmuch);
1250
1251     return status;
1252 }
1253
1254 const char *
1255 notmuch_database_get_path (notmuch_database_t *notmuch)
1256 {
1257     return notmuch->path;
1258 }
1259
1260 unsigned int
1261 notmuch_database_get_version (notmuch_database_t *notmuch)
1262 {
1263     unsigned int version;
1264     string version_string;
1265     const char *str;
1266     char *end;
1267
1268     version_string = notmuch->xapian_db->get_metadata ("version");
1269     if (version_string.empty ())
1270         return 0;
1271
1272     str = version_string.c_str ();
1273     if (str == NULL || *str == '\0')
1274         return 0;
1275
1276     version = strtoul (str, &end, 10);
1277     if (*end != '\0')
1278         INTERNAL_ERROR ("Malformed database version: %s", str);
1279
1280     return version;
1281 }
1282
1283 notmuch_bool_t
1284 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1285 {
1286     return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1287         ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1288          (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1289 }
1290
1291 static volatile sig_atomic_t do_progress_notify = 0;
1292
1293 static void
1294 handle_sigalrm (unused (int signal))
1295 {
1296     do_progress_notify = 1;
1297 }
1298
1299 /* Upgrade the current database.
1300  *
1301  * After opening a database in read-write mode, the client should
1302  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1303  * if so, upgrade with this function before making any modifications.
1304  *
1305  * The optional progress_notify callback can be used by the caller to
1306  * provide progress indication to the user. If non-NULL it will be
1307  * called periodically with 'count' as the number of messages upgraded
1308  * so far and 'total' the overall number of messages that will be
1309  * converted.
1310  */
1311 notmuch_status_t
1312 notmuch_database_upgrade (notmuch_database_t *notmuch,
1313                           void (*progress_notify) (void *closure,
1314                                                    double progress),
1315                           void *closure)
1316 {
1317     void *local = talloc_new (NULL);
1318     Xapian::TermIterator t, t_end;
1319     Xapian::WritableDatabase *db;
1320     struct sigaction action;
1321     struct itimerval timerval;
1322     bool timer_is_active = false;
1323     enum _notmuch_features target_features, new_features;
1324     notmuch_status_t status;
1325     notmuch_private_status_t private_status;
1326     notmuch_query_t *query = NULL;
1327     unsigned int count = 0, total = 0;
1328
1329     status = _notmuch_database_ensure_writable (notmuch);
1330     if (status)
1331         return status;
1332
1333     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1334
1335     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1336     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1337
1338     if (! notmuch_database_needs_upgrade (notmuch))
1339         return NOTMUCH_STATUS_SUCCESS;
1340
1341     if (progress_notify) {
1342         /* Set up our handler for SIGALRM */
1343         memset (&action, 0, sizeof (struct sigaction));
1344         action.sa_handler = handle_sigalrm;
1345         sigemptyset (&action.sa_mask);
1346         action.sa_flags = SA_RESTART;
1347         sigaction (SIGALRM, &action, NULL);
1348
1349         /* Then start a timer to send SIGALRM once per second. */
1350         timerval.it_interval.tv_sec = 1;
1351         timerval.it_interval.tv_usec = 0;
1352         timerval.it_value.tv_sec = 1;
1353         timerval.it_value.tv_usec = 0;
1354         setitimer (ITIMER_REAL, &timerval, NULL);
1355
1356         timer_is_active = true;
1357     }
1358
1359     /* Figure out how much total work we need to do. */
1360     if (new_features &
1361         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1362          NOTMUCH_FEATURE_LAST_MOD)) {
1363         query = notmuch_query_create (notmuch, "");
1364         unsigned msg_count;
1365
1366         status = notmuch_query_count_messages (query, &msg_count);
1367         if (status)
1368             goto DONE;
1369
1370         total += msg_count;
1371         notmuch_query_destroy (query);
1372         query = NULL;
1373     }
1374     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1375         t_end = db->allterms_end ("XTIMESTAMP");
1376         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1377             ++total;
1378     }
1379     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1380         /* The ghost message upgrade converts all thread_id_*
1381          * metadata values into ghost message documents. */
1382         t_end = db->metadata_keys_end ("thread_id_");
1383         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1384             ++total;
1385     }
1386
1387     /* Perform the upgrade in a transaction. */
1388     db->begin_transaction (true);
1389
1390     /* Set the target features so we write out changes in the desired
1391      * format. */
1392     notmuch->features = target_features;
1393
1394     /* Perform per-message upgrades. */
1395     if (new_features &
1396         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1397          NOTMUCH_FEATURE_LAST_MOD)) {
1398         notmuch_messages_t *messages;
1399         notmuch_message_t *message;
1400         char *filename;
1401
1402         query = notmuch_query_create (notmuch, "");
1403
1404         status = notmuch_query_search_messages (query, &messages);
1405         if (status)
1406             goto DONE;
1407         for (;
1408              notmuch_messages_valid (messages);
1409              notmuch_messages_move_to_next (messages))
1410         {
1411             if (do_progress_notify) {
1412                 progress_notify (closure, (double) count / total);
1413                 do_progress_notify = 0;
1414             }
1415
1416             message = notmuch_messages_get (messages);
1417
1418             /* Before version 1, each message document had its
1419              * filename in the data field. Copy that into the new
1420              * format by calling notmuch_message_add_filename.
1421              */
1422             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1423                 filename = _notmuch_message_talloc_copy_data (message);
1424                 if (filename && *filename != '\0') {
1425                     _notmuch_message_add_filename (message, filename);
1426                     _notmuch_message_clear_data (message);
1427                 }
1428                 talloc_free (filename);
1429             }
1430
1431             /* Prior to version 2, the "folder:" prefix was
1432              * probabilistic and stemmed. Change it to the current
1433              * boolean prefix. Add "path:" prefixes while at it.
1434              */
1435             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1436                 _notmuch_message_upgrade_folder (message);
1437
1438             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1439              * track modification revisions.  Give all messages the
1440              * next available revision; since we just started tracking
1441              * revisions for this database, that will be 1.
1442              */
1443             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1444                 _notmuch_message_upgrade_last_mod (message);
1445
1446             _notmuch_message_sync (message);
1447
1448             notmuch_message_destroy (message);
1449
1450             count++;
1451         }
1452
1453         notmuch_query_destroy (query);
1454         query = NULL;
1455     }
1456
1457     /* Perform per-directory upgrades. */
1458
1459     /* Before version 1 we stored directory timestamps in
1460      * XTIMESTAMP documents instead of the current XDIRECTORY
1461      * documents. So copy those as well. */
1462     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1463         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1464
1465         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1466              t != t_end;
1467              t++)
1468         {
1469             Xapian::PostingIterator p, p_end;
1470             std::string term = *t;
1471
1472             p_end = notmuch->xapian_db->postlist_end (term);
1473
1474             for (p = notmuch->xapian_db->postlist_begin (term);
1475                  p != p_end;
1476                  p++)
1477             {
1478                 Xapian::Document document;
1479                 time_t mtime;
1480                 notmuch_directory_t *directory;
1481
1482                 if (do_progress_notify) {
1483                     progress_notify (closure, (double) count / total);
1484                     do_progress_notify = 0;
1485                 }
1486
1487                 document = find_document_for_doc_id (notmuch, *p);
1488                 mtime = Xapian::sortable_unserialise (
1489                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1490
1491                 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1492                                                        NOTMUCH_FIND_CREATE, &status);
1493                 notmuch_directory_set_mtime (directory, mtime);
1494                 notmuch_directory_destroy (directory);
1495
1496                 db->delete_document (*p);
1497             }
1498
1499             ++count;
1500         }
1501     }
1502
1503     /* Perform metadata upgrades. */
1504
1505     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1506      * messages were stored as database metadata. Change these to
1507      * ghost messages.
1508      */
1509     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1510         notmuch_message_t *message;
1511         std::string message_id, thread_id;
1512
1513         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1514         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1515              t != t_end; ++t) {
1516             if (do_progress_notify) {
1517                 progress_notify (closure, (double) count / total);
1518                 do_progress_notify = 0;
1519             }
1520
1521             message_id = (*t).substr (
1522                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1523             thread_id = db->get_metadata (*t);
1524
1525             /* Create ghost message */
1526             message = _notmuch_message_create_for_message_id (
1527                 notmuch, message_id.c_str (), &private_status);
1528             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1529                 /* Document already exists; ignore the stored thread ID */
1530             } else if (private_status ==
1531                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1532                 private_status = _notmuch_message_initialize_ghost (
1533                     message, thread_id.c_str ());
1534                 if (! private_status)
1535                     _notmuch_message_sync (message);
1536             }
1537
1538             if (private_status) {
1539                 _notmuch_database_log (notmuch,
1540                          "Upgrade failed while creating ghost messages.\n");
1541                 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1542                 goto DONE;
1543             }
1544
1545             /* Clear saved metadata thread ID */
1546             db->set_metadata (*t, "");
1547
1548             ++count;
1549         }
1550     }
1551
1552     status = NOTMUCH_STATUS_SUCCESS;
1553     db->set_metadata ("features", _print_features (local, notmuch->features));
1554     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1555
1556  DONE:
1557     if (status == NOTMUCH_STATUS_SUCCESS)
1558         db->commit_transaction ();
1559     else
1560         db->cancel_transaction ();
1561
1562     if (timer_is_active) {
1563         /* Now stop the timer. */
1564         timerval.it_interval.tv_sec = 0;
1565         timerval.it_interval.tv_usec = 0;
1566         timerval.it_value.tv_sec = 0;
1567         timerval.it_value.tv_usec = 0;
1568         setitimer (ITIMER_REAL, &timerval, NULL);
1569
1570         /* And disable the signal handler. */
1571         action.sa_handler = SIG_IGN;
1572         sigaction (SIGALRM, &action, NULL);
1573     }
1574
1575     if (query)
1576         notmuch_query_destroy (query);
1577
1578     talloc_free (local);
1579     return status;
1580 }
1581
1582 notmuch_status_t
1583 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1584 {
1585     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1586         notmuch->atomic_nesting > 0)
1587         goto DONE;
1588
1589     if (notmuch_database_needs_upgrade (notmuch))
1590         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1591
1592     try {
1593         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1594     } catch (const Xapian::Error &error) {
1595         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1596                  error.get_msg().c_str());
1597         notmuch->exception_reported = true;
1598         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1599     }
1600
1601 DONE:
1602     notmuch->atomic_nesting++;
1603     return NOTMUCH_STATUS_SUCCESS;
1604 }
1605
1606 notmuch_status_t
1607 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1608 {
1609     Xapian::WritableDatabase *db;
1610
1611     if (notmuch->atomic_nesting == 0)
1612         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1613
1614     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1615         notmuch->atomic_nesting > 1)
1616         goto DONE;
1617
1618     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1619     try {
1620         db->commit_transaction ();
1621
1622         /* This is a hack for testing.  Xapian never flushes on a
1623          * non-flushed commit, even if the flush threshold is 1.
1624          * However, we rely on flushing to test atomicity. */
1625         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1626         if (thresh && atoi (thresh) == 1)
1627             db->commit ();
1628     } catch (const Xapian::Error &error) {
1629         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1630                  error.get_msg().c_str());
1631         notmuch->exception_reported = true;
1632         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1633     }
1634
1635     if (notmuch->atomic_dirty) {
1636         ++notmuch->revision;
1637         notmuch->atomic_dirty = false;
1638     }
1639
1640 DONE:
1641     notmuch->atomic_nesting--;
1642     return NOTMUCH_STATUS_SUCCESS;
1643 }
1644
1645 unsigned long
1646 notmuch_database_get_revision (notmuch_database_t *notmuch,
1647                                 const char **uuid)
1648 {
1649     if (uuid)
1650         *uuid = notmuch->uuid;
1651     return notmuch->revision;
1652 }
1653
1654 /* We allow the user to use arbitrarily long paths for directories. But
1655  * we have a term-length limit. So if we exceed that, we'll use the
1656  * SHA-1 of the path for the database term.
1657  *
1658  * Note: This function may return the original value of 'path'. If it
1659  * does not, then the caller is responsible to free() the returned
1660  * value.
1661  */
1662 const char *
1663 _notmuch_database_get_directory_db_path (const char *path)
1664 {
1665     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1666
1667     if (term_len > NOTMUCH_TERM_MAX)
1668         return _notmuch_sha1_of_string (path);
1669     else
1670         return path;
1671 }
1672
1673 /* Given a path, split it into two parts: the directory part is all
1674  * components except for the last, and the basename is that last
1675  * component. Getting the return-value for either part is optional
1676  * (the caller can pass NULL).
1677  *
1678  * The original 'path' can represent either a regular file or a
1679  * directory---the splitting will be carried out in the same way in
1680  * either case. Trailing slashes on 'path' will be ignored, and any
1681  * cases of multiple '/' characters appearing in series will be
1682  * treated as a single '/'.
1683  *
1684  * Allocation (if any) will have 'ctx' as the talloc owner. But
1685  * pointers will be returned within the original path string whenever
1686  * possible.
1687  *
1688  * Note: If 'path' is non-empty and contains no non-trailing slash,
1689  * (that is, consists of a filename with no parent directory), then
1690  * the directory returned will be an empty string. However, if 'path'
1691  * is an empty string, then both directory and basename will be
1692  * returned as NULL.
1693  */
1694 notmuch_status_t
1695 _notmuch_database_split_path (void *ctx,
1696                               const char *path,
1697                               const char **directory,
1698                               const char **basename)
1699 {
1700     const char *slash;
1701
1702     if (path == NULL || *path == '\0') {
1703         if (directory)
1704             *directory = NULL;
1705         if (basename)
1706             *basename = NULL;
1707         return NOTMUCH_STATUS_SUCCESS;
1708     }
1709
1710     /* Find the last slash (not counting a trailing slash), if any. */
1711
1712     slash = path + strlen (path) - 1;
1713
1714     /* First, skip trailing slashes. */
1715     while (slash != path && *slash == '/')
1716         --slash;
1717
1718     /* Then, find a slash. */
1719     while (slash != path && *slash != '/') {
1720         if (basename)
1721             *basename = slash;
1722
1723         --slash;
1724     }
1725
1726     /* Finally, skip multiple slashes. */
1727     while (slash != path && *(slash - 1) == '/')
1728         --slash;
1729
1730     if (slash == path) {
1731         if (directory)
1732             *directory = talloc_strdup (ctx, "");
1733         if (basename)
1734             *basename = path;
1735     } else {
1736         if (directory)
1737             *directory = talloc_strndup (ctx, path, slash - path);
1738     }
1739
1740     return NOTMUCH_STATUS_SUCCESS;
1741 }
1742
1743 /* Find the document ID of the specified directory.
1744  *
1745  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1746  * created if one does not exist for 'path'.  Otherwise, if the
1747  * directory document does not exist, this sets *directory_id to
1748  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1749  */
1750 notmuch_status_t
1751 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1752                                      const char *path,
1753                                      notmuch_find_flags_t flags,
1754                                      unsigned int *directory_id)
1755 {
1756     notmuch_directory_t *directory;
1757     notmuch_status_t status;
1758
1759     if (path == NULL) {
1760         *directory_id = 0;
1761         return NOTMUCH_STATUS_SUCCESS;
1762     }
1763
1764     directory = _notmuch_directory_create (notmuch, path, flags, &status);
1765     if (status || !directory) {
1766         *directory_id = -1;
1767         return status;
1768     }
1769
1770     *directory_id = _notmuch_directory_get_document_id (directory);
1771
1772     notmuch_directory_destroy (directory);
1773
1774     return NOTMUCH_STATUS_SUCCESS;
1775 }
1776
1777 const char *
1778 _notmuch_database_get_directory_path (void *ctx,
1779                                       notmuch_database_t *notmuch,
1780                                       unsigned int doc_id)
1781 {
1782     Xapian::Document document;
1783
1784     document = find_document_for_doc_id (notmuch, doc_id);
1785
1786     return talloc_strdup (ctx, document.get_data ().c_str ());
1787 }
1788
1789 /* Given a legal 'filename' for the database, (either relative to
1790  * database path or absolute with initial components identical to
1791  * database path), return a new string (with 'ctx' as the talloc
1792  * owner) suitable for use as a direntry term value.
1793  *
1794  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1795  * will be created in the database as needed.  Otherwise, if the
1796  * necessary directory documents do not exist, this sets
1797  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1798  */
1799 notmuch_status_t
1800 _notmuch_database_filename_to_direntry (void *ctx,
1801                                         notmuch_database_t *notmuch,
1802                                         const char *filename,
1803                                         notmuch_find_flags_t flags,
1804                                         char **direntry)
1805 {
1806     const char *relative, *directory, *basename;
1807     Xapian::docid directory_id;
1808     notmuch_status_t status;
1809
1810     relative = _notmuch_database_relative_path (notmuch, filename);
1811
1812     status = _notmuch_database_split_path (ctx, relative,
1813                                            &directory, &basename);
1814     if (status)
1815         return status;
1816
1817     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1818                                                   &directory_id);
1819     if (status || directory_id == (unsigned int)-1) {
1820         *direntry = NULL;
1821         return status;
1822     }
1823
1824     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1825
1826     return NOTMUCH_STATUS_SUCCESS;
1827 }
1828
1829 /* Given a legal 'path' for the database, return the relative path.
1830  *
1831  * The return value will be a pointer to the original path contents,
1832  * and will be either the original string (if 'path' was relative) or
1833  * a portion of the string (if path was absolute and begins with the
1834  * database path).
1835  */
1836 const char *
1837 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1838                                  const char *path)
1839 {
1840     const char *db_path, *relative;
1841     unsigned int db_path_len;
1842
1843     db_path = notmuch_database_get_path (notmuch);
1844     db_path_len = strlen (db_path);
1845
1846     relative = path;
1847
1848     if (*relative == '/') {
1849         while (*relative == '/' && *(relative+1) == '/')
1850             relative++;
1851
1852         if (strncmp (relative, db_path, db_path_len) == 0)
1853         {
1854             relative += db_path_len;
1855             while (*relative == '/')
1856                 relative++;
1857         }
1858     }
1859
1860     return relative;
1861 }
1862
1863 notmuch_status_t
1864 notmuch_database_get_directory (notmuch_database_t *notmuch,
1865                                 const char *path,
1866                                 notmuch_directory_t **directory)
1867 {
1868     notmuch_status_t status;
1869
1870     if (directory == NULL)
1871         return NOTMUCH_STATUS_NULL_POINTER;
1872     *directory = NULL;
1873
1874     try {
1875         *directory = _notmuch_directory_create (notmuch, path,
1876                                                 NOTMUCH_FIND_LOOKUP, &status);
1877     } catch (const Xapian::Error &error) {
1878         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1879                  error.get_msg().c_str());
1880         notmuch->exception_reported = true;
1881         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1882     }
1883     return status;
1884 }
1885
1886 /* Allocate a document ID that satisfies the following criteria:
1887  *
1888  * 1. The ID does not exist for any document in the Xapian database
1889  *
1890  * 2. The ID was not previously returned from this function
1891  *
1892  * 3. The ID is the smallest integer satisfying (1) and (2)
1893  *
1894  * This function will trigger an internal error if these constraints
1895  * cannot all be satisfied, (that is, the pool of available document
1896  * IDs has been exhausted).
1897  */
1898 unsigned int
1899 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1900 {
1901     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1902
1903     notmuch->last_doc_id++;
1904
1905     if (notmuch->last_doc_id == 0)
1906         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1907
1908     return notmuch->last_doc_id;
1909 }
1910
1911 notmuch_status_t
1912 notmuch_database_remove_message (notmuch_database_t *notmuch,
1913                                  const char *filename)
1914 {
1915     notmuch_status_t status;
1916     notmuch_message_t *message;
1917
1918     status = notmuch_database_find_message_by_filename (notmuch, filename,
1919                                                         &message);
1920
1921     if (status == NOTMUCH_STATUS_SUCCESS && message) {
1922             status = _notmuch_message_remove_filename (message, filename);
1923             if (status == NOTMUCH_STATUS_SUCCESS)
1924                 _notmuch_message_delete (message);
1925             else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1926                 _notmuch_message_sync (message);
1927
1928             notmuch_message_destroy (message);
1929     }
1930
1931     return status;
1932 }
1933
1934 notmuch_status_t
1935 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1936                                            const char *filename,
1937                                            notmuch_message_t **message_ret)
1938 {
1939     void *local;
1940     const char *prefix = _find_prefix ("file-direntry");
1941     char *direntry, *term;
1942     Xapian::PostingIterator i, end;
1943     notmuch_status_t status;
1944
1945     if (message_ret == NULL)
1946         return NOTMUCH_STATUS_NULL_POINTER;
1947
1948     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1949         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1950
1951     /* return NULL on any failure */
1952     *message_ret = NULL;
1953
1954     local = talloc_new (notmuch);
1955
1956     try {
1957         status = _notmuch_database_filename_to_direntry (
1958             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1959         if (status || !direntry)
1960             goto DONE;
1961
1962         term = talloc_asprintf (local, "%s%s", prefix, direntry);
1963
1964         find_doc_ids_for_term (notmuch, term, &i, &end);
1965
1966         if (i != end) {
1967             notmuch_private_status_t private_status;
1968
1969             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1970                                                     &private_status);
1971             if (*message_ret == NULL)
1972                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1973         }
1974     } catch (const Xapian::Error &error) {
1975         _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1976                  error.get_msg().c_str());
1977         notmuch->exception_reported = true;
1978         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1979     }
1980
1981   DONE:
1982     talloc_free (local);
1983
1984     if (status && *message_ret) {
1985         notmuch_message_destroy (*message_ret);
1986         *message_ret = NULL;
1987     }
1988     return status;
1989 }
1990
1991 notmuch_string_list_t *
1992 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1993                                          Xapian::TermIterator &end,
1994                                          const char *prefix)
1995 {
1996     int prefix_len = strlen (prefix);
1997     notmuch_string_list_t *list;
1998
1999     list = _notmuch_string_list_create (ctx);
2000     if (unlikely (list == NULL))
2001         return NULL;
2002
2003     for (i.skip_to (prefix); i != end; i++) {
2004         /* Terminate loop at first term without desired prefix. */
2005         if (strncmp ((*i).c_str (), prefix, prefix_len))
2006             break;
2007
2008         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2009     }
2010
2011     return list;
2012 }
2013
2014 notmuch_tags_t *
2015 notmuch_database_get_all_tags (notmuch_database_t *db)
2016 {
2017     Xapian::TermIterator i, end;
2018     notmuch_string_list_t *tags;
2019
2020     try {
2021         i = db->xapian_db->allterms_begin();
2022         end = db->xapian_db->allterms_end();
2023         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2024                                                         _find_prefix ("tag"));
2025         _notmuch_string_list_sort (tags);
2026         return _notmuch_tags_create (db, tags);
2027     } catch (const Xapian::Error &error) {
2028         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2029                  error.get_msg().c_str());
2030         db->exception_reported = true;
2031         return NULL;
2032     }
2033 }
2034
2035 const char *
2036 notmuch_database_status_string (const notmuch_database_t *notmuch)
2037 {
2038     return notmuch->status_string;
2039 }