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