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