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