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