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