]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
add property: query prefix to search for specific properties
[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 "string-util.h"
25
26 #include <iostream>
27
28 #include <sys/time.h>
29 #include <sys/stat.h>
30 #include <signal.h>
31 #include <ftw.h>
32
33 #include <glib.h> /* g_free, GPtrArray, GHashTable */
34 #include <glib-object.h> /* g_type_init */
35
36 #include <gmime/gmime.h> /* g_mime_init */
37
38 using namespace std;
39
40 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
41
42 typedef struct {
43     const char *name;
44     const char *prefix;
45 } prefix_t;
46
47 #define NOTMUCH_DATABASE_VERSION 3
48
49 #define STRINGIFY(s) _SUB_STRINGIFY(s)
50 #define _SUB_STRINGIFY(s) #s
51
52 #if HAVE_XAPIAN_DB_RETRY_LOCK
53 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
54 #else
55 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
56 #endif
57
58 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
59  *
60  * We currently have three different types of documents (mail, ghost,
61  * and directory) and also some metadata.
62  *
63  * Mail document
64  * -------------
65  * A mail document is associated with a particular email message. It
66  * is stored in one or more files on disk (though only one has its
67  * content indexed) and is uniquely identified  by its "id" field
68  * (which is generally the message ID). It is indexed with the
69  * following prefixed terms which the database uses to construct
70  * threads, etc.:
71  *
72  *    Single terms of given prefix:
73  *
74  *      type:   mail
75  *
76  *      id:     Unique ID of mail. This is from the Message-ID header
77  *              if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
78  *              If it's present and too long, then we use
79  *              "notmuch-sha1-<sha1_sum_of_message_id>".
80  *              If this header is not present, we use
81  *              "notmuch-sha1-<sha1_sum_of_entire_file>".
82  *
83  *      thread: The ID of the thread to which the mail belongs
84  *
85  *      replyto: The ID from the In-Reply-To header of the mail (if any).
86  *
87  *    Multiple terms of given prefix:
88  *
89  *      reference: All message IDs from In-Reply-To and References
90  *                 headers in the message.
91  *
92  *      tag:       Any tags associated with this message by the user.
93  *
94  *      file-direntry:  A colon-separated pair of values
95  *                      (INTEGER:STRING), where INTEGER is the
96  *                      document ID of a directory document, and
97  *                      STRING is the name of a file within that
98  *                      directory for this mail message.
99  *
100  *      property:       Has a property with key=value
101  *                 FIXME: if no = is present, should match on any value
102  *
103  *    A mail document also has four values:
104  *
105  *      TIMESTAMP:      The time_t value corresponding to the message's
106  *                      Date header.
107  *
108  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
109  *
110  *      FROM:           The value of the "From" header
111  *
112  *      SUBJECT:        The value of the "Subject" header
113  *
114  *      LAST_MOD:       The revision number as of the last tag or
115  *                      filename change.
116  *
117  * In addition, terms from the content of the message are added with
118  * "from", "to", "attachment", and "subject" prefixes for use by the
119  * user in searching. Similarly, terms from the path of the mail
120  * message are added with "folder" and "path" prefixes. But the
121  * database doesn't really care itself about any of these.
122  *
123  * The data portion of a mail document is empty.
124  *
125  * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
126  * -----------------------------------------------
127  * A ghost mail document is like a mail document, but where we don't
128  * have the message content.  These are used to track thread reference
129  * information for messages we haven't received.
130  *
131  * A ghost mail document has type: ghost; id and thread fields that
132  * are identical to the mail document fields; and a MESSAGE_ID value.
133  *
134  * Directory document
135  * ------------------
136  * A directory document is used by a client of the notmuch library to
137  * maintain data necessary to allow for efficient polling of mail
138  * directories.
139  *
140  * All directory documents contain one term:
141  *
142  *      directory:      The directory path (relative to the database path)
143  *                      Or the SHA1 sum of the directory path (if the
144  *                      path itself is too long to fit in a Xapian
145  *                      term).
146  *
147  * And all directory documents for directories other than top-level
148  * directories also contain the following term:
149  *
150  *      directory-direntry: A colon-separated pair of values
151  *                          (INTEGER:STRING), where INTEGER is the
152  *                          document ID of the parent directory
153  *                          document, and STRING is the name of this
154  *                          directory within that parent.
155  *
156  * All directory documents have a single value:
157  *
158  *      TIMESTAMP:      The mtime of the directory (at last scan)
159  *
160  * The data portion of a directory document contains the path of the
161  * directory (relative to the database path).
162  *
163  * Database metadata
164  * -----------------
165  * Xapian allows us to store arbitrary name-value pairs as
166  * "metadata". We currently use the following metadata names with the
167  * given meanings:
168  *
169  *      version         The database schema version, (which is distinct
170  *                      from both the notmuch package version (see
171  *                      notmuch --version) and the libnotmuch library
172  *                      version. The version is stored as an base-10
173  *                      ASCII integer. The initial database version
174  *                      was 1, (though a schema existed before that
175  *                      were no "version" database value existed at
176  *                      all). Successive versions are allocated as
177  *                      changes are made to the database (such as by
178  *                      indexing new fields).
179  *
180  *      features        The set of features supported by this
181  *                      database. This consists of a set of
182  *                      '\n'-separated lines, where each is a feature
183  *                      name, a '\t', and compatibility flags.  If the
184  *                      compatibility flags contain 'w', then the
185  *                      opener must support this feature to safely
186  *                      write this database.  If the compatibility
187  *                      flags contain 'r', then the opener must
188  *                      support this feature to read this database.
189  *                      Introduced in database version 3.
190  *
191  *      last_thread_id  The last thread ID generated. This is stored
192  *                      as a 16-byte hexadecimal ASCII representation
193  *                      of a 64-bit unsigned integer. The first ID
194  *                      generated is 1 and the value will be
195  *                      incremented for each thread ID.
196  *
197  *      C*              metadata keys starting with C indicate
198  *                      configuration data. It can be managed with the
199  *                      n_database_*config* API.  There is a convention
200  *                      of hierarchical keys separated by '.' (e.g.
201  *                      query.notmuch stores the value for the named
202  *                      query 'notmuch'), but it is not enforced by the
203  *                      API.
204  *
205  * Obsolete metadata
206  * -----------------
207  *
208  * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
209  * Instead, the database has the following additional database
210  * metadata:
211  *
212  *      thread_id_*     A pre-allocated thread ID for a particular
213  *                      message. This is actually an arbitrarily large
214  *                      family of metadata name. Any particular name is
215  *                      formed by concatenating "thread_id_" with a message
216  *                      ID (or the SHA1 sum of a message ID if it is very
217  *                      long---see description of 'id' in the mail
218  *                      document). The value stored is a thread ID.
219  *
220  *                      These thread ID metadata values are stored
221  *                      whenever a message references a parent message
222  *                      that does not yet exist in the database. A
223  *                      thread ID will be allocated and stored, and if
224  *                      the message is later added, the stored thread
225  *                      ID will be used (and the metadata value will
226  *                      be cleared).
227  *
228  *                      Even before a message is added, it's
229  *                      pre-allocated thread ID is useful so that all
230  *                      descendant messages that reference this common
231  *                      parent can be recognized as belonging to the
232  *                      same thread.
233  */
234
235 /* With these prefix values we follow the conventions published here:
236  *
237  * https://xapian.org/docs/omega/termprefixes.html
238  *
239  * as much as makes sense. Note that I took some liberty in matching
240  * the reserved prefix values to notmuch concepts, (for example, 'G'
241  * is documented as "newsGroup (or similar entity - e.g. a web forum
242  * name)", for which I think the thread is the closest analogue in
243  * notmuch. This in spite of the fact that we will eventually be
244  * storing mailing-list messages where 'G' for "mailing list name"
245  * might be even a closer analogue. I'm treating the single-character
246  * prefixes preferentially for core notmuch concepts (which will be
247  * nearly universal to all mail messages).
248  */
249
250 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
251     { "type",                   "T" },
252     { "reference",              "XREFERENCE" },
253     { "replyto",                "XREPLYTO" },
254     { "directory",              "XDIRECTORY" },
255     { "file-direntry",          "XFDIRENTRY" },
256     { "directory-direntry",     "XDDIRENTRY" },
257 };
258
259 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
260     { "thread",                 "G" },
261     { "tag",                    "K" },
262     { "is",                     "K" },
263     { "id",                     "Q" },
264     { "path",                   "P" },
265     { "property",               "XPROPERTY" },
266     /*
267      * Unconditionally add ':' to reduce potential ambiguity with
268      * overlapping prefixes and/or terms that start with capital
269      * letters. See Xapian document termprefixes.html for related
270      * discussion.
271      */
272     { "folder",                 "XFOLDER:" },
273 };
274
275 static prefix_t PROBABILISTIC_PREFIX[]= {
276     { "from",                   "XFROM" },
277     { "to",                     "XTO" },
278     { "attachment",             "XATTACHMENT" },
279     { "mimetype",               "XMIMETYPE"},
280     { "subject",                "XSUBJECT"},
281 };
282
283 const char *
284 _find_prefix (const char *name)
285 {
286     unsigned int i;
287
288     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
289         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
290             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
291     }
292
293     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
294         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
295             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
296     }
297
298     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
299         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
300             return PROBABILISTIC_PREFIX[i].prefix;
301     }
302
303     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
304
305     return "";
306 }
307
308 static const struct {
309     /* NOTMUCH_FEATURE_* value. */
310     _notmuch_features value;
311     /* Feature name as it appears in the database.  This name should
312      * be appropriate for displaying to the user if an older version
313      * of notmuch doesn't support this feature. */
314     const char *name;
315     /* Compatibility flags when this feature is declared. */
316     const char *flags;
317 } feature_names[] = {
318     { NOTMUCH_FEATURE_FILE_TERMS,
319       "multiple paths per message", "rw" },
320     { NOTMUCH_FEATURE_DIRECTORY_DOCS,
321       "relative directory paths", "rw" },
322     /* Header values are not required for reading a database because a
323      * reader can just refer to the message file. */
324     { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
325       "from/subject/message-ID in database", "w" },
326     { NOTMUCH_FEATURE_BOOL_FOLDER,
327       "exact folder:/path: search", "rw" },
328     { NOTMUCH_FEATURE_GHOSTS,
329       "mail documents for missing messages", "w"},
330     /* Knowledge of the index mime-types are not required for reading
331      * a database because a reader will just be unable to query
332      * them. */
333     { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
334       "indexed MIME types", "w"},
335     { NOTMUCH_FEATURE_LAST_MOD,
336       "modification tracking", "w"},
337 };
338
339 const char *
340 notmuch_status_to_string (notmuch_status_t status)
341 {
342     switch (status) {
343     case NOTMUCH_STATUS_SUCCESS:
344         return "No error occurred";
345     case NOTMUCH_STATUS_OUT_OF_MEMORY:
346         return "Out of memory";
347     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
348         return "Attempt to write to a read-only database";
349     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
350         return "A Xapian exception occurred";
351     case NOTMUCH_STATUS_FILE_ERROR:
352         return "Something went wrong trying to read or write a file";
353     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
354         return "File is not an email";
355     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
356         return "Message ID is identical to a message in database";
357     case NOTMUCH_STATUS_NULL_POINTER:
358         return "Erroneous NULL pointer";
359     case NOTMUCH_STATUS_TAG_TOO_LONG:
360         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
361     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
362         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
363     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
364         return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
365     case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
366         return "Unsupported operation";
367     case NOTMUCH_STATUS_UPGRADE_REQUIRED:
368         return "Operation requires a database upgrade";
369     case NOTMUCH_STATUS_PATH_ERROR:
370         return "Path supplied is illegal for this function";
371     default:
372     case NOTMUCH_STATUS_LAST_STATUS:
373         return "Unknown error status value";
374     }
375 }
376
377 void
378 _notmuch_database_log (notmuch_database_t *notmuch,
379                       const char *format,
380                       ...)
381 {
382     va_list va_args;
383
384     va_start (va_args, format);
385
386     if (notmuch->status_string)
387         talloc_free (notmuch->status_string);
388
389     notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
390     va_end (va_args);
391 }
392
393 void
394 _notmuch_database_log_append (notmuch_database_t *notmuch,
395                       const char *format,
396                       ...)
397 {
398     va_list va_args;
399
400     va_start (va_args, format);
401
402     if (notmuch->status_string)
403         notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
404     else
405         notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
406
407     va_end (va_args);
408 }
409
410 static void
411 find_doc_ids_for_term (notmuch_database_t *notmuch,
412                        const char *term,
413                        Xapian::PostingIterator *begin,
414                        Xapian::PostingIterator *end)
415 {
416     *begin = notmuch->xapian_db->postlist_begin (term);
417
418     *end = notmuch->xapian_db->postlist_end (term);
419 }
420
421 static void
422 find_doc_ids (notmuch_database_t *notmuch,
423               const char *prefix_name,
424               const char *value,
425               Xapian::PostingIterator *begin,
426               Xapian::PostingIterator *end)
427 {
428     char *term;
429
430     term = talloc_asprintf (notmuch, "%s%s",
431                             _find_prefix (prefix_name), value);
432
433     find_doc_ids_for_term (notmuch, term, begin, end);
434
435     talloc_free (term);
436 }
437
438 notmuch_private_status_t
439 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
440                                       const char *prefix_name,
441                                       const char *value,
442                                       unsigned int *doc_id)
443 {
444     Xapian::PostingIterator i, end;
445
446     find_doc_ids (notmuch, prefix_name, value, &i, &end);
447
448     if (i == end) {
449         *doc_id = 0;
450         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
451     }
452
453     *doc_id = *i;
454
455 #if DEBUG_DATABASE_SANITY
456     i++;
457
458     if (i != end)
459         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
460                         prefix_name, value);
461 #endif
462
463     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
464 }
465
466 static Xapian::Document
467 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
468 {
469     return notmuch->xapian_db->get_document (doc_id);
470 }
471
472 /* Generate a compressed version of 'message_id' of the form:
473  *
474  *      notmuch-sha1-<sha1_sum_of_message_id>
475  */
476 char *
477 _notmuch_message_id_compressed (void *ctx, const char *message_id)
478 {
479     char *sha1, *compressed;
480
481     sha1 = _notmuch_sha1_of_string (message_id);
482
483     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
484     free (sha1);
485
486     return compressed;
487 }
488
489 notmuch_status_t
490 notmuch_database_find_message (notmuch_database_t *notmuch,
491                                const char *message_id,
492                                notmuch_message_t **message_ret)
493 {
494     notmuch_private_status_t status;
495     unsigned int doc_id;
496
497     if (message_ret == NULL)
498         return NOTMUCH_STATUS_NULL_POINTER;
499
500     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
501         message_id = _notmuch_message_id_compressed (notmuch, message_id);
502
503     try {
504         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
505                                                        message_id, &doc_id);
506
507         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
508             *message_ret = NULL;
509         else {
510             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
511                                                     NULL);
512             if (*message_ret == NULL)
513                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
514         }
515
516         return NOTMUCH_STATUS_SUCCESS;
517     } catch (const Xapian::Error &error) {
518         _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
519                  error.get_msg().c_str());
520         notmuch->exception_reported = TRUE;
521         *message_ret = NULL;
522         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
523     }
524 }
525
526 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
527  * a (potentially nested) parenthesized sequence with '\' used to
528  * escape any character (including parentheses).
529  *
530  * If the sequence to be skipped continues to the end of the string,
531  * then 'str' will be left pointing at the final terminating '\0'
532  * character.
533  */
534 static void
535 skip_space_and_comments (const char **str)
536 {
537     const char *s;
538
539     s = *str;
540     while (*s && (isspace (*s) || *s == '(')) {
541         while (*s && isspace (*s))
542             s++;
543         if (*s == '(') {
544             int nesting = 1;
545             s++;
546             while (*s && nesting) {
547                 if (*s == '(') {
548                     nesting++;
549                 } else if (*s == ')') {
550                     nesting--;
551                 } else if (*s == '\\') {
552                     if (*(s+1))
553                         s++;
554                 }
555                 s++;
556             }
557         }
558     }
559
560     *str = s;
561 }
562
563 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
564  * comments, and the '<' and '>' delimiters.
565  *
566  * If not NULL, then *next will be made to point to the first character
567  * not parsed, (possibly pointing to the final '\0' terminator.
568  *
569  * Returns a newly talloc'ed string belonging to 'ctx'.
570  *
571  * Returns NULL if there is any error parsing the message-id. */
572 static char *
573 _parse_message_id (void *ctx, const char *message_id, const char **next)
574 {
575     const char *s, *end;
576     char *result;
577
578     if (message_id == NULL || *message_id == '\0')
579         return NULL;
580
581     s = message_id;
582
583     skip_space_and_comments (&s);
584
585     /* Skip any unstructured text as well. */
586     while (*s && *s != '<')
587         s++;
588
589     if (*s == '<') {
590         s++;
591     } else {
592         if (next)
593             *next = s;
594         return NULL;
595     }
596
597     skip_space_and_comments (&s);
598
599     end = s;
600     while (*end && *end != '>')
601         end++;
602     if (next) {
603         if (*end)
604             *next = end + 1;
605         else
606             *next = end;
607     }
608
609     if (end > s && *end == '>')
610         end--;
611     if (end <= s)
612         return NULL;
613
614     result = talloc_strndup (ctx, s, end - s + 1);
615
616     /* Finally, collapse any whitespace that is within the message-id
617      * itself. */
618     {
619         char *r;
620         int len;
621
622         for (r = result, len = strlen (r); *r; r++, len--)
623             if (*r == ' ' || *r == '\t')
624                 memmove (r, r+1, len);
625     }
626
627     return result;
628 }
629
630 /* Parse a References header value, putting a (talloc'ed under 'ctx')
631  * copy of each referenced message-id into 'hash'.
632  *
633  * We explicitly avoid including any reference identical to
634  * 'message_id' in the result (to avoid mass confusion when a single
635  * message references itself cyclically---and yes, mail messages are
636  * not infrequent in the wild that do this---don't ask me why).
637  *
638  * Return the last reference parsed, if it is not equal to message_id.
639  */
640 static char *
641 parse_references (void *ctx,
642                   const char *message_id,
643                   GHashTable *hash,
644                   const char *refs)
645 {
646     char *ref, *last_ref = NULL;
647
648     if (refs == NULL || *refs == '\0')
649         return NULL;
650
651     while (*refs) {
652         ref = _parse_message_id (ctx, refs, &refs);
653
654         if (ref && strcmp (ref, message_id)) {
655             g_hash_table_insert (hash, ref, NULL);
656             last_ref = ref;
657         }
658     }
659
660     /* The return value of this function is used to add a parent
661      * reference to the database.  We should avoid making a message
662      * its own parent, thus the above check.
663      */
664     return last_ref;
665 }
666
667 notmuch_status_t
668 notmuch_database_create (const char *path, notmuch_database_t **database)
669 {
670     char *status_string = NULL;
671     notmuch_status_t status;
672
673     status = notmuch_database_create_verbose (path, database,
674                                               &status_string);
675
676     if (status_string) {
677         fputs (status_string, stderr);
678         free (status_string);
679     }
680
681     return status;
682 }
683
684 notmuch_status_t
685 notmuch_database_create_verbose (const char *path,
686                                  notmuch_database_t **database,
687                                  char **status_string)
688 {
689     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
690     notmuch_database_t *notmuch = NULL;
691     char *notmuch_path = NULL;
692     char *message = NULL;
693     struct stat st;
694     int err;
695
696     if (path == NULL) {
697         message = strdup ("Error: Cannot create a database for a NULL path.\n");
698         status = NOTMUCH_STATUS_NULL_POINTER;
699         goto DONE;
700     }
701
702     if (path[0] != '/') {
703         message = strdup ("Error: Database path must be absolute.\n");
704         status = NOTMUCH_STATUS_PATH_ERROR;
705         goto DONE;
706     }
707
708     err = stat (path, &st);
709     if (err) {
710         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
711                                 path, strerror (errno)));
712         status = NOTMUCH_STATUS_FILE_ERROR;
713         goto DONE;
714     }
715
716     if (! S_ISDIR (st.st_mode)) {
717         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
718                                  "Not a directory.\n",
719                                  path));
720         status = NOTMUCH_STATUS_FILE_ERROR;
721         goto DONE;
722     }
723
724     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
725
726     err = mkdir (notmuch_path, 0755);
727
728     if (err) {
729         IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
730                                  notmuch_path, strerror (errno)));
731         status = NOTMUCH_STATUS_FILE_ERROR;
732         goto DONE;
733     }
734
735     status = notmuch_database_open_verbose (path,
736                                             NOTMUCH_DATABASE_MODE_READ_WRITE,
737                                             &notmuch, &message);
738     if (status)
739         goto DONE;
740
741     /* Upgrade doesn't add these feature to existing databases, but
742      * new databases have them. */
743     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
744     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
745
746     status = notmuch_database_upgrade (notmuch, NULL, NULL);
747     if (status) {
748         notmuch_database_close(notmuch);
749         notmuch = NULL;
750     }
751
752   DONE:
753     if (notmuch_path)
754         talloc_free (notmuch_path);
755
756     if (message) {
757         if (status_string)
758             *status_string = message;
759         else
760             free (message);
761     }
762     if (database)
763         *database = notmuch;
764     else
765         talloc_free (notmuch);
766     return status;
767 }
768
769 notmuch_status_t
770 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
771 {
772     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
773         _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
774         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
775     }
776
777     return NOTMUCH_STATUS_SUCCESS;
778 }
779
780 /* Allocate a revision number for the next change. */
781 unsigned long
782 _notmuch_database_new_revision (notmuch_database_t *notmuch)
783 {
784     unsigned long new_revision = notmuch->revision + 1;
785
786     /* If we're in an atomic section, hold off on updating the
787      * committed revision number until we commit the atomic section.
788      */
789     if (notmuch->atomic_nesting)
790         notmuch->atomic_dirty = TRUE;
791     else
792         notmuch->revision = new_revision;
793
794     return new_revision;
795 }
796
797 /* Parse a database features string from the given database version.
798  * Returns the feature bit set.
799  *
800  * For version < 3, this ignores the features string and returns a
801  * hard-coded set of features.
802  *
803  * If there are unrecognized features that are required to open the
804  * database in mode (which should be 'r' or 'w'), return a
805  * comma-separated list of unrecognized but required features in
806  * *incompat_out suitable for presenting to the user.  *incompat_out
807  * will be allocated from ctx.
808  */
809 static _notmuch_features
810 _parse_features (const void *ctx, const char *features, unsigned int version,
811                  char mode, char **incompat_out)
812 {
813     _notmuch_features res = static_cast<_notmuch_features>(0);
814     unsigned int namelen, i;
815     size_t llen = 0;
816     const char *flags;
817
818     /* Prior to database version 3, features were implied by the
819      * version number. */
820     if (version == 0)
821         return NOTMUCH_FEATURES_V0;
822     else if (version == 1)
823         return NOTMUCH_FEATURES_V1;
824     else if (version == 2)
825         return NOTMUCH_FEATURES_V2;
826
827     /* Parse the features string */
828     while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
829         flags = strchr (features, '\t');
830         if (! flags || flags > features + llen)
831             continue;
832         namelen = flags - features;
833
834         for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
835             if (strlen (feature_names[i].name) == namelen &&
836                 strncmp (feature_names[i].name, features, namelen) == 0) {
837                 res |= feature_names[i].value;
838                 break;
839             }
840         }
841
842         if (i == ARRAY_SIZE (feature_names) && incompat_out) {
843             /* Unrecognized feature */
844             const char *have = strchr (flags, mode);
845             if (have && have < features + llen) {
846                 /* This feature is required to access this database in
847                  * 'mode', but we don't understand it. */
848                 if (! *incompat_out)
849                     *incompat_out = talloc_strdup (ctx, "");
850                 *incompat_out = talloc_asprintf_append_buffer (
851                     *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
852                     namelen, features);
853             }
854         }
855     }
856
857     return res;
858 }
859
860 static char *
861 _print_features (const void *ctx, unsigned int features)
862 {
863     unsigned int i;
864     char *res = talloc_strdup (ctx, "");
865
866     for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
867         if (features & feature_names[i].value)
868             res = talloc_asprintf_append_buffer (
869                 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
870
871     return res;
872 }
873
874 notmuch_status_t
875 notmuch_database_open (const char *path,
876                        notmuch_database_mode_t mode,
877                        notmuch_database_t **database)
878 {
879     char *status_string = NULL;
880     notmuch_status_t status;
881
882     status = notmuch_database_open_verbose (path, mode, database,
883                                            &status_string);
884
885     if (status_string) {
886         fputs (status_string, stderr);
887         free (status_string);
888     }
889
890     return status;
891 }
892
893 notmuch_status_t
894 notmuch_database_open_verbose (const char *path,
895                                notmuch_database_mode_t mode,
896                                notmuch_database_t **database,
897                                char **status_string)
898 {
899     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
900     void *local = talloc_new (NULL);
901     notmuch_database_t *notmuch = NULL;
902     char *notmuch_path, *xapian_path, *incompat_features;
903     char *message = NULL;
904     struct stat st;
905     int err;
906     unsigned int i, version;
907     static int initialized = 0;
908
909     if (path == NULL) {
910         message = strdup ("Error: Cannot open a database for a NULL path.\n");
911         status = NOTMUCH_STATUS_NULL_POINTER;
912         goto DONE;
913     }
914
915     if (path[0] != '/') {
916         message = strdup ("Error: Database path must be absolute.\n");
917         status = NOTMUCH_STATUS_PATH_ERROR;
918         goto DONE;
919     }
920
921     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
922         message = strdup ("Out of memory\n");
923         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
924         goto DONE;
925     }
926
927     err = stat (notmuch_path, &st);
928     if (err) {
929         IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
930                                  notmuch_path, strerror (errno)));
931         status = NOTMUCH_STATUS_FILE_ERROR;
932         goto DONE;
933     }
934
935     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
936         message = strdup ("Out of memory\n");
937         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
938         goto DONE;
939     }
940
941     /* Initialize the GLib type system and threads */
942 #if !GLIB_CHECK_VERSION(2, 35, 1)
943     g_type_init ();
944 #endif
945
946     /* Initialize gmime */
947     if (! initialized) {
948         g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
949         initialized = 1;
950     }
951
952     notmuch = talloc_zero (NULL, notmuch_database_t);
953     notmuch->exception_reported = FALSE;
954     notmuch->status_string = NULL;
955     notmuch->path = talloc_strdup (notmuch, path);
956
957     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
958         notmuch->path[strlen (notmuch->path) - 1] = '\0';
959
960     notmuch->mode = mode;
961     notmuch->atomic_nesting = 0;
962     try {
963         string last_thread_id;
964         string last_mod;
965
966         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
967             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
968                                                                DB_ACTION);
969         } else {
970             notmuch->xapian_db = new Xapian::Database (xapian_path);
971         }
972
973         /* Check version.  As of database version 3, we represent
974          * changes in terms of features, so assume a version bump
975          * means a dramatically incompatible change. */
976         version = notmuch_database_get_version (notmuch);
977         if (version > NOTMUCH_DATABASE_VERSION) {
978             IGNORE_RESULT (asprintf (&message,
979                       "Error: Notmuch database at %s\n"
980                       "       has a newer database format version (%u) than supported by this\n"
981                       "       version of notmuch (%u).\n",
982                                      notmuch_path, version, NOTMUCH_DATABASE_VERSION));
983             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
984             notmuch_database_destroy (notmuch);
985             notmuch = NULL;
986             status = NOTMUCH_STATUS_FILE_ERROR;
987             goto DONE;
988         }
989
990         /* Check features. */
991         incompat_features = NULL;
992         notmuch->features = _parse_features (
993             local, notmuch->xapian_db->get_metadata ("features").c_str (),
994             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
995             &incompat_features);
996         if (incompat_features) {
997             IGNORE_RESULT (asprintf (&message,
998                 "Error: Notmuch database at %s\n"
999                 "       requires features (%s)\n"
1000                 "       not supported by this version of notmuch.\n",
1001                                      notmuch_path, incompat_features));
1002             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
1003             notmuch_database_destroy (notmuch);
1004             notmuch = NULL;
1005             status = NOTMUCH_STATUS_FILE_ERROR;
1006             goto DONE;
1007         }
1008
1009         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
1010         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
1011         if (last_thread_id.empty ()) {
1012             notmuch->last_thread_id = 0;
1013         } else {
1014             const char *str;
1015             char *end;
1016
1017             str = last_thread_id.c_str ();
1018             notmuch->last_thread_id = strtoull (str, &end, 16);
1019             if (*end != '\0')
1020                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
1021         }
1022
1023         /* Get current highest revision number. */
1024         last_mod = notmuch->xapian_db->get_value_upper_bound (
1025             NOTMUCH_VALUE_LAST_MOD);
1026         if (last_mod.empty ())
1027             notmuch->revision = 0;
1028         else
1029             notmuch->revision = Xapian::sortable_unserialise (last_mod);
1030         notmuch->uuid = talloc_strdup (
1031             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
1032
1033         notmuch->query_parser = new Xapian::QueryParser;
1034         notmuch->term_gen = new Xapian::TermGenerator;
1035         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
1036         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1037         notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
1038 #if HAVE_XAPIAN_FIELD_PROCESSOR
1039         /* This currently relies on the query parser to pass anything
1040          * with a .. to the range processor */
1041         notmuch->date_field_processor = new DateFieldProcessor();
1042         notmuch->query_parser->add_boolean_prefix("date", notmuch->date_field_processor);
1043         notmuch->query_field_processor = new QueryFieldProcessor (*notmuch->query_parser, notmuch);
1044         notmuch->query_parser->add_boolean_prefix("query", notmuch->query_field_processor);
1045 #endif
1046         notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
1047
1048         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
1049         notmuch->query_parser->set_database (*notmuch->xapian_db);
1050         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
1051         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
1052         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
1053         notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
1054         notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
1055
1056         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
1057             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
1058             notmuch->query_parser->add_boolean_prefix (prefix->name,
1059                                                        prefix->prefix);
1060         }
1061
1062         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
1063             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
1064             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
1065         }
1066     } catch (const Xapian::Error &error) {
1067         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
1068                                  error.get_msg().c_str()));
1069         notmuch_database_destroy (notmuch);
1070         notmuch = NULL;
1071         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1072     }
1073
1074   DONE:
1075     talloc_free (local);
1076
1077     if (message) {
1078         if (status_string)
1079             *status_string = message;
1080         else
1081             free (message);
1082     }
1083
1084     if (database)
1085         *database = notmuch;
1086     else
1087         talloc_free (notmuch);
1088     return status;
1089 }
1090
1091 notmuch_status_t
1092 notmuch_database_close (notmuch_database_t *notmuch)
1093 {
1094     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1095
1096     /* Many Xapian objects (and thus notmuch objects) hold references to
1097      * the database, so merely deleting the database may not suffice to
1098      * close it.  Thus, we explicitly close it here. */
1099     if (notmuch->xapian_db != NULL) {
1100         try {
1101             /* If there's an outstanding transaction, it's unclear if
1102              * closing the Xapian database commits everything up to
1103              * that transaction, or may discard committed (but
1104              * unflushed) transactions.  To be certain, explicitly
1105              * cancel any outstanding transaction before closing. */
1106             if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1107                 notmuch->atomic_nesting)
1108                 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1109                     ->cancel_transaction ();
1110
1111             /* Close the database.  This implicitly flushes
1112              * outstanding changes. */
1113             notmuch->xapian_db->close();
1114         } catch (const Xapian::Error &error) {
1115             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1116             if (! notmuch->exception_reported) {
1117                 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1118                          error.get_msg().c_str());
1119             }
1120         }
1121     }
1122
1123     delete notmuch->term_gen;
1124     notmuch->term_gen = NULL;
1125     delete notmuch->query_parser;
1126     notmuch->query_parser = NULL;
1127     delete notmuch->xapian_db;
1128     notmuch->xapian_db = NULL;
1129     delete notmuch->value_range_processor;
1130     notmuch->value_range_processor = NULL;
1131     delete notmuch->date_range_processor;
1132     notmuch->date_range_processor = NULL;
1133     delete notmuch->last_mod_range_processor;
1134     notmuch->last_mod_range_processor = NULL;
1135
1136 #if HAVE_XAPIAN_FIELD_PROCESSOR
1137     delete notmuch->date_field_processor;
1138     notmuch->date_field_processor = NULL;
1139     delete notmuch->query_field_processor;
1140     notmuch->query_field_processor = NULL;
1141 #endif
1142
1143     return status;
1144 }
1145
1146 #if HAVE_XAPIAN_COMPACT
1147 static int
1148 unlink_cb (const char *path,
1149            unused (const struct stat *sb),
1150            unused (int type),
1151            unused (struct FTW *ftw))
1152 {
1153     return remove (path);
1154 }
1155
1156 static int
1157 rmtree (const char *path)
1158 {
1159     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1160 }
1161
1162 class NotmuchCompactor : public Xapian::Compactor
1163 {
1164     notmuch_compact_status_cb_t status_cb;
1165     void *status_closure;
1166
1167 public:
1168     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1169         status_cb (cb), status_closure (closure) { }
1170
1171     virtual void
1172     set_status (const std::string &table, const std::string &status)
1173     {
1174         char *msg;
1175
1176         if (status_cb == NULL)
1177             return;
1178
1179         if (status.length () == 0)
1180             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1181         else
1182             msg = talloc_asprintf (NULL, "     %s", status.c_str());
1183
1184         if (msg == NULL) {
1185             return;
1186         }
1187
1188         status_cb (msg, status_closure);
1189         talloc_free (msg);
1190     }
1191 };
1192
1193 /* Compacts the given database, optionally saving the original database
1194  * in backup_path. Additionally, a callback function can be provided to
1195  * give the user feedback on the progress of the (likely long-lived)
1196  * compaction process.
1197  *
1198  * The backup path must point to a directory on the same volume as the
1199  * original database. Passing a NULL backup_path will result in the
1200  * uncompacted database being deleted after compaction has finished.
1201  * Note that the database write lock will be held during the
1202  * compaction process to protect data integrity.
1203  */
1204 notmuch_status_t
1205 notmuch_database_compact (const char *path,
1206                           const char *backup_path,
1207                           notmuch_compact_status_cb_t status_cb,
1208                           void *closure)
1209 {
1210     void *local;
1211     char *notmuch_path, *xapian_path, *compact_xapian_path;
1212     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1213     notmuch_database_t *notmuch = NULL;
1214     struct stat statbuf;
1215     notmuch_bool_t keep_backup;
1216     char *message = NULL;
1217
1218     local = talloc_new (NULL);
1219     if (! local)
1220         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1221
1222     ret = notmuch_database_open_verbose (path,
1223                                          NOTMUCH_DATABASE_MODE_READ_WRITE,
1224                                          &notmuch,
1225                                          &message);
1226     if (ret) {
1227         if (status_cb) status_cb (message, closure);
1228         goto DONE;
1229     }
1230
1231     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1232         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1233         goto DONE;
1234     }
1235
1236     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1237         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1238         goto DONE;
1239     }
1240
1241     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1242         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1243         goto DONE;
1244     }
1245
1246     if (backup_path == NULL) {
1247         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1248             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1249             goto DONE;
1250         }
1251         keep_backup = FALSE;
1252     }
1253     else {
1254         keep_backup = TRUE;
1255     }
1256
1257     if (stat (backup_path, &statbuf) != -1) {
1258         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1259         ret = NOTMUCH_STATUS_FILE_ERROR;
1260         goto DONE;
1261     }
1262     if (errno != ENOENT) {
1263         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1264                  strerror (errno));
1265         ret = NOTMUCH_STATUS_FILE_ERROR;
1266         goto DONE;
1267     }
1268
1269     /* Unconditionally attempt to remove old work-in-progress database (if
1270      * any). This is "protected" by database lock. If this fails due to write
1271      * errors (etc), the following code will fail and provide error message.
1272      */
1273     (void) rmtree (compact_xapian_path);
1274
1275     try {
1276         NotmuchCompactor compactor (status_cb, closure);
1277
1278         compactor.set_renumber (false);
1279         compactor.add_source (xapian_path);
1280         compactor.set_destdir (compact_xapian_path);
1281         compactor.compact ();
1282     } catch (const Xapian::Error &error) {
1283         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1284         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1285         goto DONE;
1286     }
1287
1288     if (rename (xapian_path, backup_path)) {
1289         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1290                  xapian_path, backup_path, strerror (errno));
1291         ret = NOTMUCH_STATUS_FILE_ERROR;
1292         goto DONE;
1293     }
1294
1295     if (rename (compact_xapian_path, xapian_path)) {
1296         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1297                  compact_xapian_path, xapian_path, strerror (errno));
1298         ret = NOTMUCH_STATUS_FILE_ERROR;
1299         goto DONE;
1300     }
1301
1302     if (! keep_backup) {
1303         if (rmtree (backup_path)) {
1304             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1305                      backup_path, strerror (errno));
1306             ret = NOTMUCH_STATUS_FILE_ERROR;
1307             goto DONE;
1308         }
1309     }
1310
1311   DONE:
1312     if (notmuch) {
1313         notmuch_status_t ret2;
1314
1315         const char *str = notmuch_database_status_string (notmuch);
1316         if (status_cb && str)
1317             status_cb (str, closure);
1318
1319         ret2 = notmuch_database_destroy (notmuch);
1320
1321         /* don't clobber previous error status */
1322         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1323             ret = ret2;
1324     }
1325
1326     talloc_free (local);
1327
1328     return ret;
1329 }
1330 #else
1331 notmuch_status_t
1332 notmuch_database_compact (unused (const char *path),
1333                           unused (const char *backup_path),
1334                           unused (notmuch_compact_status_cb_t status_cb),
1335                           unused (void *closure))
1336 {
1337     _notmuch_database_log (notmuch, "notmuch was compiled against a xapian version lacking compaction support.\n");
1338     return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1339 }
1340 #endif
1341
1342 notmuch_status_t
1343 notmuch_database_destroy (notmuch_database_t *notmuch)
1344 {
1345     notmuch_status_t status;
1346
1347     status = notmuch_database_close (notmuch);
1348     talloc_free (notmuch);
1349
1350     return status;
1351 }
1352
1353 const char *
1354 notmuch_database_get_path (notmuch_database_t *notmuch)
1355 {
1356     return notmuch->path;
1357 }
1358
1359 unsigned int
1360 notmuch_database_get_version (notmuch_database_t *notmuch)
1361 {
1362     unsigned int version;
1363     string version_string;
1364     const char *str;
1365     char *end;
1366
1367     version_string = notmuch->xapian_db->get_metadata ("version");
1368     if (version_string.empty ())
1369         return 0;
1370
1371     str = version_string.c_str ();
1372     if (str == NULL || *str == '\0')
1373         return 0;
1374
1375     version = strtoul (str, &end, 10);
1376     if (*end != '\0')
1377         INTERNAL_ERROR ("Malformed database version: %s", str);
1378
1379     return version;
1380 }
1381
1382 notmuch_bool_t
1383 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1384 {
1385     return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1386         ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1387          (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1388 }
1389
1390 static volatile sig_atomic_t do_progress_notify = 0;
1391
1392 static void
1393 handle_sigalrm (unused (int signal))
1394 {
1395     do_progress_notify = 1;
1396 }
1397
1398 /* Upgrade the current database.
1399  *
1400  * After opening a database in read-write mode, the client should
1401  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1402  * if so, upgrade with this function before making any modifications.
1403  *
1404  * The optional progress_notify callback can be used by the caller to
1405  * provide progress indication to the user. If non-NULL it will be
1406  * called periodically with 'count' as the number of messages upgraded
1407  * so far and 'total' the overall number of messages that will be
1408  * converted.
1409  */
1410 notmuch_status_t
1411 notmuch_database_upgrade (notmuch_database_t *notmuch,
1412                           void (*progress_notify) (void *closure,
1413                                                    double progress),
1414                           void *closure)
1415 {
1416     void *local = talloc_new (NULL);
1417     Xapian::TermIterator t, t_end;
1418     Xapian::WritableDatabase *db;
1419     struct sigaction action;
1420     struct itimerval timerval;
1421     notmuch_bool_t timer_is_active = FALSE;
1422     enum _notmuch_features target_features, new_features;
1423     notmuch_status_t status;
1424     notmuch_private_status_t private_status;
1425     notmuch_query_t *query = NULL;
1426     unsigned int count = 0, total = 0;
1427
1428     status = _notmuch_database_ensure_writable (notmuch);
1429     if (status)
1430         return status;
1431
1432     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1433
1434     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1435     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1436
1437     if (! notmuch_database_needs_upgrade (notmuch))
1438         return NOTMUCH_STATUS_SUCCESS;
1439
1440     if (progress_notify) {
1441         /* Set up our handler for SIGALRM */
1442         memset (&action, 0, sizeof (struct sigaction));
1443         action.sa_handler = handle_sigalrm;
1444         sigemptyset (&action.sa_mask);
1445         action.sa_flags = SA_RESTART;
1446         sigaction (SIGALRM, &action, NULL);
1447
1448         /* Then start a timer to send SIGALRM once per second. */
1449         timerval.it_interval.tv_sec = 1;
1450         timerval.it_interval.tv_usec = 0;
1451         timerval.it_value.tv_sec = 1;
1452         timerval.it_value.tv_usec = 0;
1453         setitimer (ITIMER_REAL, &timerval, NULL);
1454
1455         timer_is_active = TRUE;
1456     }
1457
1458     /* Figure out how much total work we need to do. */
1459     if (new_features &
1460         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1461          NOTMUCH_FEATURE_LAST_MOD)) {
1462         query = notmuch_query_create (notmuch, "");
1463         unsigned msg_count;
1464
1465         status = notmuch_query_count_messages_st (query, &msg_count);
1466         if (status)
1467             goto DONE;
1468
1469         total += msg_count;
1470         notmuch_query_destroy (query);
1471         query = NULL;
1472     }
1473     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1474         t_end = db->allterms_end ("XTIMESTAMP");
1475         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1476             ++total;
1477     }
1478     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1479         /* The ghost message upgrade converts all thread_id_*
1480          * metadata values into ghost message documents. */
1481         t_end = db->metadata_keys_end ("thread_id_");
1482         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1483             ++total;
1484     }
1485
1486     /* Perform the upgrade in a transaction. */
1487     db->begin_transaction (true);
1488
1489     /* Set the target features so we write out changes in the desired
1490      * format. */
1491     notmuch->features = target_features;
1492
1493     /* Perform per-message upgrades. */
1494     if (new_features &
1495         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1496          NOTMUCH_FEATURE_LAST_MOD)) {
1497         notmuch_messages_t *messages;
1498         notmuch_message_t *message;
1499         char *filename;
1500
1501         query = notmuch_query_create (notmuch, "");
1502
1503         status = notmuch_query_search_messages_st (query, &messages);
1504         if (status)
1505             goto DONE;
1506         for (;
1507              notmuch_messages_valid (messages);
1508              notmuch_messages_move_to_next (messages))
1509         {
1510             if (do_progress_notify) {
1511                 progress_notify (closure, (double) count / total);
1512                 do_progress_notify = 0;
1513             }
1514
1515             message = notmuch_messages_get (messages);
1516
1517             /* Before version 1, each message document had its
1518              * filename in the data field. Copy that into the new
1519              * format by calling notmuch_message_add_filename.
1520              */
1521             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1522                 filename = _notmuch_message_talloc_copy_data (message);
1523                 if (filename && *filename != '\0') {
1524                     _notmuch_message_add_filename (message, filename);
1525                     _notmuch_message_clear_data (message);
1526                 }
1527                 talloc_free (filename);
1528             }
1529
1530             /* Prior to version 2, the "folder:" prefix was
1531              * probabilistic and stemmed. Change it to the current
1532              * boolean prefix. Add "path:" prefixes while at it.
1533              */
1534             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1535                 _notmuch_message_upgrade_folder (message);
1536
1537             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1538              * track modification revisions.  Give all messages the
1539              * next available revision; since we just started tracking
1540              * revisions for this database, that will be 1.
1541              */
1542             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1543                 _notmuch_message_upgrade_last_mod (message);
1544
1545             _notmuch_message_sync (message);
1546
1547             notmuch_message_destroy (message);
1548
1549             count++;
1550         }
1551
1552         notmuch_query_destroy (query);
1553         query = NULL;
1554     }
1555
1556     /* Perform per-directory upgrades. */
1557
1558     /* Before version 1 we stored directory timestamps in
1559      * XTIMESTAMP documents instead of the current XDIRECTORY
1560      * documents. So copy those as well. */
1561     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1562         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1563
1564         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1565              t != t_end;
1566              t++)
1567         {
1568             Xapian::PostingIterator p, p_end;
1569             std::string term = *t;
1570
1571             p_end = notmuch->xapian_db->postlist_end (term);
1572
1573             for (p = notmuch->xapian_db->postlist_begin (term);
1574                  p != p_end;
1575                  p++)
1576             {
1577                 Xapian::Document document;
1578                 time_t mtime;
1579                 notmuch_directory_t *directory;
1580
1581                 if (do_progress_notify) {
1582                     progress_notify (closure, (double) count / total);
1583                     do_progress_notify = 0;
1584                 }
1585
1586                 document = find_document_for_doc_id (notmuch, *p);
1587                 mtime = Xapian::sortable_unserialise (
1588                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1589
1590                 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1591                                                        NOTMUCH_FIND_CREATE, &status);
1592                 notmuch_directory_set_mtime (directory, mtime);
1593                 notmuch_directory_destroy (directory);
1594
1595                 db->delete_document (*p);
1596             }
1597
1598             ++count;
1599         }
1600     }
1601
1602     /* Perform metadata upgrades. */
1603
1604     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1605      * messages were stored as database metadata. Change these to
1606      * ghost messages.
1607      */
1608     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1609         notmuch_message_t *message;
1610         std::string message_id, thread_id;
1611
1612         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1613         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1614              t != t_end; ++t) {
1615             if (do_progress_notify) {
1616                 progress_notify (closure, (double) count / total);
1617                 do_progress_notify = 0;
1618             }
1619
1620             message_id = (*t).substr (
1621                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1622             thread_id = db->get_metadata (*t);
1623
1624             /* Create ghost message */
1625             message = _notmuch_message_create_for_message_id (
1626                 notmuch, message_id.c_str (), &private_status);
1627             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1628                 /* Document already exists; ignore the stored thread ID */
1629             } else if (private_status ==
1630                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1631                 private_status = _notmuch_message_initialize_ghost (
1632                     message, thread_id.c_str ());
1633                 if (! private_status)
1634                     _notmuch_message_sync (message);
1635             }
1636
1637             if (private_status) {
1638                 _notmuch_database_log (notmuch,
1639                          "Upgrade failed while creating ghost messages.\n");
1640                 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1641                 goto DONE;
1642             }
1643
1644             /* Clear saved metadata thread ID */
1645             db->set_metadata (*t, "");
1646
1647             ++count;
1648         }
1649     }
1650
1651     status = NOTMUCH_STATUS_SUCCESS;
1652     db->set_metadata ("features", _print_features (local, notmuch->features));
1653     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1654
1655  DONE:
1656     if (status == NOTMUCH_STATUS_SUCCESS)
1657         db->commit_transaction ();
1658     else
1659         db->cancel_transaction ();
1660
1661     if (timer_is_active) {
1662         /* Now stop the timer. */
1663         timerval.it_interval.tv_sec = 0;
1664         timerval.it_interval.tv_usec = 0;
1665         timerval.it_value.tv_sec = 0;
1666         timerval.it_value.tv_usec = 0;
1667         setitimer (ITIMER_REAL, &timerval, NULL);
1668
1669         /* And disable the signal handler. */
1670         action.sa_handler = SIG_IGN;
1671         sigaction (SIGALRM, &action, NULL);
1672     }
1673
1674     if (query)
1675         notmuch_query_destroy (query);
1676
1677     talloc_free (local);
1678     return status;
1679 }
1680
1681 notmuch_status_t
1682 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1683 {
1684     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1685         notmuch->atomic_nesting > 0)
1686         goto DONE;
1687
1688         if (notmuch_database_needs_upgrade(notmuch))
1689                 return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1690
1691     try {
1692         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1693     } catch (const Xapian::Error &error) {
1694         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1695                  error.get_msg().c_str());
1696         notmuch->exception_reported = TRUE;
1697         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1698     }
1699
1700 DONE:
1701     notmuch->atomic_nesting++;
1702     return NOTMUCH_STATUS_SUCCESS;
1703 }
1704
1705 notmuch_status_t
1706 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1707 {
1708     Xapian::WritableDatabase *db;
1709
1710     if (notmuch->atomic_nesting == 0)
1711         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1712
1713     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1714         notmuch->atomic_nesting > 1)
1715         goto DONE;
1716
1717     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1718     try {
1719         db->commit_transaction ();
1720
1721         /* This is a hack for testing.  Xapian never flushes on a
1722          * non-flushed commit, even if the flush threshold is 1.
1723          * However, we rely on flushing to test atomicity. */
1724         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1725         if (thresh && atoi (thresh) == 1)
1726             db->flush ();
1727     } catch (const Xapian::Error &error) {
1728         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1729                  error.get_msg().c_str());
1730         notmuch->exception_reported = TRUE;
1731         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1732     }
1733
1734     if (notmuch->atomic_dirty) {
1735         ++notmuch->revision;
1736         notmuch->atomic_dirty = FALSE;
1737     }
1738
1739 DONE:
1740     notmuch->atomic_nesting--;
1741     return NOTMUCH_STATUS_SUCCESS;
1742 }
1743
1744 unsigned long
1745 notmuch_database_get_revision (notmuch_database_t *notmuch,
1746                                 const char **uuid)
1747 {
1748     if (uuid)
1749         *uuid = notmuch->uuid;
1750     return notmuch->revision;
1751 }
1752
1753 /* We allow the user to use arbitrarily long paths for directories. But
1754  * we have a term-length limit. So if we exceed that, we'll use the
1755  * SHA-1 of the path for the database term.
1756  *
1757  * Note: This function may return the original value of 'path'. If it
1758  * does not, then the caller is responsible to free() the returned
1759  * value.
1760  */
1761 const char *
1762 _notmuch_database_get_directory_db_path (const char *path)
1763 {
1764     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1765
1766     if (term_len > NOTMUCH_TERM_MAX)
1767         return _notmuch_sha1_of_string (path);
1768     else
1769         return path;
1770 }
1771
1772 /* Given a path, split it into two parts: the directory part is all
1773  * components except for the last, and the basename is that last
1774  * component. Getting the return-value for either part is optional
1775  * (the caller can pass NULL).
1776  *
1777  * The original 'path' can represent either a regular file or a
1778  * directory---the splitting will be carried out in the same way in
1779  * either case. Trailing slashes on 'path' will be ignored, and any
1780  * cases of multiple '/' characters appearing in series will be
1781  * treated as a single '/'.
1782  *
1783  * Allocation (if any) will have 'ctx' as the talloc owner. But
1784  * pointers will be returned within the original path string whenever
1785  * possible.
1786  *
1787  * Note: If 'path' is non-empty and contains no non-trailing slash,
1788  * (that is, consists of a filename with no parent directory), then
1789  * the directory returned will be an empty string. However, if 'path'
1790  * is an empty string, then both directory and basename will be
1791  * returned as NULL.
1792  */
1793 notmuch_status_t
1794 _notmuch_database_split_path (void *ctx,
1795                               const char *path,
1796                               const char **directory,
1797                               const char **basename)
1798 {
1799     const char *slash;
1800
1801     if (path == NULL || *path == '\0') {
1802         if (directory)
1803             *directory = NULL;
1804         if (basename)
1805             *basename = NULL;
1806         return NOTMUCH_STATUS_SUCCESS;
1807     }
1808
1809     /* Find the last slash (not counting a trailing slash), if any. */
1810
1811     slash = path + strlen (path) - 1;
1812
1813     /* First, skip trailing slashes. */
1814     while (slash != path && *slash == '/')
1815         --slash;
1816
1817     /* Then, find a slash. */
1818     while (slash != path && *slash != '/') {
1819         if (basename)
1820             *basename = slash;
1821
1822         --slash;
1823     }
1824
1825     /* Finally, skip multiple slashes. */
1826     while (slash != path && *(slash - 1) == '/')
1827         --slash;
1828
1829     if (slash == path) {
1830         if (directory)
1831             *directory = talloc_strdup (ctx, "");
1832         if (basename)
1833             *basename = path;
1834     } else {
1835         if (directory)
1836             *directory = talloc_strndup (ctx, path, slash - path);
1837     }
1838
1839     return NOTMUCH_STATUS_SUCCESS;
1840 }
1841
1842 /* Find the document ID of the specified directory.
1843  *
1844  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1845  * created if one does not exist for 'path'.  Otherwise, if the
1846  * directory document does not exist, this sets *directory_id to
1847  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1848  */
1849 notmuch_status_t
1850 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1851                                      const char *path,
1852                                      notmuch_find_flags_t flags,
1853                                      unsigned int *directory_id)
1854 {
1855     notmuch_directory_t *directory;
1856     notmuch_status_t status;
1857
1858     if (path == NULL) {
1859         *directory_id = 0;
1860         return NOTMUCH_STATUS_SUCCESS;
1861     }
1862
1863     directory = _notmuch_directory_create (notmuch, path, flags, &status);
1864     if (status || !directory) {
1865         *directory_id = -1;
1866         return status;
1867     }
1868
1869     *directory_id = _notmuch_directory_get_document_id (directory);
1870
1871     notmuch_directory_destroy (directory);
1872
1873     return NOTMUCH_STATUS_SUCCESS;
1874 }
1875
1876 const char *
1877 _notmuch_database_get_directory_path (void *ctx,
1878                                       notmuch_database_t *notmuch,
1879                                       unsigned int doc_id)
1880 {
1881     Xapian::Document document;
1882
1883     document = find_document_for_doc_id (notmuch, doc_id);
1884
1885     return talloc_strdup (ctx, document.get_data ().c_str ());
1886 }
1887
1888 /* Given a legal 'filename' for the database, (either relative to
1889  * database path or absolute with initial components identical to
1890  * database path), return a new string (with 'ctx' as the talloc
1891  * owner) suitable for use as a direntry term value.
1892  *
1893  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1894  * will be created in the database as needed.  Otherwise, if the
1895  * necessary directory documents do not exist, this sets
1896  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1897  */
1898 notmuch_status_t
1899 _notmuch_database_filename_to_direntry (void *ctx,
1900                                         notmuch_database_t *notmuch,
1901                                         const char *filename,
1902                                         notmuch_find_flags_t flags,
1903                                         char **direntry)
1904 {
1905     const char *relative, *directory, *basename;
1906     Xapian::docid directory_id;
1907     notmuch_status_t status;
1908
1909     relative = _notmuch_database_relative_path (notmuch, filename);
1910
1911     status = _notmuch_database_split_path (ctx, relative,
1912                                            &directory, &basename);
1913     if (status)
1914         return status;
1915
1916     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1917                                                   &directory_id);
1918     if (status || directory_id == (unsigned int)-1) {
1919         *direntry = NULL;
1920         return status;
1921     }
1922
1923     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1924
1925     return NOTMUCH_STATUS_SUCCESS;
1926 }
1927
1928 /* Given a legal 'path' for the database, return the relative path.
1929  *
1930  * The return value will be a pointer to the original path contents,
1931  * and will be either the original string (if 'path' was relative) or
1932  * a portion of the string (if path was absolute and begins with the
1933  * database path).
1934  */
1935 const char *
1936 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1937                                  const char *path)
1938 {
1939     const char *db_path, *relative;
1940     unsigned int db_path_len;
1941
1942     db_path = notmuch_database_get_path (notmuch);
1943     db_path_len = strlen (db_path);
1944
1945     relative = path;
1946
1947     if (*relative == '/') {
1948         while (*relative == '/' && *(relative+1) == '/')
1949             relative++;
1950
1951         if (strncmp (relative, db_path, db_path_len) == 0)
1952         {
1953             relative += db_path_len;
1954             while (*relative == '/')
1955                 relative++;
1956         }
1957     }
1958
1959     return relative;
1960 }
1961
1962 notmuch_status_t
1963 notmuch_database_get_directory (notmuch_database_t *notmuch,
1964                                 const char *path,
1965                                 notmuch_directory_t **directory)
1966 {
1967     notmuch_status_t status;
1968
1969     if (directory == NULL)
1970         return NOTMUCH_STATUS_NULL_POINTER;
1971     *directory = NULL;
1972
1973     try {
1974         *directory = _notmuch_directory_create (notmuch, path,
1975                                                 NOTMUCH_FIND_LOOKUP, &status);
1976     } catch (const Xapian::Error &error) {
1977         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1978                  error.get_msg().c_str());
1979         notmuch->exception_reported = TRUE;
1980         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1981     }
1982     return status;
1983 }
1984
1985 /* Allocate a document ID that satisfies the following criteria:
1986  *
1987  * 1. The ID does not exist for any document in the Xapian database
1988  *
1989  * 2. The ID was not previously returned from this function
1990  *
1991  * 3. The ID is the smallest integer satisfying (1) and (2)
1992  *
1993  * This function will trigger an internal error if these constraints
1994  * cannot all be satisfied, (that is, the pool of available document
1995  * IDs has been exhausted).
1996  */
1997 unsigned int
1998 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1999 {
2000     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
2001
2002     notmuch->last_doc_id++;
2003
2004     if (notmuch->last_doc_id == 0)
2005         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
2006
2007     return notmuch->last_doc_id;
2008 }
2009
2010 static const char *
2011 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
2012 {
2013     /* 16 bytes (+ terminator) for hexadecimal representation of
2014      * a 64-bit integer. */
2015     static char thread_id[17];
2016     Xapian::WritableDatabase *db;
2017
2018     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2019
2020     notmuch->last_thread_id++;
2021
2022     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
2023
2024     db->set_metadata ("last_thread_id", thread_id);
2025
2026     return thread_id;
2027 }
2028
2029 static char *
2030 _get_metadata_thread_id_key (void *ctx, const char *message_id)
2031 {
2032     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
2033         message_id = _notmuch_message_id_compressed (ctx, message_id);
2034
2035     return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
2036                             message_id);
2037 }
2038
2039 static notmuch_status_t
2040 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2041                                       void *ctx,
2042                                       const char *message_id,
2043                                       const char **thread_id_ret);
2044
2045 /* Find the thread ID to which the message with 'message_id' belongs.
2046  *
2047  * Note: 'thread_id_ret' must not be NULL!
2048  * On success '*thread_id_ret' is set to a newly talloced string belonging to
2049  * 'ctx'.
2050  *
2051  * Note: If there is no message in the database with the given
2052  * 'message_id' then a new thread_id will be allocated for this
2053  * message ID and stored in the database metadata so that the
2054  * thread ID can be looked up if the message is added to the database
2055  * later.
2056  */
2057 static notmuch_status_t
2058 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
2059                                   void *ctx,
2060                                   const char *message_id,
2061                                   const char **thread_id_ret)
2062 {
2063     notmuch_private_status_t status;
2064     notmuch_message_t *message;
2065
2066     if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
2067         return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
2068                                                      thread_id_ret);
2069
2070     /* Look for this message (regular or ghost) */
2071     message = _notmuch_message_create_for_message_id (
2072         notmuch, message_id, &status);
2073     if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
2074         /* Message exists */
2075         *thread_id_ret = talloc_steal (
2076             ctx, notmuch_message_get_thread_id (message));
2077     } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
2078         /* Message did not exist.  Give it a fresh thread ID and
2079          * populate this message as a ghost message. */
2080         *thread_id_ret = talloc_strdup (
2081             ctx, _notmuch_database_generate_thread_id (notmuch));
2082         if (! *thread_id_ret) {
2083             status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
2084         } else {
2085             status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
2086             if (status == 0)
2087                 /* Commit the new ghost message */
2088                 _notmuch_message_sync (message);
2089         }
2090     } else {
2091         /* Create failed. Fall through. */
2092     }
2093
2094     notmuch_message_destroy (message);
2095
2096     return COERCE_STATUS (status, "Error creating ghost message");
2097 }
2098
2099 /* Pre-ghost messages _resolve_message_id_to_thread_id */
2100 static notmuch_status_t
2101 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
2102                                       void *ctx,
2103                                       const char *message_id,
2104                                       const char **thread_id_ret)
2105 {
2106     notmuch_status_t status;
2107     notmuch_message_t *message;
2108     string thread_id_string;
2109     char *metadata_key;
2110     Xapian::WritableDatabase *db;
2111
2112     status = notmuch_database_find_message (notmuch, message_id, &message);
2113
2114     if (status)
2115         return status;
2116
2117     if (message) {
2118         *thread_id_ret = talloc_steal (ctx,
2119                                        notmuch_message_get_thread_id (message));
2120
2121         notmuch_message_destroy (message);
2122
2123         return NOTMUCH_STATUS_SUCCESS;
2124     }
2125
2126     /* Message has not been seen yet.
2127      *
2128      * We may have seen a reference to it already, in which case, we
2129      * can return the thread ID stored in the metadata. Otherwise, we
2130      * generate a new thread ID and store it there.
2131      */
2132     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2133     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2134     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
2135
2136     if (thread_id_string.empty()) {
2137         *thread_id_ret = talloc_strdup (ctx,
2138                                         _notmuch_database_generate_thread_id (notmuch));
2139         db->set_metadata (metadata_key, *thread_id_ret);
2140     } else {
2141         *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
2142     }
2143
2144     talloc_free (metadata_key);
2145
2146     return NOTMUCH_STATUS_SUCCESS;
2147 }
2148
2149 static notmuch_status_t
2150 _merge_threads (notmuch_database_t *notmuch,
2151                 const char *winner_thread_id,
2152                 const char *loser_thread_id)
2153 {
2154     Xapian::PostingIterator loser, loser_end;
2155     notmuch_message_t *message = NULL;
2156     notmuch_private_status_t private_status;
2157     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2158
2159     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
2160
2161     for ( ; loser != loser_end; loser++) {
2162         message = _notmuch_message_create (notmuch, notmuch,
2163                                            *loser, &private_status);
2164         if (message == NULL) {
2165             ret = COERCE_STATUS (private_status,
2166                                  "Cannot find document for doc_id from query");
2167             goto DONE;
2168         }
2169
2170         _notmuch_message_remove_term (message, "thread", loser_thread_id);
2171         _notmuch_message_add_term (message, "thread", winner_thread_id);
2172         _notmuch_message_sync (message);
2173
2174         notmuch_message_destroy (message);
2175         message = NULL;
2176     }
2177
2178   DONE:
2179     if (message)
2180         notmuch_message_destroy (message);
2181
2182     return ret;
2183 }
2184
2185 static void
2186 _my_talloc_free_for_g_hash (void *ptr)
2187 {
2188     talloc_free (ptr);
2189 }
2190
2191 static notmuch_status_t
2192 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
2193                                            notmuch_message_t *message,
2194                                            notmuch_message_file_t *message_file,
2195                                            const char **thread_id)
2196 {
2197     GHashTable *parents = NULL;
2198     const char *refs, *in_reply_to, *in_reply_to_message_id;
2199     const char *last_ref_message_id, *this_message_id;
2200     GList *l, *keys = NULL;
2201     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2202
2203     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
2204                                      _my_talloc_free_for_g_hash, NULL);
2205     this_message_id = notmuch_message_get_message_id (message);
2206
2207     refs = _notmuch_message_file_get_header (message_file, "references");
2208     last_ref_message_id = parse_references (message,
2209                                             this_message_id,
2210                                             parents, refs);
2211
2212     in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
2213     in_reply_to_message_id = parse_references (message,
2214                                                this_message_id,
2215                                                parents, in_reply_to);
2216
2217     /* For the parent of this message, use the last message ID of the
2218      * References header, if available.  If not, fall back to the
2219      * first message ID in the In-Reply-To header. */
2220     if (last_ref_message_id) {
2221         _notmuch_message_add_term (message, "replyto",
2222                                    last_ref_message_id);
2223     } else if (in_reply_to_message_id) {
2224         _notmuch_message_add_term (message, "replyto",
2225                              in_reply_to_message_id);
2226     }
2227
2228     keys = g_hash_table_get_keys (parents);
2229     for (l = keys; l; l = l->next) {
2230         char *parent_message_id;
2231         const char *parent_thread_id = NULL;
2232
2233         parent_message_id = (char *) l->data;
2234
2235         _notmuch_message_add_term (message, "reference",
2236                                    parent_message_id);
2237
2238         ret = _resolve_message_id_to_thread_id (notmuch,
2239                                                 message,
2240                                                 parent_message_id,
2241                                                 &parent_thread_id);
2242         if (ret)
2243             goto DONE;
2244
2245         if (*thread_id == NULL) {
2246             *thread_id = talloc_strdup (message, parent_thread_id);
2247             _notmuch_message_add_term (message, "thread", *thread_id);
2248         } else if (strcmp (*thread_id, parent_thread_id)) {
2249             ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2250             if (ret)
2251                 goto DONE;
2252         }
2253     }
2254
2255   DONE:
2256     if (keys)
2257         g_list_free (keys);
2258     if (parents)
2259         g_hash_table_unref (parents);
2260
2261     return ret;
2262 }
2263
2264 static notmuch_status_t
2265 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2266                                             notmuch_message_t *message,
2267                                             const char **thread_id)
2268 {
2269     const char *message_id = notmuch_message_get_message_id (message);
2270     Xapian::PostingIterator child, children_end;
2271     notmuch_message_t *child_message = NULL;
2272     const char *child_thread_id;
2273     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2274     notmuch_private_status_t private_status;
2275
2276     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2277
2278     for ( ; child != children_end; child++) {
2279
2280         child_message = _notmuch_message_create (message, notmuch,
2281                                                  *child, &private_status);
2282         if (child_message == NULL) {
2283             ret = COERCE_STATUS (private_status,
2284                                  "Cannot find document for doc_id from query");
2285             goto DONE;
2286         }
2287
2288         child_thread_id = notmuch_message_get_thread_id (child_message);
2289         if (*thread_id == NULL) {
2290             *thread_id = talloc_strdup (message, child_thread_id);
2291             _notmuch_message_add_term (message, "thread", *thread_id);
2292         } else if (strcmp (*thread_id, child_thread_id)) {
2293             _notmuch_message_remove_term (child_message, "reference",
2294                                           message_id);
2295             _notmuch_message_sync (child_message);
2296             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2297             if (ret)
2298                 goto DONE;
2299         }
2300
2301         notmuch_message_destroy (child_message);
2302         child_message = NULL;
2303     }
2304
2305   DONE:
2306     if (child_message)
2307         notmuch_message_destroy (child_message);
2308
2309     return ret;
2310 }
2311
2312 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2313 static char *
2314 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2315                              notmuch_message_t *message)
2316 {
2317     const char *message_id;
2318     string stored_id;
2319     char *metadata_key;
2320
2321     message_id = notmuch_message_get_message_id (message);
2322     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2323
2324     /* Check if we have already seen related messages to this one.
2325      * If we have then use the thread_id that we stored at that time.
2326      */
2327     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2328     if (stored_id.empty ()) {
2329         return NULL;
2330     } else {
2331         Xapian::WritableDatabase *db;
2332
2333         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2334
2335         /* Clear the metadata for this message ID. We don't need it
2336          * anymore. */
2337         db->set_metadata (metadata_key, "");
2338
2339         return talloc_strdup (ctx, stored_id.c_str ());
2340     }
2341 }
2342
2343 /* Given a blank or ghost 'message' and its corresponding
2344  * 'message_file' link it to existing threads in the database.
2345  *
2346  * First, if is_ghost, this retrieves the thread ID already stored in
2347  * the message (which will be the case if a message was previously
2348  * added that referenced this one).  If the message is blank
2349  * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2350  * later in this function).  If the database does not support ghost
2351  * messages, this checks for a thread ID stored in database metadata
2352  * for this message ID.
2353  *
2354  * Second, we look at 'message_file' and its link-relevant headers
2355  * (References and In-Reply-To) for message IDs.
2356  *
2357  * Finally, we look in the database for existing message that
2358  * reference 'message'.
2359  *
2360  * In all cases, we assign to the current message the first thread ID
2361  * found. We will also merge any existing, distinct threads where this
2362  * message belongs to both, (which is not uncommon when messages are
2363  * processed out of order).
2364  *
2365  * Finally, if no thread ID has been found through referenced messages, we
2366  * call _notmuch_message_generate_thread_id to generate a new thread
2367  * ID. This should only happen for new, top-level messages, (no
2368  * References or In-Reply-To header in this message, and no previously
2369  * added message refers to this message).
2370  */
2371 static notmuch_status_t
2372 _notmuch_database_link_message (notmuch_database_t *notmuch,
2373                                 notmuch_message_t *message,
2374                                 notmuch_message_file_t *message_file,
2375                                 notmuch_bool_t is_ghost)
2376 {
2377     void *local = talloc_new (NULL);
2378     notmuch_status_t status;
2379     const char *thread_id = NULL;
2380
2381     /* Check if the message already had a thread ID */
2382     if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2383         if (is_ghost)
2384             thread_id = notmuch_message_get_thread_id (message);
2385     } else {
2386         thread_id = _consume_metadata_thread_id (local, notmuch, message);
2387         if (thread_id)
2388             _notmuch_message_add_term (message, "thread", thread_id);
2389     }
2390
2391     status = _notmuch_database_link_message_to_parents (notmuch, message,
2392                                                         message_file,
2393                                                         &thread_id);
2394     if (status)
2395         goto DONE;
2396
2397     if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS)) {
2398         /* In general, it shouldn't be necessary to link children,
2399          * since the earlier indexing of those children will have
2400          * stored a thread ID for the missing parent.  However, prior
2401          * to ghost messages, these stored thread IDs were NOT
2402          * rewritten during thread merging (and there was no
2403          * performant way to do so), so if indexed children were
2404          * pulled into a different thread ID by a merge, it was
2405          * necessary to pull them *back* into the stored thread ID of
2406          * the parent.  With ghost messages, we just rewrite the
2407          * stored thread IDs during merging, so this workaround isn't
2408          * necessary. */
2409         status = _notmuch_database_link_message_to_children (notmuch, message,
2410                                                              &thread_id);
2411         if (status)
2412             goto DONE;
2413     }
2414
2415     /* If not part of any existing thread, generate a new thread ID. */
2416     if (thread_id == NULL) {
2417         thread_id = _notmuch_database_generate_thread_id (notmuch);
2418
2419         _notmuch_message_add_term (message, "thread", thread_id);
2420     }
2421
2422  DONE:
2423     talloc_free (local);
2424
2425     return status;
2426 }
2427
2428 notmuch_status_t
2429 notmuch_database_add_message (notmuch_database_t *notmuch,
2430                               const char *filename,
2431                               notmuch_message_t **message_ret)
2432 {
2433     notmuch_message_file_t *message_file;
2434     notmuch_message_t *message = NULL;
2435     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2436     notmuch_private_status_t private_status;
2437     notmuch_bool_t is_ghost = false;
2438
2439     const char *date, *header;
2440     const char *from, *to, *subject;
2441     char *message_id = NULL;
2442
2443     if (message_ret)
2444         *message_ret = NULL;
2445
2446     ret = _notmuch_database_ensure_writable (notmuch);
2447     if (ret)
2448         return ret;
2449
2450     message_file = _notmuch_message_file_open (notmuch, filename);
2451     if (message_file == NULL)
2452         return NOTMUCH_STATUS_FILE_ERROR;
2453
2454     /* Adding a message may change many documents.  Do this all
2455      * atomically. */
2456     ret = notmuch_database_begin_atomic (notmuch);
2457     if (ret)
2458         goto DONE;
2459
2460     /* Parse message up front to get better error status. */
2461     ret = _notmuch_message_file_parse (message_file);
2462     if (ret)
2463         goto DONE;
2464
2465     try {
2466         /* Before we do any real work, (especially before doing a
2467          * potential SHA-1 computation on the entire file's contents),
2468          * let's make sure that what we're looking at looks like an
2469          * actual email message.
2470          */
2471         from = _notmuch_message_file_get_header (message_file, "from");
2472         subject = _notmuch_message_file_get_header (message_file, "subject");
2473         to = _notmuch_message_file_get_header (message_file, "to");
2474
2475         if ((from == NULL || *from == '\0') &&
2476             (subject == NULL || *subject == '\0') &&
2477             (to == NULL || *to == '\0'))
2478         {
2479             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2480             goto DONE;
2481         }
2482
2483         /* Now that we're sure it's mail, the first order of business
2484          * is to find a message ID (or else create one ourselves). */
2485
2486         header = _notmuch_message_file_get_header (message_file, "message-id");
2487         if (header && *header != '\0') {
2488             message_id = _parse_message_id (message_file, header, NULL);
2489
2490             /* So the header value isn't RFC-compliant, but it's
2491              * better than no message-id at all. */
2492             if (message_id == NULL)
2493                 message_id = talloc_strdup (message_file, header);
2494         }
2495
2496         if (message_id == NULL ) {
2497             /* No message-id at all, let's generate one by taking a
2498              * hash over the file's contents. */
2499             char *sha1 = _notmuch_sha1_of_file (filename);
2500
2501             /* If that failed too, something is really wrong. Give up. */
2502             if (sha1 == NULL) {
2503                 ret = NOTMUCH_STATUS_FILE_ERROR;
2504                 goto DONE;
2505             }
2506
2507             message_id = talloc_asprintf (message_file,
2508                                           "notmuch-sha1-%s", sha1);
2509             free (sha1);
2510         }
2511
2512         /* Now that we have a message ID, we get a message object,
2513          * (which may or may not reference an existing document in the
2514          * database). */
2515
2516         message = _notmuch_message_create_for_message_id (notmuch,
2517                                                           message_id,
2518                                                           &private_status);
2519
2520         talloc_free (message_id);
2521
2522         if (message == NULL) {
2523             ret = COERCE_STATUS (private_status,
2524                                  "Unexpected status value from _notmuch_message_create_for_message_id");
2525             goto DONE;
2526         }
2527
2528         _notmuch_message_add_filename (message, filename);
2529
2530         /* Is this a newly created message object or a ghost
2531          * message?  We have to be slightly careful: if this is a
2532          * blank message, it's not safe to call
2533          * notmuch_message_get_flag yet. */
2534         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2535             (is_ghost = notmuch_message_get_flag (
2536                 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2537             _notmuch_message_add_term (message, "type", "mail");
2538             if (is_ghost)
2539                 /* Convert ghost message to a regular message */
2540                 _notmuch_message_remove_term (message, "type", "ghost");
2541
2542             ret = _notmuch_database_link_message (notmuch, message,
2543                                                   message_file, is_ghost);
2544             if (ret)
2545                 goto DONE;
2546
2547             date = _notmuch_message_file_get_header (message_file, "date");
2548             _notmuch_message_set_header_values (message, date, from, subject);
2549
2550             ret = _notmuch_message_index_file (message, message_file);
2551             if (ret)
2552                 goto DONE;
2553         } else {
2554             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2555         }
2556
2557         _notmuch_message_sync (message);
2558     } catch (const Xapian::Error &error) {
2559         _notmuch_database_log (notmuch, "A Xapian exception occurred adding message: %s.\n",
2560                  error.get_msg().c_str());
2561         notmuch->exception_reported = TRUE;
2562         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2563         goto DONE;
2564     }
2565
2566   DONE:
2567     if (message) {
2568         if ((ret == NOTMUCH_STATUS_SUCCESS ||
2569              ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2570             *message_ret = message;
2571         else
2572             notmuch_message_destroy (message);
2573     }
2574
2575     if (message_file)
2576         _notmuch_message_file_close (message_file);
2577
2578     ret2 = notmuch_database_end_atomic (notmuch);
2579     if ((ret == NOTMUCH_STATUS_SUCCESS ||
2580          ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2581         ret2 != NOTMUCH_STATUS_SUCCESS)
2582         ret = ret2;
2583
2584     return ret;
2585 }
2586
2587 notmuch_status_t
2588 notmuch_database_remove_message (notmuch_database_t *notmuch,
2589                                  const char *filename)
2590 {
2591     notmuch_status_t status;
2592     notmuch_message_t *message;
2593
2594     status = notmuch_database_find_message_by_filename (notmuch, filename,
2595                                                         &message);
2596
2597     if (status == NOTMUCH_STATUS_SUCCESS && message) {
2598             status = _notmuch_message_remove_filename (message, filename);
2599             if (status == NOTMUCH_STATUS_SUCCESS)
2600                 _notmuch_message_delete (message);
2601             else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2602                 _notmuch_message_sync (message);
2603
2604             notmuch_message_destroy (message);
2605     }
2606
2607     return status;
2608 }
2609
2610 notmuch_status_t
2611 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2612                                            const char *filename,
2613                                            notmuch_message_t **message_ret)
2614 {
2615     void *local;
2616     const char *prefix = _find_prefix ("file-direntry");
2617     char *direntry, *term;
2618     Xapian::PostingIterator i, end;
2619     notmuch_status_t status;
2620
2621     if (message_ret == NULL)
2622         return NOTMUCH_STATUS_NULL_POINTER;
2623
2624     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2625         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2626
2627     /* return NULL on any failure */
2628     *message_ret = NULL;
2629
2630     local = talloc_new (notmuch);
2631
2632     try {
2633         status = _notmuch_database_filename_to_direntry (
2634             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2635         if (status || !direntry)
2636             goto DONE;
2637
2638         term = talloc_asprintf (local, "%s%s", prefix, direntry);
2639
2640         find_doc_ids_for_term (notmuch, term, &i, &end);
2641
2642         if (i != end) {
2643             notmuch_private_status_t private_status;
2644
2645             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2646                                                     &private_status);
2647             if (*message_ret == NULL)
2648                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2649         }
2650     } catch (const Xapian::Error &error) {
2651         _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
2652                  error.get_msg().c_str());
2653         notmuch->exception_reported = TRUE;
2654         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2655     }
2656
2657   DONE:
2658     talloc_free (local);
2659
2660     if (status && *message_ret) {
2661         notmuch_message_destroy (*message_ret);
2662         *message_ret = NULL;
2663     }
2664     return status;
2665 }
2666
2667 notmuch_string_list_t *
2668 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2669                                          Xapian::TermIterator &end,
2670                                          const char *prefix)
2671 {
2672     int prefix_len = strlen (prefix);
2673     notmuch_string_list_t *list;
2674
2675     list = _notmuch_string_list_create (ctx);
2676     if (unlikely (list == NULL))
2677         return NULL;
2678
2679     for (i.skip_to (prefix); i != end; i++) {
2680         /* Terminate loop at first term without desired prefix. */
2681         if (strncmp ((*i).c_str (), prefix, prefix_len))
2682             break;
2683
2684         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2685     }
2686
2687     return list;
2688 }
2689
2690 notmuch_tags_t *
2691 notmuch_database_get_all_tags (notmuch_database_t *db)
2692 {
2693     Xapian::TermIterator i, end;
2694     notmuch_string_list_t *tags;
2695
2696     try {
2697         i = db->xapian_db->allterms_begin();
2698         end = db->xapian_db->allterms_end();
2699         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2700                                                         _find_prefix ("tag"));
2701         _notmuch_string_list_sort (tags);
2702         return _notmuch_tags_create (db, tags);
2703     } catch (const Xapian::Error &error) {
2704         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2705                  error.get_msg().c_str());
2706         db->exception_reported = TRUE;
2707         return NULL;
2708     }
2709 }
2710
2711 const char *
2712 notmuch_database_status_string (const notmuch_database_t *notmuch)
2713 {
2714     return notmuch->status_string;
2715 }