]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib: drop two gratuitous assignments to database mode
[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_database_destroy (notmuch);
998             notmuch = NULL;
999             status = NOTMUCH_STATUS_FILE_ERROR;
1000             goto DONE;
1001         }
1002
1003         /* Check features. */
1004         incompat_features = NULL;
1005         notmuch->features = _parse_features (
1006             local, notmuch->xapian_db->get_metadata ("features").c_str (),
1007             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
1008             &incompat_features);
1009         if (incompat_features) {
1010             IGNORE_RESULT (asprintf (&message,
1011                                      "Error: Notmuch database at %s\n"
1012                                      "       requires features (%s)\n"
1013                                      "       not supported by this version of notmuch.\n",
1014                                      notmuch_path, incompat_features));
1015             notmuch_database_destroy (notmuch);
1016             notmuch = NULL;
1017             status = NOTMUCH_STATUS_FILE_ERROR;
1018             goto DONE;
1019         }
1020
1021         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1022         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1023         if (last_thread_id.empty ()) {
1024             notmuch->last_thread_id = 0;
1025         } else {
1026             const char *str;
1027             char *end;
1028
1029             str = last_thread_id.c_str ();
1030             notmuch->last_thread_id = strtoull (str, &end, 16);
1031             if (*end != '\0')
1032                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1033         }
1034
1035         /* Get current highest revision number. */
1036         last_mod = notmuch->xapian_db->get_value_upper_bound (
1037             NOTMUCH_VALUE_LAST_MOD);
1038         if (last_mod.empty ())
1039             notmuch->revision = 0;
1040         else
1041             notmuch->revision = Xapian::sortable_unserialise (last_mod);
1042         notmuch->uuid = talloc_strdup (
1043             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1044
1045         notmuch->query_parser = new Xapian::QueryParser;
1046         notmuch->term_gen = new Xapian::TermGenerator;
1047         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1048         notmuch->value_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1049         notmuch->date_range_processor = new ParseTimeRangeProcessor (NOTMUCH_VALUE_TIMESTAMP, "date:");
1050         notmuch->last_mod_range_processor = new Xapian::NumberRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1051         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1052         notmuch->query_parser->set_database (*notmuch->xapian_db);
1053         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1054         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1055         notmuch->query_parser->add_rangeprocessor (notmuch->value_range_processor);
1056         notmuch->query_parser->add_rangeprocessor (notmuch->date_range_processor);
1057         notmuch->query_parser->add_rangeprocessor (notmuch->last_mod_range_processor);
1058
1059         for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
1060             const prefix_t *prefix = &prefix_table[i];
1061             if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
1062                 _setup_query_field (prefix, notmuch);
1063             }
1064         }
1065         status = _setup_user_query_fields (notmuch);
1066     } catch (const Xapian::Error &error) {
1067         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1068                                  error.get_msg ().c_str ()));
1069         notmuch_database_destroy (notmuch);
1070         notmuch = NULL;
1071         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1072     }
1073
1074   DONE:
1075     talloc_free (local);
1076
1077     if (message) {
1078         if (status_string)
1079             *status_string = message;
1080         else
1081             free (message);
1082     }
1083
1084     if (database)
1085         *database = notmuch;
1086     else
1087         talloc_free (notmuch);
1088
1089     if (notmuch)
1090         notmuch->open = true;
1091
1092     return status;
1093 }
1094
1095 notmuch_status_t
1096 notmuch_database_close (notmuch_database_t *notmuch)
1097 {
1098     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1099
1100     /* Many Xapian objects (and thus notmuch objects) hold references to
1101      * the database, so merely deleting the database may not suffice to
1102      * close it.  Thus, we explicitly close it here. */
1103     if (notmuch->open) {
1104         try {
1105             /* If there's an outstanding transaction, it's unclear if
1106              * closing the Xapian database commits everything up to
1107              * that transaction, or may discard committed (but
1108              * unflushed) transactions.  To be certain, explicitly
1109              * cancel any outstanding transaction before closing. */
1110             if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1111                 notmuch->atomic_nesting)
1112                 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1113                 ->cancel_transaction ();
1114
1115             /* Close the database.  This implicitly flushes
1116              * outstanding changes. */
1117             notmuch->xapian_db->close ();
1118         } catch (const Xapian::Error &error) {
1119             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1120             if (! notmuch->exception_reported) {
1121                 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1122                                        error.get_msg ().c_str ());
1123             }
1124         }
1125     }
1126     notmuch->open = false;
1127     return status;
1128 }
1129
1130 notmuch_status_t
1131 _notmuch_database_reopen (notmuch_database_t *notmuch)
1132 {
1133     if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1134         return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1135
1136     try {
1137         notmuch->xapian_db->reopen ();
1138     } catch (const Xapian::Error &error) {
1139         if (! notmuch->exception_reported) {
1140             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1141                                    error.get_msg ().c_str ());
1142             notmuch->exception_reported = true;
1143         }
1144         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1145     }
1146
1147     notmuch->view++;
1148
1149     return NOTMUCH_STATUS_SUCCESS;
1150 }
1151
1152 static int
1153 unlink_cb (const char *path,
1154            unused (const struct stat *sb),
1155            unused (int type),
1156            unused (struct FTW *ftw))
1157 {
1158     return remove (path);
1159 }
1160
1161 static int
1162 rmtree (const char *path)
1163 {
1164     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1165 }
1166
1167 class NotmuchCompactor : public Xapian::Compactor
1168 {
1169     notmuch_compact_status_cb_t status_cb;
1170     void *status_closure;
1171
1172 public:
1173     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1174         status_cb (cb), status_closure (closure)
1175     {
1176     }
1177
1178     virtual void
1179     set_status (const std::string &table, const std::string &status)
1180     {
1181         char *msg;
1182
1183         if (status_cb == NULL)
1184             return;
1185
1186         if (status.length () == 0)
1187             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str ());
1188         else
1189             msg = talloc_asprintf (NULL, "     %s", status.c_str ());
1190
1191         if (msg == NULL) {
1192             return;
1193         }
1194
1195         status_cb (msg, status_closure);
1196         talloc_free (msg);
1197     }
1198 };
1199
1200 /* Compacts the given database, optionally saving the original database
1201  * in backup_path. Additionally, a callback function can be provided to
1202  * give the user feedback on the progress of the (likely long-lived)
1203  * compaction process.
1204  *
1205  * The backup path must point to a directory on the same volume as the
1206  * original database. Passing a NULL backup_path will result in the
1207  * uncompacted database being deleted after compaction has finished.
1208  * Note that the database write lock will be held during the
1209  * compaction process to protect data integrity.
1210  */
1211 notmuch_status_t
1212 notmuch_database_compact (const char *path,
1213                           const char *backup_path,
1214                           notmuch_compact_status_cb_t status_cb,
1215                           void *closure)
1216 {
1217     void *local;
1218     char *notmuch_path, *xapian_path, *compact_xapian_path;
1219     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1220     notmuch_database_t *notmuch = NULL;
1221     struct stat statbuf;
1222     bool keep_backup;
1223     char *message = NULL;
1224
1225     local = talloc_new (NULL);
1226     if (! local)
1227         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1228
1229     ret = notmuch_database_open_verbose (path,
1230                                          NOTMUCH_DATABASE_MODE_READ_WRITE,
1231                                          &notmuch,
1232                                          &message);
1233     if (ret) {
1234         if (status_cb) status_cb (message, closure);
1235         goto DONE;
1236     }
1237
1238     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1239         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1240         goto DONE;
1241     }
1242
1243     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1244         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1245         goto DONE;
1246     }
1247
1248     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1249         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1250         goto DONE;
1251     }
1252
1253     if (backup_path == NULL) {
1254         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1255             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1256             goto DONE;
1257         }
1258         keep_backup = false;
1259     } else {
1260         keep_backup = true;
1261     }
1262
1263     if (stat (backup_path, &statbuf) != -1) {
1264         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1265         ret = NOTMUCH_STATUS_FILE_ERROR;
1266         goto DONE;
1267     }
1268     if (errno != ENOENT) {
1269         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1270                                strerror (errno));
1271         ret = NOTMUCH_STATUS_FILE_ERROR;
1272         goto DONE;
1273     }
1274
1275     /* Unconditionally attempt to remove old work-in-progress database (if
1276      * any). This is "protected" by database lock. If this fails due to write
1277      * errors (etc), the following code will fail and provide error message.
1278      */
1279     (void) rmtree (compact_xapian_path);
1280
1281     try {
1282         NotmuchCompactor compactor (status_cb, closure);
1283         notmuch->xapian_db->compact (compact_xapian_path, Xapian::DBCOMPACT_NO_RENUMBER, 0, compactor);
1284     } catch (const Xapian::Error &error) {
1285         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg ().c_str ());
1286         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1287         goto DONE;
1288     }
1289
1290     if (rename (xapian_path, backup_path)) {
1291         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1292                                xapian_path, backup_path, strerror (errno));
1293         ret = NOTMUCH_STATUS_FILE_ERROR;
1294         goto DONE;
1295     }
1296
1297     if (rename (compact_xapian_path, xapian_path)) {
1298         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1299                                compact_xapian_path, xapian_path, strerror (errno));
1300         ret = NOTMUCH_STATUS_FILE_ERROR;
1301         goto DONE;
1302     }
1303
1304     if (! keep_backup) {
1305         if (rmtree (backup_path)) {
1306             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1307                                    backup_path, strerror (errno));
1308             ret = NOTMUCH_STATUS_FILE_ERROR;
1309             goto DONE;
1310         }
1311     }
1312
1313   DONE:
1314     if (notmuch) {
1315         notmuch_status_t ret2;
1316
1317         const char *str = notmuch_database_status_string (notmuch);
1318         if (status_cb && str)
1319             status_cb (str, closure);
1320
1321         ret2 = notmuch_database_destroy (notmuch);
1322
1323         /* don't clobber previous error status */
1324         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1325             ret = ret2;
1326     }
1327
1328     talloc_free (local);
1329
1330     return ret;
1331 }
1332
1333 notmuch_status_t
1334 notmuch_database_destroy (notmuch_database_t *notmuch)
1335 {
1336     notmuch_status_t status;
1337
1338     status = notmuch_database_close (notmuch);
1339
1340     delete notmuch->term_gen;
1341     notmuch->term_gen = NULL;
1342     delete notmuch->query_parser;
1343     notmuch->query_parser = NULL;
1344     delete notmuch->xapian_db;
1345     notmuch->xapian_db = NULL;
1346     delete notmuch->value_range_processor;
1347     notmuch->value_range_processor = NULL;
1348     delete notmuch->date_range_processor;
1349     notmuch->date_range_processor = NULL;
1350     delete notmuch->last_mod_range_processor;
1351     notmuch->last_mod_range_processor = NULL;
1352
1353     talloc_free (notmuch);
1354
1355     return status;
1356 }
1357
1358 const char *
1359 notmuch_database_get_path (notmuch_database_t *notmuch)
1360 {
1361     return notmuch->path;
1362 }
1363
1364 unsigned int
1365 notmuch_database_get_version (notmuch_database_t *notmuch)
1366 {
1367     unsigned int version;
1368     string version_string;
1369     const char *str;
1370     char *end;
1371
1372     try {
1373         version_string = notmuch->xapian_db->get_metadata ("version");
1374     } catch (const Xapian::Error &error) {
1375         LOG_XAPIAN_EXCEPTION (notmuch, error);
1376         return 0;
1377     }
1378
1379     if (version_string.empty ())
1380         return 0;
1381
1382     str = version_string.c_str ();
1383     if (str == NULL || *str == '\0')
1384         return 0;
1385
1386     version = strtoul (str, &end, 10);
1387     if (*end != '\0')
1388         INTERNAL_ERROR ("Malformed database version: %s", str);
1389
1390     return version;
1391 }
1392
1393 notmuch_bool_t
1394 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1395 {
1396     unsigned int version;
1397
1398     if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_WRITE)
1399         return FALSE;
1400
1401     if (NOTMUCH_FEATURES_CURRENT & ~notmuch->features)
1402         return TRUE;
1403
1404     version = notmuch_database_get_version (notmuch);
1405
1406     return (version > 0 && version < NOTMUCH_DATABASE_VERSION);
1407 }
1408
1409 static volatile sig_atomic_t do_progress_notify = 0;
1410
1411 static void
1412 handle_sigalrm (unused (int signal))
1413 {
1414     do_progress_notify = 1;
1415 }
1416
1417 /* Upgrade the current database.
1418  *
1419  * After opening a database in read-write mode, the client should
1420  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1421  * if so, upgrade with this function before making any modifications.
1422  *
1423  * The optional progress_notify callback can be used by the caller to
1424  * provide progress indication to the user. If non-NULL it will be
1425  * called periodically with 'count' as the number of messages upgraded
1426  * so far and 'total' the overall number of messages that will be
1427  * converted.
1428  */
1429 notmuch_status_t
1430 notmuch_database_upgrade (notmuch_database_t *notmuch,
1431                           void (*progress_notify) (void *closure,
1432                                                    double progress),
1433                           void *closure)
1434 {
1435     void *local = talloc_new (NULL);
1436     Xapian::TermIterator t, t_end;
1437     Xapian::WritableDatabase *db;
1438     struct sigaction action;
1439     struct itimerval timerval;
1440     bool timer_is_active = false;
1441     enum _notmuch_features target_features, new_features;
1442     notmuch_status_t status;
1443     notmuch_private_status_t private_status;
1444     notmuch_query_t *query = NULL;
1445     unsigned int count = 0, total = 0;
1446
1447     status = _notmuch_database_ensure_writable (notmuch);
1448     if (status)
1449         return status;
1450
1451     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1452
1453     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1454     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1455
1456     if (! notmuch_database_needs_upgrade (notmuch))
1457         return NOTMUCH_STATUS_SUCCESS;
1458
1459     if (progress_notify) {
1460         /* Set up our handler for SIGALRM */
1461         memset (&action, 0, sizeof (struct sigaction));
1462         action.sa_handler = handle_sigalrm;
1463         sigemptyset (&action.sa_mask);
1464         action.sa_flags = SA_RESTART;
1465         sigaction (SIGALRM, &action, NULL);
1466
1467         /* Then start a timer to send SIGALRM once per second. */
1468         timerval.it_interval.tv_sec = 1;
1469         timerval.it_interval.tv_usec = 0;
1470         timerval.it_value.tv_sec = 1;
1471         timerval.it_value.tv_usec = 0;
1472         setitimer (ITIMER_REAL, &timerval, NULL);
1473
1474         timer_is_active = true;
1475     }
1476
1477     /* Figure out how much total work we need to do. */
1478     if (new_features &
1479         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1480          NOTMUCH_FEATURE_LAST_MOD)) {
1481         query = notmuch_query_create (notmuch, "");
1482         unsigned msg_count;
1483
1484         status = notmuch_query_count_messages (query, &msg_count);
1485         if (status)
1486             goto DONE;
1487
1488         total += msg_count;
1489         notmuch_query_destroy (query);
1490         query = NULL;
1491     }
1492     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1493         t_end = db->allterms_end ("XTIMESTAMP");
1494         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1495             ++total;
1496     }
1497     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1498         /* The ghost message upgrade converts all thread_id_*
1499          * metadata values into ghost message documents. */
1500         t_end = db->metadata_keys_end ("thread_id_");
1501         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1502             ++total;
1503     }
1504
1505     /* Perform the upgrade in a transaction. */
1506     db->begin_transaction (true);
1507
1508     /* Set the target features so we write out changes in the desired
1509      * format. */
1510     notmuch->features = target_features;
1511
1512     /* Perform per-message upgrades. */
1513     if (new_features &
1514         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1515          NOTMUCH_FEATURE_LAST_MOD)) {
1516         notmuch_messages_t *messages;
1517         notmuch_message_t *message;
1518         char *filename;
1519
1520         query = notmuch_query_create (notmuch, "");
1521
1522         status = notmuch_query_search_messages (query, &messages);
1523         if (status)
1524             goto DONE;
1525         for (;
1526              notmuch_messages_valid (messages);
1527              notmuch_messages_move_to_next (messages)) {
1528             if (do_progress_notify) {
1529                 progress_notify (closure, (double) count / total);
1530                 do_progress_notify = 0;
1531             }
1532
1533             message = notmuch_messages_get (messages);
1534
1535             /* Before version 1, each message document had its
1536              * filename in the data field. Copy that into the new
1537              * format by calling notmuch_message_add_filename.
1538              */
1539             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1540                 filename = _notmuch_message_talloc_copy_data (message);
1541                 if (filename && *filename != '\0') {
1542                     _notmuch_message_add_filename (message, filename);
1543                     _notmuch_message_clear_data (message);
1544                 }
1545                 talloc_free (filename);
1546             }
1547
1548             /* Prior to version 2, the "folder:" prefix was
1549              * probabilistic and stemmed. Change it to the current
1550              * boolean prefix. Add "path:" prefixes while at it.
1551              */
1552             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1553                 _notmuch_message_upgrade_folder (message);
1554
1555             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1556              * track modification revisions.  Give all messages the
1557              * next available revision; since we just started tracking
1558              * revisions for this database, that will be 1.
1559              */
1560             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1561                 _notmuch_message_upgrade_last_mod (message);
1562
1563             _notmuch_message_sync (message);
1564
1565             notmuch_message_destroy (message);
1566
1567             count++;
1568         }
1569
1570         notmuch_query_destroy (query);
1571         query = NULL;
1572     }
1573
1574     /* Perform per-directory upgrades. */
1575
1576     /* Before version 1 we stored directory timestamps in
1577      * XTIMESTAMP documents instead of the current XDIRECTORY
1578      * documents. So copy those as well. */
1579     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1580         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1581
1582         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1583              t != t_end;
1584              t++) {
1585             Xapian::PostingIterator p, p_end;
1586             std::string term = *t;
1587
1588             p_end = notmuch->xapian_db->postlist_end (term);
1589
1590             for (p = notmuch->xapian_db->postlist_begin (term);
1591                  p != p_end;
1592                  p++) {
1593                 Xapian::Document document;
1594                 time_t mtime;
1595                 notmuch_directory_t *directory;
1596
1597                 if (do_progress_notify) {
1598                     progress_notify (closure, (double) count / total);
1599                     do_progress_notify = 0;
1600                 }
1601
1602                 document = find_document_for_doc_id (notmuch, *p);
1603                 mtime = Xapian::sortable_unserialise (
1604                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1605
1606                 directory = _notmuch_directory_find_or_create (notmuch, term.c_str () + 10,
1607                                                                NOTMUCH_FIND_CREATE, &status);
1608                 notmuch_directory_set_mtime (directory, mtime);
1609                 notmuch_directory_destroy (directory);
1610
1611                 db->delete_document (*p);
1612             }
1613
1614             ++count;
1615         }
1616     }
1617
1618     /* Perform metadata upgrades. */
1619
1620     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1621      * messages were stored as database metadata. Change these to
1622      * ghost messages.
1623      */
1624     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1625         notmuch_message_t *message;
1626         std::string message_id, thread_id;
1627
1628         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1629         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1630              t != t_end; ++t) {
1631             if (do_progress_notify) {
1632                 progress_notify (closure, (double) count / total);
1633                 do_progress_notify = 0;
1634             }
1635
1636             message_id = (*t).substr (
1637                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1638             thread_id = db->get_metadata (*t);
1639
1640             /* Create ghost message */
1641             message = _notmuch_message_create_for_message_id (
1642                 notmuch, message_id.c_str (), &private_status);
1643             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1644                 /* Document already exists; ignore the stored thread ID */
1645             } else if (private_status ==
1646                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1647                 private_status = _notmuch_message_initialize_ghost (
1648                     message, thread_id.c_str ());
1649                 if (! private_status)
1650                     _notmuch_message_sync (message);
1651             }
1652
1653             if (private_status) {
1654                 _notmuch_database_log (notmuch,
1655                                        "Upgrade failed while creating ghost messages.\n");
1656                 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1657                 goto DONE;
1658             }
1659
1660             /* Clear saved metadata thread ID */
1661             db->set_metadata (*t, "");
1662
1663             ++count;
1664         }
1665     }
1666
1667     status = NOTMUCH_STATUS_SUCCESS;
1668     db->set_metadata ("features", _print_features (local, notmuch->features));
1669     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1670
1671   DONE:
1672     if (status == NOTMUCH_STATUS_SUCCESS)
1673         db->commit_transaction ();
1674     else
1675         db->cancel_transaction ();
1676
1677     if (timer_is_active) {
1678         /* Now stop the timer. */
1679         timerval.it_interval.tv_sec = 0;
1680         timerval.it_interval.tv_usec = 0;
1681         timerval.it_value.tv_sec = 0;
1682         timerval.it_value.tv_usec = 0;
1683         setitimer (ITIMER_REAL, &timerval, NULL);
1684
1685         /* And disable the signal handler. */
1686         action.sa_handler = SIG_IGN;
1687         sigaction (SIGALRM, &action, NULL);
1688     }
1689
1690     if (query)
1691         notmuch_query_destroy (query);
1692
1693     talloc_free (local);
1694     return status;
1695 }
1696
1697 notmuch_status_t
1698 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1699 {
1700     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1701         notmuch->atomic_nesting > 0)
1702         goto DONE;
1703
1704     if (notmuch_database_needs_upgrade (notmuch))
1705         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1706
1707     try {
1708         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1709     } catch (const Xapian::Error &error) {
1710         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1711                                error.get_msg ().c_str ());
1712         notmuch->exception_reported = true;
1713         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1714     }
1715
1716   DONE:
1717     notmuch->atomic_nesting++;
1718     return NOTMUCH_STATUS_SUCCESS;
1719 }
1720
1721 notmuch_status_t
1722 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1723 {
1724     Xapian::WritableDatabase *db;
1725
1726     if (notmuch->atomic_nesting == 0)
1727         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1728
1729     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1730         notmuch->atomic_nesting > 1)
1731         goto DONE;
1732
1733     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1734     try {
1735         db->commit_transaction ();
1736
1737         /* This is a hack for testing.  Xapian never flushes on a
1738          * non-flushed commit, even if the flush threshold is 1.
1739          * However, we rely on flushing to test atomicity. */
1740         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1741         if (thresh && atoi (thresh) == 1)
1742             db->commit ();
1743     } catch (const Xapian::Error &error) {
1744         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1745                                error.get_msg ().c_str ());
1746         notmuch->exception_reported = true;
1747         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1748     }
1749
1750     if (notmuch->atomic_dirty) {
1751         ++notmuch->revision;
1752         notmuch->atomic_dirty = false;
1753     }
1754
1755   DONE:
1756     notmuch->atomic_nesting--;
1757     return NOTMUCH_STATUS_SUCCESS;
1758 }
1759
1760 unsigned long
1761 notmuch_database_get_revision (notmuch_database_t *notmuch,
1762                                const char **uuid)
1763 {
1764     if (uuid)
1765         *uuid = notmuch->uuid;
1766     return notmuch->revision;
1767 }
1768
1769 /* We allow the user to use arbitrarily long paths for directories. But
1770  * we have a term-length limit. So if we exceed that, we'll use the
1771  * SHA-1 of the path for the database term.
1772  *
1773  * Note: This function may return the original value of 'path'. If it
1774  * does not, then the caller is responsible to free() the returned
1775  * value.
1776  */
1777 const char *
1778 _notmuch_database_get_directory_db_path (const char *path)
1779 {
1780     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1781
1782     if (term_len > NOTMUCH_TERM_MAX)
1783         return _notmuch_sha1_of_string (path);
1784     else
1785         return path;
1786 }
1787
1788 /* Given a path, split it into two parts: the directory part is all
1789  * components except for the last, and the basename is that last
1790  * component. Getting the return-value for either part is optional
1791  * (the caller can pass NULL).
1792  *
1793  * The original 'path' can represent either a regular file or a
1794  * directory---the splitting will be carried out in the same way in
1795  * either case. Trailing slashes on 'path' will be ignored, and any
1796  * cases of multiple '/' characters appearing in series will be
1797  * treated as a single '/'.
1798  *
1799  * Allocation (if any) will have 'ctx' as the talloc owner. But
1800  * pointers will be returned within the original path string whenever
1801  * possible.
1802  *
1803  * Note: If 'path' is non-empty and contains no non-trailing slash,
1804  * (that is, consists of a filename with no parent directory), then
1805  * the directory returned will be an empty string. However, if 'path'
1806  * is an empty string, then both directory and basename will be
1807  * returned as NULL.
1808  */
1809 notmuch_status_t
1810 _notmuch_database_split_path (void *ctx,
1811                               const char *path,
1812                               const char **directory,
1813                               const char **basename)
1814 {
1815     const char *slash;
1816
1817     if (path == NULL || *path == '\0') {
1818         if (directory)
1819             *directory = NULL;
1820         if (basename)
1821             *basename = NULL;
1822         return NOTMUCH_STATUS_SUCCESS;
1823     }
1824
1825     /* Find the last slash (not counting a trailing slash), if any. */
1826
1827     slash = path + strlen (path) - 1;
1828
1829     /* First, skip trailing slashes. */
1830     while (slash != path && *slash == '/')
1831         --slash;
1832
1833     /* Then, find a slash. */
1834     while (slash != path && *slash != '/') {
1835         if (basename)
1836             *basename = slash;
1837
1838         --slash;
1839     }
1840
1841     /* Finally, skip multiple slashes. */
1842     while (slash != path && *(slash - 1) == '/')
1843         --slash;
1844
1845     if (slash == path) {
1846         if (directory)
1847             *directory = talloc_strdup (ctx, "");
1848         if (basename)
1849             *basename = path;
1850     } else {
1851         if (directory)
1852             *directory = talloc_strndup (ctx, path, slash - path);
1853     }
1854
1855     return NOTMUCH_STATUS_SUCCESS;
1856 }
1857
1858 /* Find the document ID of the specified directory.
1859  *
1860  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1861  * created if one does not exist for 'path'.  Otherwise, if the
1862  * directory document does not exist, this sets *directory_id to
1863  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1864  */
1865 notmuch_status_t
1866 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1867                                      const char *path,
1868                                      notmuch_find_flags_t flags,
1869                                      unsigned int *directory_id)
1870 {
1871     notmuch_directory_t *directory;
1872     notmuch_status_t status;
1873
1874     if (path == NULL) {
1875         *directory_id = 0;
1876         return NOTMUCH_STATUS_SUCCESS;
1877     }
1878
1879     directory = _notmuch_directory_find_or_create (notmuch, path, flags, &status);
1880     if (status || ! directory) {
1881         *directory_id = -1;
1882         return status;
1883     }
1884
1885     *directory_id = _notmuch_directory_get_document_id (directory);
1886
1887     notmuch_directory_destroy (directory);
1888
1889     return NOTMUCH_STATUS_SUCCESS;
1890 }
1891
1892 const char *
1893 _notmuch_database_get_directory_path (void *ctx,
1894                                       notmuch_database_t *notmuch,
1895                                       unsigned int doc_id)
1896 {
1897     Xapian::Document document;
1898
1899     document = find_document_for_doc_id (notmuch, doc_id);
1900
1901     return talloc_strdup (ctx, document.get_data ().c_str ());
1902 }
1903
1904 /* Given a legal 'filename' for the database, (either relative to
1905  * database path or absolute with initial components identical to
1906  * database path), return a new string (with 'ctx' as the talloc
1907  * owner) suitable for use as a direntry term value.
1908  *
1909  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1910  * will be created in the database as needed.  Otherwise, if the
1911  * necessary directory documents do not exist, this sets
1912  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1913  */
1914 notmuch_status_t
1915 _notmuch_database_filename_to_direntry (void *ctx,
1916                                         notmuch_database_t *notmuch,
1917                                         const char *filename,
1918                                         notmuch_find_flags_t flags,
1919                                         char **direntry)
1920 {
1921     const char *relative, *directory, *basename;
1922     Xapian::docid directory_id;
1923     notmuch_status_t status;
1924
1925     relative = _notmuch_database_relative_path (notmuch, filename);
1926
1927     status = _notmuch_database_split_path (ctx, relative,
1928                                            &directory, &basename);
1929     if (status)
1930         return status;
1931
1932     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1933                                                   &directory_id);
1934     if (status || directory_id == (unsigned int) -1) {
1935         *direntry = NULL;
1936         return status;
1937     }
1938
1939     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1940
1941     return NOTMUCH_STATUS_SUCCESS;
1942 }
1943
1944 /* Given a legal 'path' for the database, return the relative path.
1945  *
1946  * The return value will be a pointer to the original path contents,
1947  * and will be either the original string (if 'path' was relative) or
1948  * a portion of the string (if path was absolute and begins with the
1949  * database path).
1950  */
1951 const char *
1952 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1953                                  const char *path)
1954 {
1955     const char *db_path, *relative;
1956     unsigned int db_path_len;
1957
1958     db_path = notmuch_database_get_path (notmuch);
1959     db_path_len = strlen (db_path);
1960
1961     relative = path;
1962
1963     if (*relative == '/') {
1964         while (*relative == '/' && *(relative + 1) == '/')
1965             relative++;
1966
1967         if (strncmp (relative, db_path, db_path_len) == 0) {
1968             relative += db_path_len;
1969             while (*relative == '/')
1970                 relative++;
1971         }
1972     }
1973
1974     return relative;
1975 }
1976
1977 notmuch_status_t
1978 notmuch_database_get_directory (notmuch_database_t *notmuch,
1979                                 const char *path,
1980                                 notmuch_directory_t **directory)
1981 {
1982     notmuch_status_t status;
1983
1984     if (directory == NULL)
1985         return NOTMUCH_STATUS_NULL_POINTER;
1986     *directory = NULL;
1987
1988     try {
1989         *directory = _notmuch_directory_find_or_create (notmuch, path,
1990                                                         NOTMUCH_FIND_LOOKUP, &status);
1991     } catch (const Xapian::Error &error) {
1992         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1993                                error.get_msg ().c_str ());
1994         notmuch->exception_reported = true;
1995         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1996     }
1997     return status;
1998 }
1999
2000 /* Allocate a document ID that satisfies the following criteria:
2001  *
2002  * 1. The ID does not exist for any document in the Xapian database
2003  *
2004  * 2. The ID was not previously returned from this function
2005  *
2006  * 3. The ID is the smallest integer satisfying (1) and (2)
2007  *
2008  * This function will trigger an internal error if these constraints
2009  * cannot all be satisfied, (that is, the pool of available document
2010  * IDs has been exhausted).
2011  */
2012 unsigned int
2013 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
2014 {
2015     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2016
2017     notmuch->last_doc_id++;
2018
2019     if (notmuch->last_doc_id == 0)
2020         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2021
2022     return notmuch->last_doc_id;
2023 }
2024
2025 notmuch_status_t
2026 notmuch_database_remove_message (notmuch_database_t *notmuch,
2027                                  const char *filename)
2028 {
2029     notmuch_status_t status;
2030     notmuch_message_t *message;
2031
2032     status = notmuch_database_find_message_by_filename (notmuch, filename,
2033                                                         &message);
2034
2035     if (status == NOTMUCH_STATUS_SUCCESS && message) {
2036         status = _notmuch_message_remove_filename (message, filename);
2037         if (status == NOTMUCH_STATUS_SUCCESS)
2038             _notmuch_message_delete (message);
2039         else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2040             _notmuch_message_sync (message);
2041
2042         notmuch_message_destroy (message);
2043     }
2044
2045     return status;
2046 }
2047
2048 notmuch_status_t
2049 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2050                                            const char *filename,
2051                                            notmuch_message_t **message_ret)
2052 {
2053     void *local;
2054     const char *prefix = _find_prefix ("file-direntry");
2055     char *direntry, *term;
2056     Xapian::PostingIterator i, end;
2057     notmuch_status_t status;
2058
2059     if (message_ret == NULL)
2060         return NOTMUCH_STATUS_NULL_POINTER;
2061
2062     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2063         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2064
2065     /* return NULL on any failure */
2066     *message_ret = NULL;
2067
2068     local = talloc_new (notmuch);
2069
2070     try {
2071         status = _notmuch_database_filename_to_direntry (
2072             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2073         if (status || ! direntry)
2074             goto DONE;
2075
2076         term = talloc_asprintf (local, "%s%s", prefix, direntry);
2077
2078         find_doc_ids_for_term (notmuch, term, &i, &end);
2079
2080         if (i != end) {
2081             notmuch_private_status_t private_status;
2082
2083             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2084                                                     &private_status);
2085             if (*message_ret == NULL)
2086                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2087         }
2088     } catch (const Xapian::Error &error) {
2089         _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2090                                error.get_msg ().c_str ());
2091         notmuch->exception_reported = true;
2092         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2093     }
2094
2095   DONE:
2096     talloc_free (local);
2097
2098     if (status && *message_ret) {
2099         notmuch_message_destroy (*message_ret);
2100         *message_ret = NULL;
2101     }
2102     return status;
2103 }
2104
2105 notmuch_string_list_t *
2106 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2107                                          Xapian::TermIterator &end,
2108                                          const char *prefix)
2109 {
2110     int prefix_len = strlen (prefix);
2111     notmuch_string_list_t *list;
2112
2113     list = _notmuch_string_list_create (ctx);
2114     if (unlikely (list == NULL))
2115         return NULL;
2116
2117     for (i.skip_to (prefix); i != end; i++) {
2118         /* Terminate loop at first term without desired prefix. */
2119         if (strncmp ((*i).c_str (), prefix, prefix_len))
2120             break;
2121
2122         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2123     }
2124
2125     return list;
2126 }
2127
2128 notmuch_tags_t *
2129 notmuch_database_get_all_tags (notmuch_database_t *db)
2130 {
2131     Xapian::TermIterator i, end;
2132     notmuch_string_list_t *tags;
2133
2134     try {
2135         i = db->xapian_db->allterms_begin ();
2136         end = db->xapian_db->allterms_end ();
2137         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2138                                                         _find_prefix ("tag"));
2139         _notmuch_string_list_sort (tags);
2140         return _notmuch_tags_create (db, tags);
2141     } catch (const Xapian::Error &error) {
2142         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2143                                error.get_msg ().c_str ());
2144         db->exception_reported = true;
2145         return NULL;
2146     }
2147 }
2148
2149 const char *
2150 notmuch_database_status_string (const notmuch_database_t *notmuch)
2151 {
2152     return notmuch->status_string;
2153 }