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