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