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