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