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