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