]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib/n_d_needs_upgrade: handle error return from n_d_get_version
[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 "parse-time-vrp.h"
23 #include "query-fp.h"
24 #include "thread-fp.h"
25 #include "regexp-fields.h"
26 #include "string-util.h"
27
28 #include <iostream>
29
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <signal.h>
33 #include <ftw.h>
34
35 #include <glib.h>               /* g_free, GPtrArray, GHashTable */
36 #include <glib-object.h>        /* g_type_init */
37
38 #include <gmime/gmime.h>        /* g_mime_init */
39
40 using namespace std;
41
42 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
43
44 typedef struct {
45     const char *name;
46     const char *prefix;
47     notmuch_field_flag_t flags;
48 } prefix_t;
49
50 #define NOTMUCH_DATABASE_VERSION 3
51
52 #define STRINGIFY(s) _SUB_STRINGIFY (s)
53 #define _SUB_STRINGIFY(s) #s
54
55 #if HAVE_XAPIAN_DB_RETRY_LOCK
56 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
57 #else
58 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
59 #endif
60
61 #define LOG_XAPIAN_EXCEPTION(message, error) _log_xapian_exception (__location__, message, error)
62
63 static void
64 _log_xapian_exception (const char *where, notmuch_database_t *notmuch,  const Xapian::Error error) {
65     _notmuch_database_log (notmuch,
66                            "A Xapian exception occurred at %s: %s\n",
67                            where,
68                            error.get_msg ().c_str ());
69     notmuch->exception_reported = true;
70 }
71
72 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
73  *
74  * We currently have three different types of documents (mail, ghost,
75  * and directory) and also some metadata.
76  *
77  * There are two kinds of prefixes used in notmuch. There are the
78  * human friendly 'prefix names' like "thread:", which are also used
79  * in the query parser, and the actual prefix terms in the database
80  * (e.g. "G"). The correspondence is maintained in the file scope data
81  * structure 'prefix_table'.
82  *
83  * Mail document
84  * -------------
85  * A mail document is associated with a particular email message. It
86  * is stored in one or more files on disk and is uniquely identified
87  * by its "id" field (which is generally the message ID). It is
88  * indexed with the following prefixed terms which the database uses
89  * to construct threads, etc.:
90  *
91  *    Single terms of given prefix:
92  *
93  *      type:   mail
94  *
95  *      id:     Unique ID of mail. This is from the Message-ID header
96  *              if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
97  *              If it's present and too long, then we use
98  *              "notmuch-sha1-<sha1_sum_of_message_id>".
99  *              If this header is not present, we use
100  *              "notmuch-sha1-<sha1_sum_of_entire_file>".
101  *
102  *      thread: The ID of the thread to which the mail belongs
103  *
104  *      replyto: The ID from the In-Reply-To header of the mail (if any).
105  *
106  *    Multiple terms of given prefix:
107  *
108  *      reference: All message IDs from In-Reply-To and References
109  *                 headers in the message.
110  *
111  *      tag:       Any tags associated with this message by the user.
112  *
113  *      file-direntry:  A colon-separated pair of values
114  *                      (INTEGER:STRING), where INTEGER is the
115  *                      document ID of a directory document, and
116  *                      STRING is the name of a file within that
117  *                      directory for this mail message.
118  *
119  *      property:       Has a property with key=value
120  *                 FIXME: if no = is present, should match on any value
121  *
122  *    A mail document also has four values:
123  *
124  *      TIMESTAMP:      The time_t value corresponding to the message's
125  *                      Date header.
126  *
127  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
128  *
129  *      FROM:           The value of the "From" header
130  *
131  *      SUBJECT:        The value of the "Subject" header
132  *
133  *      LAST_MOD:       The revision number as of the last tag or
134  *                      filename change.
135  *
136  * The prefixed terms described above are also searchable without an
137  * explicit field name, but as of notmuch 0.29 this is due to
138  * query-parser setup, not extra terms in the database.  In addition,
139  * terms from the content of the message are added without a prefix
140  * for use by the user in searching. Note that the prefix name "body"
141  * is used to refer to the empty prefix string in the database.
142  *
143  * The path of the containing folder is added with the "folder" prefix
144  * (see _notmuch_message_add_folder_terms).  Sub-paths of the the path
145  * of the mail message are added with the "path" prefix.
146  *
147  * The data portion of a mail document is empty.
148  *
149  * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
150  * -----------------------------------------------
151  * A ghost mail document is like a mail document, but where we don't
152  * have the message content.  These are used to track thread reference
153  * information for messages we haven't received.
154  *
155  * A ghost mail document has type: ghost; id and thread fields that
156  * are identical to the mail document fields; and a MESSAGE_ID value.
157  *
158  * Directory document
159  * ------------------
160  * A directory document is used by a client of the notmuch library to
161  * maintain data necessary to allow for efficient polling of mail
162  * directories.
163  *
164  * All directory documents contain one term:
165  *
166  *      directory:      The directory path (relative to the database path)
167  *                      Or the SHA1 sum of the directory path (if the
168  *                      path itself is too long to fit in a Xapian
169  *                      term).
170  *
171  * And all directory documents for directories other than top-level
172  * directories also contain the following term:
173  *
174  *      directory-direntry: A colon-separated pair of values
175  *                          (INTEGER:STRING), where INTEGER is the
176  *                          document ID of the parent directory
177  *                          document, and STRING is the name of this
178  *                          directory within that parent.
179  *
180  * All directory documents have a single value:
181  *
182  *      TIMESTAMP:      The mtime of the directory (at last scan)
183  *
184  * The data portion of a directory document contains the path of the
185  * directory (relative to the database path).
186  *
187  * Database metadata
188  * -----------------
189  * Xapian allows us to store arbitrary name-value pairs as
190  * "metadata". We currently use the following metadata names with the
191  * given meanings:
192  *
193  *      version         The database schema version, (which is distinct
194  *                      from both the notmuch package version (see
195  *                      notmuch --version) and the libnotmuch library
196  *                      version. The version is stored as an base-10
197  *                      ASCII integer. The initial database version
198  *                      was 1, (though a schema existed before that
199  *                      were no "version" database value existed at
200  *                      all). Successive versions are allocated as
201  *                      changes are made to the database (such as by
202  *                      indexing new fields).
203  *
204  *      features        The set of features supported by this
205  *                      database. This consists of a set of
206  *                      '\n'-separated lines, where each is a feature
207  *                      name, a '\t', and compatibility flags.  If the
208  *                      compatibility flags contain 'w', then the
209  *                      opener must support this feature to safely
210  *                      write this database.  If the compatibility
211  *                      flags contain 'r', then the opener must
212  *                      support this feature to read this database.
213  *                      Introduced in database version 3.
214  *
215  *      last_thread_id  The last thread ID generated. This is stored
216  *                      as a 16-byte hexadecimal ASCII representation
217  *                      of a 64-bit unsigned integer. The first ID
218  *                      generated is 1 and the value will be
219  *                      incremented for each thread ID.
220  *
221  *      C*              metadata keys starting with C indicate
222  *                      configuration data. It can be managed with the
223  *                      n_database_*config* API.  There is a convention
224  *                      of hierarchical keys separated by '.' (e.g.
225  *                      query.notmuch stores the value for the named
226  *                      query 'notmuch'), but it is not enforced by the
227  *                      API.
228  *
229  * Obsolete metadata
230  * -----------------
231  *
232  * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
233  * Instead, the database has the following additional database
234  * metadata:
235  *
236  *      thread_id_*     A pre-allocated thread ID for a particular
237  *                      message. This is actually an arbitrarily large
238  *                      family of metadata name. Any particular name is
239  *                      formed by concatenating "thread_id_" with a message
240  *                      ID (or the SHA1 sum of a message ID if it is very
241  *                      long---see description of 'id' in the mail
242  *                      document). The value stored is a thread ID.
243  *
244  *                      These thread ID metadata values are stored
245  *                      whenever a message references a parent message
246  *                      that does not yet exist in the database. A
247  *                      thread ID will be allocated and stored, and if
248  *                      the message is later added, the stored thread
249  *                      ID will be used (and the metadata value will
250  *                      be cleared).
251  *
252  *                      Even before a message is added, it's
253  *                      pre-allocated thread ID is useful so that all
254  *                      descendant messages that reference this common
255  *                      parent can be recognized as belonging to the
256  *                      same thread.
257  */
258
259 /* With these prefix values we follow the conventions published here:
260  *
261  * https://xapian.org/docs/omega/termprefixes.html
262  *
263  * as much as makes sense. Note that I took some liberty in matching
264  * the reserved prefix values to notmuch concepts, (for example, 'G'
265  * is documented as "newsGroup (or similar entity - e.g. a web forum
266  * name)", for which I think the thread is the closest analogue in
267  * notmuch. This in spite of the fact that we will eventually be
268  * storing mailing-list messages where 'G' for "mailing list name"
269  * might be even a closer analogue. I'm treating the single-character
270  * prefixes preferentially for core notmuch concepts (which will be
271  * nearly universal to all mail messages).
272  */
273
274 static const
275 prefix_t prefix_table[] = {
276     /* name                     term prefix     flags */
277     { "type",                   "T",            NOTMUCH_FIELD_NO_FLAGS },
278     { "reference",              "XREFERENCE",   NOTMUCH_FIELD_NO_FLAGS },
279     { "replyto",                "XREPLYTO",     NOTMUCH_FIELD_NO_FLAGS },
280     { "directory",              "XDIRECTORY",   NOTMUCH_FIELD_NO_FLAGS },
281     { "file-direntry",          "XFDIRENTRY",   NOTMUCH_FIELD_NO_FLAGS },
282     { "directory-direntry",     "XDDIRENTRY",   NOTMUCH_FIELD_NO_FLAGS },
283     { "body",                   "",             NOTMUCH_FIELD_EXTERNAL |
284       NOTMUCH_FIELD_PROBABILISTIC },
285     { "thread",                 "G",            NOTMUCH_FIELD_EXTERNAL |
286       NOTMUCH_FIELD_PROCESSOR },
287     { "tag",                    "K",            NOTMUCH_FIELD_EXTERNAL |
288       NOTMUCH_FIELD_PROCESSOR },
289     { "is",                     "K",            NOTMUCH_FIELD_EXTERNAL |
290       NOTMUCH_FIELD_PROCESSOR },
291     { "id",                     "Q",            NOTMUCH_FIELD_EXTERNAL },
292     { "mid",                    "Q",            NOTMUCH_FIELD_EXTERNAL |
293       NOTMUCH_FIELD_PROCESSOR },
294     { "path",                   "P",            NOTMUCH_FIELD_EXTERNAL |
295       NOTMUCH_FIELD_PROCESSOR },
296     { "property",               "XPROPERTY",    NOTMUCH_FIELD_EXTERNAL },
297     /*
298      * Unconditionally add ':' to reduce potential ambiguity with
299      * overlapping prefixes and/or terms that start with capital
300      * letters. See Xapian document termprefixes.html for related
301      * discussion.
302      */
303     { "folder",                 "XFOLDER:",     NOTMUCH_FIELD_EXTERNAL |
304       NOTMUCH_FIELD_PROCESSOR },
305     { "date",                   NULL,           NOTMUCH_FIELD_EXTERNAL |
306       NOTMUCH_FIELD_PROCESSOR },
307     { "query",                  NULL,           NOTMUCH_FIELD_EXTERNAL |
308       NOTMUCH_FIELD_PROCESSOR },
309     { "from",                   "XFROM",        NOTMUCH_FIELD_EXTERNAL |
310       NOTMUCH_FIELD_PROBABILISTIC |
311       NOTMUCH_FIELD_PROCESSOR },
312     { "to",                     "XTO",          NOTMUCH_FIELD_EXTERNAL |
313       NOTMUCH_FIELD_PROBABILISTIC },
314     { "attachment",             "XATTACHMENT",  NOTMUCH_FIELD_EXTERNAL |
315       NOTMUCH_FIELD_PROBABILISTIC },
316     { "mimetype",               "XMIMETYPE",    NOTMUCH_FIELD_EXTERNAL |
317       NOTMUCH_FIELD_PROBABILISTIC },
318     { "subject",                "XSUBJECT",     NOTMUCH_FIELD_EXTERNAL |
319       NOTMUCH_FIELD_PROBABILISTIC |
320       NOTMUCH_FIELD_PROCESSOR },
321 };
322
323 static void
324 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
325 {
326     if (prefix->prefix)
327         notmuch->query_parser->add_prefix ("", prefix->prefix);
328     if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
329         notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
330     else
331         notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
332 }
333
334 notmuch_string_map_iterator_t *
335 _notmuch_database_user_headers (notmuch_database_t *notmuch)
336 {
337     return _notmuch_string_map_iterator_create (notmuch->user_header, "", false);
338 }
339
340 const char *
341 _user_prefix (void *ctx, const char *name)
342 {
343     return talloc_asprintf (ctx, "XU%s:", name);
344 }
345
346 static notmuch_status_t
347 _setup_user_query_fields (notmuch_database_t *notmuch)
348 {
349     notmuch_config_list_t *list;
350     notmuch_status_t status;
351
352     notmuch->user_prefix = _notmuch_string_map_create (notmuch);
353     if (notmuch->user_prefix == NULL)
354         return NOTMUCH_STATUS_OUT_OF_MEMORY;
355
356     notmuch->user_header = _notmuch_string_map_create (notmuch);
357     if (notmuch->user_header == NULL)
358         return NOTMUCH_STATUS_OUT_OF_MEMORY;
359
360     status = notmuch_database_get_config_list (notmuch, CONFIG_HEADER_PREFIX, &list);
361     if (status)
362         return status;
363
364     for (; notmuch_config_list_valid (list); notmuch_config_list_move_to_next (list)) {
365
366         prefix_t query_field;
367
368         const char *key = notmuch_config_list_key (list)
369                           + sizeof (CONFIG_HEADER_PREFIX) - 1;
370
371         _notmuch_string_map_append (notmuch->user_prefix,
372                                     key,
373                                     _user_prefix (notmuch, key));
374
375         _notmuch_string_map_append (notmuch->user_header,
376                                     key,
377                                     notmuch_config_list_value (list));
378
379         query_field.name = talloc_strdup (notmuch, key);
380         query_field.prefix = _user_prefix (notmuch, key);
381         query_field.flags = NOTMUCH_FIELD_PROBABILISTIC
382                             | NOTMUCH_FIELD_EXTERNAL;
383
384         _setup_query_field_default (&query_field, notmuch);
385     }
386
387     notmuch_config_list_destroy (list);
388
389     return NOTMUCH_STATUS_SUCCESS;
390 }
391
392 static void
393 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
394 {
395     if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
396         Xapian::FieldProcessor *fp;
397
398         if (STRNCMP_LITERAL (prefix->name, "date") == 0)
399             fp = (new DateFieldProcessor(NOTMUCH_VALUE_TIMESTAMP))->release ();
400         else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
401             fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
402         else if (STRNCMP_LITERAL (prefix->name, "thread") == 0)
403             fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
404         else
405             fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
406                                             *notmuch->query_parser, notmuch))->release ();
407
408         /* we treat all field-processor fields as boolean in order to get the raw input */
409         if (prefix->prefix)
410             notmuch->query_parser->add_prefix ("", prefix->prefix);
411         notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
412     } else {
413         _setup_query_field_default (prefix, notmuch);
414     }
415 }
416
417 const char *
418 _find_prefix (const char *name)
419 {
420     unsigned int i;
421
422     for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
423         if (strcmp (name, prefix_table[i].name) == 0)
424             return prefix_table[i].prefix;
425     }
426
427     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
428
429     return "";
430 }
431
432 /* Like find prefix, but include the possibility of user defined
433  * prefixes specific to this database */
434
435 const char *
436 _notmuch_database_prefix (notmuch_database_t *notmuch, const char *name)
437 {
438     unsigned int i;
439
440     /*XXX TODO: reduce code duplication */
441     for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
442         if (strcmp (name, prefix_table[i].name) == 0)
443             return prefix_table[i].prefix;
444     }
445
446     if (notmuch->user_prefix)
447         return _notmuch_string_map_get (notmuch->user_prefix, name);
448
449     return NULL;
450 }
451
452 static const struct {
453     /* NOTMUCH_FEATURE_* value. */
454     _notmuch_features value;
455     /* Feature name as it appears in the database.  This name should
456      * be appropriate for displaying to the user if an older version
457      * of notmuch doesn't support this feature. */
458     const char *name;
459     /* Compatibility flags when this feature is declared. */
460     const char *flags;
461 } feature_names[] = {
462     { NOTMUCH_FEATURE_FILE_TERMS,
463       "multiple paths per message", "rw" },
464     { NOTMUCH_FEATURE_DIRECTORY_DOCS,
465       "relative directory paths", "rw" },
466     /* Header values are not required for reading a database because a
467      * reader can just refer to the message file. */
468     { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
469       "from/subject/message-ID in database", "w" },
470     { NOTMUCH_FEATURE_BOOL_FOLDER,
471       "exact folder:/path: search", "rw" },
472     { NOTMUCH_FEATURE_GHOSTS,
473       "mail documents for missing messages", "w" },
474     /* Knowledge of the index mime-types are not required for reading
475      * a database because a reader will just be unable to query
476      * them. */
477     { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
478       "indexed MIME types", "w" },
479     { NOTMUCH_FEATURE_LAST_MOD,
480       "modification tracking", "w" },
481     /* Existing databases will work fine for all queries not involving
482      * 'body:' */
483     { NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY,
484       "index body and headers separately", "w" },
485 };
486
487 const char *
488 notmuch_status_to_string (notmuch_status_t status)
489 {
490     switch (status) {
491     case NOTMUCH_STATUS_SUCCESS:
492         return "No error occurred";
493     case NOTMUCH_STATUS_OUT_OF_MEMORY:
494         return "Out of memory";
495     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
496         return "Attempt to write to a read-only database";
497     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
498         return "A Xapian exception occurred";
499     case NOTMUCH_STATUS_FILE_ERROR:
500         return "Something went wrong trying to read or write a file";
501     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
502         return "File is not an email";
503     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
504         return "Message ID is identical to a message in database";
505     case NOTMUCH_STATUS_NULL_POINTER:
506         return "Erroneous NULL pointer";
507     case NOTMUCH_STATUS_TAG_TOO_LONG:
508         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
509     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
510         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
511     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
512         return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
513     case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
514         return "Unsupported operation";
515     case NOTMUCH_STATUS_UPGRADE_REQUIRED:
516         return "Operation requires a database upgrade";
517     case NOTMUCH_STATUS_PATH_ERROR:
518         return "Path supplied is illegal for this function";
519     case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
520         return "Crypto protocol missing, malformed, or unintelligible";
521     case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
522         return "Crypto engine initialization failure";
523     case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
524         return "Unknown crypto protocol";
525     default:
526     case NOTMUCH_STATUS_LAST_STATUS:
527         return "Unknown error status value";
528     }
529 }
530
531 void
532 _notmuch_database_log (notmuch_database_t *notmuch,
533                        const char *format,
534                        ...)
535 {
536     va_list va_args;
537
538     va_start (va_args, format);
539
540     if (notmuch->status_string)
541         talloc_free (notmuch->status_string);
542
543     notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
544     va_end (va_args);
545 }
546
547 void
548 _notmuch_database_log_append (notmuch_database_t *notmuch,
549                               const char *format,
550                               ...)
551 {
552     va_list va_args;
553
554     va_start (va_args, format);
555
556     if (notmuch->status_string)
557         notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
558     else
559         notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
560
561     va_end (va_args);
562 }
563
564 static void
565 find_doc_ids_for_term (notmuch_database_t *notmuch,
566                        const char *term,
567                        Xapian::PostingIterator *begin,
568                        Xapian::PostingIterator *end)
569 {
570     *begin = notmuch->xapian_db->postlist_begin (term);
571
572     *end = notmuch->xapian_db->postlist_end (term);
573 }
574
575 void
576 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
577                                 const char *prefix_name,
578                                 const char *value,
579                                 Xapian::PostingIterator *begin,
580                                 Xapian::PostingIterator *end)
581 {
582     char *term;
583
584     term = talloc_asprintf (notmuch, "%s%s",
585                             _find_prefix (prefix_name), value);
586
587     find_doc_ids_for_term (notmuch, term, begin, end);
588
589     talloc_free (term);
590 }
591
592 notmuch_private_status_t
593 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
594                                       const char *prefix_name,
595                                       const char *value,
596                                       unsigned int *doc_id)
597 {
598     Xapian::PostingIterator i, end;
599
600     _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
601
602     if (i == end) {
603         *doc_id = 0;
604         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
605     }
606
607     *doc_id = *i;
608
609 #if DEBUG_DATABASE_SANITY
610     i++;
611
612     if (i != end)
613         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
614                         prefix_name, value);
615 #endif
616
617     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
618 }
619
620 static Xapian::Document
621 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
622 {
623     return notmuch->xapian_db->get_document (doc_id);
624 }
625
626 /* Generate a compressed version of 'message_id' of the form:
627  *
628  *      notmuch-sha1-<sha1_sum_of_message_id>
629  */
630 char *
631 _notmuch_message_id_compressed (void *ctx, const char *message_id)
632 {
633     char *sha1, *compressed;
634
635     sha1 = _notmuch_sha1_of_string (message_id);
636
637     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
638     free (sha1);
639
640     return compressed;
641 }
642
643 notmuch_status_t
644 notmuch_database_find_message (notmuch_database_t *notmuch,
645                                const char *message_id,
646                                notmuch_message_t **message_ret)
647 {
648     notmuch_private_status_t status;
649     unsigned int doc_id;
650
651     if (message_ret == NULL)
652         return NOTMUCH_STATUS_NULL_POINTER;
653
654     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
655         message_id = _notmuch_message_id_compressed (notmuch, message_id);
656
657     try {
658         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
659                                                        message_id, &doc_id);
660
661         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
662             *message_ret = NULL;
663         else {
664             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
665                                                     NULL);
666             if (*message_ret == NULL)
667                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
668         }
669
670         return NOTMUCH_STATUS_SUCCESS;
671     } catch (const Xapian::Error &error) {
672         _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
673                                error.get_msg ().c_str ());
674         notmuch->exception_reported = true;
675         *message_ret = NULL;
676         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
677     }
678 }
679
680 notmuch_status_t
681 notmuch_database_create (const char *path, notmuch_database_t **database)
682 {
683     char *status_string = NULL;
684     notmuch_status_t status;
685
686     status = notmuch_database_create_verbose (path, database,
687                                               &status_string);
688
689     if (status_string) {
690         fputs (status_string, stderr);
691         free (status_string);
692     }
693
694     return status;
695 }
696
697 notmuch_status_t
698 notmuch_database_create_verbose (const char *path,
699                                  notmuch_database_t **database,
700                                  char **status_string)
701 {
702     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
703     notmuch_database_t *notmuch = NULL;
704     char *notmuch_path = NULL;
705     char *message = NULL;
706     struct stat st;
707     int err;
708
709     if (path == NULL) {
710         message = strdup ("Error: Cannot create a database for a NULL path.\n");
711         status = NOTMUCH_STATUS_NULL_POINTER;
712         goto DONE;
713     }
714
715     if (path[0] != '/') {
716         message = strdup ("Error: Database path must be absolute.\n");
717         status = NOTMUCH_STATUS_PATH_ERROR;
718         goto DONE;
719     }
720
721     err = stat (path, &st);
722     if (err) {
723         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
724                                  path, strerror (errno)));
725         status = NOTMUCH_STATUS_FILE_ERROR;
726         goto DONE;
727     }
728
729     if (! S_ISDIR (st.st_mode)) {
730         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
731                                  "Not a directory.\n",
732                                  path));
733         status = NOTMUCH_STATUS_FILE_ERROR;
734         goto DONE;
735     }
736
737     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
738
739     err = mkdir (notmuch_path, 0755);
740
741     if (err) {
742         IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
743                                  notmuch_path, strerror (errno)));
744         status = NOTMUCH_STATUS_FILE_ERROR;
745         goto DONE;
746     }
747
748     status = notmuch_database_open_verbose (path,
749                                             NOTMUCH_DATABASE_MODE_READ_WRITE,
750                                             &notmuch, &message);
751     if (status)
752         goto DONE;
753
754     /* Upgrade doesn't add these feature to existing databases, but
755      * new databases have them. */
756     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
757     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
758     notmuch->features |= NOTMUCH_FEATURE_UNPREFIX_BODY_ONLY;
759
760     status = notmuch_database_upgrade (notmuch, NULL, NULL);
761     if (status) {
762         notmuch_database_close (notmuch);
763         notmuch = NULL;
764     }
765
766   DONE:
767     if (notmuch_path)
768         talloc_free (notmuch_path);
769
770     if (message) {
771         if (status_string)
772             *status_string = message;
773         else
774             free (message);
775     }
776     if (database)
777         *database = notmuch;
778     else
779         talloc_free (notmuch);
780     return status;
781 }
782
783 notmuch_status_t
784 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
785 {
786     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
787         _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
788         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
789     }
790
791     return NOTMUCH_STATUS_SUCCESS;
792 }
793
794 /* Allocate a revision number for the next change. */
795 unsigned long
796 _notmuch_database_new_revision (notmuch_database_t *notmuch)
797 {
798     unsigned long new_revision = notmuch->revision + 1;
799
800     /* If we're in an atomic section, hold off on updating the
801      * committed revision number until we commit the atomic section.
802      */
803     if (notmuch->atomic_nesting)
804         notmuch->atomic_dirty = true;
805     else
806         notmuch->revision = new_revision;
807
808     return new_revision;
809 }
810
811 /* Parse a database features string from the given database version.
812  * Returns the feature bit set.
813  *
814  * For version < 3, this ignores the features string and returns a
815  * hard-coded set of features.
816  *
817  * If there are unrecognized features that are required to open the
818  * database in mode (which should be 'r' or 'w'), return a
819  * comma-separated list of unrecognized but required features in
820  * *incompat_out suitable for presenting to the user.  *incompat_out
821  * will be allocated from ctx.
822  */
823 static _notmuch_features
824 _parse_features (const void *ctx, const char *features, unsigned int version,
825                  char mode, char **incompat_out)
826 {
827     _notmuch_features res = static_cast<_notmuch_features>(0);
828     unsigned int namelen, i;
829     size_t llen = 0;
830     const char *flags;
831
832     /* Prior to database version 3, features were implied by the
833      * version number. */
834     if (version == 0)
835         return NOTMUCH_FEATURES_V0;
836     else if (version == 1)
837         return NOTMUCH_FEATURES_V1;
838     else if (version == 2)
839         return NOTMUCH_FEATURES_V2;
840
841     /* Parse the features string */
842     while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
843         flags = strchr (features, '\t');
844         if (! flags || flags > features + llen)
845             continue;
846         namelen = flags - features;
847
848         for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
849             if (strlen (feature_names[i].name) == namelen &&
850                 strncmp (feature_names[i].name, features, namelen) == 0) {
851                 res |= feature_names[i].value;
852                 break;
853             }
854         }
855
856         if (i == ARRAY_SIZE (feature_names) && incompat_out) {
857             /* Unrecognized feature */
858             const char *have = strchr (flags, mode);
859             if (have && have < features + llen) {
860                 /* This feature is required to access this database in
861                  * 'mode', but we don't understand it. */
862                 if (! *incompat_out)
863                     *incompat_out = talloc_strdup (ctx, "");
864                 *incompat_out = talloc_asprintf_append_buffer (
865                     *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
866                     namelen, features);
867             }
868         }
869     }
870
871     return res;
872 }
873
874 static char *
875 _print_features (const void *ctx, unsigned int features)
876 {
877     unsigned int i;
878     char *res = talloc_strdup (ctx, "");
879
880     for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
881         if (features & feature_names[i].value)
882             res = talloc_asprintf_append_buffer (
883                 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
884
885     return res;
886 }
887
888 notmuch_status_t
889 notmuch_database_open (const char *path,
890                        notmuch_database_mode_t mode,
891                        notmuch_database_t **database)
892 {
893     char *status_string = NULL;
894     notmuch_status_t status;
895
896     status = notmuch_database_open_verbose (path, mode, database,
897                                             &status_string);
898
899     if (status_string) {
900         fputs (status_string, stderr);
901         free (status_string);
902     }
903
904     return status;
905 }
906
907 notmuch_status_t
908 notmuch_database_open_verbose (const char *path,
909                                notmuch_database_mode_t mode,
910                                notmuch_database_t **database,
911                                char **status_string)
912 {
913     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
914     void *local = talloc_new (NULL);
915     notmuch_database_t *notmuch = NULL;
916     char *notmuch_path, *xapian_path, *incompat_features;
917     char *message = NULL;
918     struct stat st;
919     int err;
920     unsigned int i, version;
921     static int initialized = 0;
922
923     if (path == NULL) {
924         message = strdup ("Error: Cannot open a database for a NULL path.\n");
925         status = NOTMUCH_STATUS_NULL_POINTER;
926         goto DONE;
927     }
928
929     if (path[0] != '/') {
930         message = strdup ("Error: Database path must be absolute.\n");
931         status = NOTMUCH_STATUS_PATH_ERROR;
932         goto DONE;
933     }
934
935     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
936         message = strdup ("Out of memory\n");
937         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
938         goto DONE;
939     }
940
941     err = stat (notmuch_path, &st);
942     if (err) {
943         IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
944                                  notmuch_path, strerror (errno)));
945         status = NOTMUCH_STATUS_FILE_ERROR;
946         goto DONE;
947     }
948
949     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
950         message = strdup ("Out of memory\n");
951         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
952         goto DONE;
953     }
954
955     /* Initialize the GLib type system and threads */
956 #if ! GLIB_CHECK_VERSION (2, 35, 1)
957     g_type_init ();
958 #endif
959
960     /* Initialize gmime */
961     if (! initialized) {
962         g_mime_init ();
963         initialized = 1;
964     }
965
966     notmuch = talloc_zero (NULL, notmuch_database_t);
967     notmuch->exception_reported = false;
968     notmuch->status_string = NULL;
969     notmuch->path = talloc_strdup (notmuch, path);
970
971     strip_trailing (notmuch->path, '/');
972
973     notmuch->mode = mode;
974     notmuch->atomic_nesting = 0;
975     notmuch->view = 1;
976     try {
977         string last_thread_id;
978         string last_mod;
979
980         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
981             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
982                                                                DB_ACTION);
983         } else {
984             notmuch->xapian_db = new Xapian::Database (xapian_path);
985         }
986
987         /* Check version.  As of database version 3, we represent
988          * changes in terms of features, so assume a version bump
989          * means a dramatically incompatible change. */
990         version = notmuch_database_get_version (notmuch);
991         if (version > NOTMUCH_DATABASE_VERSION) {
992             IGNORE_RESULT (asprintf (&message,
993                                      "Error: Notmuch database at %s\n"
994                                      "       has a newer database format version (%u) than supported by this\n"
995                                      "       version of notmuch (%u).\n",
996                                      notmuch_path, version, NOTMUCH_DATABASE_VERSION));
997             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
998             notmuch_database_destroy (notmuch);
999             notmuch = NULL;
1000             status = NOTMUCH_STATUS_FILE_ERROR;
1001             goto DONE;
1002         }
1003
1004         /* Check features. */
1005         incompat_features = NULL;
1006         notmuch->features = _parse_features (
1007             local, notmuch->xapian_db->get_metadata ("features").c_str (),
1008             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1009             &incompat_features);
1010         if (incompat_features) {
1011             IGNORE_RESULT (asprintf (&message,
1012                                      "Error: Notmuch database at %s\n"
1013                                      "       requires features (%s)\n"
1014                                      "       not supported by this version of notmuch.\n",
1015                                      notmuch_path, incompat_features));
1016             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1017             notmuch_database_destroy (notmuch);
1018             notmuch = NULL;
1019             status = NOTMUCH_STATUS_FILE_ERROR;
1020             goto DONE;
1021         }
1022
1023         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1024         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1025         if (last_thread_id.empty ()) {
1026             notmuch->last_thread_id = 0;
1027         } else {
1028             const char *str;
1029             char *end;
1030
1031             str = last_thread_id.c_str ();
1032             notmuch->last_thread_id = strtoull (str, &end, 16);
1033             if (*end != '\0')
1034                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1035         }
1036
1037         /* Get current highest revision number. */
1038         last_mod = notmuch->xapian_db->get_value_upper_bound (
1039             NOTMUCH_VALUE_LAST_MOD);
1040         if (last_mod.empty ())
1041             notmuch->revision = 0;
1042         else
1043             notmuch->revision = Xapian::sortable_unserialise (last_mod);
1044         notmuch->uuid = talloc_strdup (
1045             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1046
1047         notmuch->query_parser = new Xapian::QueryParser;
1048         notmuch->term_gen = new Xapian::TermGenerator;
1049         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1050         notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1051         notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP, "date:");
1052         notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1053         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1054         notmuch->query_parser->set_database (*notmuch->xapian_db);
1055         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1056         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1057         notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
1058         notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
1059         notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
1060
1061         for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1062             const prefix_t *prefix = &prefix_table[i];
1063             if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1064                 _setup_query_field (prefix, notmuch);
1065             }
1066         }
1067         status = _setup_user_query_fields (notmuch);
1068     } catch (const Xapian::Error &error) {
1069         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1070                                  error.get_msg ().c_str ()));
1071         notmuch_database_destroy (notmuch);
1072         notmuch = NULL;
1073         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1074     }
1075
1076   DONE:
1077     talloc_free (local);
1078
1079     if (message) {
1080         if (status_string)
1081             *status_string = message;
1082         else
1083             free (message);
1084     }
1085
1086     if (database)
1087         *database = notmuch;
1088     else
1089         talloc_free (notmuch);
1090
1091     if (notmuch)
1092         notmuch->open = true;
1093
1094     return status;
1095 }
1096
1097 notmuch_status_t
1098 notmuch_database_close (notmuch_database_t *notmuch)
1099 {
1100     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1101
1102     /* Many Xapian objects (and thus notmuch objects) hold references to
1103      * the database, so merely deleting the database may not suffice to
1104      * close it.  Thus, we explicitly close it here. */
1105     if (notmuch->open) {
1106         try {
1107             /* If there's an outstanding transaction, it's unclear if
1108              * closing the Xapian database commits everything up to
1109              * that transaction, or may discard committed (but
1110              * unflushed) transactions.  To be certain, explicitly
1111              * cancel any outstanding transaction before closing. */
1112             if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1113                 notmuch->atomic_nesting)
1114                 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1115                 ->cancel_transaction ();
1116
1117             /* Close the database.  This implicitly flushes
1118              * outstanding changes. */
1119             notmuch->xapian_db->close ();
1120         } catch (const Xapian::Error &error) {
1121             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1122             if (! notmuch->exception_reported) {
1123                 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1124                                        error.get_msg ().c_str ());
1125             }
1126         }
1127     }
1128     notmuch->open = false;
1129     return status;
1130 }
1131
1132 notmuch_status_t
1133 _notmuch_database_reopen (notmuch_database_t *notmuch)
1134 {
1135     if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1136         return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1137
1138     try {
1139         notmuch->xapian_db->reopen ();
1140     } catch (const Xapian::Error &error) {
1141         if (! notmuch->exception_reported) {
1142             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1143                                    error.get_msg ().c_str ());
1144             notmuch->exception_reported = true;
1145         }
1146         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1147     }
1148
1149     notmuch->view++;
1150
1151     return NOTMUCH_STATUS_SUCCESS;
1152 }
1153
1154 static int
1155 unlink_cb (const char *path,
1156            unused (const struct stat *sb),
1157            unused (int type),
1158            unused (struct FTW *ftw))
1159 {
1160     return remove (path);
1161 }
1162
1163 static int
1164 rmtree (const char *path)
1165 {
1166     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1167 }
1168
1169 class NotmuchCompactor : public Xapian::Compactor
1170 {
1171     notmuch_compact_status_cb_t status_cb;
1172     void *status_closure;
1173
1174 public:
1175     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1176         status_cb (cb), status_closure (closure)
1177     {
1178     }
1179
1180     virtual void
1181     set_status (const std::string &table, const std::string &status)
1182     {
1183         char *msg;
1184
1185         if (status_cb == NULL)
1186             return;
1187
1188         if (status.length () == 0)
1189             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
1190         else
1191             msg = talloc_asprintf (NULL, "     %s", status.c_str ());
1192
1193         if (msg == NULL) {
1194             return;
1195         }
1196
1197         status_cb (msg, status_closure);
1198         talloc_free (msg);
1199     }
1200 };
1201
1202 /* Compacts the given database, optionally saving the original database
1203  * in backup_path. Additionally, a callback function can be provided to
1204  * give the user feedback on the progress of the (likely long-lived)
1205  * compaction process.
1206  *
1207  * The backup path must point to a directory on the same volume as the
1208  * original database. Passing a NULL backup_path will result in the
1209  * uncompacted database being deleted after compaction has finished.
1210  * Note that the database write lock will be held during the
1211  * compaction process to protect data integrity.
1212  */
1213 notmuch_status_t
1214 notmuch_database_compact (const char *path,
1215                           const char *backup_path,
1216                           notmuch_compact_status_cb_t status_cb,
1217                           void *closure)
1218 {
1219     void *local;
1220     char *notmuch_path, *xapian_path, *compact_xapian_path;
1221     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1222     notmuch_database_t *notmuch = NULL;
1223     struct stat statbuf;
1224     bool keep_backup;
1225     char *message = NULL;
1226
1227     local = talloc_new (NULL);
1228     if (! local)
1229         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1230
1231     ret = notmuch_database_open_verbose (path,
1232                                          NOTMUCH_DATABASE_MODE_READ_WRITE,
1233                                          &notmuch,
1234                                          &message);
1235     if (ret) {
1236         if (status_cb) status_cb (message, closure);
1237         goto DONE;
1238     }
1239
1240     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1241         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1242         goto DONE;
1243     }
1244
1245     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1246         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1247         goto DONE;
1248     }
1249
1250     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1251         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1252         goto DONE;
1253     }
1254
1255     if (backup_path == NULL) {
1256         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1257             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1258             goto DONE;
1259         }
1260         keep_backup = false;
1261     } else {
1262         keep_backup = true;
1263     }
1264
1265     if (stat (backup_path, &statbuf) != -1) {
1266         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1267         ret = NOTMUCH_STATUS_FILE_ERROR;
1268         goto DONE;
1269     }
1270     if (errno != ENOENT) {
1271         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1272                                strerror (errno));
1273         ret = NOTMUCH_STATUS_FILE_ERROR;
1274         goto DONE;
1275     }
1276
1277     /* Unconditionally attempt to remove old work-in-progress database (if
1278      * any). This is "protected" by database lock. If this fails due to write
1279      * errors (etc), the following code will fail and provide error message.
1280      */
1281     (void) rmtree (compact_xapian_path);
1282
1283     try {
1284         NotmuchCompactor compactor (status_cb, closure);
1285         notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0, compactor);
1286     } catch (const Xapian::Error &error) {
1287         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
1288         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1289         goto DONE;
1290     }
1291
1292     if (rename (xapian_path, backup_path)) {
1293         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1294                                xapian_path, backup_path, strerror (errno));
1295         ret = NOTMUCH_STATUS_FILE_ERROR;
1296         goto DONE;
1297     }
1298
1299     if (rename (compact_xapian_path, xapian_path)) {
1300         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1301                                compact_xapian_path, xapian_path, strerror (errno));
1302         ret = NOTMUCH_STATUS_FILE_ERROR;
1303         goto DONE;
1304     }
1305
1306     if (! keep_backup) {
1307         if (rmtree (backup_path)) {
1308             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1309                                    backup_path, strerror (errno));
1310             ret = NOTMUCH_STATUS_FILE_ERROR;
1311             goto DONE;
1312         }
1313     }
1314
1315   DONE:
1316     if (notmuch) {
1317         notmuch_status_t ret2;
1318
1319         const char *str = notmuch_database_status_string (notmuch);
1320         if (status_cb && str)
1321             status_cb (str, closure);
1322
1323         ret2 = notmuch_database_destroy (notmuch);
1324
1325         /* don't clobber previous error status */
1326         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1327             ret = ret2;
1328     }
1329
1330     talloc_free (local);
1331
1332     return ret;
1333 }
1334
1335 notmuch_status_t
1336 notmuch_database_destroy (notmuch_database_t *notmuch)
1337 {
1338     notmuch_status_t status;
1339
1340     status = notmuch_database_close (notmuch);
1341
1342     delete notmuch->term_gen;
1343     notmuch->term_gen = NULL;
1344     delete notmuch->query_parser;
1345     notmuch->query_parser = NULL;
1346     delete notmuch->xapian_db;
1347     notmuch->xapian_db = NULL;
1348     delete notmuch->value_range_processor;
1349     notmuch->value_range_processor = NULL;
1350     delete notmuch->date_range_processor;
1351     notmuch->date_range_processor = NULL;
1352     delete notmuch->last_mod_range_processor;
1353     notmuch->last_mod_range_processor = NULL;
1354
1355     talloc_free (notmuch);
1356
1357     return status;
1358 }
1359
1360 const char *
1361 notmuch_database_get_path (notmuch_database_t *notmuch)
1362 {
1363     return notmuch->path;
1364 }
1365
1366 unsigned int
1367 notmuch_database_get_version (notmuch_database_t *notmuch)
1368 {
1369     unsigned int version;
1370     string version_string;
1371     const char *str;
1372     char *end;
1373
1374     try {
1375         version_string = notmuch->xapian_db->get_metadata ("version");
1376     } catch (const Xapian::Error &error) {
1377         LOG_XAPIAN_EXCEPTION (notmuch, error);
1378         return 0;
1379     }
1380
1381     if (version_string.empty ())
1382         return 0;
1383
1384     str = version_string.c_str ();
1385     if (str == NULL || *str == '\0')
1386         return 0;
1387
1388     version = strtoul (str, &end, 10);
1389     if (*end != '\0')
1390         INTERNAL_ERROR ("Malformed database version: %s", str);
1391
1392     return version;
1393 }
1394
1395 notmuch_bool_t
1396 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1397 {
1398     unsigned int version;
1399
1400     if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_WRITE)
1401         return FALSE;
1402
1403     if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
1404         return TRUE;
1405
1406     version = notmuch_database_get_version (notmuch);
1407
1408     return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
1409 }
1410
1411 static volatile sig_atomic_t do_progress_notify = 0;
1412
1413 static void
1414 handle_sigalrm (unused (int signal))
1415 {
1416     do_progress_notify = 1;
1417 }
1418
1419 /* Upgrade the current database.
1420  *
1421  * After opening a database in read-write mode, the client should
1422  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1423  * if so, upgrade with this function before making any modifications.
1424  *
1425  * The optional progress_notify callback can be used by the caller to
1426  * provide progress indication to the user. If non-NULL it will be
1427  * called periodically with 'count' as the number of messages upgraded
1428  * so far and 'total' the overall number of messages that will be
1429  * converted.
1430  */
1431 notmuch_status_t
1432 notmuch_database_upgrade (notmuch_database_t *notmuch,
1433                           void (*progress_notify) (void *closure,
1434                                                    double progress),
1435                           void *closure)
1436 {
1437     void *local = talloc_new (NULL);
1438     Xapian::TermIterator t, t_end;
1439     Xapian::WritableDatabase *db;
1440     struct sigaction action;
1441     struct itimerval timerval;
1442     bool timer_is_active = false;
1443     enum _notmuch_features target_features, new_features;
1444     notmuch_status_t status;
1445     notmuch_private_status_t private_status;
1446     notmuch_query_t *query = NULL;
1447     unsigned int count = 0, total = 0;
1448
1449     status = _notmuch_database_ensure_writable (notmuch);
1450     if (status)
1451         return status;
1452
1453     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1454
1455     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1456     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1457
1458     if (! notmuch_database_needs_upgrade (notmuch))
1459         return NOTMUCH_STATUS_SUCCESS;
1460
1461     if (progress_notify) {
1462         /* Set up our handler for SIGALRM */
1463         memset (&action, 0, sizeof (struct sigaction));
1464         action.sa_handler = handle_sigalrm;
1465         sigemptyset (&action.sa_mask);
1466         action.sa_flags = SA_RESTART;
1467         sigaction (SIGALRM, &action, NULL);
1468
1469         /* Then start a timer to send SIGALRM once per second. */
1470         timerval.it_interval.tv_sec = 1;
1471         timerval.it_interval.tv_usec = 0;
1472         timerval.it_value.tv_sec = 1;
1473         timerval.it_value.tv_usec = 0;
1474         setitimer (ITIMER_REAL, &timerval, NULL);
1475
1476         timer_is_active = true;
1477     }
1478
1479     /* Figure out how much total work we need to do. */
1480     if (new_features &
1481         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1482          NOTMUCH_FEATURE_LAST_MOD)) {
1483         query = notmuch_query_create (notmuch, "");
1484         unsigned msg_count;
1485
1486         status = notmuch_query_count_messages (query, &msg_count);
1487         if (status)
1488             goto DONE;
1489
1490         total += msg_count;
1491         notmuch_query_destroy (query);
1492         query = NULL;
1493     }
1494     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1495         t_end = db->allterms_end ("XTIMESTAMP");
1496         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1497             ++total;
1498     }
1499     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1500         /* The ghost message upgrade converts all thread_id_*
1501          * metadata values into ghost message documents. */
1502         t_end = db->metadata_keys_end ("thread_id_");
1503         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1504             ++total;
1505     }
1506
1507     /* Perform the upgrade in a transaction. */
1508     db->begin_transaction (true);
1509
1510     /* Set the target features so we write out changes in the desired
1511      * format. */
1512     notmuch->features = target_features;
1513
1514     /* Perform per-message upgrades. */
1515     if (new_features &
1516         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1517          NOTMUCH_FEATURE_LAST_MOD)) {
1518         notmuch_messages_t *messages;
1519         notmuch_message_t *message;
1520         char *filename;
1521
1522         query = notmuch_query_create (notmuch, "");
1523
1524         status = notmuch_query_search_messages (query, &messages);
1525         if (status)
1526             goto DONE;
1527         for (;
1528              notmuch_messages_valid (messages);
1529              notmuch_messages_move_to_next (messages)) {
1530             if (do_progress_notify) {
1531                 progress_notify (closure, (double) count / total);
1532                 do_progress_notify = 0;
1533             }
1534
1535             message = notmuch_messages_get (messages);
1536
1537             /* Before version 1, each message document had its
1538              * filename in the data field. Copy that into the new
1539              * format by calling notmuch_message_add_filename.
1540              */
1541             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1542                 filename = _notmuch_message_talloc_copy_data (message);
1543                 if (filename && *filename != '\0') {
1544                     _notmuch_message_add_filename (message, filename);
1545                     _notmuch_message_clear_data (message);
1546                 }
1547                 talloc_free (filename);
1548             }
1549
1550             /* Prior to version 2, the "folder:" prefix was
1551              * probabilistic and stemmed. Change it to the current
1552              * boolean prefix. Add "path:" prefixes while at it.
1553              */
1554             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1555                 _notmuch_message_upgrade_folder (message);
1556
1557             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1558              * track modification revisions.  Give all messages the
1559              * next available revision; since we just started tracking
1560              * revisions for this database, that will be 1.
1561              */
1562             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1563                 _notmuch_message_upgrade_last_mod (message);
1564
1565             _notmuch_message_sync (message);
1566
1567             notmuch_message_destroy (message);
1568
1569             count++;
1570         }
1571
1572         notmuch_query_destroy (query);
1573         query = NULL;
1574     }
1575
1576     /* Perform per-directory upgrades. */
1577
1578     /* Before version 1 we stored directory timestamps in
1579      * XTIMESTAMP documents instead of the current XDIRECTORY
1580      * documents. So copy those as well. */
1581     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1582         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1583
1584         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1585              t != t_end;
1586              t++) {
1587             Xapian::PostingIterator p, p_end;
1588             std::string term = *t;
1589
1590             p_end = notmuch->xapian_db->postlist_end (term);
1591
1592             for (p = notmuch->xapian_db->postlist_begin (term);
1593                  p != p_end;
1594                  p++) {
1595                 Xapian::Document document;
1596                 time_t mtime;
1597                 notmuch_directory_t *directory;
1598
1599                 if (do_progress_notify) {
1600                     progress_notify (closure, (double) count / total);
1601                     do_progress_notify = 0;
1602                 }
1603
1604                 document = find_document_for_doc_id (notmuch, *p);
1605                 mtime = Xapian::sortable_unserialise (
1606                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1607
1608                 directory = _notmuch_directory_create (notmuch, term.c_str () + 10,
1609                                                        NOTMUCH_FIND_CREATE, &status);
1610                 notmuch_directory_set_mtime (directory, mtime);
1611                 notmuch_directory_destroy (directory);
1612
1613                 db->delete_document (*p);
1614             }
1615
1616             ++count;
1617         }
1618     }
1619
1620     /* Perform metadata upgrades. */
1621
1622     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1623      * messages were stored as database metadata. Change these to
1624      * ghost messages.
1625      */
1626     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1627         notmuch_message_t *message;
1628         std::string message_id, thread_id;
1629
1630         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1631         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1632              t != t_end; ++t) {
1633             if (do_progress_notify) {
1634                 progress_notify (closure, (double) count / total);
1635                 do_progress_notify = 0;
1636             }
1637
1638             message_id = (*t).substr (
1639                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1640             thread_id = db->get_metadata (*t);
1641
1642             /* Create ghost message */
1643             message = _notmuch_message_create_for_message_id (
1644                 notmuch, message_id.c_str (), &private_status);
1645             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1646                 /* Document already exists; ignore the stored thread ID */
1647             } else if (private_status ==
1648                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1649                 private_status = _notmuch_message_initialize_ghost (
1650                     message, thread_id.c_str ());
1651                 if (! private_status)
1652                     _notmuch_message_sync (message);
1653             }
1654
1655             if (private_status) {
1656                 _notmuch_database_log (notmuch,
1657                                        "Upgrade failed while creating ghost messages.\n");
1658                 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1659                 goto DONE;
1660             }
1661
1662             /* Clear saved metadata thread ID */
1663             db->set_metadata (*t, "");
1664
1665             ++count;
1666         }
1667     }
1668
1669     status = NOTMUCH_STATUS_SUCCESS;
1670     db->set_metadata ("features", _print_features (local, notmuch->features));
1671     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1672
1673   DONE:
1674     if (status == NOTMUCH_STATUS_SUCCESS)
1675         db->commit_transaction ();
1676     else
1677         db->cancel_transaction ();
1678
1679     if (timer_is_active) {
1680         /* Now stop the timer. */
1681         timerval.it_interval.tv_sec = 0;
1682         timerval.it_interval.tv_usec = 0;
1683         timerval.it_value.tv_sec = 0;
1684         timerval.it_value.tv_usec = 0;
1685         setitimer (ITIMER_REAL, &timerval, NULL);
1686
1687         /* And disable the signal handler. */
1688         action.sa_handler = SIG_IGN;
1689         sigaction (SIGALRM, &action, NULL);
1690     }
1691
1692     if (query)
1693         notmuch_query_destroy (query);
1694
1695     talloc_free (local);
1696     return status;
1697 }
1698
1699 notmuch_status_t
1700 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1701 {
1702     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1703         notmuch->atomic_nesting > 0)
1704         goto DONE;
1705
1706     if (notmuch_database_needs_upgrade (notmuch))
1707         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1708
1709     try {
1710         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1711     } catch (const Xapian::Error &error) {
1712         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1713                                error.get_msg ().c_str ());
1714         notmuch->exception_reported = true;
1715         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1716     }
1717
1718   DONE:
1719     notmuch->atomic_nesting++;
1720     return NOTMUCH_STATUS_SUCCESS;
1721 }
1722
1723 notmuch_status_t
1724 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1725 {
1726     Xapian::WritableDatabase *db;
1727
1728     if (notmuch->atomic_nesting == 0)
1729         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1730
1731     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1732         notmuch->atomic_nesting > 1)
1733         goto DONE;
1734
1735     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1736     try {
1737         db->commit_transaction ();
1738
1739         /* This is a hack for testing.  Xapian never flushes on a
1740          * non-flushed commit, even if the flush threshold is 1.
1741          * However, we rely on flushing to test atomicity. */
1742         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1743         if (thresh && atoi (thresh) == 1)
1744             db->commit ();
1745     } catch (const Xapian::Error &error) {
1746         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1747                                error.get_msg ().c_str ());
1748         notmuch->exception_reported = true;
1749         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1750     }
1751
1752     if (notmuch->atomic_dirty) {
1753         ++notmuch->revision;
1754         notmuch->atomic_dirty = false;
1755     }
1756
1757   DONE:
1758     notmuch->atomic_nesting--;
1759     return NOTMUCH_STATUS_SUCCESS;
1760 }
1761
1762 unsigned long
1763 notmuch_database_get_revision (notmuch_database_t *notmuch,
1764                                const char **uuid)
1765 {
1766     if (uuid)
1767         *uuid = notmuch->uuid;
1768     return notmuch->revision;
1769 }
1770
1771 /* We allow the user to use arbitrarily long paths for directories. But
1772  * we have a term-length limit. So if we exceed that, we'll use the
1773  * SHA-1 of the path for the database term.
1774  *
1775  * Note: This function may return the original value of 'path'. If it
1776  * does not, then the caller is responsible to free() the returned
1777  * value.
1778  */
1779 const char *
1780 _notmuch_database_get_directory_db_path (const char *path)
1781 {
1782     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1783
1784     if (term_len > NOTMUCH_TERM_MAX)
1785         return _notmuch_sha1_of_string (path);
1786     else
1787         return path;
1788 }
1789
1790 /* Given a path, split it into two parts: the directory part is all
1791  * components except for the last, and the basename is that last
1792  * component. Getting the return-value for either part is optional
1793  * (the caller can pass NULL).
1794  *
1795  * The original 'path' can represent either a regular file or a
1796  * directory---the splitting will be carried out in the same way in
1797  * either case. Trailing slashes on 'path' will be ignored, and any
1798  * cases of multiple '/' characters appearing in series will be
1799  * treated as a single '/'.
1800  *
1801  * Allocation (if any) will have 'ctx' as the talloc owner. But
1802  * pointers will be returned within the original path string whenever
1803  * possible.
1804  *
1805  * Note: If 'path' is non-empty and contains no non-trailing slash,
1806  * (that is, consists of a filename with no parent directory), then
1807  * the directory returned will be an empty string. However, if 'path'
1808  * is an empty string, then both directory and basename will be
1809  * returned as NULL.
1810  */
1811 notmuch_status_t
1812 _notmuch_database_split_path (void *ctx,
1813                               const char *path,
1814                               const char **directory,
1815                               const char **basename)
1816 {
1817     const char *slash;
1818
1819     if (path == NULL || *path == '\0') {
1820         if (directory)
1821             *directory = NULL;
1822         if (basename)
1823             *basename = NULL;
1824         return NOTMUCH_STATUS_SUCCESS;
1825     }
1826
1827     /* Find the last slash (not counting a trailing slash), if any. */
1828
1829     slash = path + strlen (path) - 1;
1830
1831     /* First, skip trailing slashes. */
1832     while (slash != path && *slash == '/')
1833         --slash;
1834
1835     /* Then, find a slash. */
1836     while (slash != path && *slash != '/') {
1837         if (basename)
1838             *basename = slash;
1839
1840         --slash;
1841     }
1842
1843     /* Finally, skip multiple slashes. */
1844     while (slash != path && *(slash - 1) == '/')
1845         --slash;
1846
1847     if (slash == path) {
1848         if (directory)
1849             *directory = talloc_strdup (ctx, "");
1850         if (basename)
1851             *basename = path;
1852     } else {
1853         if (directory)
1854             *directory = talloc_strndup (ctx, path, slash - path);
1855     }
1856
1857     return NOTMUCH_STATUS_SUCCESS;
1858 }
1859
1860 /* Find the document ID of the specified directory.
1861  *
1862  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1863  * created if one does not exist for 'path'.  Otherwise, if the
1864  * directory document does not exist, this sets *directory_id to
1865  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1866  */
1867 notmuch_status_t
1868 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1869                                      const char *path,
1870                                      notmuch_find_flags_t flags,
1871                                      unsigned int *directory_id)
1872 {
1873     notmuch_directory_t *directory;
1874     notmuch_status_t status;
1875
1876     if (path == NULL) {
1877         *directory_id = 0;
1878         return NOTMUCH_STATUS_SUCCESS;
1879     }
1880
1881     directory = _notmuch_directory_create (notmuch, path, flags, &status);
1882     if (status || ! directory) {
1883         *directory_id = -1;
1884         return status;
1885     }
1886
1887     *directory_id = _notmuch_directory_get_document_id (directory);
1888
1889     notmuch_directory_destroy (directory);
1890
1891     return NOTMUCH_STATUS_SUCCESS;
1892 }
1893
1894 const char *
1895 _notmuch_database_get_directory_path (void *ctx,
1896                                       notmuch_database_t *notmuch,
1897                                       unsigned int doc_id)
1898 {
1899     Xapian::Document document;
1900
1901     document = find_document_for_doc_id (notmuch, doc_id);
1902
1903     return talloc_strdup (ctx, document.get_data ().c_str ());
1904 }
1905
1906 /* Given a legal 'filename' for the database, (either relative to
1907  * database path or absolute with initial components identical to
1908  * database path), return a new string (with 'ctx' as the talloc
1909  * owner) suitable for use as a direntry term value.
1910  *
1911  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1912  * will be created in the database as needed.  Otherwise, if the
1913  * necessary directory documents do not exist, this sets
1914  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1915  */
1916 notmuch_status_t
1917 _notmuch_database_filename_to_direntry (void *ctx,
1918                                         notmuch_database_t *notmuch,
1919                                         const char *filename,
1920                                         notmuch_find_flags_t flags,
1921                                         char **direntry)
1922 {
1923     const char *relative, *directory, *basename;
1924     Xapian::docid directory_id;
1925     notmuch_status_t status;
1926
1927     relative = _notmuch_database_relative_path (notmuch, filename);
1928
1929     status = _notmuch_database_split_path (ctx, relative,
1930                                            &directory, &basename);
1931     if (status)
1932         return status;
1933
1934     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1935                                                   &directory_id);
1936     if (status || directory_id == (unsigned int) -1) {
1937         *direntry = NULL;
1938         return status;
1939     }
1940
1941     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1942
1943     return NOTMUCH_STATUS_SUCCESS;
1944 }
1945
1946 /* Given a legal 'path' for the database, return the relative path.
1947  *
1948  * The return value will be a pointer to the original path contents,
1949  * and will be either the original string (if 'path' was relative) or
1950  * a portion of the string (if path was absolute and begins with the
1951  * database path).
1952  */
1953 const char *
1954 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1955                                  const char *path)
1956 {
1957     const char *db_path, *relative;
1958     unsigned int db_path_len;
1959
1960     db_path = notmuch_database_get_path (notmuch);
1961     db_path_len = strlen (db_path);
1962
1963     relative = path;
1964
1965     if (*relative == '/') {
1966         while (*relative == '/' && *(relative + 1) == '/')
1967             relative++;
1968
1969         if (strncmp (relative, db_path, db_path_len) == 0) {
1970             relative += db_path_len;
1971             while (*relative == '/')
1972                 relative++;
1973         }
1974     }
1975
1976     return relative;
1977 }
1978
1979 notmuch_status_t
1980 notmuch_database_get_directory (notmuch_database_t *notmuch,
1981                                 const char *path,
1982                                 notmuch_directory_t **directory)
1983 {
1984     notmuch_status_t status;
1985
1986     if (directory == NULL)
1987         return NOTMUCH_STATUS_NULL_POINTER;
1988     *directory = NULL;
1989
1990     try {
1991         *directory = _notmuch_directory_create (notmuch, path,
1992                                                 NOTMUCH_FIND_LOOKUP, &status);
1993     } catch (const Xapian::Error &error) {
1994         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1995                                error.get_msg ().c_str ());
1996         notmuch->exception_reported = true;
1997         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1998     }
1999     return status;
2000 }
2001
2002 /* Allocate a document ID that satisfies the following criteria:
2003  *
2004  * 1. The ID does not exist for any document in the Xapian database
2005  *
2006  * 2. The ID was not previously returned from this function
2007  *
2008  * 3. The ID is the smallest integer satisfying (1) and (2)
2009  *
2010  * This function will trigger an internal error if these constraints
2011  * cannot all be satisfied, (that is, the pool of available document
2012  * IDs has been exhausted).
2013  */
2014 unsigned int
2015 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2016 {
2017     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2018
2019     notmuch->last_doc_id++;
2020
2021     if (notmuch->last_doc_id == 0)
2022         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2023
2024     return notmuch->last_doc_id;
2025 }
2026
2027 notmuch_status_t
2028 notmuch_database_remove_message (notmuch_database_t *notmuch,
2029                                  const char *filename)
2030 {
2031     notmuch_status_t status;
2032     notmuch_message_t *message;
2033
2034     status = notmuch_database_find_message_by_filename (notmuch, filename,
2035                                                         &message);
2036
2037     if (status == NOTMUCH_STATUS_SUCCESS && message) {
2038         status = _notmuch_message_remove_filename (message, filename);
2039         if (status == NOTMUCH_STATUS_SUCCESS)
2040             _notmuch_message_delete (message);
2041         else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2042             _notmuch_message_sync (message);
2043
2044         notmuch_message_destroy (message);
2045     }
2046
2047     return status;
2048 }
2049
2050 notmuch_status_t
2051 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2052                                            const char *filename,
2053                                            notmuch_message_t **message_ret)
2054 {
2055     void *local;
2056     const char *prefix = _find_prefix ("file-direntry");
2057     char *direntry, *term;
2058     Xapian::PostingIterator i, end;
2059     notmuch_status_t status;
2060
2061     if (message_ret == NULL)
2062         return NOTMUCH_STATUS_NULL_POINTER;
2063
2064     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2065         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2066
2067     /* return NULL on any failure */
2068     *message_ret = NULL;
2069
2070     local = talloc_new (notmuch);
2071
2072     try {
2073         status = _notmuch_database_filename_to_direntry (
2074             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2075         if (status || ! direntry)
2076             goto DONE;
2077
2078         term = talloc_asprintf (local, "%s%s", prefix, direntry);
2079
2080         find_doc_ids_for_term (notmuch, term, &i, &end);
2081
2082         if (i != end) {
2083             notmuch_private_status_t private_status;
2084
2085             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2086                                                     &private_status);
2087             if (*message_ret == NULL)
2088                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2089         }
2090     } catch (const Xapian::Error &error) {
2091         _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2092                                error.get_msg ().c_str ());
2093         notmuch->exception_reported = true;
2094         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2095     }
2096
2097   DONE:
2098     talloc_free (local);
2099
2100     if (status && *message_ret) {
2101         notmuch_message_destroy (*message_ret);
2102         *message_ret = NULL;
2103     }
2104     return status;
2105 }
2106
2107 notmuch_string_list_t *
2108 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2109                                          Xapian::TermIterator &end,
2110                                          const char *prefix)
2111 {
2112     int prefix_len = strlen (prefix);
2113     notmuch_string_list_t *list;
2114
2115     list = _notmuch_string_list_create (ctx);
2116     if (unlikely (list == NULL))
2117         return NULL;
2118
2119     for (i.skip_to (prefix); i != end; i++) {
2120         /* Terminate loop at first term without desired prefix. */
2121         if (strncmp ((*i).c_str (), prefix, prefix_len))
2122             break;
2123
2124         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2125     }
2126
2127     return list;
2128 }
2129
2130 notmuch_tags_t *
2131 notmuch_database_get_all_tags (notmuch_database_t *db)
2132 {
2133     Xapian::TermIterator i, end;
2134     notmuch_string_list_t *tags;
2135
2136     try {
2137         i = db->xapian_db->allterms_begin ();
2138         end = db->xapian_db->allterms_end ();
2139         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2140                                                         _find_prefix ("tag"));
2141         _notmuch_string_list_sort (tags);
2142         return _notmuch_tags_create (db, tags);
2143     } catch (const Xapian::Error &error) {
2144         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2145                                error.get_msg ().c_str ());
2146         db->exception_reported = true;
2147         return NULL;
2148     }
2149 }
2150
2151 const char *
2152 notmuch_database_status_string (const notmuch_database_t *notmuch)
2153 {
2154     return notmuch->status_string;
2155 }