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