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