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