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