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