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