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