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