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