]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib: publish API for notmuch_database_reopen
[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 "string-util.h"
23
24 #include <iostream>
25
26 #include <sys/time.h>
27 #include <sys/stat.h>
28 #include <signal.h>
29 #include <ftw.h>
30
31 #include <glib.h>               /* g_free, GPtrArray, GHashTable */
32 #include <glib-object.h>        /* g_type_init */
33
34 #include <gmime/gmime.h>        /* g_mime_init */
35
36 using namespace std;
37
38 typedef struct {
39     const char *name;
40     const char *prefix;
41     notmuch_field_flag_t flags;
42 } prefix_t;
43
44 #define NOTMUCH_DATABASE_VERSION 3
45
46 #define STRINGIFY(s) _SUB_STRINGIFY (s)
47 #define _SUB_STRINGIFY(s) #s
48
49 #define LOG_XAPIAN_EXCEPTION(message, error) _log_xapian_exception (__location__, message, error)
50
51 static void
52 _log_xapian_exception (const char *where, notmuch_database_t *notmuch,  const Xapian::Error error)
53 {
54     _notmuch_database_log (notmuch,
55                            "A Xapian exception occurred at %s: %s\n",
56                            where,
57                            error.get_msg ().c_str ());
58     notmuch->exception_reported = true;
59 }
60
61 notmuch_database_mode_t
62 _notmuch_database_mode (notmuch_database_t *notmuch)
63 {
64     if (notmuch->writable_xapian_db)
65         return NOTMUCH_DATABASE_MODE_READ_WRITE;
66     else
67         return NOTMUCH_DATABASE_MODE_READ_ONLY;
68 }
69
70 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
71  *
72  * We currently have three different types of documents (mail, ghost,
73  * and directory) and also some metadata.
74  *
75  * There are two kinds of prefixes used in notmuch. There are the
76  * human friendly 'prefix names' like "thread:", which are also used
77  * in the query parser, and the actual prefix terms in the database
78  * (e.g. "G"). The correspondence is maintained in the file scope data
79  * structure 'prefix_table'.
80  *
81  * Mail document
82  * -------------
83  * A mail document is associated with a particular email message. It
84  * is stored in one or more files on disk and is uniquely identified
85  * by its "id" field (which is generally the message ID). It is
86  * indexed with the following prefixed terms which the database uses
87  * to construct threads, etc.:
88  *
89  *    Single terms of given prefix:
90  *
91  *      type:   mail
92  *
93  *      id:     Unique ID of mail. This is from the Message-ID header
94  *              if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
95  *              If it's present and too long, then we use
96  *              "notmuch-sha1-<sha1_sum_of_message_id>".
97  *              If this header is not present, we use
98  *              "notmuch-sha1-<sha1_sum_of_entire_file>".
99  *
100  *      thread: The ID of the thread to which the mail belongs
101  *
102  *      replyto: The ID from the In-Reply-To header of the mail (if any).
103  *
104  *    Multiple terms of given prefix:
105  *
106  *      reference: All message IDs from In-Reply-To and References
107  *                 headers in the message.
108  *
109  *      tag:       Any tags associated with this message by the user.
110  *
111  *      file-direntry:  A colon-separated pair of values
112  *                      (INTEGER:STRING), where INTEGER is the
113  *                      document ID of a directory document, and
114  *                      STRING is the name of a file within that
115  *                      directory for this mail message.
116  *
117  *      property:       Has a property with key=value
118  *                 FIXME: if no = is present, should match on any value
119  *
120  *    A mail document also has four values:
121  *
122  *      TIMESTAMP:      The time_t value corresponding to the message's
123  *                      Date header.
124  *
125  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
126  *
127  *      FROM:           The value of the "From" header
128  *
129  *      SUBJECT:        The value of the "Subject" header
130  *
131  *      LAST_MOD:       The revision number as of the last tag or
132  *                      filename change.
133  *
134  * The prefixed terms described above are also searchable without an
135  * explicit field name, but as of notmuch 0.29 this is due to
136  * query-parser setup, not extra terms in the database.  In addition,
137  * terms from the content of the message are added without a prefix
138  * for use by the user in searching. Note that the prefix name "body"
139  * is used to refer to the empty prefix string in the database.
140  *
141  * The path of the containing folder is added with the "folder" prefix
142  * (see _notmuch_message_add_folder_terms).  Sub-paths of the the path
143  * of the mail message are added with the "path" prefix.
144  *
145  * The data portion of a mail document is empty.
146  *
147  * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
148  * -----------------------------------------------
149  * A ghost mail document is like a mail document, but where we don't
150  * have the message content.  These are used to track thread reference
151  * information for messages we haven't received.
152  *
153  * A ghost mail document has type: ghost; id and thread fields that
154  * are identical to the mail document fields; and a MESSAGE_ID value.
155  *
156  * Directory document
157  * ------------------
158  * A directory document is used by a client of the notmuch library to
159  * maintain data necessary to allow for efficient polling of mail
160  * directories.
161  *
162  * All directory documents contain one term:
163  *
164  *      directory:      The directory path (relative to the database path)
165  *                      Or the SHA1 sum of the directory path (if the
166  *                      path itself is too long to fit in a Xapian
167  *                      term).
168  *
169  * And all directory documents for directories other than top-level
170  * directories also contain the following term:
171  *
172  *      directory-direntry: A colon-separated pair of values
173  *                          (INTEGER:STRING), where INTEGER is the
174  *                          document ID of the parent directory
175  *                          document, and STRING is the name of this
176  *                          directory within that parent.
177  *
178  * All directory documents have a single value:
179  *
180  *      TIMESTAMP:      The mtime of the directory (at last scan)
181  *
182  * The data portion of a directory document contains the path of the
183  * directory (relative to the database path).
184  *
185  * Database metadata
186  * -----------------
187  * Xapian allows us to store arbitrary name-value pairs as
188  * "metadata". We currently use the following metadata names with the
189  * given meanings:
190  *
191  *      version         The database schema version, (which is distinct
192  *                      from both the notmuch package version (see
193  *                      notmuch --version) and the libnotmuch library
194  *                      version. The version is stored as an base-10
195  *                      ASCII integer. The initial database version
196  *                      was 1, (though a schema existed before that
197  *                      were no "version" database value existed at
198  *                      all). Successive versions are allocated as
199  *                      changes are made to the database (such as by
200  *                      indexing new fields).
201  *
202  *      features        The set of features supported by this
203  *                      database. This consists of a set of
204  *                      '\n'-separated lines, where each is a feature
205  *                      name, a '\t', and compatibility flags.  If the
206  *                      compatibility flags contain 'w', then the
207  *                      opener must support this feature to safely
208  *                      write this database.  If the compatibility
209  *                      flags contain 'r', then the opener must
210  *                      support this feature to read this database.
211  *                      Introduced in database version 3.
212  *
213  *      last_thread_id  The last thread ID generated. This is stored
214  *                      as a 16-byte hexadecimal ASCII representation
215  *                      of a 64-bit unsigned integer. The first ID
216  *                      generated is 1 and the value will be
217  *                      incremented for each thread ID.
218  *
219  *      C*              metadata keys starting with C indicate
220  *                      configuration data. It can be managed with the
221  *                      n_database_*config* API.  There is a convention
222  *                      of hierarchical keys separated by '.' (e.g.
223  *                      query.notmuch stores the value for the named
224  *                      query 'notmuch'), but it is not enforced by the
225  *                      API.
226  *
227  * Obsolete metadata
228  * -----------------
229  *
230  * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
231  * Instead, the database has the following additional database
232  * metadata:
233  *
234  *      thread_id_*     A pre-allocated thread ID for a particular
235  *                      message. This is actually an arbitrarily large
236  *                      family of metadata name. Any particular name is
237  *                      formed by concatenating "thread_id_" with a message
238  *                      ID (or the SHA1 sum of a message ID if it is very
239  *                      long---see description of 'id' in the mail
240  *                      document). The value stored is a thread ID.
241  *
242  *                      These thread ID metadata values are stored
243  *                      whenever a message references a parent message
244  *                      that does not yet exist in the database. A
245  *                      thread ID will be allocated and stored, and if
246  *                      the message is later added, the stored thread
247  *                      ID will be used (and the metadata value will
248  *                      be cleared).
249  *
250  *                      Even before a message is added, it's
251  *                      pre-allocated thread ID is useful so that all
252  *                      descendant messages that reference this common
253  *                      parent can be recognized as belonging to the
254  *                      same thread.
255  */
256
257
258 notmuch_string_map_iterator_t *
259 _notmuch_database_user_headers (notmuch_database_t *notmuch)
260 {
261     return _notmuch_string_map_iterator_create (notmuch->user_header, "", false);
262 }
263
264 const char *
265 notmuch_status_to_string (notmuch_status_t status)
266 {
267     switch (status) {
268     case NOTMUCH_STATUS_SUCCESS:
269         return "No error occurred";
270     case NOTMUCH_STATUS_OUT_OF_MEMORY:
271         return "Out of memory";
272     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
273         return "Attempt to write to a read-only database";
274     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
275         return "A Xapian exception occurred";
276     case NOTMUCH_STATUS_FILE_ERROR:
277         return "Something went wrong trying to read or write a file";
278     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
279         return "File is not an email";
280     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
281         return "Message ID is identical to a message in database";
282     case NOTMUCH_STATUS_NULL_POINTER:
283         return "Erroneous NULL pointer";
284     case NOTMUCH_STATUS_TAG_TOO_LONG:
285         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
286     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
287         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
288     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
289         return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
290     case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
291         return "Unsupported operation";
292     case NOTMUCH_STATUS_UPGRADE_REQUIRED:
293         return "Operation requires a database upgrade";
294     case NOTMUCH_STATUS_PATH_ERROR:
295         return "Path supplied is illegal for this function";
296     case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
297         return "Crypto protocol missing, malformed, or unintelligible";
298     case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
299         return "Crypto engine initialization failure";
300     case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
301         return "Unknown crypto protocol";
302     default:
303     case NOTMUCH_STATUS_LAST_STATUS:
304         return "Unknown error status value";
305     }
306 }
307
308 void
309 _notmuch_database_log (notmuch_database_t *notmuch,
310                        const char *format,
311                        ...)
312 {
313     va_list va_args;
314
315     va_start (va_args, format);
316
317     if (notmuch->status_string)
318         talloc_free (notmuch->status_string);
319
320     notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
321     va_end (va_args);
322 }
323
324 void
325 _notmuch_database_log_append (notmuch_database_t *notmuch,
326                               const char *format,
327                               ...)
328 {
329     va_list va_args;
330
331     va_start (va_args, format);
332
333     if (notmuch->status_string)
334         notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
335     else
336         notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
337
338     va_end (va_args);
339 }
340
341 static void
342 find_doc_ids_for_term (notmuch_database_t *notmuch,
343                        const char *term,
344                        Xapian::PostingIterator *begin,
345                        Xapian::PostingIterator *end)
346 {
347     *begin = notmuch->xapian_db->postlist_begin (term);
348
349     *end = notmuch->xapian_db->postlist_end (term);
350 }
351
352 void
353 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
354                                 const char *prefix_name,
355                                 const char *value,
356                                 Xapian::PostingIterator *begin,
357                                 Xapian::PostingIterator *end)
358 {
359     char *term;
360
361     term = talloc_asprintf (notmuch, "%s%s",
362                             _find_prefix (prefix_name), value);
363
364     find_doc_ids_for_term (notmuch, term, begin, end);
365
366     talloc_free (term);
367 }
368
369 notmuch_private_status_t
370 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
371                                       const char *prefix_name,
372                                       const char *value,
373                                       unsigned int *doc_id)
374 {
375     Xapian::PostingIterator i, end;
376
377     _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
378
379     if (i == end) {
380         *doc_id = 0;
381         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
382     }
383
384     *doc_id = *i;
385
386 #if DEBUG_DATABASE_SANITY
387     i++;
388
389     if (i != end)
390         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
391                         prefix_name, value);
392 #endif
393
394     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
395 }
396
397 static Xapian::Document
398 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
399 {
400     return notmuch->xapian_db->get_document (doc_id);
401 }
402
403 /* Generate a compressed version of 'message_id' of the form:
404  *
405  *      notmuch-sha1-<sha1_sum_of_message_id>
406  */
407 char *
408 _notmuch_message_id_compressed (void *ctx, const char *message_id)
409 {
410     char *sha1, *compressed;
411
412     sha1 = _notmuch_sha1_of_string (message_id);
413
414     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
415     free (sha1);
416
417     return compressed;
418 }
419
420 notmuch_status_t
421 notmuch_database_find_message (notmuch_database_t *notmuch,
422                                const char *message_id,
423                                notmuch_message_t **message_ret)
424 {
425     notmuch_private_status_t status;
426     unsigned int doc_id;
427
428     if (message_ret == NULL)
429         return NOTMUCH_STATUS_NULL_POINTER;
430
431     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
432         message_id = _notmuch_message_id_compressed (notmuch, message_id);
433
434     try {
435         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
436                                                        message_id, &doc_id);
437
438         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
439             *message_ret = NULL;
440         else {
441             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
442                                                     NULL);
443             if (*message_ret == NULL)
444                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
445         }
446
447         return NOTMUCH_STATUS_SUCCESS;
448     } catch (const Xapian::Error &error) {
449         _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
450                                error.get_msg ().c_str ());
451         notmuch->exception_reported = true;
452         *message_ret = NULL;
453         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
454     }
455 }
456
457 notmuch_status_t
458 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
459 {
460     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY) {
461         _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
462         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
463     }
464
465     return NOTMUCH_STATUS_SUCCESS;
466 }
467
468 /* Allocate a revision number for the next change. */
469 unsigned long
470 _notmuch_database_new_revision (notmuch_database_t *notmuch)
471 {
472     unsigned long new_revision = notmuch->revision + 1;
473
474     /* If we're in an atomic section, hold off on updating the
475      * committed revision number until we commit the atomic section.
476      */
477     if (notmuch->atomic_nesting)
478         notmuch->atomic_dirty = true;
479     else
480         notmuch->revision = new_revision;
481
482     return new_revision;
483 }
484
485 notmuch_status_t
486 notmuch_database_close (notmuch_database_t *notmuch)
487 {
488     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
489
490     /* Many Xapian objects (and thus notmuch objects) hold references to
491      * the database, so merely deleting the database may not suffice to
492      * close it.  Thus, we explicitly close it here. */
493     if (notmuch->open) {
494         try {
495             /* If there's an outstanding transaction, it's unclear if
496              * closing the Xapian database commits everything up to
497              * that transaction, or may discard committed (but
498              * unflushed) transactions.  To be certain, explicitly
499              * cancel any outstanding transaction before closing. */
500             if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_WRITE &&
501                 notmuch->atomic_nesting)
502                 notmuch->writable_xapian_db->cancel_transaction ();
503
504             /* Close the database.  This implicitly flushes
505              * outstanding changes. */
506             notmuch->xapian_db->close ();
507         } catch (const Xapian::Error &error) {
508             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
509             if (! notmuch->exception_reported) {
510                 _notmuch_database_log (notmuch,
511                                        "Error: A Xapian exception occurred closing database: %s\n",
512                                        error.get_msg ().c_str ());
513             }
514         }
515     }
516     notmuch->open = false;
517     return status;
518 }
519
520 notmuch_status_t
521 notmuch_database_reopen (notmuch_database_t *notmuch,
522                          unused(notmuch_database_mode_t mode))
523 {
524     if (_notmuch_database_mode (notmuch) != NOTMUCH_DATABASE_MODE_READ_ONLY)
525         return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
526
527     try {
528         notmuch->xapian_db->reopen ();
529     } catch (const Xapian::Error &error) {
530         if (! notmuch->exception_reported) {
531             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
532                                    error.get_msg ().c_str ());
533             notmuch->exception_reported = true;
534         }
535         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
536     }
537
538     notmuch->view++;
539
540     return NOTMUCH_STATUS_SUCCESS;
541 }
542
543 static int
544 unlink_cb (const char *path,
545            unused (const struct stat *sb),
546            unused (int type),
547            unused (struct FTW *ftw))
548 {
549     return remove (path);
550 }
551
552 static int
553 rmtree (const char *path)
554 {
555     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
556 }
557
558 class NotmuchCompactor : public Xapian::Compactor
559 {
560     notmuch_compact_status_cb_t status_cb;
561     void *status_closure;
562
563 public:
564     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
565         status_cb (cb), status_closure (closure)
566     {
567     }
568
569     virtual void
570     set_status (const std::string &table, const std::string &status)
571     {
572         char *msg;
573
574         if (status_cb == NULL)
575             return;
576
577         if (status.length () == 0)
578             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
579         else
580             msg = talloc_asprintf (NULL, "     %s", status.c_str ());
581
582         if (msg == NULL) {
583             return;
584         }
585
586         status_cb (msg, status_closure);
587         talloc_free (msg);
588     }
589 };
590
591 /* Compacts the given database, optionally saving the original database
592  * in backup_path. Additionally, a callback function can be provided to
593  * give the user feedback on the progress of the (likely long-lived)
594  * compaction process.
595  *
596  * The backup path must point to a directory on the same volume as the
597  * original database. Passing a NULL backup_path will result in the
598  * uncompacted database being deleted after compaction has finished.
599  * Note that the database write lock will be held during the
600  * compaction process to protect data integrity.
601  */
602 notmuch_status_t
603 notmuch_database_compact (const char *path,
604                           const char *backup_path,
605                           notmuch_compact_status_cb_t status_cb,
606                           void *closure)
607 {
608     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
609     notmuch_database_t *notmuch = NULL;
610     char *message = NULL;
611
612     ret = notmuch_database_open_verbose (path,
613                                          NOTMUCH_DATABASE_MODE_READ_WRITE,
614                                          &notmuch,
615                                          &message);
616     if (ret) {
617         if (status_cb) status_cb (message, closure);
618         return ret;
619     }
620
621     _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_DATABASE_PATH, path);
622
623     return notmuch_database_compact_db (notmuch,
624                                         backup_path,
625                                         status_cb,
626                                         closure);
627 }
628
629 notmuch_status_t
630 notmuch_database_compact_db (notmuch_database_t *notmuch,
631                              const char *backup_path,
632                              notmuch_compact_status_cb_t status_cb,
633                              void *closure)
634 {
635     void *local;
636     char *notmuch_path, *xapian_path, *compact_xapian_path;
637     const char *path;
638     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
639     struct stat statbuf;
640     bool keep_backup;
641
642     ret = _notmuch_database_ensure_writable (notmuch);
643     if (ret)
644         return ret;
645
646     path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
647     if (! path)
648         return NOTMUCH_STATUS_PATH_ERROR;
649
650     local = talloc_new (NULL);
651     if (! local)
652         return NOTMUCH_STATUS_OUT_OF_MEMORY;
653
654     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
655         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
656         goto DONE;
657     }
658
659     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
660         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
661         goto DONE;
662     }
663
664     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
665         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
666         goto DONE;
667     }
668
669     if (backup_path == NULL) {
670         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
671             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
672             goto DONE;
673         }
674         keep_backup = false;
675     } else {
676         keep_backup = true;
677     }
678
679     if (stat (backup_path, &statbuf) != -1) {
680         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
681         ret = NOTMUCH_STATUS_FILE_ERROR;
682         goto DONE;
683     }
684     if (errno != ENOENT) {
685         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
686                                strerror (errno));
687         ret = NOTMUCH_STATUS_FILE_ERROR;
688         goto DONE;
689     }
690
691     /* Unconditionally attempt to remove old work-in-progress database (if
692      * any). This is "protected" by database lock. If this fails due to write
693      * errors (etc), the following code will fail and provide error message.
694      */
695     (void) rmtree (compact_xapian_path);
696
697     try {
698         NotmuchCompactor compactor (status_cb, closure);
699         notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0,
700                                      compactor);
701     } catch (const Xapian::Error &error) {
702         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
703         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
704         goto DONE;
705     }
706
707     if (rename (xapian_path, backup_path)) {
708         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
709                                xapian_path, backup_path, strerror (errno));
710         ret = NOTMUCH_STATUS_FILE_ERROR;
711         goto DONE;
712     }
713
714     if (rename (compact_xapian_path, xapian_path)) {
715         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
716                                compact_xapian_path, xapian_path, strerror (errno));
717         ret = NOTMUCH_STATUS_FILE_ERROR;
718         goto DONE;
719     }
720
721     if (! keep_backup) {
722         if (rmtree (backup_path)) {
723             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
724                                    backup_path, strerror (errno));
725             ret = NOTMUCH_STATUS_FILE_ERROR;
726             goto DONE;
727         }
728     }
729
730   DONE:
731     if (notmuch) {
732         notmuch_status_t ret2;
733
734         const char *str = notmuch_database_status_string (notmuch);
735         if (status_cb && str)
736             status_cb (str, closure);
737
738         ret2 = notmuch_database_destroy (notmuch);
739
740         /* don't clobber previous error status */
741         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
742             ret = ret2;
743     }
744
745     talloc_free (local);
746
747     return ret;
748 }
749
750 notmuch_status_t
751 notmuch_database_destroy (notmuch_database_t *notmuch)
752 {
753     notmuch_status_t status;
754
755     status = notmuch_database_close (notmuch);
756
757     delete notmuch->term_gen;
758     notmuch->term_gen = NULL;
759     delete notmuch->query_parser;
760     notmuch->query_parser = NULL;
761     delete notmuch->xapian_db;
762     notmuch->xapian_db = NULL;
763     delete notmuch->value_range_processor;
764     notmuch->value_range_processor = NULL;
765     delete notmuch->date_range_processor;
766     notmuch->date_range_processor = NULL;
767     delete notmuch->last_mod_range_processor;
768     notmuch->last_mod_range_processor = NULL;
769
770     talloc_free (notmuch);
771
772     return status;
773 }
774
775 const char *
776 notmuch_database_get_path (notmuch_database_t *notmuch)
777 {
778     return notmuch->path;
779 }
780
781 unsigned int
782 notmuch_database_get_version (notmuch_database_t *notmuch)
783 {
784     unsigned int version;
785     string version_string;
786     const char *str;
787     char *end;
788
789     try {
790         version_string = notmuch->xapian_db->get_metadata ("version");
791     } catch (const Xapian::Error &error) {
792         LOG_XAPIAN_EXCEPTION (notmuch, error);
793         return 0;
794     }
795
796     if (version_string.empty ())
797         return 0;
798
799     str = version_string.c_str ();
800     if (str == NULL || *str == '\0')
801         return 0;
802
803     version = strtoul (str, &end, 10);
804     if (*end != '\0')
805         INTERNAL_ERROR ("Malformed database version: %s", str);
806
807     return version;
808 }
809
810 notmuch_bool_t
811 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
812 {
813     unsigned int version;
814
815     if (_notmuch_database_mode (notmuch) != NOTMUCH_DATABASE_MODE_READ_WRITE)
816         return FALSE;
817
818     if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
819         return TRUE;
820
821     version = notmuch_database_get_version (notmuch);
822
823     return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
824 }
825
826 static volatile sig_atomic_t do_progress_notify = 0;
827
828 static void
829 handle_sigalrm (unused (int signal))
830 {
831     do_progress_notify = 1;
832 }
833
834 /* Upgrade the current database.
835  *
836  * After opening a database in read-write mode, the client should
837  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
838  * if so, upgrade with this function before making any modifications.
839  *
840  * The optional progress_notify callback can be used by the caller to
841  * provide progress indication to the user. If non-NULL it will be
842  * called periodically with 'count' as the number of messages upgraded
843  * so far and 'total' the overall number of messages that will be
844  * converted.
845  */
846 notmuch_status_t
847 notmuch_database_upgrade (notmuch_database_t *notmuch,
848                           void (*progress_notify)(void *closure,
849                                                   double progress),
850                           void *closure)
851 {
852     void *local = talloc_new (NULL);
853     Xapian::TermIterator t, t_end;
854     Xapian::WritableDatabase *db;
855     struct sigaction action;
856     struct itimerval timerval;
857     bool timer_is_active = false;
858     enum _notmuch_features target_features, new_features;
859     notmuch_status_t status;
860     notmuch_private_status_t private_status;
861     notmuch_query_t *query = NULL;
862     unsigned int count = 0, total = 0;
863
864     status = _notmuch_database_ensure_writable (notmuch);
865     if (status)
866         return status;
867
868     db = notmuch->writable_xapian_db;
869
870     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
871     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
872
873     if (! notmuch_database_needs_upgrade (notmuch))
874         return NOTMUCH_STATUS_SUCCESS;
875
876     if (progress_notify) {
877         /* Set up our handler for SIGALRM */
878         memset (&action, 0, sizeof (struct sigaction));
879         action.sa_handler = handle_sigalrm;
880         sigemptyset (&action.sa_mask);
881         action.sa_flags = SA_RESTART;
882         sigaction (SIGALRM, &action, NULL);
883
884         /* Then start a timer to send SIGALRM once per second. */
885         timerval.it_interval.tv_sec = 1;
886         timerval.it_interval.tv_usec = 0;
887         timerval.it_value.tv_sec = 1;
888         timerval.it_value.tv_usec = 0;
889         setitimer (ITIMER_REAL, &timerval, NULL);
890
891         timer_is_active = true;
892     }
893
894     /* Figure out how much total work we need to do. */
895     if (new_features &
896         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
897          NOTMUCH_FEATURE_LAST_MOD)) {
898         query = notmuch_query_create (notmuch, "");
899         unsigned msg_count;
900
901         status = notmuch_query_count_messages (query, &msg_count);
902         if (status)
903             goto DONE;
904
905         total += msg_count;
906         notmuch_query_destroy (query);
907         query = NULL;
908     }
909     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
910         t_end = db->allterms_end ("XTIMESTAMP");
911         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
912             ++total;
913     }
914     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
915         /* The ghost message upgrade converts all thread_id_*
916          * metadata values into ghost message documents. */
917         t_end = db->metadata_keys_end ("thread_id_");
918         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
919             ++total;
920     }
921
922     /* Perform the upgrade in a transaction. */
923     db->begin_transaction (true);
924
925     /* Set the target features so we write out changes in the desired
926      * format. */
927     notmuch->features = target_features;
928
929     /* Perform per-message upgrades. */
930     if (new_features &
931         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
932          NOTMUCH_FEATURE_LAST_MOD)) {
933         notmuch_messages_t *messages;
934         notmuch_message_t *message;
935         char *filename;
936
937         query = notmuch_query_create (notmuch, "");
938
939         status = notmuch_query_search_messages (query, &messages);
940         if (status)
941             goto DONE;
942         for (;
943              notmuch_messages_valid (messages);
944              notmuch_messages_move_to_next (messages)) {
945             if (do_progress_notify) {
946                 progress_notify (closure, (double) count / total);
947                 do_progress_notify = 0;
948             }
949
950             message = notmuch_messages_get (messages);
951
952             /* Before version 1, each message document had its
953              * filename in the data field. Copy that into the new
954              * format by calling notmuch_message_add_filename.
955              */
956             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
957                 filename = _notmuch_message_talloc_copy_data (message);
958                 if (filename && *filename != '\0') {
959                     _notmuch_message_add_filename (message, filename);
960                     _notmuch_message_clear_data (message);
961                 }
962                 talloc_free (filename);
963             }
964
965             /* Prior to version 2, the "folder:" prefix was
966              * probabilistic and stemmed. Change it to the current
967              * boolean prefix. Add "path:" prefixes while at it.
968              */
969             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
970                 _notmuch_message_upgrade_folder (message);
971
972             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
973              * track modification revisions.  Give all messages the
974              * next available revision; since we just started tracking
975              * revisions for this database, that will be 1.
976              */
977             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
978                 _notmuch_message_upgrade_last_mod (message);
979
980             _notmuch_message_sync (message);
981
982             notmuch_message_destroy (message);
983
984             count++;
985         }
986
987         notmuch_query_destroy (query);
988         query = NULL;
989     }
990
991     /* Perform per-directory upgrades. */
992
993     /* Before version 1 we stored directory timestamps in
994      * XTIMESTAMP documents instead of the current XDIRECTORY
995      * documents. So copy those as well. */
996     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
997         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
998
999         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1000              t != t_end;
1001              t++) {
1002             Xapian::PostingIterator p, p_end;
1003             std::string term = *t;
1004
1005             p_end = notmuch->xapian_db->postlist_end (term);
1006
1007             for (p = notmuch->xapian_db->postlist_begin (term);
1008                  p != p_end;
1009                  p++) {
1010                 Xapian::Document document;
1011                 time_t mtime;
1012                 notmuch_directory_t *directory;
1013
1014                 if (do_progress_notify) {
1015                     progress_notify (closure, (double) count / total);
1016                     do_progress_notify = 0;
1017                 }
1018
1019                 document = find_document_for_doc_id (notmuch, *p);
1020                 mtime = Xapian::sortable_unserialise (
1021                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1022
1023                 directory = _notmuch_directory_find_or_create (notmuch, term.c_str () + 10,
1024                                                                NOTMUCH_FIND_CREATE, &status);
1025                 notmuch_directory_set_mtime (directory, mtime);
1026                 notmuch_directory_destroy (directory);
1027
1028                 db->delete_document (*p);
1029             }
1030
1031             ++count;
1032         }
1033     }
1034
1035     /* Perform metadata upgrades. */
1036
1037     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1038      * messages were stored as database metadata. Change these to
1039      * ghost messages.
1040      */
1041     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1042         notmuch_message_t *message;
1043         std::string message_id, thread_id;
1044
1045         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1046         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1047              t != t_end; ++t) {
1048             if (do_progress_notify) {
1049                 progress_notify (closure, (double) count / total);
1050                 do_progress_notify = 0;
1051             }
1052
1053             message_id = (*t).substr (
1054                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1055             thread_id = db->get_metadata (*t);
1056
1057             /* Create ghost message */
1058             message = _notmuch_message_create_for_message_id (
1059                 notmuch, message_id.c_str (), &private_status);
1060             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1061                 /* Document already exists; ignore the stored thread ID */
1062             } else if (private_status ==
1063                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1064                 private_status = _notmuch_message_initialize_ghost (
1065                     message, thread_id.c_str ());
1066                 if (! private_status)
1067                     _notmuch_message_sync (message);
1068             }
1069
1070             if (private_status) {
1071                 _notmuch_database_log (notmuch,
1072                                        "Upgrade failed while creating ghost messages.\n");
1073                 status = COERCE_STATUS (private_status,
1074                                         "Unexpected status from _notmuch_message_initialize_ghost");
1075                 goto DONE;
1076             }
1077
1078             /* Clear saved metadata thread ID */
1079             db->set_metadata (*t, "");
1080
1081             ++count;
1082         }
1083     }
1084
1085     status = NOTMUCH_STATUS_SUCCESS;
1086     db->set_metadata ("features", _notmuch_database_print_features (local, notmuch->features));
1087     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1088
1089   DONE:
1090     if (status == NOTMUCH_STATUS_SUCCESS)
1091         db->commit_transaction ();
1092     else
1093         db->cancel_transaction ();
1094
1095     if (timer_is_active) {
1096         /* Now stop the timer. */
1097         timerval.it_interval.tv_sec = 0;
1098         timerval.it_interval.tv_usec = 0;
1099         timerval.it_value.tv_sec = 0;
1100         timerval.it_value.tv_usec = 0;
1101         setitimer (ITIMER_REAL, &timerval, NULL);
1102
1103         /* And disable the signal handler. */
1104         action.sa_handler = SIG_IGN;
1105         sigaction (SIGALRM, &action, NULL);
1106     }
1107
1108     if (query)
1109         notmuch_query_destroy (query);
1110
1111     talloc_free (local);
1112     return status;
1113 }
1114
1115 notmuch_status_t
1116 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1117 {
1118     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1119         notmuch->atomic_nesting > 0)
1120         goto DONE;
1121
1122     if (notmuch_database_needs_upgrade (notmuch))
1123         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1124
1125     try {
1126         notmuch->writable_xapian_db->begin_transaction (false);
1127     } catch (const Xapian::Error &error) {
1128         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1129                                error.get_msg ().c_str ());
1130         notmuch->exception_reported = true;
1131         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1132     }
1133
1134   DONE:
1135     notmuch->atomic_nesting++;
1136     return NOTMUCH_STATUS_SUCCESS;
1137 }
1138
1139 notmuch_status_t
1140 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1141 {
1142     Xapian::WritableDatabase *db;
1143
1144     if (notmuch->atomic_nesting == 0)
1145         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1146
1147     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1148         notmuch->atomic_nesting > 1)
1149         goto DONE;
1150
1151     db = notmuch->writable_xapian_db;
1152     try {
1153         db->commit_transaction ();
1154
1155         /* This is a hack for testing.  Xapian never flushes on a
1156          * non-flushed commit, even if the flush threshold is 1.
1157          * However, we rely on flushing to test atomicity. */
1158         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1159         if (thresh && atoi (thresh) == 1)
1160             db->commit ();
1161     } catch (const Xapian::Error &error) {
1162         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1163                                error.get_msg ().c_str ());
1164         notmuch->exception_reported = true;
1165         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1166     }
1167
1168     if (notmuch->atomic_dirty) {
1169         ++notmuch->revision;
1170         notmuch->atomic_dirty = false;
1171     }
1172
1173   DONE:
1174     notmuch->atomic_nesting--;
1175     return NOTMUCH_STATUS_SUCCESS;
1176 }
1177
1178 unsigned long
1179 notmuch_database_get_revision (notmuch_database_t *notmuch,
1180                                const char **uuid)
1181 {
1182     if (uuid)
1183         *uuid = notmuch->uuid;
1184     return notmuch->revision;
1185 }
1186
1187 /* We allow the user to use arbitrarily long paths for directories. But
1188  * we have a term-length limit. So if we exceed that, we'll use the
1189  * SHA-1 of the path for the database term.
1190  *
1191  * Note: This function may return the original value of 'path'. If it
1192  * does not, then the caller is responsible to free() the returned
1193  * value.
1194  */
1195 const char *
1196 _notmuch_database_get_directory_db_path (const char *path)
1197 {
1198     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1199
1200     if (term_len > NOTMUCH_TERM_MAX)
1201         return _notmuch_sha1_of_string (path);
1202     else
1203         return path;
1204 }
1205
1206 /* Given a path, split it into two parts: the directory part is all
1207  * components except for the last, and the basename is that last
1208  * component. Getting the return-value for either part is optional
1209  * (the caller can pass NULL).
1210  *
1211  * The original 'path' can represent either a regular file or a
1212  * directory---the splitting will be carried out in the same way in
1213  * either case. Trailing slashes on 'path' will be ignored, and any
1214  * cases of multiple '/' characters appearing in series will be
1215  * treated as a single '/'.
1216  *
1217  * Allocation (if any) will have 'ctx' as the talloc owner. But
1218  * pointers will be returned within the original path string whenever
1219  * possible.
1220  *
1221  * Note: If 'path' is non-empty and contains no non-trailing slash,
1222  * (that is, consists of a filename with no parent directory), then
1223  * the directory returned will be an empty string. However, if 'path'
1224  * is an empty string, then both directory and basename will be
1225  * returned as NULL.
1226  */
1227 notmuch_status_t
1228 _notmuch_database_split_path (void *ctx,
1229                               const char *path,
1230                               const char **directory,
1231                               const char **basename)
1232 {
1233     const char *slash;
1234
1235     if (path == NULL || *path == '\0') {
1236         if (directory)
1237             *directory = NULL;
1238         if (basename)
1239             *basename = NULL;
1240         return NOTMUCH_STATUS_SUCCESS;
1241     }
1242
1243     /* Find the last slash (not counting a trailing slash), if any. */
1244
1245     slash = path + strlen (path) - 1;
1246
1247     /* First, skip trailing slashes. */
1248     while (slash != path && *slash == '/')
1249         --slash;
1250
1251     /* Then, find a slash. */
1252     while (slash != path && *slash != '/') {
1253         if (basename)
1254             *basename = slash;
1255
1256         --slash;
1257     }
1258
1259     /* Finally, skip multiple slashes. */
1260     while (slash != path && *(slash - 1) == '/')
1261         --slash;
1262
1263     if (slash == path) {
1264         if (directory)
1265             *directory = talloc_strdup (ctx, "");
1266         if (basename)
1267             *basename = path;
1268     } else {
1269         if (directory)
1270             *directory = talloc_strndup (ctx, path, slash - path);
1271     }
1272
1273     return NOTMUCH_STATUS_SUCCESS;
1274 }
1275
1276 /* Find the document ID of the specified directory.
1277  *
1278  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1279  * created if one does not exist for 'path'.  Otherwise, if the
1280  * directory document does not exist, this sets *directory_id to
1281  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1282  */
1283 notmuch_status_t
1284 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1285                                      const char *path,
1286                                      notmuch_find_flags_t flags,
1287                                      unsigned int *directory_id)
1288 {
1289     notmuch_directory_t *directory;
1290     notmuch_status_t status;
1291
1292     if (path == NULL) {
1293         *directory_id = 0;
1294         return NOTMUCH_STATUS_SUCCESS;
1295     }
1296
1297     directory = _notmuch_directory_find_or_create (notmuch, path, flags, &status);
1298     if (status || ! directory) {
1299         *directory_id = -1;
1300         return status;
1301     }
1302
1303     *directory_id = _notmuch_directory_get_document_id (directory);
1304
1305     notmuch_directory_destroy (directory);
1306
1307     return NOTMUCH_STATUS_SUCCESS;
1308 }
1309
1310 const char *
1311 _notmuch_database_get_directory_path (void *ctx,
1312                                       notmuch_database_t *notmuch,
1313                                       unsigned int doc_id)
1314 {
1315     Xapian::Document document;
1316
1317     document = find_document_for_doc_id (notmuch, doc_id);
1318
1319     return talloc_strdup (ctx, document.get_data ().c_str ());
1320 }
1321
1322 /* Given a legal 'filename' for the database, (either relative to
1323  * database path or absolute with initial components identical to
1324  * database path), return a new string (with 'ctx' as the talloc
1325  * owner) suitable for use as a direntry term value.
1326  *
1327  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1328  * will be created in the database as needed.  Otherwise, if the
1329  * necessary directory documents do not exist, this sets
1330  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1331  */
1332 notmuch_status_t
1333 _notmuch_database_filename_to_direntry (void *ctx,
1334                                         notmuch_database_t *notmuch,
1335                                         const char *filename,
1336                                         notmuch_find_flags_t flags,
1337                                         char **direntry)
1338 {
1339     const char *relative, *directory, *basename;
1340     Xapian::docid directory_id;
1341     notmuch_status_t status;
1342
1343     relative = _notmuch_database_relative_path (notmuch, filename);
1344
1345     status = _notmuch_database_split_path (ctx, relative,
1346                                            &directory, &basename);
1347     if (status)
1348         return status;
1349
1350     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1351                                                   &directory_id);
1352     if (status || directory_id == (unsigned int) -1) {
1353         *direntry = NULL;
1354         return status;
1355     }
1356
1357     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1358
1359     return NOTMUCH_STATUS_SUCCESS;
1360 }
1361
1362 /* Given a legal 'path' for the database, return the relative path.
1363  *
1364  * The return value will be a pointer to the original path contents,
1365  * and will be either the original string (if 'path' was relative) or
1366  * a portion of the string (if path was absolute and begins with the
1367  * database path).
1368  */
1369 const char *
1370 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1371                                  const char *path)
1372 {
1373     const char *db_path, *relative;
1374     unsigned int db_path_len;
1375
1376     db_path = notmuch_database_get_path (notmuch);
1377     db_path_len = strlen (db_path);
1378
1379     relative = path;
1380
1381     if (*relative == '/') {
1382         while (*relative == '/' && *(relative + 1) == '/')
1383             relative++;
1384
1385         if (strncmp (relative, db_path, db_path_len) == 0) {
1386             relative += db_path_len;
1387             while (*relative == '/')
1388                 relative++;
1389         }
1390     }
1391
1392     return relative;
1393 }
1394
1395 notmuch_status_t
1396 notmuch_database_get_directory (notmuch_database_t *notmuch,
1397                                 const char *path,
1398                                 notmuch_directory_t **directory)
1399 {
1400     notmuch_status_t status;
1401
1402     if (directory == NULL)
1403         return NOTMUCH_STATUS_NULL_POINTER;
1404     *directory = NULL;
1405
1406     try {
1407         *directory = _notmuch_directory_find_or_create (notmuch, path,
1408                                                         NOTMUCH_FIND_LOOKUP, &status);
1409     } catch (const Xapian::Error &error) {
1410         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1411                                error.get_msg ().c_str ());
1412         notmuch->exception_reported = true;
1413         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1414     }
1415     return status;
1416 }
1417
1418 /* Allocate a document ID that satisfies the following criteria:
1419  *
1420  * 1. The ID does not exist for any document in the Xapian database
1421  *
1422  * 2. The ID was not previously returned from this function
1423  *
1424  * 3. The ID is the smallest integer satisfying (1) and (2)
1425  *
1426  * This function will trigger an internal error if these constraints
1427  * cannot all be satisfied, (that is, the pool of available document
1428  * IDs has been exhausted).
1429  */
1430 unsigned int
1431 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1432 {
1433     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1434
1435     notmuch->last_doc_id++;
1436
1437     if (notmuch->last_doc_id == 0)
1438         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1439
1440     return notmuch->last_doc_id;
1441 }
1442
1443 notmuch_status_t
1444 notmuch_database_remove_message (notmuch_database_t *notmuch,
1445                                  const char *filename)
1446 {
1447     notmuch_status_t status;
1448     notmuch_message_t *message;
1449
1450     status = notmuch_database_find_message_by_filename (notmuch, filename,
1451                                                         &message);
1452
1453     if (status == NOTMUCH_STATUS_SUCCESS && message) {
1454         status = _notmuch_message_remove_filename (message, filename);
1455         if (status == NOTMUCH_STATUS_SUCCESS)
1456             _notmuch_message_delete (message);
1457         else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1458             _notmuch_message_sync (message);
1459
1460         notmuch_message_destroy (message);
1461     }
1462
1463     return status;
1464 }
1465
1466 notmuch_status_t
1467 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1468                                            const char *filename,
1469                                            notmuch_message_t **message_ret)
1470 {
1471     void *local;
1472     const char *prefix = _find_prefix ("file-direntry");
1473     char *direntry, *term;
1474     Xapian::PostingIterator i, end;
1475     notmuch_status_t status;
1476
1477     if (message_ret == NULL)
1478         return NOTMUCH_STATUS_NULL_POINTER;
1479
1480     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1481         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1482
1483     /* return NULL on any failure */
1484     *message_ret = NULL;
1485
1486     local = talloc_new (notmuch);
1487
1488     try {
1489         status = _notmuch_database_filename_to_direntry (
1490             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1491         if (status || ! direntry)
1492             goto DONE;
1493
1494         term = talloc_asprintf (local, "%s%s", prefix, direntry);
1495
1496         find_doc_ids_for_term (notmuch, term, &i, &end);
1497
1498         if (i != end) {
1499             notmuch_private_status_t private_status;
1500
1501             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1502                                                     &private_status);
1503             if (*message_ret == NULL)
1504                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1505         }
1506     } catch (const Xapian::Error &error) {
1507         _notmuch_database_log (notmuch,
1508                                "Error: A Xapian exception occurred finding message by filename: %s\n",
1509                                error.get_msg ().c_str ());
1510         notmuch->exception_reported = true;
1511         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1512     }
1513
1514   DONE:
1515     talloc_free (local);
1516
1517     if (status && *message_ret) {
1518         notmuch_message_destroy (*message_ret);
1519         *message_ret = NULL;
1520     }
1521     return status;
1522 }
1523
1524 notmuch_string_list_t *
1525 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1526                                          Xapian::TermIterator &end,
1527                                          const char *prefix)
1528 {
1529     int prefix_len = strlen (prefix);
1530     notmuch_string_list_t *list;
1531
1532     list = _notmuch_string_list_create (ctx);
1533     if (unlikely (list == NULL))
1534         return NULL;
1535
1536     for (i.skip_to (prefix); i != end; i++) {
1537         /* Terminate loop at first term without desired prefix. */
1538         if (strncmp ((*i).c_str (), prefix, prefix_len))
1539             break;
1540
1541         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1542     }
1543
1544     return list;
1545 }
1546
1547 notmuch_tags_t *
1548 notmuch_database_get_all_tags (notmuch_database_t *db)
1549 {
1550     Xapian::TermIterator i, end;
1551     notmuch_string_list_t *tags;
1552
1553     try {
1554         i = db->xapian_db->allterms_begin ();
1555         end = db->xapian_db->allterms_end ();
1556         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1557                                                         _find_prefix ("tag"));
1558         _notmuch_string_list_sort (tags);
1559         return _notmuch_tags_create (db, tags);
1560     } catch (const Xapian::Error &error) {
1561         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
1562                                error.get_msg ().c_str ());
1563         db->exception_reported = true;
1564         return NULL;
1565     }
1566 }
1567
1568 const char *
1569 notmuch_database_status_string (const notmuch_database_t *notmuch)
1570 {
1571     return notmuch->status_string;
1572 }