]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
database: move striping of trailing '/' into helper function
[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     strip_trailing(notmuch->path, '/');
862
863     notmuch->mode = mode;
864     notmuch->atomic_nesting = 0;
865     notmuch->view = 1;
866     try {
867         string last_thread_id;
868         string last_mod;
869
870         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
871             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
872                                                                DB_ACTION);
873         } else {
874             notmuch->xapian_db = new Xapian::Database (xapian_path);
875         }
876
877         /* Check version.  As of database version 3, we represent
878          * changes in terms of features, so assume a version bump
879          * means a dramatically incompatible change. */
880         version = notmuch_database_get_version (notmuch);
881         if (version > NOTMUCH_DATABASE_VERSION) {
882             IGNORE_RESULT (asprintf (&message,
883                       "Error: Notmuch database at %s\n"
884                       "       has a newer database format version (%u) than supported by this\n"
885                       "       version of notmuch (%u).\n",
886                                      notmuch_path, version, NOTMUCH_DATABASE_VERSION));
887             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
888             notmuch_database_destroy (notmuch);
889             notmuch = NULL;
890             status = NOTMUCH_STATUS_FILE_ERROR;
891             goto DONE;
892         }
893
894         /* Check features. */
895         incompat_features = NULL;
896         notmuch->features = _parse_features (
897             local, notmuch->xapian_db->get_metadata ("features").c_str (),
898             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
899             &incompat_features);
900         if (incompat_features) {
901             IGNORE_RESULT (asprintf (&message,
902                 "Error: Notmuch database at %s\n"
903                 "       requires features (%s)\n"
904                 "       not supported by this version of notmuch.\n",
905                                      notmuch_path, incompat_features));
906             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
907             notmuch_database_destroy (notmuch);
908             notmuch = NULL;
909             status = NOTMUCH_STATUS_FILE_ERROR;
910             goto DONE;
911         }
912
913         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
914         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
915         if (last_thread_id.empty ()) {
916             notmuch->last_thread_id = 0;
917         } else {
918             const char *str;
919             char *end;
920
921             str = last_thread_id.c_str ();
922             notmuch->last_thread_id = strtoull (str, &end, 16);
923             if (*end != '\0')
924                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
925         }
926
927         /* Get current highest revision number. */
928         last_mod = notmuch->xapian_db->get_value_upper_bound (
929             NOTMUCH_VALUE_LAST_MOD);
930         if (last_mod.empty ())
931             notmuch->revision = 0;
932         else
933             notmuch->revision = Xapian::sortable_unserialise (last_mod);
934         notmuch->uuid = talloc_strdup (
935             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
936
937         notmuch->query_parser = new Xapian::QueryParser;
938         notmuch->term_gen = new Xapian::TermGenerator;
939         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
940         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
941         notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
942         notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
943
944         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
945         notmuch->query_parser->set_database (*notmuch->xapian_db);
946         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
947         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
948         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
949         notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
950         notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
951
952         for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
953             const prefix_t *prefix = &prefix_table[i];
954             if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
955                 _setup_query_field (prefix, notmuch);
956             }
957         }
958     } catch (const Xapian::Error &error) {
959         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
960                                  error.get_msg().c_str()));
961         notmuch_database_destroy (notmuch);
962         notmuch = NULL;
963         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
964     }
965
966   DONE:
967     talloc_free (local);
968
969     if (message) {
970         if (status_string)
971             *status_string = message;
972         else
973             free (message);
974     }
975
976     if (database)
977         *database = notmuch;
978     else
979         talloc_free (notmuch);
980     return status;
981 }
982
983 notmuch_status_t
984 notmuch_database_close (notmuch_database_t *notmuch)
985 {
986     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
987
988     /* Many Xapian objects (and thus notmuch objects) hold references to
989      * the database, so merely deleting the database may not suffice to
990      * close it.  Thus, we explicitly close it here. */
991     if (notmuch->xapian_db != NULL) {
992         try {
993             /* If there's an outstanding transaction, it's unclear if
994              * closing the Xapian database commits everything up to
995              * that transaction, or may discard committed (but
996              * unflushed) transactions.  To be certain, explicitly
997              * cancel any outstanding transaction before closing. */
998             if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
999                 notmuch->atomic_nesting)
1000                 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1001                     ->cancel_transaction ();
1002
1003             /* Close the database.  This implicitly flushes
1004              * outstanding changes. */
1005             notmuch->xapian_db->close();
1006         } catch (const Xapian::Error &error) {
1007             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1008             if (! notmuch->exception_reported) {
1009                 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1010                          error.get_msg().c_str());
1011             }
1012         }
1013     }
1014
1015     delete notmuch->term_gen;
1016     notmuch->term_gen = NULL;
1017     delete notmuch->query_parser;
1018     notmuch->query_parser = NULL;
1019     delete notmuch->xapian_db;
1020     notmuch->xapian_db = NULL;
1021     delete notmuch->value_range_processor;
1022     notmuch->value_range_processor = NULL;
1023     delete notmuch->date_range_processor;
1024     notmuch->date_range_processor = NULL;
1025     delete notmuch->last_mod_range_processor;
1026     notmuch->last_mod_range_processor = NULL;
1027
1028     return status;
1029 }
1030
1031 notmuch_status_t
1032 _notmuch_database_reopen (notmuch_database_t *notmuch)
1033 {
1034     if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1035         return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1036
1037     try {
1038         notmuch->xapian_db->reopen ();
1039     } catch (const Xapian::Error &error) {
1040         if (! notmuch->exception_reported) {
1041             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1042                                    error.get_msg ().c_str ());
1043             notmuch->exception_reported = TRUE;
1044         }
1045         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1046     }
1047
1048     notmuch->view++;
1049
1050     return NOTMUCH_STATUS_SUCCESS;
1051 }
1052
1053 static int
1054 unlink_cb (const char *path,
1055            unused (const struct stat *sb),
1056            unused (int type),
1057            unused (struct FTW *ftw))
1058 {
1059     return remove (path);
1060 }
1061
1062 static int
1063 rmtree (const char *path)
1064 {
1065     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1066 }
1067
1068 class NotmuchCompactor : public Xapian::Compactor
1069 {
1070     notmuch_compact_status_cb_t status_cb;
1071     void *status_closure;
1072
1073 public:
1074     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1075         status_cb (cb), status_closure (closure) { }
1076
1077     virtual void
1078     set_status (const std::string &table, const std::string &status)
1079     {
1080         char *msg;
1081
1082         if (status_cb == NULL)
1083             return;
1084
1085         if (status.length () == 0)
1086             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1087         else
1088             msg = talloc_asprintf (NULL, "     %s", status.c_str());
1089
1090         if (msg == NULL) {
1091             return;
1092         }
1093
1094         status_cb (msg, status_closure);
1095         talloc_free (msg);
1096     }
1097 };
1098
1099 /* Compacts the given database, optionally saving the original database
1100  * in backup_path. Additionally, a callback function can be provided to
1101  * give the user feedback on the progress of the (likely long-lived)
1102  * compaction process.
1103  *
1104  * The backup path must point to a directory on the same volume as the
1105  * original database. Passing a NULL backup_path will result in the
1106  * uncompacted database being deleted after compaction has finished.
1107  * Note that the database write lock will be held during the
1108  * compaction process to protect data integrity.
1109  */
1110 notmuch_status_t
1111 notmuch_database_compact (const char *path,
1112                           const char *backup_path,
1113                           notmuch_compact_status_cb_t status_cb,
1114                           void *closure)
1115 {
1116     void *local;
1117     char *notmuch_path, *xapian_path, *compact_xapian_path;
1118     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1119     notmuch_database_t *notmuch = NULL;
1120     struct stat statbuf;
1121     notmuch_bool_t keep_backup;
1122     char *message = NULL;
1123
1124     local = talloc_new (NULL);
1125     if (! local)
1126         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1127
1128     ret = notmuch_database_open_verbose (path,
1129                                          NOTMUCH_DATABASE_MODE_READ_WRITE,
1130                                          &notmuch,
1131                                          &message);
1132     if (ret) {
1133         if (status_cb) status_cb (message, closure);
1134         goto DONE;
1135     }
1136
1137     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1138         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1139         goto DONE;
1140     }
1141
1142     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1143         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1144         goto DONE;
1145     }
1146
1147     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1148         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1149         goto DONE;
1150     }
1151
1152     if (backup_path == NULL) {
1153         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1154             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1155             goto DONE;
1156         }
1157         keep_backup = FALSE;
1158     }
1159     else {
1160         keep_backup = TRUE;
1161     }
1162
1163     if (stat (backup_path, &statbuf) != -1) {
1164         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1165         ret = NOTMUCH_STATUS_FILE_ERROR;
1166         goto DONE;
1167     }
1168     if (errno != ENOENT) {
1169         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1170                  strerror (errno));
1171         ret = NOTMUCH_STATUS_FILE_ERROR;
1172         goto DONE;
1173     }
1174
1175     /* Unconditionally attempt to remove old work-in-progress database (if
1176      * any). This is "protected" by database lock. If this fails due to write
1177      * errors (etc), the following code will fail and provide error message.
1178      */
1179     (void) rmtree (compact_xapian_path);
1180
1181     try {
1182         NotmuchCompactor compactor (status_cb, closure);
1183
1184         compactor.set_renumber (false);
1185         compactor.add_source (xapian_path);
1186         compactor.set_destdir (compact_xapian_path);
1187         compactor.compact ();
1188     } catch (const Xapian::Error &error) {
1189         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1190         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1191         goto DONE;
1192     }
1193
1194     if (rename (xapian_path, backup_path)) {
1195         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1196                  xapian_path, backup_path, strerror (errno));
1197         ret = NOTMUCH_STATUS_FILE_ERROR;
1198         goto DONE;
1199     }
1200
1201     if (rename (compact_xapian_path, xapian_path)) {
1202         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1203                  compact_xapian_path, xapian_path, strerror (errno));
1204         ret = NOTMUCH_STATUS_FILE_ERROR;
1205         goto DONE;
1206     }
1207
1208     if (! keep_backup) {
1209         if (rmtree (backup_path)) {
1210             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1211                      backup_path, strerror (errno));
1212             ret = NOTMUCH_STATUS_FILE_ERROR;
1213             goto DONE;
1214         }
1215     }
1216
1217   DONE:
1218     if (notmuch) {
1219         notmuch_status_t ret2;
1220
1221         const char *str = notmuch_database_status_string (notmuch);
1222         if (status_cb && str)
1223             status_cb (str, closure);
1224
1225         ret2 = notmuch_database_destroy (notmuch);
1226
1227         /* don't clobber previous error status */
1228         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1229             ret = ret2;
1230     }
1231
1232     talloc_free (local);
1233
1234     return ret;
1235 }
1236
1237 notmuch_status_t
1238 notmuch_database_destroy (notmuch_database_t *notmuch)
1239 {
1240     notmuch_status_t status;
1241
1242     status = notmuch_database_close (notmuch);
1243     talloc_free (notmuch);
1244
1245     return status;
1246 }
1247
1248 const char *
1249 notmuch_database_get_path (notmuch_database_t *notmuch)
1250 {
1251     return notmuch->path;
1252 }
1253
1254 unsigned int
1255 notmuch_database_get_version (notmuch_database_t *notmuch)
1256 {
1257     unsigned int version;
1258     string version_string;
1259     const char *str;
1260     char *end;
1261
1262     version_string = notmuch->xapian_db->get_metadata ("version");
1263     if (version_string.empty ())
1264         return 0;
1265
1266     str = version_string.c_str ();
1267     if (str == NULL || *str == '\0')
1268         return 0;
1269
1270     version = strtoul (str, &end, 10);
1271     if (*end != '\0')
1272         INTERNAL_ERROR ("Malformed database version: %s", str);
1273
1274     return version;
1275 }
1276
1277 notmuch_bool_t
1278 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1279 {
1280     return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1281         ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1282          (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1283 }
1284
1285 static volatile sig_atomic_t do_progress_notify = 0;
1286
1287 static void
1288 handle_sigalrm (unused (int signal))
1289 {
1290     do_progress_notify = 1;
1291 }
1292
1293 /* Upgrade the current database.
1294  *
1295  * After opening a database in read-write mode, the client should
1296  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1297  * if so, upgrade with this function before making any modifications.
1298  *
1299  * The optional progress_notify callback can be used by the caller to
1300  * provide progress indication to the user. If non-NULL it will be
1301  * called periodically with 'count' as the number of messages upgraded
1302  * so far and 'total' the overall number of messages that will be
1303  * converted.
1304  */
1305 notmuch_status_t
1306 notmuch_database_upgrade (notmuch_database_t *notmuch,
1307                           void (*progress_notify) (void *closure,
1308                                                    double progress),
1309                           void *closure)
1310 {
1311     void *local = talloc_new (NULL);
1312     Xapian::TermIterator t, t_end;
1313     Xapian::WritableDatabase *db;
1314     struct sigaction action;
1315     struct itimerval timerval;
1316     notmuch_bool_t timer_is_active = FALSE;
1317     enum _notmuch_features target_features, new_features;
1318     notmuch_status_t status;
1319     notmuch_private_status_t private_status;
1320     notmuch_query_t *query = NULL;
1321     unsigned int count = 0, total = 0;
1322
1323     status = _notmuch_database_ensure_writable (notmuch);
1324     if (status)
1325         return status;
1326
1327     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1328
1329     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1330     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1331
1332     if (! notmuch_database_needs_upgrade (notmuch))
1333         return NOTMUCH_STATUS_SUCCESS;
1334
1335     if (progress_notify) {
1336         /* Set up our handler for SIGALRM */
1337         memset (&action, 0, sizeof (struct sigaction));
1338         action.sa_handler = handle_sigalrm;
1339         sigemptyset (&action.sa_mask);
1340         action.sa_flags = SA_RESTART;
1341         sigaction (SIGALRM, &action, NULL);
1342
1343         /* Then start a timer to send SIGALRM once per second. */
1344         timerval.it_interval.tv_sec = 1;
1345         timerval.it_interval.tv_usec = 0;
1346         timerval.it_value.tv_sec = 1;
1347         timerval.it_value.tv_usec = 0;
1348         setitimer (ITIMER_REAL, &timerval, NULL);
1349
1350         timer_is_active = TRUE;
1351     }
1352
1353     /* Figure out how much total work we need to do. */
1354     if (new_features &
1355         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1356          NOTMUCH_FEATURE_LAST_MOD)) {
1357         query = notmuch_query_create (notmuch, "");
1358         unsigned msg_count;
1359
1360         status = notmuch_query_count_messages (query, &msg_count);
1361         if (status)
1362             goto DONE;
1363
1364         total += msg_count;
1365         notmuch_query_destroy (query);
1366         query = NULL;
1367     }
1368     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1369         t_end = db->allterms_end ("XTIMESTAMP");
1370         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1371             ++total;
1372     }
1373     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1374         /* The ghost message upgrade converts all thread_id_*
1375          * metadata values into ghost message documents. */
1376         t_end = db->metadata_keys_end ("thread_id_");
1377         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1378             ++total;
1379     }
1380
1381     /* Perform the upgrade in a transaction. */
1382     db->begin_transaction (true);
1383
1384     /* Set the target features so we write out changes in the desired
1385      * format. */
1386     notmuch->features = target_features;
1387
1388     /* Perform per-message upgrades. */
1389     if (new_features &
1390         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1391          NOTMUCH_FEATURE_LAST_MOD)) {
1392         notmuch_messages_t *messages;
1393         notmuch_message_t *message;
1394         char *filename;
1395
1396         query = notmuch_query_create (notmuch, "");
1397
1398         status = notmuch_query_search_messages (query, &messages);
1399         if (status)
1400             goto DONE;
1401         for (;
1402              notmuch_messages_valid (messages);
1403              notmuch_messages_move_to_next (messages))
1404         {
1405             if (do_progress_notify) {
1406                 progress_notify (closure, (double) count / total);
1407                 do_progress_notify = 0;
1408             }
1409
1410             message = notmuch_messages_get (messages);
1411
1412             /* Before version 1, each message document had its
1413              * filename in the data field. Copy that into the new
1414              * format by calling notmuch_message_add_filename.
1415              */
1416             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1417                 filename = _notmuch_message_talloc_copy_data (message);
1418                 if (filename && *filename != '\0') {
1419                     _notmuch_message_add_filename (message, filename);
1420                     _notmuch_message_clear_data (message);
1421                 }
1422                 talloc_free (filename);
1423             }
1424
1425             /* Prior to version 2, the "folder:" prefix was
1426              * probabilistic and stemmed. Change it to the current
1427              * boolean prefix. Add "path:" prefixes while at it.
1428              */
1429             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1430                 _notmuch_message_upgrade_folder (message);
1431
1432             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1433              * track modification revisions.  Give all messages the
1434              * next available revision; since we just started tracking
1435              * revisions for this database, that will be 1.
1436              */
1437             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1438                 _notmuch_message_upgrade_last_mod (message);
1439
1440             _notmuch_message_sync (message);
1441
1442             notmuch_message_destroy (message);
1443
1444             count++;
1445         }
1446
1447         notmuch_query_destroy (query);
1448         query = NULL;
1449     }
1450
1451     /* Perform per-directory upgrades. */
1452
1453     /* Before version 1 we stored directory timestamps in
1454      * XTIMESTAMP documents instead of the current XDIRECTORY
1455      * documents. So copy those as well. */
1456     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1457         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1458
1459         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1460              t != t_end;
1461              t++)
1462         {
1463             Xapian::PostingIterator p, p_end;
1464             std::string term = *t;
1465
1466             p_end = notmuch->xapian_db->postlist_end (term);
1467
1468             for (p = notmuch->xapian_db->postlist_begin (term);
1469                  p != p_end;
1470                  p++)
1471             {
1472                 Xapian::Document document;
1473                 time_t mtime;
1474                 notmuch_directory_t *directory;
1475
1476                 if (do_progress_notify) {
1477                     progress_notify (closure, (double) count / total);
1478                     do_progress_notify = 0;
1479                 }
1480
1481                 document = find_document_for_doc_id (notmuch, *p);
1482                 mtime = Xapian::sortable_unserialise (
1483                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1484
1485                 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1486                                                        NOTMUCH_FIND_CREATE, &status);
1487                 notmuch_directory_set_mtime (directory, mtime);
1488                 notmuch_directory_destroy (directory);
1489
1490                 db->delete_document (*p);
1491             }
1492
1493             ++count;
1494         }
1495     }
1496
1497     /* Perform metadata upgrades. */
1498
1499     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1500      * messages were stored as database metadata. Change these to
1501      * ghost messages.
1502      */
1503     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1504         notmuch_message_t *message;
1505         std::string message_id, thread_id;
1506
1507         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1508         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1509              t != t_end; ++t) {
1510             if (do_progress_notify) {
1511                 progress_notify (closure, (double) count / total);
1512                 do_progress_notify = 0;
1513             }
1514
1515             message_id = (*t).substr (
1516                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1517             thread_id = db->get_metadata (*t);
1518
1519             /* Create ghost message */
1520             message = _notmuch_message_create_for_message_id (
1521                 notmuch, message_id.c_str (), &private_status);
1522             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1523                 /* Document already exists; ignore the stored thread ID */
1524             } else if (private_status ==
1525                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1526                 private_status = _notmuch_message_initialize_ghost (
1527                     message, thread_id.c_str ());
1528                 if (! private_status)
1529                     _notmuch_message_sync (message);
1530             }
1531
1532             if (private_status) {
1533                 _notmuch_database_log (notmuch,
1534                          "Upgrade failed while creating ghost messages.\n");
1535                 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1536                 goto DONE;
1537             }
1538
1539             /* Clear saved metadata thread ID */
1540             db->set_metadata (*t, "");
1541
1542             ++count;
1543         }
1544     }
1545
1546     status = NOTMUCH_STATUS_SUCCESS;
1547     db->set_metadata ("features", _print_features (local, notmuch->features));
1548     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1549
1550  DONE:
1551     if (status == NOTMUCH_STATUS_SUCCESS)
1552         db->commit_transaction ();
1553     else
1554         db->cancel_transaction ();
1555
1556     if (timer_is_active) {
1557         /* Now stop the timer. */
1558         timerval.it_interval.tv_sec = 0;
1559         timerval.it_interval.tv_usec = 0;
1560         timerval.it_value.tv_sec = 0;
1561         timerval.it_value.tv_usec = 0;
1562         setitimer (ITIMER_REAL, &timerval, NULL);
1563
1564         /* And disable the signal handler. */
1565         action.sa_handler = SIG_IGN;
1566         sigaction (SIGALRM, &action, NULL);
1567     }
1568
1569     if (query)
1570         notmuch_query_destroy (query);
1571
1572     talloc_free (local);
1573     return status;
1574 }
1575
1576 notmuch_status_t
1577 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1578 {
1579     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1580         notmuch->atomic_nesting > 0)
1581         goto DONE;
1582
1583     if (notmuch_database_needs_upgrade (notmuch))
1584         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1585
1586     try {
1587         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1588     } catch (const Xapian::Error &error) {
1589         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1590                  error.get_msg().c_str());
1591         notmuch->exception_reported = TRUE;
1592         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1593     }
1594
1595 DONE:
1596     notmuch->atomic_nesting++;
1597     return NOTMUCH_STATUS_SUCCESS;
1598 }
1599
1600 notmuch_status_t
1601 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1602 {
1603     Xapian::WritableDatabase *db;
1604
1605     if (notmuch->atomic_nesting == 0)
1606         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1607
1608     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1609         notmuch->atomic_nesting > 1)
1610         goto DONE;
1611
1612     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1613     try {
1614         db->commit_transaction ();
1615
1616         /* This is a hack for testing.  Xapian never flushes on a
1617          * non-flushed commit, even if the flush threshold is 1.
1618          * However, we rely on flushing to test atomicity. */
1619         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1620         if (thresh && atoi (thresh) == 1)
1621             db->commit ();
1622     } catch (const Xapian::Error &error) {
1623         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1624                  error.get_msg().c_str());
1625         notmuch->exception_reported = TRUE;
1626         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1627     }
1628
1629     if (notmuch->atomic_dirty) {
1630         ++notmuch->revision;
1631         notmuch->atomic_dirty = FALSE;
1632     }
1633
1634 DONE:
1635     notmuch->atomic_nesting--;
1636     return NOTMUCH_STATUS_SUCCESS;
1637 }
1638
1639 unsigned long
1640 notmuch_database_get_revision (notmuch_database_t *notmuch,
1641                                 const char **uuid)
1642 {
1643     if (uuid)
1644         *uuid = notmuch->uuid;
1645     return notmuch->revision;
1646 }
1647
1648 /* We allow the user to use arbitrarily long paths for directories. But
1649  * we have a term-length limit. So if we exceed that, we'll use the
1650  * SHA-1 of the path for the database term.
1651  *
1652  * Note: This function may return the original value of 'path'. If it
1653  * does not, then the caller is responsible to free() the returned
1654  * value.
1655  */
1656 const char *
1657 _notmuch_database_get_directory_db_path (const char *path)
1658 {
1659     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1660
1661     if (term_len > NOTMUCH_TERM_MAX)
1662         return _notmuch_sha1_of_string (path);
1663     else
1664         return path;
1665 }
1666
1667 /* Given a path, split it into two parts: the directory part is all
1668  * components except for the last, and the basename is that last
1669  * component. Getting the return-value for either part is optional
1670  * (the caller can pass NULL).
1671  *
1672  * The original 'path' can represent either a regular file or a
1673  * directory---the splitting will be carried out in the same way in
1674  * either case. Trailing slashes on 'path' will be ignored, and any
1675  * cases of multiple '/' characters appearing in series will be
1676  * treated as a single '/'.
1677  *
1678  * Allocation (if any) will have 'ctx' as the talloc owner. But
1679  * pointers will be returned within the original path string whenever
1680  * possible.
1681  *
1682  * Note: If 'path' is non-empty and contains no non-trailing slash,
1683  * (that is, consists of a filename with no parent directory), then
1684  * the directory returned will be an empty string. However, if 'path'
1685  * is an empty string, then both directory and basename will be
1686  * returned as NULL.
1687  */
1688 notmuch_status_t
1689 _notmuch_database_split_path (void *ctx,
1690                               const char *path,
1691                               const char **directory,
1692                               const char **basename)
1693 {
1694     const char *slash;
1695
1696     if (path == NULL || *path == '\0') {
1697         if (directory)
1698             *directory = NULL;
1699         if (basename)
1700             *basename = NULL;
1701         return NOTMUCH_STATUS_SUCCESS;
1702     }
1703
1704     /* Find the last slash (not counting a trailing slash), if any. */
1705
1706     slash = path + strlen (path) - 1;
1707
1708     /* First, skip trailing slashes. */
1709     while (slash != path && *slash == '/')
1710         --slash;
1711
1712     /* Then, find a slash. */
1713     while (slash != path && *slash != '/') {
1714         if (basename)
1715             *basename = slash;
1716
1717         --slash;
1718     }
1719
1720     /* Finally, skip multiple slashes. */
1721     while (slash != path && *(slash - 1) == '/')
1722         --slash;
1723
1724     if (slash == path) {
1725         if (directory)
1726             *directory = talloc_strdup (ctx, "");
1727         if (basename)
1728             *basename = path;
1729     } else {
1730         if (directory)
1731             *directory = talloc_strndup (ctx, path, slash - path);
1732     }
1733
1734     return NOTMUCH_STATUS_SUCCESS;
1735 }
1736
1737 /* Find the document ID of the specified directory.
1738  *
1739  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1740  * created if one does not exist for 'path'.  Otherwise, if the
1741  * directory document does not exist, this sets *directory_id to
1742  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1743  */
1744 notmuch_status_t
1745 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1746                                      const char *path,
1747                                      notmuch_find_flags_t flags,
1748                                      unsigned int *directory_id)
1749 {
1750     notmuch_directory_t *directory;
1751     notmuch_status_t status;
1752
1753     if (path == NULL) {
1754         *directory_id = 0;
1755         return NOTMUCH_STATUS_SUCCESS;
1756     }
1757
1758     directory = _notmuch_directory_create (notmuch, path, flags, &status);
1759     if (status || !directory) {
1760         *directory_id = -1;
1761         return status;
1762     }
1763
1764     *directory_id = _notmuch_directory_get_document_id (directory);
1765
1766     notmuch_directory_destroy (directory);
1767
1768     return NOTMUCH_STATUS_SUCCESS;
1769 }
1770
1771 const char *
1772 _notmuch_database_get_directory_path (void *ctx,
1773                                       notmuch_database_t *notmuch,
1774                                       unsigned int doc_id)
1775 {
1776     Xapian::Document document;
1777
1778     document = find_document_for_doc_id (notmuch, doc_id);
1779
1780     return talloc_strdup (ctx, document.get_data ().c_str ());
1781 }
1782
1783 /* Given a legal 'filename' for the database, (either relative to
1784  * database path or absolute with initial components identical to
1785  * database path), return a new string (with 'ctx' as the talloc
1786  * owner) suitable for use as a direntry term value.
1787  *
1788  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1789  * will be created in the database as needed.  Otherwise, if the
1790  * necessary directory documents do not exist, this sets
1791  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1792  */
1793 notmuch_status_t
1794 _notmuch_database_filename_to_direntry (void *ctx,
1795                                         notmuch_database_t *notmuch,
1796                                         const char *filename,
1797                                         notmuch_find_flags_t flags,
1798                                         char **direntry)
1799 {
1800     const char *relative, *directory, *basename;
1801     Xapian::docid directory_id;
1802     notmuch_status_t status;
1803
1804     relative = _notmuch_database_relative_path (notmuch, filename);
1805
1806     status = _notmuch_database_split_path (ctx, relative,
1807                                            &directory, &basename);
1808     if (status)
1809         return status;
1810
1811     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1812                                                   &directory_id);
1813     if (status || directory_id == (unsigned int)-1) {
1814         *direntry = NULL;
1815         return status;
1816     }
1817
1818     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1819
1820     return NOTMUCH_STATUS_SUCCESS;
1821 }
1822
1823 /* Given a legal 'path' for the database, return the relative path.
1824  *
1825  * The return value will be a pointer to the original path contents,
1826  * and will be either the original string (if 'path' was relative) or
1827  * a portion of the string (if path was absolute and begins with the
1828  * database path).
1829  */
1830 const char *
1831 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1832                                  const char *path)
1833 {
1834     const char *db_path, *relative;
1835     unsigned int db_path_len;
1836
1837     db_path = notmuch_database_get_path (notmuch);
1838     db_path_len = strlen (db_path);
1839
1840     relative = path;
1841
1842     if (*relative == '/') {
1843         while (*relative == '/' && *(relative+1) == '/')
1844             relative++;
1845
1846         if (strncmp (relative, db_path, db_path_len) == 0)
1847         {
1848             relative += db_path_len;
1849             while (*relative == '/')
1850                 relative++;
1851         }
1852     }
1853
1854     return relative;
1855 }
1856
1857 notmuch_status_t
1858 notmuch_database_get_directory (notmuch_database_t *notmuch,
1859                                 const char *path,
1860                                 notmuch_directory_t **directory)
1861 {
1862     notmuch_status_t status;
1863
1864     if (directory == NULL)
1865         return NOTMUCH_STATUS_NULL_POINTER;
1866     *directory = NULL;
1867
1868     try {
1869         *directory = _notmuch_directory_create (notmuch, path,
1870                                                 NOTMUCH_FIND_LOOKUP, &status);
1871     } catch (const Xapian::Error &error) {
1872         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1873                  error.get_msg().c_str());
1874         notmuch->exception_reported = TRUE;
1875         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1876     }
1877     return status;
1878 }
1879
1880 /* Allocate a document ID that satisfies the following criteria:
1881  *
1882  * 1. The ID does not exist for any document in the Xapian database
1883  *
1884  * 2. The ID was not previously returned from this function
1885  *
1886  * 3. The ID is the smallest integer satisfying (1) and (2)
1887  *
1888  * This function will trigger an internal error if these constraints
1889  * cannot all be satisfied, (that is, the pool of available document
1890  * IDs has been exhausted).
1891  */
1892 unsigned int
1893 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1894 {
1895     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1896
1897     notmuch->last_doc_id++;
1898
1899     if (notmuch->last_doc_id == 0)
1900         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1901
1902     return notmuch->last_doc_id;
1903 }
1904
1905 notmuch_status_t
1906 notmuch_database_remove_message (notmuch_database_t *notmuch,
1907                                  const char *filename)
1908 {
1909     notmuch_status_t status;
1910     notmuch_message_t *message;
1911
1912     status = notmuch_database_find_message_by_filename (notmuch, filename,
1913                                                         &message);
1914
1915     if (status == NOTMUCH_STATUS_SUCCESS && message) {
1916             status = _notmuch_message_remove_filename (message, filename);
1917             if (status == NOTMUCH_STATUS_SUCCESS)
1918                 _notmuch_message_delete (message);
1919             else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1920                 _notmuch_message_sync (message);
1921
1922             notmuch_message_destroy (message);
1923     }
1924
1925     return status;
1926 }
1927
1928 notmuch_status_t
1929 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1930                                            const char *filename,
1931                                            notmuch_message_t **message_ret)
1932 {
1933     void *local;
1934     const char *prefix = _find_prefix ("file-direntry");
1935     char *direntry, *term;
1936     Xapian::PostingIterator i, end;
1937     notmuch_status_t status;
1938
1939     if (message_ret == NULL)
1940         return NOTMUCH_STATUS_NULL_POINTER;
1941
1942     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1943         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1944
1945     /* return NULL on any failure */
1946     *message_ret = NULL;
1947
1948     local = talloc_new (notmuch);
1949
1950     try {
1951         status = _notmuch_database_filename_to_direntry (
1952             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1953         if (status || !direntry)
1954             goto DONE;
1955
1956         term = talloc_asprintf (local, "%s%s", prefix, direntry);
1957
1958         find_doc_ids_for_term (notmuch, term, &i, &end);
1959
1960         if (i != end) {
1961             notmuch_private_status_t private_status;
1962
1963             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1964                                                     &private_status);
1965             if (*message_ret == NULL)
1966                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1967         }
1968     } catch (const Xapian::Error &error) {
1969         _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1970                  error.get_msg().c_str());
1971         notmuch->exception_reported = TRUE;
1972         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1973     }
1974
1975   DONE:
1976     talloc_free (local);
1977
1978     if (status && *message_ret) {
1979         notmuch_message_destroy (*message_ret);
1980         *message_ret = NULL;
1981     }
1982     return status;
1983 }
1984
1985 notmuch_string_list_t *
1986 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1987                                          Xapian::TermIterator &end,
1988                                          const char *prefix)
1989 {
1990     int prefix_len = strlen (prefix);
1991     notmuch_string_list_t *list;
1992
1993     list = _notmuch_string_list_create (ctx);
1994     if (unlikely (list == NULL))
1995         return NULL;
1996
1997     for (i.skip_to (prefix); i != end; i++) {
1998         /* Terminate loop at first term without desired prefix. */
1999         if (strncmp ((*i).c_str (), prefix, prefix_len))
2000             break;
2001
2002         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2003     }
2004
2005     return list;
2006 }
2007
2008 notmuch_tags_t *
2009 notmuch_database_get_all_tags (notmuch_database_t *db)
2010 {
2011     Xapian::TermIterator i, end;
2012     notmuch_string_list_t *tags;
2013
2014     try {
2015         i = db->xapian_db->allterms_begin();
2016         end = db->xapian_db->allterms_end();
2017         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2018                                                         _find_prefix ("tag"));
2019         _notmuch_string_list_sort (tags);
2020         return _notmuch_tags_create (db, tags);
2021     } catch (const Xapian::Error &error) {
2022         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2023                  error.get_msg().c_str());
2024         db->exception_reported = TRUE;
2025         return NULL;
2026     }
2027 }
2028
2029 const char *
2030 notmuch_database_status_string (const notmuch_database_t *notmuch)
2031 {
2032     return notmuch->status_string;
2033 }