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