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