]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib: add clarification about the use of "prefix" in the docs.
[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 "thread-fp.h"
25 #include "regexp-fields.h"
26 #include "string-util.h"
27
28 #include <iostream>
29
30 #include <sys/time.h>
31 #include <sys/stat.h>
32 #include <signal.h>
33 #include <ftw.h>
34
35 #include <glib.h> /* g_free, GPtrArray, GHashTable */
36 #include <glib-object.h> /* g_type_init */
37
38 #include <gmime/gmime.h> /* g_mime_init */
39
40 using namespace std;
41
42 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
43
44 typedef struct {
45     const char *name;
46     const char *prefix;
47     notmuch_field_flag_t flags;
48 } prefix_t;
49
50 #define NOTMUCH_DATABASE_VERSION 3
51
52 #define STRINGIFY(s) _SUB_STRINGIFY(s)
53 #define _SUB_STRINGIFY(s) #s
54
55 #if HAVE_XAPIAN_DB_RETRY_LOCK
56 #define DB_ACTION (Xapian::DB_CREATE_OR_OPEN | Xapian::DB_RETRY_LOCK)
57 #else
58 #define DB_ACTION Xapian::DB_CREATE_OR_OPEN
59 #endif
60
61 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
62  *
63  * We currently have three different types of documents (mail, ghost,
64  * and directory) and also some metadata.
65  *
66  * There are two kinds of prefixes used in notmuch. There are the
67  * human friendly 'prefix names' like "thread:", which are also used
68  * in the query parser, and the actual prefix terms in the database
69  * (e.g. "G"). The correspondence is maintained in the file scope data
70  * structure 'prefix_table'.
71  *
72  * Mail document
73  * -------------
74  * A mail document is associated with a particular email message. It
75  * is stored in one or more files on disk and is uniquely identified
76  * by its "id" field (which is generally the message ID). It is
77  * indexed with the following prefixed terms which the database uses
78  * to construct threads, etc.:
79  *
80  *    Single terms of given prefix:
81  *
82  *      type:   mail
83  *
84  *      id:     Unique ID of mail. This is from the Message-ID header
85  *              if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
86  *              If it's present and too long, then we use
87  *              "notmuch-sha1-<sha1_sum_of_message_id>".
88  *              If this header is not present, we use
89  *              "notmuch-sha1-<sha1_sum_of_entire_file>".
90  *
91  *      thread: The ID of the thread to which the mail belongs
92  *
93  *      replyto: The ID from the In-Reply-To header of the mail (if any).
94  *
95  *    Multiple terms of given prefix:
96  *
97  *      reference: All message IDs from In-Reply-To and References
98  *                 headers in the message.
99  *
100  *      tag:       Any tags associated with this message by the user.
101  *
102  *      file-direntry:  A colon-separated pair of values
103  *                      (INTEGER:STRING), where INTEGER is the
104  *                      document ID of a directory document, and
105  *                      STRING is the name of a file within that
106  *                      directory for this mail message.
107  *
108  *      property:       Has a property with key=value
109  *                 FIXME: if no = is present, should match on any value
110  *
111  *    A mail document also has four values:
112  *
113  *      TIMESTAMP:      The time_t value corresponding to the message's
114  *                      Date header.
115  *
116  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
117  *
118  *      FROM:           The value of the "From" header
119  *
120  *      SUBJECT:        The value of the "Subject" header
121  *
122  *      LAST_MOD:       The revision number as of the last tag or
123  *                      filename change.
124  *
125  * In addition, terms from the content of the message are added with
126  * "from", "to", "attachment", and "subject" prefixes for use by the
127  * user in searching. Similarly, terms from the path of the mail
128  * message are added with "folder" and "path" prefixes. But the
129  * database doesn't really care itself about any of these.
130  *
131  * The data portion of a mail document is empty.
132  *
133  * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
134  * -----------------------------------------------
135  * A ghost mail document is like a mail document, but where we don't
136  * have the message content.  These are used to track thread reference
137  * information for messages we haven't received.
138  *
139  * A ghost mail document has type: ghost; id and thread fields that
140  * are identical to the mail document fields; and a MESSAGE_ID value.
141  *
142  * Directory document
143  * ------------------
144  * A directory document is used by a client of the notmuch library to
145  * maintain data necessary to allow for efficient polling of mail
146  * directories.
147  *
148  * All directory documents contain one term:
149  *
150  *      directory:      The directory path (relative to the database path)
151  *                      Or the SHA1 sum of the directory path (if the
152  *                      path itself is too long to fit in a Xapian
153  *                      term).
154  *
155  * And all directory documents for directories other than top-level
156  * directories also contain the following term:
157  *
158  *      directory-direntry: A colon-separated pair of values
159  *                          (INTEGER:STRING), where INTEGER is the
160  *                          document ID of the parent directory
161  *                          document, and STRING is the name of this
162  *                          directory within that parent.
163  *
164  * All directory documents have a single value:
165  *
166  *      TIMESTAMP:      The mtime of the directory (at last scan)
167  *
168  * The data portion of a directory document contains the path of the
169  * directory (relative to the database path).
170  *
171  * Database metadata
172  * -----------------
173  * Xapian allows us to store arbitrary name-value pairs as
174  * "metadata". We currently use the following metadata names with the
175  * given meanings:
176  *
177  *      version         The database schema version, (which is distinct
178  *                      from both the notmuch package version (see
179  *                      notmuch --version) and the libnotmuch library
180  *                      version. The version is stored as an base-10
181  *                      ASCII integer. The initial database version
182  *                      was 1, (though a schema existed before that
183  *                      were no "version" database value existed at
184  *                      all). Successive versions are allocated as
185  *                      changes are made to the database (such as by
186  *                      indexing new fields).
187  *
188  *      features        The set of features supported by this
189  *                      database. This consists of a set of
190  *                      '\n'-separated lines, where each is a feature
191  *                      name, a '\t', and compatibility flags.  If the
192  *                      compatibility flags contain 'w', then the
193  *                      opener must support this feature to safely
194  *                      write this database.  If the compatibility
195  *                      flags contain 'r', then the opener must
196  *                      support this feature to read this database.
197  *                      Introduced in database version 3.
198  *
199  *      last_thread_id  The last thread ID generated. This is stored
200  *                      as a 16-byte hexadecimal ASCII representation
201  *                      of a 64-bit unsigned integer. The first ID
202  *                      generated is 1 and the value will be
203  *                      incremented for each thread ID.
204  *
205  *      C*              metadata keys starting with C indicate
206  *                      configuration data. It can be managed with the
207  *                      n_database_*config* API.  There is a convention
208  *                      of hierarchical keys separated by '.' (e.g.
209  *                      query.notmuch stores the value for the named
210  *                      query 'notmuch'), but it is not enforced by the
211  *                      API.
212  *
213  * Obsolete metadata
214  * -----------------
215  *
216  * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
217  * Instead, the database has the following additional database
218  * metadata:
219  *
220  *      thread_id_*     A pre-allocated thread ID for a particular
221  *                      message. This is actually an arbitrarily large
222  *                      family of metadata name. Any particular name is
223  *                      formed by concatenating "thread_id_" with a message
224  *                      ID (or the SHA1 sum of a message ID if it is very
225  *                      long---see description of 'id' in the mail
226  *                      document). The value stored is a thread ID.
227  *
228  *                      These thread ID metadata values are stored
229  *                      whenever a message references a parent message
230  *                      that does not yet exist in the database. A
231  *                      thread ID will be allocated and stored, and if
232  *                      the message is later added, the stored thread
233  *                      ID will be used (and the metadata value will
234  *                      be cleared).
235  *
236  *                      Even before a message is added, it's
237  *                      pre-allocated thread ID is useful so that all
238  *                      descendant messages that reference this common
239  *                      parent can be recognized as belonging to the
240  *                      same thread.
241  */
242
243 /* With these prefix values we follow the conventions published here:
244  *
245  * https://xapian.org/docs/omega/termprefixes.html
246  *
247  * as much as makes sense. Note that I took some liberty in matching
248  * the reserved prefix values to notmuch concepts, (for example, 'G'
249  * is documented as "newsGroup (or similar entity - e.g. a web forum
250  * name)", for which I think the thread is the closest analogue in
251  * notmuch. This in spite of the fact that we will eventually be
252  * storing mailing-list messages where 'G' for "mailing list name"
253  * might be even a closer analogue. I'm treating the single-character
254  * prefixes preferentially for core notmuch concepts (which will be
255  * nearly universal to all mail messages).
256  */
257
258 static const
259 prefix_t prefix_table[] = {
260     /* name                     term prefix     flags */
261     { "type",                   "T",            NOTMUCH_FIELD_NO_FLAGS },
262     { "reference",              "XREFERENCE",   NOTMUCH_FIELD_NO_FLAGS },
263     { "replyto",                "XREPLYTO",     NOTMUCH_FIELD_NO_FLAGS },
264     { "directory",              "XDIRECTORY",   NOTMUCH_FIELD_NO_FLAGS },
265     { "file-direntry",          "XFDIRENTRY",   NOTMUCH_FIELD_NO_FLAGS },
266     { "directory-direntry",     "XDDIRENTRY",   NOTMUCH_FIELD_NO_FLAGS },
267     { "thread",                 "G",            NOTMUCH_FIELD_EXTERNAL |
268                                                 NOTMUCH_FIELD_PROCESSOR },
269     { "tag",                    "K",            NOTMUCH_FIELD_EXTERNAL |
270                                                 NOTMUCH_FIELD_PROCESSOR },
271     { "is",                     "K",            NOTMUCH_FIELD_EXTERNAL |
272                                                 NOTMUCH_FIELD_PROCESSOR },
273     { "id",                     "Q",            NOTMUCH_FIELD_EXTERNAL },
274     { "mid",                    "Q",            NOTMUCH_FIELD_EXTERNAL |
275                                                 NOTMUCH_FIELD_PROCESSOR },
276     { "path",                   "P",            NOTMUCH_FIELD_EXTERNAL|
277                                                 NOTMUCH_FIELD_PROCESSOR },
278     { "property",               "XPROPERTY",    NOTMUCH_FIELD_EXTERNAL },
279     /*
280      * Unconditionally add ':' to reduce potential ambiguity with
281      * overlapping prefixes and/or terms that start with capital
282      * letters. See Xapian document termprefixes.html for related
283      * discussion.
284      */
285     { "folder",                 "XFOLDER:",     NOTMUCH_FIELD_EXTERNAL |
286                                                 NOTMUCH_FIELD_PROCESSOR },
287 #if HAVE_XAPIAN_FIELD_PROCESSOR
288     { "date",                   NULL,           NOTMUCH_FIELD_EXTERNAL |
289                                                 NOTMUCH_FIELD_PROCESSOR },
290     { "query",                  NULL,           NOTMUCH_FIELD_EXTERNAL |
291                                                 NOTMUCH_FIELD_PROCESSOR },
292 #endif
293     { "from",                   "XFROM",        NOTMUCH_FIELD_EXTERNAL |
294                                                 NOTMUCH_FIELD_PROBABILISTIC |
295                                                 NOTMUCH_FIELD_PROCESSOR },
296     { "to",                     "XTO",          NOTMUCH_FIELD_EXTERNAL |
297                                                 NOTMUCH_FIELD_PROBABILISTIC },
298     { "attachment",             "XATTACHMENT",  NOTMUCH_FIELD_EXTERNAL |
299                                                 NOTMUCH_FIELD_PROBABILISTIC },
300     { "mimetype",               "XMIMETYPE",    NOTMUCH_FIELD_EXTERNAL |
301                                                 NOTMUCH_FIELD_PROBABILISTIC },
302     { "subject",                "XSUBJECT",     NOTMUCH_FIELD_EXTERNAL |
303                                                 NOTMUCH_FIELD_PROBABILISTIC |
304                                                 NOTMUCH_FIELD_PROCESSOR},
305 };
306
307 static void
308 _setup_query_field_default (const prefix_t *prefix, notmuch_database_t *notmuch)
309 {
310     if (prefix->flags & NOTMUCH_FIELD_PROBABILISTIC)
311         notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
312     else
313         notmuch->query_parser->add_boolean_prefix (prefix->name, prefix->prefix);
314 }
315
316 #if HAVE_XAPIAN_FIELD_PROCESSOR
317 static void
318 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
319 {
320     if (prefix->flags & NOTMUCH_FIELD_PROCESSOR) {
321         Xapian::FieldProcessor *fp;
322
323         if (STRNCMP_LITERAL (prefix->name, "date") == 0)
324             fp = (new DateFieldProcessor())->release ();
325         else if (STRNCMP_LITERAL(prefix->name, "query") == 0)
326             fp = (new QueryFieldProcessor (*notmuch->query_parser, notmuch))->release ();
327         else if (STRNCMP_LITERAL(prefix->name, "thread") == 0)
328             fp = (new ThreadFieldProcessor (*notmuch->query_parser, notmuch))->release ();
329         else
330             fp = (new RegexpFieldProcessor (prefix->name, prefix->flags,
331                                             *notmuch->query_parser, notmuch))->release ();
332
333         /* we treat all field-processor fields as boolean in order to get the raw input */
334         notmuch->query_parser->add_boolean_prefix (prefix->name, fp);
335     } else {
336         _setup_query_field_default (prefix, notmuch);
337     }
338 }
339 #else
340 static inline void
341 _setup_query_field (const prefix_t *prefix, notmuch_database_t *notmuch)
342 {
343     _setup_query_field_default (prefix, notmuch);
344 }
345 #endif
346
347 const char *
348 _find_prefix (const char *name)
349 {
350     unsigned int i;
351
352     for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
353         if (strcmp (name, prefix_table[i].name) == 0)
354             return prefix_table[i].prefix;
355     }
356
357     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
358
359     return "";
360 }
361
362 static const struct {
363     /* NOTMUCH_FEATURE_* value. */
364     _notmuch_features value;
365     /* Feature name as it appears in the database.  This name should
366      * be appropriate for displaying to the user if an older version
367      * of notmuch doesn't support this feature. */
368     const char *name;
369     /* Compatibility flags when this feature is declared. */
370     const char *flags;
371 } feature_names[] = {
372     { NOTMUCH_FEATURE_FILE_TERMS,
373       "multiple paths per message", "rw" },
374     { NOTMUCH_FEATURE_DIRECTORY_DOCS,
375       "relative directory paths", "rw" },
376     /* Header values are not required for reading a database because a
377      * reader can just refer to the message file. */
378     { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
379       "from/subject/message-ID in database", "w" },
380     { NOTMUCH_FEATURE_BOOL_FOLDER,
381       "exact folder:/path: search", "rw" },
382     { NOTMUCH_FEATURE_GHOSTS,
383       "mail documents for missing messages", "w"},
384     /* Knowledge of the index mime-types are not required for reading
385      * a database because a reader will just be unable to query
386      * them. */
387     { NOTMUCH_FEATURE_INDEXED_MIMETYPES,
388       "indexed MIME types", "w"},
389     { NOTMUCH_FEATURE_LAST_MOD,
390       "modification tracking", "w"},
391 };
392
393 const char *
394 notmuch_status_to_string (notmuch_status_t status)
395 {
396     switch (status) {
397     case NOTMUCH_STATUS_SUCCESS:
398         return "No error occurred";
399     case NOTMUCH_STATUS_OUT_OF_MEMORY:
400         return "Out of memory";
401     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
402         return "Attempt to write to a read-only database";
403     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
404         return "A Xapian exception occurred";
405     case NOTMUCH_STATUS_FILE_ERROR:
406         return "Something went wrong trying to read or write a file";
407     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
408         return "File is not an email";
409     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
410         return "Message ID is identical to a message in database";
411     case NOTMUCH_STATUS_NULL_POINTER:
412         return "Erroneous NULL pointer";
413     case NOTMUCH_STATUS_TAG_TOO_LONG:
414         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
415     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
416         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
417     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
418         return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
419     case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
420         return "Unsupported operation";
421     case NOTMUCH_STATUS_UPGRADE_REQUIRED:
422         return "Operation requires a database upgrade";
423     case NOTMUCH_STATUS_PATH_ERROR:
424         return "Path supplied is illegal for this function";
425     case NOTMUCH_STATUS_MALFORMED_CRYPTO_PROTOCOL:
426         return "Crypto protocol missing, malformed, or unintelligible";
427     case NOTMUCH_STATUS_FAILED_CRYPTO_CONTEXT_CREATION:
428         return "Crypto engine initialization failure";
429     case NOTMUCH_STATUS_UNKNOWN_CRYPTO_PROTOCOL:
430         return "Unknown crypto protocol";
431     default:
432     case NOTMUCH_STATUS_LAST_STATUS:
433         return "Unknown error status value";
434     }
435 }
436
437 void
438 _notmuch_database_log (notmuch_database_t *notmuch,
439                       const char *format,
440                       ...)
441 {
442     va_list va_args;
443
444     va_start (va_args, format);
445
446     if (notmuch->status_string)
447         talloc_free (notmuch->status_string);
448
449     notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
450     va_end (va_args);
451 }
452
453 void
454 _notmuch_database_log_append (notmuch_database_t *notmuch,
455                       const char *format,
456                       ...)
457 {
458     va_list va_args;
459
460     va_start (va_args, format);
461
462     if (notmuch->status_string)
463         notmuch->status_string = talloc_vasprintf_append (notmuch->status_string, format, va_args);
464     else
465         notmuch->status_string = talloc_vasprintf (notmuch, format, va_args);
466
467     va_end (va_args);
468 }
469
470 static void
471 find_doc_ids_for_term (notmuch_database_t *notmuch,
472                        const char *term,
473                        Xapian::PostingIterator *begin,
474                        Xapian::PostingIterator *end)
475 {
476     *begin = notmuch->xapian_db->postlist_begin (term);
477
478     *end = notmuch->xapian_db->postlist_end (term);
479 }
480
481 void
482 _notmuch_database_find_doc_ids (notmuch_database_t *notmuch,
483                                 const char *prefix_name,
484                                 const char *value,
485                                 Xapian::PostingIterator *begin,
486                                 Xapian::PostingIterator *end)
487 {
488     char *term;
489
490     term = talloc_asprintf (notmuch, "%s%s",
491                             _find_prefix (prefix_name), value);
492
493     find_doc_ids_for_term (notmuch, term, begin, end);
494
495     talloc_free (term);
496 }
497
498 notmuch_private_status_t
499 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
500                                       const char *prefix_name,
501                                       const char *value,
502                                       unsigned int *doc_id)
503 {
504     Xapian::PostingIterator i, end;
505
506     _notmuch_database_find_doc_ids (notmuch, prefix_name, value, &i, &end);
507
508     if (i == end) {
509         *doc_id = 0;
510         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
511     }
512
513     *doc_id = *i;
514
515 #if DEBUG_DATABASE_SANITY
516     i++;
517
518     if (i != end)
519         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
520                         prefix_name, value);
521 #endif
522
523     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
524 }
525
526 static Xapian::Document
527 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
528 {
529     return notmuch->xapian_db->get_document (doc_id);
530 }
531
532 /* Generate a compressed version of 'message_id' of the form:
533  *
534  *      notmuch-sha1-<sha1_sum_of_message_id>
535  */
536 char *
537 _notmuch_message_id_compressed (void *ctx, const char *message_id)
538 {
539     char *sha1, *compressed;
540
541     sha1 = _notmuch_sha1_of_string (message_id);
542
543     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
544     free (sha1);
545
546     return compressed;
547 }
548
549 notmuch_status_t
550 notmuch_database_find_message (notmuch_database_t *notmuch,
551                                const char *message_id,
552                                notmuch_message_t **message_ret)
553 {
554     notmuch_private_status_t status;
555     unsigned int doc_id;
556
557     if (message_ret == NULL)
558         return NOTMUCH_STATUS_NULL_POINTER;
559
560     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
561         message_id = _notmuch_message_id_compressed (notmuch, message_id);
562
563     try {
564         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
565                                                        message_id, &doc_id);
566
567         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
568             *message_ret = NULL;
569         else {
570             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
571                                                     NULL);
572             if (*message_ret == NULL)
573                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
574         }
575
576         return NOTMUCH_STATUS_SUCCESS;
577     } catch (const Xapian::Error &error) {
578         _notmuch_database_log (notmuch, "A Xapian exception occurred finding message: %s.\n",
579                  error.get_msg().c_str());
580         notmuch->exception_reported = true;
581         *message_ret = NULL;
582         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
583     }
584 }
585
586 notmuch_status_t
587 notmuch_database_create (const char *path, notmuch_database_t **database)
588 {
589     char *status_string = NULL;
590     notmuch_status_t status;
591
592     status = notmuch_database_create_verbose (path, database,
593                                               &status_string);
594
595     if (status_string) {
596         fputs (status_string, stderr);
597         free (status_string);
598     }
599
600     return status;
601 }
602
603 notmuch_status_t
604 notmuch_database_create_verbose (const char *path,
605                                  notmuch_database_t **database,
606                                  char **status_string)
607 {
608     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
609     notmuch_database_t *notmuch = NULL;
610     char *notmuch_path = NULL;
611     char *message = NULL;
612     struct stat st;
613     int err;
614
615     if (path == NULL) {
616         message = strdup ("Error: Cannot create a database for a NULL path.\n");
617         status = NOTMUCH_STATUS_NULL_POINTER;
618         goto DONE;
619     }
620
621     if (path[0] != '/') {
622         message = strdup ("Error: Database path must be absolute.\n");
623         status = NOTMUCH_STATUS_PATH_ERROR;
624         goto DONE;
625     }
626
627     err = stat (path, &st);
628     if (err) {
629         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: %s.\n",
630                                 path, strerror (errno)));
631         status = NOTMUCH_STATUS_FILE_ERROR;
632         goto DONE;
633     }
634
635     if (! S_ISDIR (st.st_mode)) {
636         IGNORE_RESULT (asprintf (&message, "Error: Cannot create database at %s: "
637                                  "Not a directory.\n",
638                                  path));
639         status = NOTMUCH_STATUS_FILE_ERROR;
640         goto DONE;
641     }
642
643     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
644
645     err = mkdir (notmuch_path, 0755);
646
647     if (err) {
648         IGNORE_RESULT (asprintf (&message, "Error: Cannot create directory %s: %s.\n",
649                                  notmuch_path, strerror (errno)));
650         status = NOTMUCH_STATUS_FILE_ERROR;
651         goto DONE;
652     }
653
654     status = notmuch_database_open_verbose (path,
655                                             NOTMUCH_DATABASE_MODE_READ_WRITE,
656                                             &notmuch, &message);
657     if (status)
658         goto DONE;
659
660     /* Upgrade doesn't add these feature to existing databases, but
661      * new databases have them. */
662     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
663     notmuch->features |= NOTMUCH_FEATURE_INDEXED_MIMETYPES;
664
665     status = notmuch_database_upgrade (notmuch, NULL, NULL);
666     if (status) {
667         notmuch_database_close(notmuch);
668         notmuch = NULL;
669     }
670
671   DONE:
672     if (notmuch_path)
673         talloc_free (notmuch_path);
674
675     if (message) {
676         if (status_string)
677             *status_string = message;
678         else
679             free (message);
680     }
681     if (database)
682         *database = notmuch;
683     else
684         talloc_free (notmuch);
685     return status;
686 }
687
688 notmuch_status_t
689 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
690 {
691     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
692         _notmuch_database_log (notmuch, "Cannot write to a read-only database.\n");
693         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
694     }
695
696     return NOTMUCH_STATUS_SUCCESS;
697 }
698
699 /* Allocate a revision number for the next change. */
700 unsigned long
701 _notmuch_database_new_revision (notmuch_database_t *notmuch)
702 {
703     unsigned long new_revision = notmuch->revision + 1;
704
705     /* If we're in an atomic section, hold off on updating the
706      * committed revision number until we commit the atomic section.
707      */
708     if (notmuch->atomic_nesting)
709         notmuch->atomic_dirty = true;
710     else
711         notmuch->revision = new_revision;
712
713     return new_revision;
714 }
715
716 /* Parse a database features string from the given database version.
717  * Returns the feature bit set.
718  *
719  * For version < 3, this ignores the features string and returns a
720  * hard-coded set of features.
721  *
722  * If there are unrecognized features that are required to open the
723  * database in mode (which should be 'r' or 'w'), return a
724  * comma-separated list of unrecognized but required features in
725  * *incompat_out suitable for presenting to the user.  *incompat_out
726  * will be allocated from ctx.
727  */
728 static _notmuch_features
729 _parse_features (const void *ctx, const char *features, unsigned int version,
730                  char mode, char **incompat_out)
731 {
732     _notmuch_features res = static_cast<_notmuch_features>(0);
733     unsigned int namelen, i;
734     size_t llen = 0;
735     const char *flags;
736
737     /* Prior to database version 3, features were implied by the
738      * version number. */
739     if (version == 0)
740         return NOTMUCH_FEATURES_V0;
741     else if (version == 1)
742         return NOTMUCH_FEATURES_V1;
743     else if (version == 2)
744         return NOTMUCH_FEATURES_V2;
745
746     /* Parse the features string */
747     while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
748         flags = strchr (features, '\t');
749         if (! flags || flags > features + llen)
750             continue;
751         namelen = flags - features;
752
753         for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
754             if (strlen (feature_names[i].name) == namelen &&
755                 strncmp (feature_names[i].name, features, namelen) == 0) {
756                 res |= feature_names[i].value;
757                 break;
758             }
759         }
760
761         if (i == ARRAY_SIZE (feature_names) && incompat_out) {
762             /* Unrecognized feature */
763             const char *have = strchr (flags, mode);
764             if (have && have < features + llen) {
765                 /* This feature is required to access this database in
766                  * 'mode', but we don't understand it. */
767                 if (! *incompat_out)
768                     *incompat_out = talloc_strdup (ctx, "");
769                 *incompat_out = talloc_asprintf_append_buffer (
770                     *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
771                     namelen, features);
772             }
773         }
774     }
775
776     return res;
777 }
778
779 static char *
780 _print_features (const void *ctx, unsigned int features)
781 {
782     unsigned int i;
783     char *res = talloc_strdup (ctx, "");
784
785     for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
786         if (features & feature_names[i].value)
787             res = talloc_asprintf_append_buffer (
788                 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
789
790     return res;
791 }
792
793 notmuch_status_t
794 notmuch_database_open (const char *path,
795                        notmuch_database_mode_t mode,
796                        notmuch_database_t **database)
797 {
798     char *status_string = NULL;
799     notmuch_status_t status;
800
801     status = notmuch_database_open_verbose (path, mode, database,
802                                            &status_string);
803
804     if (status_string) {
805         fputs (status_string, stderr);
806         free (status_string);
807     }
808
809     return status;
810 }
811
812 notmuch_status_t
813 notmuch_database_open_verbose (const char *path,
814                                notmuch_database_mode_t mode,
815                                notmuch_database_t **database,
816                                char **status_string)
817 {
818     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
819     void *local = talloc_new (NULL);
820     notmuch_database_t *notmuch = NULL;
821     char *notmuch_path, *xapian_path, *incompat_features;
822     char *message = NULL;
823     struct stat st;
824     int err;
825     unsigned int i, version;
826     static int initialized = 0;
827
828     if (path == NULL) {
829         message = strdup ("Error: Cannot open a database for a NULL path.\n");
830         status = NOTMUCH_STATUS_NULL_POINTER;
831         goto DONE;
832     }
833
834     if (path[0] != '/') {
835         message = strdup ("Error: Database path must be absolute.\n");
836         status = NOTMUCH_STATUS_PATH_ERROR;
837         goto DONE;
838     }
839
840     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
841         message = strdup ("Out of memory\n");
842         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
843         goto DONE;
844     }
845
846     err = stat (notmuch_path, &st);
847     if (err) {
848         IGNORE_RESULT (asprintf (&message, "Error opening database at %s: %s\n",
849                                  notmuch_path, strerror (errno)));
850         status = NOTMUCH_STATUS_FILE_ERROR;
851         goto DONE;
852     }
853
854     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
855         message = strdup ("Out of memory\n");
856         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
857         goto DONE;
858     }
859
860     /* Initialize the GLib type system and threads */
861 #if !GLIB_CHECK_VERSION(2, 35, 1)
862     g_type_init ();
863 #endif
864
865     /* Initialize gmime */
866     if (! initialized) {
867         g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
868         initialized = 1;
869     }
870
871     notmuch = talloc_zero (NULL, notmuch_database_t);
872     notmuch->exception_reported = false;
873     notmuch->status_string = NULL;
874     notmuch->path = talloc_strdup (notmuch, path);
875
876     strip_trailing(notmuch->path, '/');
877
878     notmuch->mode = mode;
879     notmuch->atomic_nesting = 0;
880     notmuch->view = 1;
881     try {
882         string last_thread_id;
883         string last_mod;
884
885         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
886             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
887                                                                DB_ACTION);
888         } else {
889             notmuch->xapian_db = new Xapian::Database (xapian_path);
890         }
891
892         /* Check version.  As of database version 3, we represent
893          * changes in terms of features, so assume a version bump
894          * means a dramatically incompatible change. */
895         version = notmuch_database_get_version (notmuch);
896         if (version > NOTMUCH_DATABASE_VERSION) {
897             IGNORE_RESULT (asprintf (&message,
898                       "Error: Notmuch database at %s\n"
899                       "       has a newer database format version (%u) than supported by this\n"
900                       "       version of notmuch (%u).\n",
901                                      notmuch_path, version, NOTMUCH_DATABASE_VERSION));
902             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
903             notmuch_database_destroy (notmuch);
904             notmuch = NULL;
905             status = NOTMUCH_STATUS_FILE_ERROR;
906             goto DONE;
907         }
908
909         /* Check features. */
910         incompat_features = NULL;
911         notmuch->features = _parse_features (
912             local, notmuch->xapian_db->get_metadata ("features").c_str (),
913             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
914             &incompat_features);
915         if (incompat_features) {
916             IGNORE_RESULT (asprintf (&message,
917                 "Error: Notmuch database at %s\n"
918                 "       requires features (%s)\n"
919                 "       not supported by this version of notmuch.\n",
920                                      notmuch_path, incompat_features));
921             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
922             notmuch_database_destroy (notmuch);
923             notmuch = NULL;
924             status = NOTMUCH_STATUS_FILE_ERROR;
925             goto DONE;
926         }
927
928         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
929         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
930         if (last_thread_id.empty ()) {
931             notmuch->last_thread_id = 0;
932         } else {
933             const char *str;
934             char *end;
935
936             str = last_thread_id.c_str ();
937             notmuch->last_thread_id = strtoull (str, &end, 16);
938             if (*end != '\0')
939                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
940         }
941
942         /* Get current highest revision number. */
943         last_mod = notmuch->xapian_db->get_value_upper_bound (
944             NOTMUCH_VALUE_LAST_MOD);
945         if (last_mod.empty ())
946             notmuch->revision = 0;
947         else
948             notmuch->revision = Xapian::sortable_unserialise (last_mod);
949         notmuch->uuid = talloc_strdup (
950             notmuch, notmuch->xapian_db->get_uuid ().c_str ());
951
952         notmuch->query_parser = new Xapian::QueryParser;
953         notmuch->term_gen = new Xapian::TermGenerator;
954         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
955         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
956         notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
957         notmuch->last_mod_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_LAST_MOD, "lastmod:");
958
959         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
960         notmuch->query_parser->set_database (*notmuch->xapian_db);
961         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
962         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
963         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
964         notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
965         notmuch->query_parser->add_valuerangeprocessor (notmuch->last_mod_range_processor);
966
967         for (i = 0; i < ARRAY_SIZE (prefix_table); i++) {
968             const prefix_t *prefix = &prefix_table[i];
969             if (prefix->flags & NOTMUCH_FIELD_EXTERNAL) {
970                 _setup_query_field (prefix, notmuch);
971             }
972         }
973     } catch (const Xapian::Error &error) {
974         IGNORE_RESULT (asprintf (&message, "A Xapian exception occurred opening database: %s\n",
975                                  error.get_msg().c_str()));
976         notmuch_database_destroy (notmuch);
977         notmuch = NULL;
978         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
979     }
980
981   DONE:
982     talloc_free (local);
983
984     if (message) {
985         if (status_string)
986             *status_string = message;
987         else
988             free (message);
989     }
990
991     if (database)
992         *database = notmuch;
993     else
994         talloc_free (notmuch);
995     return status;
996 }
997
998 notmuch_status_t
999 notmuch_database_close (notmuch_database_t *notmuch)
1000 {
1001     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1002
1003     /* Many Xapian objects (and thus notmuch objects) hold references to
1004      * the database, so merely deleting the database may not suffice to
1005      * close it.  Thus, we explicitly close it here. */
1006     if (notmuch->xapian_db != NULL) {
1007         try {
1008             /* If there's an outstanding transaction, it's unclear if
1009              * closing the Xapian database commits everything up to
1010              * that transaction, or may discard committed (but
1011              * unflushed) transactions.  To be certain, explicitly
1012              * cancel any outstanding transaction before closing. */
1013             if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1014                 notmuch->atomic_nesting)
1015                 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
1016                     ->cancel_transaction ();
1017
1018             /* Close the database.  This implicitly flushes
1019              * outstanding changes. */
1020             notmuch->xapian_db->close();
1021         } catch (const Xapian::Error &error) {
1022             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1023             if (! notmuch->exception_reported) {
1024                 _notmuch_database_log (notmuch, "Error: A Xapian exception occurred closing database: %s\n",
1025                          error.get_msg().c_str());
1026             }
1027         }
1028     }
1029
1030     delete notmuch->term_gen;
1031     notmuch->term_gen = NULL;
1032     delete notmuch->query_parser;
1033     notmuch->query_parser = NULL;
1034     delete notmuch->xapian_db;
1035     notmuch->xapian_db = NULL;
1036     delete notmuch->value_range_processor;
1037     notmuch->value_range_processor = NULL;
1038     delete notmuch->date_range_processor;
1039     notmuch->date_range_processor = NULL;
1040     delete notmuch->last_mod_range_processor;
1041     notmuch->last_mod_range_processor = NULL;
1042
1043     return status;
1044 }
1045
1046 notmuch_status_t
1047 _notmuch_database_reopen (notmuch_database_t *notmuch)
1048 {
1049     if (notmuch->mode != NOTMUCH_DATABASE_MODE_READ_ONLY)
1050         return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1051
1052     try {
1053         notmuch->xapian_db->reopen ();
1054     } catch (const Xapian::Error &error) {
1055         if (! notmuch->exception_reported) {
1056             _notmuch_database_log (notmuch, "Error: A Xapian exception reopening database: %s\n",
1057                                    error.get_msg ().c_str ());
1058             notmuch->exception_reported = true;
1059         }
1060         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1061     }
1062
1063     notmuch->view++;
1064
1065     return NOTMUCH_STATUS_SUCCESS;
1066 }
1067
1068 static int
1069 unlink_cb (const char *path,
1070            unused (const struct stat *sb),
1071            unused (int type),
1072            unused (struct FTW *ftw))
1073 {
1074     return remove (path);
1075 }
1076
1077 static int
1078 rmtree (const char *path)
1079 {
1080     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
1081 }
1082
1083 class NotmuchCompactor : public Xapian::Compactor
1084 {
1085     notmuch_compact_status_cb_t status_cb;
1086     void *status_closure;
1087
1088 public:
1089     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
1090         status_cb (cb), status_closure (closure) { }
1091
1092     virtual void
1093     set_status (const std::string &table, const std::string &status)
1094     {
1095         char *msg;
1096
1097         if (status_cb == NULL)
1098             return;
1099
1100         if (status.length () == 0)
1101             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1102         else
1103             msg = talloc_asprintf (NULL, "     %s", status.c_str());
1104
1105         if (msg == NULL) {
1106             return;
1107         }
1108
1109         status_cb (msg, status_closure);
1110         talloc_free (msg);
1111     }
1112 };
1113
1114 /* Compacts the given database, optionally saving the original database
1115  * in backup_path. Additionally, a callback function can be provided to
1116  * give the user feedback on the progress of the (likely long-lived)
1117  * compaction process.
1118  *
1119  * The backup path must point to a directory on the same volume as the
1120  * original database. Passing a NULL backup_path will result in the
1121  * uncompacted database being deleted after compaction has finished.
1122  * Note that the database write lock will be held during the
1123  * compaction process to protect data integrity.
1124  */
1125 notmuch_status_t
1126 notmuch_database_compact (const char *path,
1127                           const char *backup_path,
1128                           notmuch_compact_status_cb_t status_cb,
1129                           void *closure)
1130 {
1131     void *local;
1132     char *notmuch_path, *xapian_path, *compact_xapian_path;
1133     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1134     notmuch_database_t *notmuch = NULL;
1135     struct stat statbuf;
1136     bool keep_backup;
1137     char *message = NULL;
1138
1139     local = talloc_new (NULL);
1140     if (! local)
1141         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1142
1143     ret = notmuch_database_open_verbose (path,
1144                                          NOTMUCH_DATABASE_MODE_READ_WRITE,
1145                                          &notmuch,
1146                                          &message);
1147     if (ret) {
1148         if (status_cb) status_cb (message, closure);
1149         goto DONE;
1150     }
1151
1152     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1153         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1154         goto DONE;
1155     }
1156
1157     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1158         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1159         goto DONE;
1160     }
1161
1162     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1163         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1164         goto DONE;
1165     }
1166
1167     if (backup_path == NULL) {
1168         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1169             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1170             goto DONE;
1171         }
1172         keep_backup = false;
1173     }
1174     else {
1175         keep_backup = true;
1176     }
1177
1178     if (stat (backup_path, &statbuf) != -1) {
1179         _notmuch_database_log (notmuch, "Path already exists: %s\n", backup_path);
1180         ret = NOTMUCH_STATUS_FILE_ERROR;
1181         goto DONE;
1182     }
1183     if (errno != ENOENT) {
1184         _notmuch_database_log (notmuch, "Unknown error while stat()ing path: %s\n",
1185                  strerror (errno));
1186         ret = NOTMUCH_STATUS_FILE_ERROR;
1187         goto DONE;
1188     }
1189
1190     /* Unconditionally attempt to remove old work-in-progress database (if
1191      * any). This is "protected" by database lock. If this fails due to write
1192      * errors (etc), the following code will fail and provide error message.
1193      */
1194     (void) rmtree (compact_xapian_path);
1195
1196     try {
1197         NotmuchCompactor compactor (status_cb, closure);
1198
1199         compactor.set_renumber (false);
1200         compactor.add_source (xapian_path);
1201         compactor.set_destdir (compact_xapian_path);
1202         compactor.compact ();
1203     } catch (const Xapian::Error &error) {
1204         _notmuch_database_log (notmuch, "Error while compacting: %s\n", error.get_msg().c_str());
1205         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1206         goto DONE;
1207     }
1208
1209     if (rename (xapian_path, backup_path)) {
1210         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1211                  xapian_path, backup_path, strerror (errno));
1212         ret = NOTMUCH_STATUS_FILE_ERROR;
1213         goto DONE;
1214     }
1215
1216     if (rename (compact_xapian_path, xapian_path)) {
1217         _notmuch_database_log (notmuch, "Error moving %s to %s: %s\n",
1218                  compact_xapian_path, xapian_path, strerror (errno));
1219         ret = NOTMUCH_STATUS_FILE_ERROR;
1220         goto DONE;
1221     }
1222
1223     if (! keep_backup) {
1224         if (rmtree (backup_path)) {
1225             _notmuch_database_log (notmuch, "Error removing old database %s: %s\n",
1226                      backup_path, strerror (errno));
1227             ret = NOTMUCH_STATUS_FILE_ERROR;
1228             goto DONE;
1229         }
1230     }
1231
1232   DONE:
1233     if (notmuch) {
1234         notmuch_status_t ret2;
1235
1236         const char *str = notmuch_database_status_string (notmuch);
1237         if (status_cb && str)
1238             status_cb (str, closure);
1239
1240         ret2 = notmuch_database_destroy (notmuch);
1241
1242         /* don't clobber previous error status */
1243         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1244             ret = ret2;
1245     }
1246
1247     talloc_free (local);
1248
1249     return ret;
1250 }
1251
1252 notmuch_status_t
1253 notmuch_database_destroy (notmuch_database_t *notmuch)
1254 {
1255     notmuch_status_t status;
1256
1257     status = notmuch_database_close (notmuch);
1258     talloc_free (notmuch);
1259
1260     return status;
1261 }
1262
1263 const char *
1264 notmuch_database_get_path (notmuch_database_t *notmuch)
1265 {
1266     return notmuch->path;
1267 }
1268
1269 unsigned int
1270 notmuch_database_get_version (notmuch_database_t *notmuch)
1271 {
1272     unsigned int version;
1273     string version_string;
1274     const char *str;
1275     char *end;
1276
1277     version_string = notmuch->xapian_db->get_metadata ("version");
1278     if (version_string.empty ())
1279         return 0;
1280
1281     str = version_string.c_str ();
1282     if (str == NULL || *str == '\0')
1283         return 0;
1284
1285     version = strtoul (str, &end, 10);
1286     if (*end != '\0')
1287         INTERNAL_ERROR ("Malformed database version: %s", str);
1288
1289     return version;
1290 }
1291
1292 notmuch_bool_t
1293 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1294 {
1295     return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1296         ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1297          (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1298 }
1299
1300 static volatile sig_atomic_t do_progress_notify = 0;
1301
1302 static void
1303 handle_sigalrm (unused (int signal))
1304 {
1305     do_progress_notify = 1;
1306 }
1307
1308 /* Upgrade the current database.
1309  *
1310  * After opening a database in read-write mode, the client should
1311  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1312  * if so, upgrade with this function before making any modifications.
1313  *
1314  * The optional progress_notify callback can be used by the caller to
1315  * provide progress indication to the user. If non-NULL it will be
1316  * called periodically with 'count' as the number of messages upgraded
1317  * so far and 'total' the overall number of messages that will be
1318  * converted.
1319  */
1320 notmuch_status_t
1321 notmuch_database_upgrade (notmuch_database_t *notmuch,
1322                           void (*progress_notify) (void *closure,
1323                                                    double progress),
1324                           void *closure)
1325 {
1326     void *local = talloc_new (NULL);
1327     Xapian::TermIterator t, t_end;
1328     Xapian::WritableDatabase *db;
1329     struct sigaction action;
1330     struct itimerval timerval;
1331     bool timer_is_active = false;
1332     enum _notmuch_features target_features, new_features;
1333     notmuch_status_t status;
1334     notmuch_private_status_t private_status;
1335     notmuch_query_t *query = NULL;
1336     unsigned int count = 0, total = 0;
1337
1338     status = _notmuch_database_ensure_writable (notmuch);
1339     if (status)
1340         return status;
1341
1342     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1343
1344     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1345     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1346
1347     if (! notmuch_database_needs_upgrade (notmuch))
1348         return NOTMUCH_STATUS_SUCCESS;
1349
1350     if (progress_notify) {
1351         /* Set up our handler for SIGALRM */
1352         memset (&action, 0, sizeof (struct sigaction));
1353         action.sa_handler = handle_sigalrm;
1354         sigemptyset (&action.sa_mask);
1355         action.sa_flags = SA_RESTART;
1356         sigaction (SIGALRM, &action, NULL);
1357
1358         /* Then start a timer to send SIGALRM once per second. */
1359         timerval.it_interval.tv_sec = 1;
1360         timerval.it_interval.tv_usec = 0;
1361         timerval.it_value.tv_sec = 1;
1362         timerval.it_value.tv_usec = 0;
1363         setitimer (ITIMER_REAL, &timerval, NULL);
1364
1365         timer_is_active = true;
1366     }
1367
1368     /* Figure out how much total work we need to do. */
1369     if (new_features &
1370         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1371          NOTMUCH_FEATURE_LAST_MOD)) {
1372         query = notmuch_query_create (notmuch, "");
1373         unsigned msg_count;
1374
1375         status = notmuch_query_count_messages (query, &msg_count);
1376         if (status)
1377             goto DONE;
1378
1379         total += msg_count;
1380         notmuch_query_destroy (query);
1381         query = NULL;
1382     }
1383     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1384         t_end = db->allterms_end ("XTIMESTAMP");
1385         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1386             ++total;
1387     }
1388     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1389         /* The ghost message upgrade converts all thread_id_*
1390          * metadata values into ghost message documents. */
1391         t_end = db->metadata_keys_end ("thread_id_");
1392         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1393             ++total;
1394     }
1395
1396     /* Perform the upgrade in a transaction. */
1397     db->begin_transaction (true);
1398
1399     /* Set the target features so we write out changes in the desired
1400      * format. */
1401     notmuch->features = target_features;
1402
1403     /* Perform per-message upgrades. */
1404     if (new_features &
1405         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER |
1406          NOTMUCH_FEATURE_LAST_MOD)) {
1407         notmuch_messages_t *messages;
1408         notmuch_message_t *message;
1409         char *filename;
1410
1411         query = notmuch_query_create (notmuch, "");
1412
1413         status = notmuch_query_search_messages (query, &messages);
1414         if (status)
1415             goto DONE;
1416         for (;
1417              notmuch_messages_valid (messages);
1418              notmuch_messages_move_to_next (messages))
1419         {
1420             if (do_progress_notify) {
1421                 progress_notify (closure, (double) count / total);
1422                 do_progress_notify = 0;
1423             }
1424
1425             message = notmuch_messages_get (messages);
1426
1427             /* Before version 1, each message document had its
1428              * filename in the data field. Copy that into the new
1429              * format by calling notmuch_message_add_filename.
1430              */
1431             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1432                 filename = _notmuch_message_talloc_copy_data (message);
1433                 if (filename && *filename != '\0') {
1434                     _notmuch_message_add_filename (message, filename);
1435                     _notmuch_message_clear_data (message);
1436                 }
1437                 talloc_free (filename);
1438             }
1439
1440             /* Prior to version 2, the "folder:" prefix was
1441              * probabilistic and stemmed. Change it to the current
1442              * boolean prefix. Add "path:" prefixes while at it.
1443              */
1444             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1445                 _notmuch_message_upgrade_folder (message);
1446
1447             /* Prior to NOTMUCH_FEATURE_LAST_MOD, messages did not
1448              * track modification revisions.  Give all messages the
1449              * next available revision; since we just started tracking
1450              * revisions for this database, that will be 1.
1451              */
1452             if (new_features & NOTMUCH_FEATURE_LAST_MOD)
1453                 _notmuch_message_upgrade_last_mod (message);
1454
1455             _notmuch_message_sync (message);
1456
1457             notmuch_message_destroy (message);
1458
1459             count++;
1460         }
1461
1462         notmuch_query_destroy (query);
1463         query = NULL;
1464     }
1465
1466     /* Perform per-directory upgrades. */
1467
1468     /* Before version 1 we stored directory timestamps in
1469      * XTIMESTAMP documents instead of the current XDIRECTORY
1470      * documents. So copy those as well. */
1471     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1472         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1473
1474         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1475              t != t_end;
1476              t++)
1477         {
1478             Xapian::PostingIterator p, p_end;
1479             std::string term = *t;
1480
1481             p_end = notmuch->xapian_db->postlist_end (term);
1482
1483             for (p = notmuch->xapian_db->postlist_begin (term);
1484                  p != p_end;
1485                  p++)
1486             {
1487                 Xapian::Document document;
1488                 time_t mtime;
1489                 notmuch_directory_t *directory;
1490
1491                 if (do_progress_notify) {
1492                     progress_notify (closure, (double) count / total);
1493                     do_progress_notify = 0;
1494                 }
1495
1496                 document = find_document_for_doc_id (notmuch, *p);
1497                 mtime = Xapian::sortable_unserialise (
1498                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1499
1500                 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1501                                                        NOTMUCH_FIND_CREATE, &status);
1502                 notmuch_directory_set_mtime (directory, mtime);
1503                 notmuch_directory_destroy (directory);
1504
1505                 db->delete_document (*p);
1506             }
1507
1508             ++count;
1509         }
1510     }
1511
1512     /* Perform metadata upgrades. */
1513
1514     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1515      * messages were stored as database metadata. Change these to
1516      * ghost messages.
1517      */
1518     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1519         notmuch_message_t *message;
1520         std::string message_id, thread_id;
1521
1522         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1523         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1524              t != t_end; ++t) {
1525             if (do_progress_notify) {
1526                 progress_notify (closure, (double) count / total);
1527                 do_progress_notify = 0;
1528             }
1529
1530             message_id = (*t).substr (
1531                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1532             thread_id = db->get_metadata (*t);
1533
1534             /* Create ghost message */
1535             message = _notmuch_message_create_for_message_id (
1536                 notmuch, message_id.c_str (), &private_status);
1537             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1538                 /* Document already exists; ignore the stored thread ID */
1539             } else if (private_status ==
1540                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1541                 private_status = _notmuch_message_initialize_ghost (
1542                     message, thread_id.c_str ());
1543                 if (! private_status)
1544                     _notmuch_message_sync (message);
1545             }
1546
1547             if (private_status) {
1548                 _notmuch_database_log (notmuch,
1549                          "Upgrade failed while creating ghost messages.\n");
1550                 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1551                 goto DONE;
1552             }
1553
1554             /* Clear saved metadata thread ID */
1555             db->set_metadata (*t, "");
1556
1557             ++count;
1558         }
1559     }
1560
1561     status = NOTMUCH_STATUS_SUCCESS;
1562     db->set_metadata ("features", _print_features (local, notmuch->features));
1563     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1564
1565  DONE:
1566     if (status == NOTMUCH_STATUS_SUCCESS)
1567         db->commit_transaction ();
1568     else
1569         db->cancel_transaction ();
1570
1571     if (timer_is_active) {
1572         /* Now stop the timer. */
1573         timerval.it_interval.tv_sec = 0;
1574         timerval.it_interval.tv_usec = 0;
1575         timerval.it_value.tv_sec = 0;
1576         timerval.it_value.tv_usec = 0;
1577         setitimer (ITIMER_REAL, &timerval, NULL);
1578
1579         /* And disable the signal handler. */
1580         action.sa_handler = SIG_IGN;
1581         sigaction (SIGALRM, &action, NULL);
1582     }
1583
1584     if (query)
1585         notmuch_query_destroy (query);
1586
1587     talloc_free (local);
1588     return status;
1589 }
1590
1591 notmuch_status_t
1592 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1593 {
1594     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1595         notmuch->atomic_nesting > 0)
1596         goto DONE;
1597
1598     if (notmuch_database_needs_upgrade (notmuch))
1599         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1600
1601     try {
1602         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1603     } catch (const Xapian::Error &error) {
1604         _notmuch_database_log (notmuch, "A Xapian exception occurred beginning transaction: %s.\n",
1605                  error.get_msg().c_str());
1606         notmuch->exception_reported = true;
1607         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1608     }
1609
1610 DONE:
1611     notmuch->atomic_nesting++;
1612     return NOTMUCH_STATUS_SUCCESS;
1613 }
1614
1615 notmuch_status_t
1616 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1617 {
1618     Xapian::WritableDatabase *db;
1619
1620     if (notmuch->atomic_nesting == 0)
1621         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1622
1623     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1624         notmuch->atomic_nesting > 1)
1625         goto DONE;
1626
1627     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1628     try {
1629         db->commit_transaction ();
1630
1631         /* This is a hack for testing.  Xapian never flushes on a
1632          * non-flushed commit, even if the flush threshold is 1.
1633          * However, we rely on flushing to test atomicity. */
1634         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1635         if (thresh && atoi (thresh) == 1)
1636             db->commit ();
1637     } catch (const Xapian::Error &error) {
1638         _notmuch_database_log (notmuch, "A Xapian exception occurred committing transaction: %s.\n",
1639                  error.get_msg().c_str());
1640         notmuch->exception_reported = true;
1641         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1642     }
1643
1644     if (notmuch->atomic_dirty) {
1645         ++notmuch->revision;
1646         notmuch->atomic_dirty = false;
1647     }
1648
1649 DONE:
1650     notmuch->atomic_nesting--;
1651     return NOTMUCH_STATUS_SUCCESS;
1652 }
1653
1654 unsigned long
1655 notmuch_database_get_revision (notmuch_database_t *notmuch,
1656                                 const char **uuid)
1657 {
1658     if (uuid)
1659         *uuid = notmuch->uuid;
1660     return notmuch->revision;
1661 }
1662
1663 /* We allow the user to use arbitrarily long paths for directories. But
1664  * we have a term-length limit. So if we exceed that, we'll use the
1665  * SHA-1 of the path for the database term.
1666  *
1667  * Note: This function may return the original value of 'path'. If it
1668  * does not, then the caller is responsible to free() the returned
1669  * value.
1670  */
1671 const char *
1672 _notmuch_database_get_directory_db_path (const char *path)
1673 {
1674     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1675
1676     if (term_len > NOTMUCH_TERM_MAX)
1677         return _notmuch_sha1_of_string (path);
1678     else
1679         return path;
1680 }
1681
1682 /* Given a path, split it into two parts: the directory part is all
1683  * components except for the last, and the basename is that last
1684  * component. Getting the return-value for either part is optional
1685  * (the caller can pass NULL).
1686  *
1687  * The original 'path' can represent either a regular file or a
1688  * directory---the splitting will be carried out in the same way in
1689  * either case. Trailing slashes on 'path' will be ignored, and any
1690  * cases of multiple '/' characters appearing in series will be
1691  * treated as a single '/'.
1692  *
1693  * Allocation (if any) will have 'ctx' as the talloc owner. But
1694  * pointers will be returned within the original path string whenever
1695  * possible.
1696  *
1697  * Note: If 'path' is non-empty and contains no non-trailing slash,
1698  * (that is, consists of a filename with no parent directory), then
1699  * the directory returned will be an empty string. However, if 'path'
1700  * is an empty string, then both directory and basename will be
1701  * returned as NULL.
1702  */
1703 notmuch_status_t
1704 _notmuch_database_split_path (void *ctx,
1705                               const char *path,
1706                               const char **directory,
1707                               const char **basename)
1708 {
1709     const char *slash;
1710
1711     if (path == NULL || *path == '\0') {
1712         if (directory)
1713             *directory = NULL;
1714         if (basename)
1715             *basename = NULL;
1716         return NOTMUCH_STATUS_SUCCESS;
1717     }
1718
1719     /* Find the last slash (not counting a trailing slash), if any. */
1720
1721     slash = path + strlen (path) - 1;
1722
1723     /* First, skip trailing slashes. */
1724     while (slash != path && *slash == '/')
1725         --slash;
1726
1727     /* Then, find a slash. */
1728     while (slash != path && *slash != '/') {
1729         if (basename)
1730             *basename = slash;
1731
1732         --slash;
1733     }
1734
1735     /* Finally, skip multiple slashes. */
1736     while (slash != path && *(slash - 1) == '/')
1737         --slash;
1738
1739     if (slash == path) {
1740         if (directory)
1741             *directory = talloc_strdup (ctx, "");
1742         if (basename)
1743             *basename = path;
1744     } else {
1745         if (directory)
1746             *directory = talloc_strndup (ctx, path, slash - path);
1747     }
1748
1749     return NOTMUCH_STATUS_SUCCESS;
1750 }
1751
1752 /* Find the document ID of the specified directory.
1753  *
1754  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1755  * created if one does not exist for 'path'.  Otherwise, if the
1756  * directory document does not exist, this sets *directory_id to
1757  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1758  */
1759 notmuch_status_t
1760 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1761                                      const char *path,
1762                                      notmuch_find_flags_t flags,
1763                                      unsigned int *directory_id)
1764 {
1765     notmuch_directory_t *directory;
1766     notmuch_status_t status;
1767
1768     if (path == NULL) {
1769         *directory_id = 0;
1770         return NOTMUCH_STATUS_SUCCESS;
1771     }
1772
1773     directory = _notmuch_directory_create (notmuch, path, flags, &status);
1774     if (status || !directory) {
1775         *directory_id = -1;
1776         return status;
1777     }
1778
1779     *directory_id = _notmuch_directory_get_document_id (directory);
1780
1781     notmuch_directory_destroy (directory);
1782
1783     return NOTMUCH_STATUS_SUCCESS;
1784 }
1785
1786 const char *
1787 _notmuch_database_get_directory_path (void *ctx,
1788                                       notmuch_database_t *notmuch,
1789                                       unsigned int doc_id)
1790 {
1791     Xapian::Document document;
1792
1793     document = find_document_for_doc_id (notmuch, doc_id);
1794
1795     return talloc_strdup (ctx, document.get_data ().c_str ());
1796 }
1797
1798 /* Given a legal 'filename' for the database, (either relative to
1799  * database path or absolute with initial components identical to
1800  * database path), return a new string (with 'ctx' as the talloc
1801  * owner) suitable for use as a direntry term value.
1802  *
1803  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1804  * will be created in the database as needed.  Otherwise, if the
1805  * necessary directory documents do not exist, this sets
1806  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1807  */
1808 notmuch_status_t
1809 _notmuch_database_filename_to_direntry (void *ctx,
1810                                         notmuch_database_t *notmuch,
1811                                         const char *filename,
1812                                         notmuch_find_flags_t flags,
1813                                         char **direntry)
1814 {
1815     const char *relative, *directory, *basename;
1816     Xapian::docid directory_id;
1817     notmuch_status_t status;
1818
1819     relative = _notmuch_database_relative_path (notmuch, filename);
1820
1821     status = _notmuch_database_split_path (ctx, relative,
1822                                            &directory, &basename);
1823     if (status)
1824         return status;
1825
1826     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1827                                                   &directory_id);
1828     if (status || directory_id == (unsigned int)-1) {
1829         *direntry = NULL;
1830         return status;
1831     }
1832
1833     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1834
1835     return NOTMUCH_STATUS_SUCCESS;
1836 }
1837
1838 /* Given a legal 'path' for the database, return the relative path.
1839  *
1840  * The return value will be a pointer to the original path contents,
1841  * and will be either the original string (if 'path' was relative) or
1842  * a portion of the string (if path was absolute and begins with the
1843  * database path).
1844  */
1845 const char *
1846 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1847                                  const char *path)
1848 {
1849     const char *db_path, *relative;
1850     unsigned int db_path_len;
1851
1852     db_path = notmuch_database_get_path (notmuch);
1853     db_path_len = strlen (db_path);
1854
1855     relative = path;
1856
1857     if (*relative == '/') {
1858         while (*relative == '/' && *(relative+1) == '/')
1859             relative++;
1860
1861         if (strncmp (relative, db_path, db_path_len) == 0)
1862         {
1863             relative += db_path_len;
1864             while (*relative == '/')
1865                 relative++;
1866         }
1867     }
1868
1869     return relative;
1870 }
1871
1872 notmuch_status_t
1873 notmuch_database_get_directory (notmuch_database_t *notmuch,
1874                                 const char *path,
1875                                 notmuch_directory_t **directory)
1876 {
1877     notmuch_status_t status;
1878
1879     if (directory == NULL)
1880         return NOTMUCH_STATUS_NULL_POINTER;
1881     *directory = NULL;
1882
1883     try {
1884         *directory = _notmuch_directory_create (notmuch, path,
1885                                                 NOTMUCH_FIND_LOOKUP, &status);
1886     } catch (const Xapian::Error &error) {
1887         _notmuch_database_log (notmuch, "A Xapian exception occurred getting directory: %s.\n",
1888                  error.get_msg().c_str());
1889         notmuch->exception_reported = true;
1890         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1891     }
1892     return status;
1893 }
1894
1895 /* Allocate a document ID that satisfies the following criteria:
1896  *
1897  * 1. The ID does not exist for any document in the Xapian database
1898  *
1899  * 2. The ID was not previously returned from this function
1900  *
1901  * 3. The ID is the smallest integer satisfying (1) and (2)
1902  *
1903  * This function will trigger an internal error if these constraints
1904  * cannot all be satisfied, (that is, the pool of available document
1905  * IDs has been exhausted).
1906  */
1907 unsigned int
1908 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1909 {
1910     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1911
1912     notmuch->last_doc_id++;
1913
1914     if (notmuch->last_doc_id == 0)
1915         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1916
1917     return notmuch->last_doc_id;
1918 }
1919
1920 notmuch_status_t
1921 notmuch_database_remove_message (notmuch_database_t *notmuch,
1922                                  const char *filename)
1923 {
1924     notmuch_status_t status;
1925     notmuch_message_t *message;
1926
1927     status = notmuch_database_find_message_by_filename (notmuch, filename,
1928                                                         &message);
1929
1930     if (status == NOTMUCH_STATUS_SUCCESS && message) {
1931             status = _notmuch_message_remove_filename (message, filename);
1932             if (status == NOTMUCH_STATUS_SUCCESS)
1933                 _notmuch_message_delete (message);
1934             else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1935                 _notmuch_message_sync (message);
1936
1937             notmuch_message_destroy (message);
1938     }
1939
1940     return status;
1941 }
1942
1943 notmuch_status_t
1944 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1945                                            const char *filename,
1946                                            notmuch_message_t **message_ret)
1947 {
1948     void *local;
1949     const char *prefix = _find_prefix ("file-direntry");
1950     char *direntry, *term;
1951     Xapian::PostingIterator i, end;
1952     notmuch_status_t status;
1953
1954     if (message_ret == NULL)
1955         return NOTMUCH_STATUS_NULL_POINTER;
1956
1957     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
1958         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
1959
1960     /* return NULL on any failure */
1961     *message_ret = NULL;
1962
1963     local = talloc_new (notmuch);
1964
1965     try {
1966         status = _notmuch_database_filename_to_direntry (
1967             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
1968         if (status || !direntry)
1969             goto DONE;
1970
1971         term = talloc_asprintf (local, "%s%s", prefix, direntry);
1972
1973         find_doc_ids_for_term (notmuch, term, &i, &end);
1974
1975         if (i != end) {
1976             notmuch_private_status_t private_status;
1977
1978             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1979                                                     &private_status);
1980             if (*message_ret == NULL)
1981                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1982         }
1983     } catch (const Xapian::Error &error) {
1984         _notmuch_database_log (notmuch, "Error: A Xapian exception occurred finding message by filename: %s\n",
1985                  error.get_msg().c_str());
1986         notmuch->exception_reported = true;
1987         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1988     }
1989
1990   DONE:
1991     talloc_free (local);
1992
1993     if (status && *message_ret) {
1994         notmuch_message_destroy (*message_ret);
1995         *message_ret = NULL;
1996     }
1997     return status;
1998 }
1999
2000 notmuch_string_list_t *
2001 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2002                                          Xapian::TermIterator &end,
2003                                          const char *prefix)
2004 {
2005     int prefix_len = strlen (prefix);
2006     notmuch_string_list_t *list;
2007
2008     list = _notmuch_string_list_create (ctx);
2009     if (unlikely (list == NULL))
2010         return NULL;
2011
2012     for (i.skip_to (prefix); i != end; i++) {
2013         /* Terminate loop at first term without desired prefix. */
2014         if (strncmp ((*i).c_str (), prefix, prefix_len))
2015             break;
2016
2017         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2018     }
2019
2020     return list;
2021 }
2022
2023 notmuch_tags_t *
2024 notmuch_database_get_all_tags (notmuch_database_t *db)
2025 {
2026     Xapian::TermIterator i, end;
2027     notmuch_string_list_t *tags;
2028
2029     try {
2030         i = db->xapian_db->allterms_begin();
2031         end = db->xapian_db->allterms_end();
2032         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2033                                                         _find_prefix ("tag"));
2034         _notmuch_string_list_sort (tags);
2035         return _notmuch_tags_create (db, tags);
2036     } catch (const Xapian::Error &error) {
2037         _notmuch_database_log (db, "A Xapian exception occurred getting tags: %s.\n",
2038                  error.get_msg().c_str());
2039         db->exception_reported = true;
2040         return NULL;
2041     }
2042 }
2043
2044 const char *
2045 notmuch_database_status_string (const notmuch_database_t *notmuch)
2046 {
2047     return notmuch->status_string;
2048 }