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