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