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