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