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