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