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