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