]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
eb7ed388d53a95f14afcd77c571a727474d262ed
[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_IGNORED:
297         return "Argument was ignored";
298     case NOTMUCH_STATUS_ILLEGAL_ARGUMENT:
299         return "Illegal argument for function";
300     case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
301         return "Crypto protocol missing, malformed, or unintelligible";
302     case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
303         return "Crypto engine initialization failure";
304     case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
305         return "Unknown crypto protocol";
306     case NOTMUCH_STATUS_NO_CONFIG:
307         return "No configuration file found";
308     case NOTMUCH_STATUS_NO_DATABASE:
309         return "No database found";
310     case NOTMUCH_STATUS_DATABASE_EXISTS:
311         return "Database exists, not recreated";
312     case NOTMUCH_STATUS_BAD_QUERY_SYNTAX:
313         return "Syntax error in query";
314     case NOTMUCH_STATUS_NO_MAIL_ROOT:
315         return "No mail root found";
316     case NOTMUCH_STATUS_ITERATOR_EXHAUSTED:
317         return "Iterator exhausted";
318     case NOTMUCH_STATUS_OPERATION_INVALIDATED:
319         return "Operation invalidated due to concurrent database modification";
320     default:
321     case NOTMUCH_STATUS_LAST_STATUS:
322         return "Unknown error status value";
323     }
324 }
325
326 void
327 _notmuch_database_log (notmuch_database_t *notmuch,
328                        const char *format,
329                        ...)
330 {
331     va_list va_args;
332
333     va_start (va_args, format);
334
335     if (notmuch->status_string)
336         talloc_free (notmuch->status_string);
337
338     notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
339     va_end (va_args);
340 }
341
342 void
343 _notmuch_database_log_append (notmuch_database_t *notmuch,
344                               const char *format,
345                               ...)
346 {
347     va_list va_args;
348
349     va_start (va_args, format);
350
351     if (notmuch->status_string)
352         notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
353     else
354         notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
355
356     va_end (va_args);
357 }
358
359 static void
360 find_doc_ids_for_term (notmuch_database_t *notmuch,
361                        const char *term,
362                        Xapian::PostingIterator *begin,
363                        Xapian::PostingIterator *end)
364 {
365     *begin = notmuch->xapian_db->postlist_begin (term);
366
367     *end = notmuch->xapian_db->postlist_end (term);
368 }
369
370 void
371 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
372                                 const char *prefix_name,
373                                 const char *value,
374                                 Xapian::PostingIterator *begin,
375                                 Xapian::PostingIterator *end)
376 {
377     char *term;
378
379     term = talloc_asprintf (notmuch, "%s%s",
380                             _find_prefix (prefix_name), value);
381
382     find_doc_ids_for_term (notmuch, term, begin, end);
383
384     talloc_free (term);
385 }
386
387 notmuch_private_status_t
388 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
389                                       const char *prefix_name,
390                                       const char *value,
391                                       unsigned int *doc_id)
392 {
393     Xapian::PostingIterator i, end;
394
395     _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
396
397     if (i == end) {
398         *doc_id = 0;
399         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
400     }
401
402     *doc_id = *i;
403
404 #if DEBUG_DATABASE_SANITY
405     i++;
406
407     if (i != end)
408         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
409                         prefix_name, value);
410 #endif
411
412     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
413 }
414
415 static Xapian::Document
416 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
417 {
418     return notmuch->xapian_db->get_document (doc_id);
419 }
420
421 /* Generate a compressed version of 'message_id' of the form:
422  *
423  *      notmuch-sha1-<sha1_sum_of_message_id>
424  */
425 char *
426 _notmuch_message_id_compressed (void *ctx, const char *message_id)
427 {
428     char *sha1, *compressed;
429
430     sha1 = _notmuch_sha1_of_string (message_id);
431
432     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
433     free (sha1);
434
435     return compressed;
436 }
437
438 notmuch_status_t
439 notmuch_database_find_message (notmuch_database_t *notmuch,
440                                const char *message_id,
441                                notmuch_message_t **message_ret)
442 {
443     notmuch_private_status_t status;
444     unsigned int doc_id;
445
446     if (message_ret == NULL)
447         return NOTMUCH_STATUS_NULL_POINTER;
448
449     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
450         message_id = _notmuch_message_id_compressed (notmuch, message_id);
451
452     try {
453         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
454                                                        message_id, &doc_id);
455
456         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
457             *message_ret = NULL;
458         else {
459             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
460                                                     NULL);
461             if (*message_ret == NULL)
462                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
463         }
464
465         return NOTMUCH_STATUS_SUCCESS;
466     } catch (const Xapian::Error &error) {
467         _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
468                                error.get_msg ().c_str ());
469         notmuch->exception_reported = true;
470         *message_ret = NULL;
471         return _notmuch_xapian_error ();
472     }
473 }
474
475 notmuch_status_t
476 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
477 {
478     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY) {
479         _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
480         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
481     }
482
483     if (! notmuch->open) {
484         _notmuch_database_log (notmuch, "Cannot write to a closed database.\n");
485         return NOTMUCH_STATUS_CLOSED_DATABASE;
486     }
487
488     return NOTMUCH_STATUS_SUCCESS;
489 }
490
491 /* Allocate a revision number for the next change. */
492 unsigned long
493 _notmuch_database_new_revision (notmuch_database_t *notmuch)
494 {
495     unsigned long new_revision = notmuch->revision + 1;
496
497     /* If we're in an atomic section, hold off on updating the
498      * committed revision number until we commit the atomic section.
499      */
500     if (notmuch->atomic_nesting)
501         notmuch->atomic_dirty = true;
502     else
503         notmuch->revision = new_revision;
504
505     return new_revision;
506 }
507
508 notmuch_status_t
509 notmuch_database_close (notmuch_database_t *notmuch)
510 {
511     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
512
513     /* Many Xapian objects (and thus notmuch objects) hold references to
514      * the database, so merely deleting the database may not suffice to
515      * close it.  Thus, we explicitly close it here. */
516     if (notmuch->open) {
517         try {
518             /* Close the database.  This implicitly flushes
519              * outstanding changes. If there is an open (non-flushed)
520              * transaction, ALL pending changes will be discarded */
521             notmuch->xapian_db->close ();
522         } catch (const Xapian::Error &error) {
523             status = _notmuch_xapian_error ();
524             if (! notmuch->exception_reported) {
525                 _notmuch_database_log (notmuch,
526                                        "Error: A Xapian exception occurred closing database: %s\n",
527                                        error.get_msg ().c_str ());
528             }
529         }
530     }
531     notmuch->open = false;
532     return status;
533 }
534
535 static int
536 unlink_cb (const char *path,
537            unused (const struct stat *sb),
538            unused (int type),
539            unused (struct FTW *ftw))
540 {
541     return remove (path);
542 }
543
544 static int
545 rmtree (const char *path)
546 {
547     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
548 }
549
550 class NotmuchCompactor : public Xapian::Compactor
551 {
552     notmuch_compact_status_cb_t status_cb;
553     void *status_closure;
554
555 public:
556     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
557         status_cb (cb), status_closure (closure)
558     {
559     }
560
561     virtual void
562     set_status (const std::string &table, const std::string &status)
563     {
564         char *msg;
565
566         if (status_cb == NULL)
567             return;
568
569         if (status.length () == 0)
570             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
571         else
572             msg = talloc_asprintf (NULL, "     %s", status.c_str ());
573
574         if (msg == NULL) {
575             return;
576         }
577
578         status_cb (msg, status_closure);
579         talloc_free (msg);
580     }
581 };
582
583 /* Compacts the given database, optionally saving the original database
584  * in backup_path. Additionally, a callback function can be provided to
585  * give the user feedback on the progress of the (likely long-lived)
586  * compaction process.
587  *
588  * The backup path must point to a directory on the same volume as the
589  * original database. Passing a NULL backup_path will result in the
590  * uncompacted database being deleted after compaction has finished.
591  * Note that the database write lock will be held during the
592  * compaction process to protect data integrity.
593  */
594 notmuch_status_t
595 notmuch_database_compact (const char *path,
596                           const char *backup_path,
597                           notmuch_compact_status_cb_t status_cb,
598                           void *closure)
599 {
600     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
601     notmuch_database_t *notmuch = NULL;
602     char *message = NULL;
603
604     ret = notmuch_database_open_with_config (path,
605                                              NOTMUCH_DATABASE_MODE_READ_WRITE,
606                                              "",
607                                              NULL,
608                                              &notmuch,
609                                              &message);
610     if (ret) {
611         if (status_cb) status_cb (message, closure);
612         return ret;
613     }
614
615     _notmuch_config_cache (notmuch, NOTMUCH_CONFIG_DATABASE_PATH, path);
616
617     return notmuch_database_compact_db (notmuch,
618                                         backup_path,
619                                         status_cb,
620                                         closure);
621 }
622
623 notmuch_status_t
624 notmuch_database_compact_db (notmuch_database_t *notmuch,
625                              const char *backup_path,
626                              notmuch_compact_status_cb_t status_cb,
627                              void *closure)
628 {
629     void *local;
630     const char *xapian_path, *compact_xapian_path;
631     const char *path;
632     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
633     struct stat statbuf;
634     bool keep_backup;
635     char *message;
636
637     ret = _notmuch_database_ensure_writable (notmuch);
638     if (ret)
639         return ret;
640
641     path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_PATH);
642     if (! path)
643         return NOTMUCH_STATUS_PATH_ERROR;
644
645     local = talloc_new (NULL);
646     if (! local)
647         return NOTMUCH_STATUS_OUT_OF_MEMORY;
648
649     ret = _notmuch_choose_xapian_path (local, path, &xapian_path, &message);
650     if (ret)
651         goto DONE;
652
653     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
654         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
655         goto DONE;
656     }
657
658     if (backup_path == NULL) {
659         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
660             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
661             goto DONE;
662         }
663         keep_backup = false;
664     } else {
665         keep_backup = true;
666     }
667
668     if (stat (backup_path, &statbuf) != -1) {
669         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
670         ret = NOTMUCH_STATUS_FILE_ERROR;
671         goto DONE;
672     }
673     if (errno != ENOENT) {
674         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
675                                strerror (errno));
676         ret = NOTMUCH_STATUS_FILE_ERROR;
677         goto DONE;
678     }
679
680     /* Unconditionally attempt to remove old work-in-progress database (if
681      * any). This is "protected" by database lock. If this fails due to write
682      * errors (etc), the following code will fail and provide error message.
683      */
684     (void) rmtree (compact_xapian_path);
685
686     try {
687         NotmuchCompactor compactor (status_cb, closure);
688         notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0,
689                                      compactor);
690     } catch (const Xapian::Error &error) {
691         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
692         ret = _notmuch_xapian_error ();
693         goto DONE;
694     }
695
696     if (rename (xapian_path, backup_path)) {
697         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
698                                xapian_path, backup_path, strerror (errno));
699         ret = NOTMUCH_STATUS_FILE_ERROR;
700         goto DONE;
701     }
702
703     if (rename (compact_xapian_path, xapian_path)) {
704         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
705                                compact_xapian_path, xapian_path, strerror (errno));
706         ret = NOTMUCH_STATUS_FILE_ERROR;
707         goto DONE;
708     }
709
710     if (! keep_backup) {
711         if (rmtree (backup_path)) {
712             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
713                                    backup_path, strerror (errno));
714             ret = NOTMUCH_STATUS_FILE_ERROR;
715             goto DONE;
716         }
717     }
718
719   DONE:
720     if (notmuch) {
721         notmuch_status_t ret2;
722
723         const char *str = notmuch_database_status_string (notmuch);
724         if (status_cb && str)
725             status_cb (str, closure);
726
727         ret2 = notmuch_database_destroy (notmuch);
728
729         /* don't clobber previous error status */
730         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
731             ret = ret2;
732     }
733
734     talloc_free (local);
735
736     return ret;
737 }
738
739 notmuch_status_t
740 notmuch_database_destroy (notmuch_database_t *notmuch)
741 {
742     notmuch_status_t status;
743     const char *talloc_report;
744
745     talloc_report = getenv ("NOTMUCH_TALLOC_REPORT");
746     if (talloc_report && strcmp (talloc_report, "") != 0) {
747         FILE *report = fopen (talloc_report, "a");
748         if (report) {
749             talloc_report_full (notmuch, report);
750         }
751     }
752
753     status = notmuch_database_close (notmuch);
754
755     delete notmuch->term_gen;
756     notmuch->term_gen = NULL;
757     delete notmuch->query_parser;
758     notmuch->query_parser = NULL;
759     delete notmuch->xapian_db;
760     notmuch->xapian_db = NULL;
761     delete notmuch->value_range_processor;
762     notmuch->value_range_processor = NULL;
763     delete notmuch->date_range_processor;
764     notmuch->date_range_processor = NULL;
765     delete notmuch->last_mod_range_processor;
766     notmuch->last_mod_range_processor = NULL;
767     delete notmuch->stemmer;
768     notmuch->stemmer = 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_config_get (notmuch, NOTMUCH_CONFIG_DATABASE_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     if (_notmuch_database_mode (notmuch) != NOTMUCH_DATABASE_MODE_READ_WRITE)
865         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
866
867     db = notmuch->writable_xapian_db;
868
869     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
870     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
871
872     if (! notmuch_database_needs_upgrade (notmuch))
873         return NOTMUCH_STATUS_SUCCESS;
874
875     if (progress_notify) {
876         /* Set up our handler for SIGALRM */
877         memset (&action, 0, sizeof (struct sigaction));
878         action.sa_handler = handle_sigalrm;
879         sigemptyset (&action.sa_mask);
880         action.sa_flags = SA_RESTART;
881         sigaction (SIGALRM, &action, NULL);
882
883         /* Then start a timer to send SIGALRM once per second. */
884         timerval.it_interval.tv_sec = 1;
885         timerval.it_interval.tv_usec = 0;
886         timerval.it_value.tv_sec = 1;
887         timerval.it_value.tv_usec = 0;
888         setitimer (ITIMER_REAL, &timerval, NULL);
889
890         timer_is_active = true;
891     }
892
893     /* Figure out how much total work we need to do. */
894     if (new_features &
895         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
896          NOTMUCH_FEATURE_LAST_MOD)) {
897         query = notmuch_query_create (notmuch, "");
898         unsigned msg_count;
899
900         status = notmuch_query_count_messages (query, &msg_count);
901         if (status)
902             goto DONE;
903
904         total += msg_count;
905         notmuch_query_destroy (query);
906         query = NULL;
907     }
908     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
909         t_end = db->allterms_end ("XTIMESTAMP");
910         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
911             ++total;
912     }
913     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
914         /* The ghost message upgrade converts all thread_id_*
915          * metadata values into ghost message documents. */
916         t_end = db->metadata_keys_end ("thread_id_");
917         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
918             ++total;
919     }
920
921     /* Perform the upgrade in a transaction. */
922     db->begin_transaction (true);
923
924     /* Set the target features so we write out changes in the desired
925      * format. */
926     notmuch->features = target_features;
927
928     /* Perform per-message upgrades. */
929     if (new_features &
930         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
931          NOTMUCH_FEATURE_LAST_MOD)) {
932         notmuch_messages_t *messages;
933         notmuch_message_t *message;
934         char *filename;
935
936         query = notmuch_query_create (notmuch, "");
937
938         status = notmuch_query_search_messages (query, &messages);
939         if (status)
940             goto DONE;
941         for (;
942              notmuch_messages_valid (messages);
943              notmuch_messages_move_to_next (messages)) {
944             if (do_progress_notify) {
945                 progress_notify (closure, (double) count / total);
946                 do_progress_notify = 0;
947             }
948
949             message = notmuch_messages_get (messages);
950
951             /* Before version 1, each message document had its
952              * filename in the data field. Copy that into the new
953              * format by calling notmuch_message_add_filename.
954              */
955             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
956                 filename = _notmuch_message_talloc_copy_data (message);
957                 if (filename && *filename != '\0') {
958                     _notmuch_message_add_filename (message, filename);
959                     _notmuch_message_clear_data (message);
960                 }
961                 talloc_free (filename);
962             }
963
964             /* Prior to version 2, the "folder:" prefix was
965              * probabilistic and stemmed. Change it to the current
966              * boolean prefix. Add "path:" prefixes while at it.
967              */
968             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
969                 _notmuch_message_upgrade_folder (message);
970
971             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
972              * track modification revisions.  Give all messages the
973              * next available revision; since we just started tracking
974              * revisions for this database, that will be 1.
975              */
976             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
977                 _notmuch_message_upgrade_last_mod (message);
978
979             _notmuch_message_sync (message);
980
981             notmuch_message_destroy (message);
982
983             count++;
984         }
985
986         notmuch_query_destroy (query);
987         query = NULL;
988     }
989
990     /* Perform per-directory upgrades. */
991
992     /* Before version 1 we stored directory timestamps in
993      * XTIMESTAMP documents instead of the current XDIRECTORY
994      * documents. So copy those as well. */
995     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
996         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
997
998         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
999              t != t_end;
1000              t++) {
1001             Xapian::PostingIterator p, p_end;
1002             std::string term = *t;
1003
1004             p_end = notmuch->xapian_db->postlist_end (term);
1005
1006             for (p = notmuch->xapian_db->postlist_begin (term);
1007                  p != p_end;
1008                  p++) {
1009                 Xapian::Document document;
1010                 time_t mtime;
1011                 notmuch_directory_t *directory;
1012
1013                 if (do_progress_notify) {
1014                     progress_notify (closure, (double) count / total);
1015                     do_progress_notify = 0;
1016                 }
1017
1018                 document = find_document_for_doc_id (notmuch, *p);
1019                 mtime = Xapian::sortable_unserialise (
1020                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1021
1022                 directory = _notmuch_directory_find_or_create (notmuch, term.c_str () + 10,
1023                                                                NOTMUCH_FIND_CREATE, &status);
1024                 notmuch_directory_set_mtime (directory, mtime);
1025                 notmuch_directory_destroy (directory);
1026
1027                 db->delete_document (*p);
1028             }
1029
1030             ++count;
1031         }
1032     }
1033
1034     /* Perform metadata upgrades. */
1035
1036     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1037      * messages were stored as database metadata. Change these to
1038      * ghost messages.
1039      */
1040     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1041         notmuch_message_t *message;
1042         std::string message_id, thread_id;
1043
1044         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1045         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1046              t != t_end; ++t) {
1047             if (do_progress_notify) {
1048                 progress_notify (closure, (double) count / total);
1049                 do_progress_notify = 0;
1050             }
1051
1052             message_id = (*t).substr (
1053                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1054             thread_id = db->get_metadata (*t);
1055
1056             /* Create ghost message */
1057             message = _notmuch_message_create_for_message_id (
1058                 notmuch, message_id.c_str (), &private_status);
1059             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1060                 /* Document already exists; ignore the stored thread ID */
1061             } else if (private_status ==
1062                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1063                 private_status = _notmuch_message_initialize_ghost (
1064                     message, thread_id.c_str ());
1065                 if (! private_status)
1066                     _notmuch_message_sync (message);
1067             }
1068
1069             if (private_status) {
1070                 _notmuch_database_log (notmuch,
1071                                        "Upgrade failed while creating ghost messages.\n");
1072                 status = COERCE_STATUS (private_status,
1073                                         "Unexpected status from _notmuch_message_initialize_ghost");
1074                 goto DONE;
1075             }
1076
1077             /* Clear saved metadata thread ID */
1078             db->set_metadata (*t, "");
1079
1080             ++count;
1081         }
1082     }
1083
1084     status = NOTMUCH_STATUS_SUCCESS;
1085     db->set_metadata ("features", _notmuch_database_print_features (local, notmuch->features));
1086     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1087
1088   DONE:
1089     if (status == NOTMUCH_STATUS_SUCCESS)
1090         db->commit_transaction ();
1091     else
1092         db->cancel_transaction ();
1093
1094     if (timer_is_active) {
1095         /* Now stop the timer. */
1096         timerval.it_interval.tv_sec = 0;
1097         timerval.it_interval.tv_usec = 0;
1098         timerval.it_value.tv_sec = 0;
1099         timerval.it_value.tv_usec = 0;
1100         setitimer (ITIMER_REAL, &timerval, NULL);
1101
1102         /* And disable the signal handler. */
1103         action.sa_handler = SIG_IGN;
1104         sigaction (SIGALRM, &action, NULL);
1105     }
1106
1107     if (query)
1108         notmuch_query_destroy (query);
1109
1110     talloc_free (local);
1111     return status;
1112 }
1113
1114 notmuch_status_t
1115 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1116 {
1117     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1118         notmuch->atomic_nesting > 0)
1119         goto DONE;
1120
1121     if (notmuch_database_needs_upgrade (notmuch))
1122         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1123
1124     try {
1125         notmuch->writable_xapian_db->begin_transaction (false);
1126     } catch (const Xapian::Error &error) {
1127         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1128                                error.get_msg ().c_str ());
1129         notmuch->exception_reported = true;
1130         return _notmuch_xapian_error ();
1131     }
1132
1133   DONE:
1134     notmuch->atomic_nesting++;
1135     return NOTMUCH_STATUS_SUCCESS;
1136 }
1137
1138 notmuch_status_t
1139 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1140 {
1141     Xapian::WritableDatabase *db;
1142
1143     if (notmuch->atomic_nesting == 0)
1144         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1145
1146     if (_notmuch_database_mode (notmuch) == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1147         notmuch->atomic_nesting > 1)
1148         goto DONE;
1149
1150     db = notmuch->writable_xapian_db;
1151     try {
1152         db->commit_transaction ();
1153         notmuch->transaction_count++;
1154
1155         /* Xapian never flushes on a non-flushed commit, even if the
1156          * flush threshold is 1.  However, we rely on flushing to test
1157          * atomicity. On the other hand, we can't straight replace
1158          * XAPIAN_FLUSH_THRESHOLD with our autocommit counter, because
1159          * the former also applies outside notmuch atomic
1160          * commits. Hence the follow complicated  test */
1161         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1162         if ((notmuch->transaction_threshold > 0 &&
1163              notmuch->transaction_count >= notmuch->transaction_threshold) ||
1164             (thresh && atoi (thresh) == 1)) {
1165             db->commit ();
1166             notmuch->transaction_count = 0;
1167         }
1168     } catch (const Xapian::Error &error) {
1169         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1170                                error.get_msg ().c_str ());
1171         notmuch->exception_reported = true;
1172         return _notmuch_xapian_error ();
1173     }
1174
1175     if (notmuch->atomic_dirty) {
1176         ++notmuch->revision;
1177         notmuch->atomic_dirty = false;
1178     }
1179
1180   DONE:
1181     notmuch->atomic_nesting--;
1182     return NOTMUCH_STATUS_SUCCESS;
1183 }
1184
1185 unsigned long
1186 notmuch_database_get_revision (notmuch_database_t *notmuch,
1187                                const char **uuid)
1188 {
1189     if (uuid)
1190         *uuid = notmuch->uuid;
1191     return notmuch->revision;
1192 }
1193
1194 /* We allow the user to use arbitrarily long paths for directories. But
1195  * we have a term-length limit. So if we exceed that, we'll use the
1196  * SHA-1 of the path for the database term.
1197  *
1198  * Note: This function may return the original value of 'path'. If it
1199  * does not, then the caller is responsible to free() the returned
1200  * value.
1201  */
1202 const char *
1203 _notmuch_database_get_directory_db_path (const char *path)
1204 {
1205     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1206
1207     if (term_len > NOTMUCH_TERM_MAX)
1208         return _notmuch_sha1_of_string (path);
1209     else
1210         return path;
1211 }
1212
1213 /* Given a path, split it into two parts: the directory part is all
1214  * components except for the last, and the basename is that last
1215  * component. Getting the return-value for either part is optional
1216  * (the caller can pass NULL).
1217  *
1218  * The original 'path' can represent either a regular file or a
1219  * directory---the splitting will be carried out in the same way in
1220  * either case. Trailing slashes on 'path' will be ignored, and any
1221  * cases of multiple '/' characters appearing in series will be
1222  * treated as a single '/'.
1223  *
1224  * Allocation (if any) will have 'ctx' as the talloc owner. But
1225  * pointers will be returned within the original path string whenever
1226  * possible.
1227  *
1228  * Note: If 'path' is non-empty and contains no non-trailing slash,
1229  * (that is, consists of a filename with no parent directory), then
1230  * the directory returned will be an empty string. However, if 'path'
1231  * is an empty string, then both directory and basename will be
1232  * returned as NULL.
1233  */
1234 notmuch_status_t
1235 _notmuch_database_split_path (void *ctx,
1236                               const char *path,
1237                               const char **directory,
1238                               const char **basename)
1239 {
1240     const char *slash;
1241
1242     if (path == NULL || *path == '\0') {
1243         if (directory)
1244             *directory = NULL;
1245         if (basename)
1246             *basename = NULL;
1247         return NOTMUCH_STATUS_SUCCESS;
1248     }
1249
1250     /* Find the last slash (not counting a trailing slash), if any. */
1251
1252     slash = path + strlen (path) - 1;
1253
1254     /* First, skip trailing slashes. */
1255     while (slash != path && *slash == '/')
1256         --slash;
1257
1258     /* Then, find a slash. */
1259     while (slash != path && *slash != '/') {
1260         if (basename)
1261             *basename = slash;
1262
1263         --slash;
1264     }
1265
1266     /* Finally, skip multiple slashes. */
1267     while (slash != path && *(slash - 1) == '/')
1268         --slash;
1269
1270     if (slash == path) {
1271         if (directory)
1272             *directory = talloc_strdup (ctx, "");
1273         if (basename)
1274             *basename = path;
1275     } else {
1276         if (directory)
1277             *directory = talloc_strndup (ctx, path, slash - path);
1278     }
1279
1280     return NOTMUCH_STATUS_SUCCESS;
1281 }
1282
1283 /* Find the document ID of the specified directory.
1284  *
1285  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1286  * created if one does not exist for 'path'.  Otherwise, if the
1287  * directory document does not exist, this sets *directory_id to
1288  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1289  */
1290 notmuch_status_t
1291 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1292                                      const char *path,
1293                                      notmuch_find_flags_t flags,
1294                                      unsigned int *directory_id)
1295 {
1296     notmuch_directory_t *directory;
1297     notmuch_status_t status;
1298
1299     if (path == NULL) {
1300         *directory_id = 0;
1301         return NOTMUCH_STATUS_SUCCESS;
1302     }
1303
1304     directory = _notmuch_directory_find_or_create (notmuch, path, flags, &status);
1305     if (status || ! directory) {
1306         *directory_id = -1;
1307         return status;
1308     }
1309
1310     *directory_id = _notmuch_directory_get_document_id (directory);
1311
1312     notmuch_directory_destroy (directory);
1313
1314     return NOTMUCH_STATUS_SUCCESS;
1315 }
1316
1317 const char *
1318 _notmuch_database_get_directory_path (void *ctx,
1319                                       notmuch_database_t *notmuch,
1320                                       unsigned int doc_id)
1321 {
1322     Xapian::Document document;
1323
1324     document = find_document_for_doc_id (notmuch, doc_id);
1325
1326     return talloc_strdup (ctx, document.get_data ().c_str ());
1327 }
1328
1329 /* Given a legal 'filename' for the database, (either relative to
1330  * database path or absolute with initial components identical to
1331  * database path), return a new string (with 'ctx' as the talloc
1332  * owner) suitable for use as a direntry term value.
1333  *
1334  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1335  * will be created in the database as needed.  Otherwise, if the
1336  * necessary directory documents do not exist, this sets
1337  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1338  */
1339 notmuch_status_t
1340 _notmuch_database_filename_to_direntry (void *ctx,
1341                                         notmuch_database_t *notmuch,
1342                                         const char *filename,
1343                                         notmuch_find_flags_t flags,
1344                                         char **direntry)
1345 {
1346     const char *relative, *directory, *basename;
1347     Xapian::docid directory_id;
1348     notmuch_status_t status;
1349
1350     relative = _notmuch_database_relative_path (notmuch, filename);
1351
1352     status = _notmuch_database_split_path (ctx, relative,
1353                                            &directory, &basename);
1354     if (status)
1355         return status;
1356
1357     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1358                                                   &directory_id);
1359     if (status || directory_id == (unsigned int) -1) {
1360         *direntry = NULL;
1361         return status;
1362     }
1363
1364     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1365
1366     return NOTMUCH_STATUS_SUCCESS;
1367 }
1368
1369 /* Given a legal 'path' for the database, return the relative path.
1370  *
1371  * The return value will be a pointer to the original path contents,
1372  * and will be either the original string (if 'path' was relative) or
1373  * a portion of the string (if path was absolute and begins with the
1374  * database path).
1375  */
1376 const char *
1377 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1378                                  const char *path)
1379 {
1380     const char *db_path, *relative;
1381     unsigned int db_path_len;
1382
1383     db_path = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
1384     db_path_len = strlen (db_path);
1385
1386     relative = path;
1387
1388     if (*relative == '/') {
1389         while (*relative == '/' && *(relative + 1) == '/')
1390             relative++;
1391
1392         if (strncmp (relative, db_path, db_path_len) == 0) {
1393             relative += db_path_len;
1394             while (*relative == '/')
1395                 relative++;
1396         }
1397     }
1398
1399     return relative;
1400 }
1401
1402 notmuch_status_t
1403 notmuch_database_get_directory (notmuch_database_t *notmuch,
1404                                 const char *path,
1405                                 notmuch_directory_t **directory)
1406 {
1407     notmuch_status_t status;
1408
1409     if (directory == NULL)
1410         return NOTMUCH_STATUS_NULL_POINTER;
1411     *directory = NULL;
1412
1413     try {
1414         *directory = _notmuch_directory_find_or_create (notmuch, path,
1415                                                         NOTMUCH_FIND_LOOKUP, &status);
1416     } catch (const Xapian::Error &error) {
1417         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1418                                error.get_msg ().c_str ());
1419         notmuch->exception_reported = true;
1420         status = _notmuch_xapian_error ();
1421     }
1422     return status;
1423 }
1424
1425 /* Allocate a document ID that satisfies the following criteria:
1426  *
1427  * 1. The ID does not exist for any document in the Xapian database
1428  *
1429  * 2. The ID was not previously returned from this function
1430  *
1431  * 3. The ID is the smallest integer satisfying (1) and (2)
1432  *
1433  * This function will trigger an internal error if these constraints
1434  * cannot all be satisfied, (that is, the pool of available document
1435  * IDs has been exhausted).
1436  */
1437 unsigned int
1438 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1439 {
1440     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1441
1442     notmuch->last_doc_id++;
1443
1444     if (notmuch->last_doc_id == 0)
1445         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1446
1447     return notmuch->last_doc_id;
1448 }
1449
1450 notmuch_status_t
1451 notmuch_database_remove_message (notmuch_database_t *notmuch,
1452                                  const char *filename)
1453 {
1454     notmuch_status_t status;
1455     notmuch_message_t *message;
1456
1457     status = notmuch_database_find_message_by_filename (notmuch, filename,
1458                                                         &message);
1459
1460     if (status == NOTMUCH_STATUS_SUCCESS && message) {
1461         if (notmuch_message_count_files (message) > 1) {
1462             status = _notmuch_message_remove_filename (message, filename);
1463         }
1464         if (status == NOTMUCH_STATUS_SUCCESS)
1465             status = _notmuch_message_delete (message);
1466         else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1467             _notmuch_message_sync (message);
1468
1469         notmuch_message_destroy (message);
1470     }
1471
1472     return status;
1473 }
1474
1475 notmuch_status_t
1476 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1477                                            const char *filename,
1478                                            notmuch_message_t **message_ret)
1479 {
1480     void *local;
1481     const char *prefix = _find_prefix ("file-direntry");
1482     char *direntry, *term;
1483     Xapian::PostingIterator i, end;
1484     notmuch_status_t status;
1485
1486     if (message_ret == NULL)
1487         return NOTMUCH_STATUS_NULL_POINTER;
1488
1489     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1490         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1491
1492     /* return NULL on any failure */
1493     *message_ret = NULL;
1494
1495     local = talloc_new (notmuch);
1496
1497     try {
1498         status = _notmuch_database_filename_to_direntry (
1499             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1500         if (status || ! direntry)
1501             goto DONE;
1502
1503         term = talloc_asprintf (local, "%s%s", prefix, direntry);
1504
1505         find_doc_ids_for_term (notmuch, term, &i, &end);
1506
1507         if (i != end) {
1508             notmuch_private_status_t private_status;
1509
1510             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1511                                                     &private_status);
1512             if (*message_ret == NULL)
1513                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1514         }
1515     } catch (const Xapian::Error &error) {
1516         _notmuch_database_log (notmuch,
1517                                "Error: A Xapian exception occurred finding message by filename: %s\n",
1518                                error.get_msg ().c_str ());
1519         notmuch->exception_reported = true;
1520         status = _notmuch_xapian_error ();
1521     }
1522
1523   DONE:
1524     talloc_free (local);
1525
1526     if (status && *message_ret) {
1527         notmuch_message_destroy (*message_ret);
1528         *message_ret = NULL;
1529     }
1530     return status;
1531 }
1532
1533 notmuch_string_list_t *
1534 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1535                                          Xapian::TermIterator &end,
1536                                          const char *prefix)
1537 {
1538     int prefix_len = strlen (prefix);
1539     notmuch_string_list_t *list;
1540
1541     list = _notmuch_string_list_create (ctx);
1542     if (unlikely (list == NULL))
1543         return NULL;
1544
1545     for (i.skip_to (prefix); i != end; i++) {
1546         /* Terminate loop at first term without desired prefix. */
1547         if (strncmp ((*i).c_str (), prefix, prefix_len))
1548             break;
1549
1550         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1551     }
1552
1553     return list;
1554 }
1555
1556 notmuch_tags_t *
1557 notmuch_database_get_all_tags (notmuch_database_t *db)
1558 {
1559     Xapian::TermIterator i, end;
1560     notmuch_string_list_t *tags;
1561
1562     try {
1563         i = db->xapian_db->allterms_begin ();
1564         end = db->xapian_db->allterms_end ();
1565         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1566                                                         _find_prefix ("tag"));
1567         _notmuch_string_list_sort (tags);
1568         return _notmuch_tags_create (db, tags);
1569     } catch (const Xapian::Error &error) {
1570         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
1571                                error.get_msg ().c_str ());
1572         db->exception_reported = true;
1573         return NULL;
1574     }
1575 }
1576
1577 const char *
1578 notmuch_database_status_string (const notmuch_database_t *notmuch)
1579 {
1580     return notmuch->status_string;
1581 }
1582
1583 bool
1584 _notmuch_database_indexable_as_text (notmuch_database_t *notmuch, const char *mime_string)
1585 {
1586     for (size_t i = 0; i < notmuch->index_as_text_length; i++) {
1587         if (regexec (&notmuch->index_as_text[i], mime_string, 0, NULL, 0) == 0) {
1588             return true;
1589         }
1590     }
1591
1592     return false;
1593 }