]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib: call g_mime_init() from notmuch_database_open()
[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
23 #include <iostream>
24
25 #include <sys/time.h>
26 #include <signal.h>
27
28 #include <glib.h> /* g_free, GPtrArray, GHashTable */
29 #include <glib-object.h> /* g_type_init */
30
31 #include <gmime/gmime.h> /* g_mime_init */
32
33 using namespace std;
34
35 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
36
37 typedef struct {
38     const char *name;
39     const char *prefix;
40 } prefix_t;
41
42 #define NOTMUCH_DATABASE_VERSION 1
43
44 #define STRINGIFY(s) _SUB_STRINGIFY(s)
45 #define _SUB_STRINGIFY(s) #s
46
47 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
48  *
49  * We currently have two different types of documents (mail and
50  * directory) and also some metadata.
51  *
52  * Mail document
53  * -------------
54  * A mail document is associated with a particular email message file
55  * on disk. It is indexed with the following prefixed terms which the
56  * database uses to construct threads, etc.:
57  *
58  *    Single terms of given prefix:
59  *
60  *      type:   mail
61  *
62  *      id:     Unique ID of mail. This is from the Message-ID header
63  *              if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
64  *              If it's present and too long, then we use
65  *              "notmuch-sha1-<sha1_sum_of_message_id>".
66  *              If this header is not present, we use
67  *              "notmuch-sha1-<sha1_sum_of_entire_file>".
68  *
69  *      thread: The ID of the thread to which the mail belongs
70  *
71  *      replyto: The ID from the In-Reply-To header of the mail (if any).
72  *
73  *    Multiple terms of given prefix:
74  *
75  *      reference: All message IDs from In-Reply-To and References
76  *                 headers in the message.
77  *
78  *      tag:       Any tags associated with this message by the user.
79  *
80  *      file-direntry:  A colon-separated pair of values
81  *                      (INTEGER:STRING), where INTEGER is the
82  *                      document ID of a directory document, and
83  *                      STRING is the name of a file within that
84  *                      directory for this mail message.
85  *
86  *    A mail document also has four values:
87  *
88  *      TIMESTAMP:      The time_t value corresponding to the message's
89  *                      Date header.
90  *
91  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
92  *
93  *      FROM:           The value of the "From" header
94  *
95  *      SUBJECT:        The value of the "Subject" header
96  *
97  * In addition, terms from the content of the message are added with
98  * "from", "to", "attachment", and "subject" prefixes for use by the
99  * user in searching. Similarly, terms from the path of the mail
100  * message are added with a "folder" prefix. But the database doesn't
101  * really care itself about any of these.
102  *
103  * The data portion of a mail document is empty.
104  *
105  * Directory document
106  * ------------------
107  * A directory document is used by a client of the notmuch library to
108  * maintain data necessary to allow for efficient polling of mail
109  * directories.
110  *
111  * All directory documents contain one term:
112  *
113  *      directory:      The directory path (relative to the database path)
114  *                      Or the SHA1 sum of the directory path (if the
115  *                      path itself is too long to fit in a Xapian
116  *                      term).
117  *
118  * And all directory documents for directories other than top-level
119  * directories also contain the following term:
120  *
121  *      directory-direntry: A colon-separated pair of values
122  *                          (INTEGER:STRING), where INTEGER is the
123  *                          document ID of the parent directory
124  *                          document, and STRING is the name of this
125  *                          directory within that parent.
126  *
127  * All directory documents have a single value:
128  *
129  *      TIMESTAMP:      The mtime of the directory (at last scan)
130  *
131  * The data portion of a directory document contains the path of the
132  * directory (relative to the database path).
133  *
134  * Database metadata
135  * -----------------
136  * Xapian allows us to store arbitrary name-value pairs as
137  * "metadata". We currently use the following metadata names with the
138  * given meanings:
139  *
140  *      version         The database schema version, (which is distinct
141  *                      from both the notmuch package version (see
142  *                      notmuch --version) and the libnotmuch library
143  *                      version. The version is stored as an base-10
144  *                      ASCII integer. The initial database version
145  *                      was 1, (though a schema existed before that
146  *                      were no "version" database value existed at
147  *                      all). Successive versions are allocated as
148  *                      changes are made to the database (such as by
149  *                      indexing new fields).
150  *
151  *      last_thread_id  The last thread ID generated. This is stored
152  *                      as a 16-byte hexadecimal ASCII representation
153  *                      of a 64-bit unsigned integer. The first ID
154  *                      generated is 1 and the value will be
155  *                      incremented for each thread ID.
156  *
157  *      thread_id_*     A pre-allocated thread ID for a particular
158  *                      message. This is actually an arbitrarily large
159  *                      family of metadata name. Any particular name is
160  *                      formed by concatenating "thread_id_" with a message
161  *                      ID (or the SHA1 sum of a message ID if it is very
162  *                      long---see description of 'id' in the mail
163  *                      document). The value stored is a thread ID.
164  *
165  *                      These thread ID metadata values are stored
166  *                      whenever a message references a parent message
167  *                      that does not yet exist in the database. A
168  *                      thread ID will be allocated and stored, and if
169  *                      the message is later added, the stored thread
170  *                      ID will be used (and the metadata value will
171  *                      be cleared).
172  *
173  *                      Even before a message is added, it's
174  *                      pre-allocated thread ID is useful so that all
175  *                      descendant messages that reference this common
176  *                      parent can be recognized as belonging to the
177  *                      same thread.
178  */
179
180 /* With these prefix values we follow the conventions published here:
181  *
182  * http://xapian.org/docs/omega/termprefixes.html
183  *
184  * as much as makes sense. Note that I took some liberty in matching
185  * the reserved prefix values to notmuch concepts, (for example, 'G'
186  * is documented as "newsGroup (or similar entity - e.g. a web forum
187  * name)", for which I think the thread is the closest analogue in
188  * notmuch. This in spite of the fact that we will eventually be
189  * storing mailing-list messages where 'G' for "mailing list name"
190  * might be even a closer analogue. I'm treating the single-character
191  * prefixes preferentially for core notmuch concepts (which will be
192  * nearly universal to all mail messages).
193  */
194
195 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
196     { "type",                   "T" },
197     { "reference",              "XREFERENCE" },
198     { "replyto",                "XREPLYTO" },
199     { "directory",              "XDIRECTORY" },
200     { "file-direntry",          "XFDIRENTRY" },
201     { "directory-direntry",     "XDDIRENTRY" },
202 };
203
204 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
205     { "thread",                 "G" },
206     { "tag",                    "K" },
207     { "is",                     "K" },
208     { "id",                     "Q" }
209 };
210
211 static prefix_t PROBABILISTIC_PREFIX[]= {
212     { "from",                   "XFROM" },
213     { "to",                     "XTO" },
214     { "attachment",             "XATTACHMENT" },
215     { "subject",                "XSUBJECT"},
216     { "folder",                 "XFOLDER"}
217 };
218
219 const char *
220 _find_prefix (const char *name)
221 {
222     unsigned int i;
223
224     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
225         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
226             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
227     }
228
229     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
230         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
231             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
232     }
233
234     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
235         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
236             return PROBABILISTIC_PREFIX[i].prefix;
237     }
238
239     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
240
241     return "";
242 }
243
244 const char *
245 notmuch_status_to_string (notmuch_status_t status)
246 {
247     switch (status) {
248     case NOTMUCH_STATUS_SUCCESS:
249         return "No error occurred";
250     case NOTMUCH_STATUS_OUT_OF_MEMORY:
251         return "Out of memory";
252     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
253         return "Attempt to write to a read-only database";
254     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
255         return "A Xapian exception occurred";
256     case NOTMUCH_STATUS_FILE_ERROR:
257         return "Something went wrong trying to read or write a file";
258     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
259         return "File is not an email";
260     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
261         return "Message ID is identical to a message in database";
262     case NOTMUCH_STATUS_NULL_POINTER:
263         return "Erroneous NULL pointer";
264     case NOTMUCH_STATUS_TAG_TOO_LONG:
265         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
266     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
267         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
268     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
269         return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
270     default:
271     case NOTMUCH_STATUS_LAST_STATUS:
272         return "Unknown error status value";
273     }
274 }
275
276 static void
277 find_doc_ids_for_term (notmuch_database_t *notmuch,
278                        const char *term,
279                        Xapian::PostingIterator *begin,
280                        Xapian::PostingIterator *end)
281 {
282     *begin = notmuch->xapian_db->postlist_begin (term);
283
284     *end = notmuch->xapian_db->postlist_end (term);
285 }
286
287 static void
288 find_doc_ids (notmuch_database_t *notmuch,
289               const char *prefix_name,
290               const char *value,
291               Xapian::PostingIterator *begin,
292               Xapian::PostingIterator *end)
293 {
294     char *term;
295
296     term = talloc_asprintf (notmuch, "%s%s",
297                             _find_prefix (prefix_name), value);
298
299     find_doc_ids_for_term (notmuch, term, begin, end);
300
301     talloc_free (term);
302 }
303
304 notmuch_private_status_t
305 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
306                                       const char *prefix_name,
307                                       const char *value,
308                                       unsigned int *doc_id)
309 {
310     Xapian::PostingIterator i, end;
311
312     find_doc_ids (notmuch, prefix_name, value, &i, &end);
313
314     if (i == end) {
315         *doc_id = 0;
316         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
317     }
318
319     *doc_id = *i;
320
321 #if DEBUG_DATABASE_SANITY
322     i++;
323
324     if (i != end)
325         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
326                         prefix_name, value);
327 #endif
328
329     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
330 }
331
332 static Xapian::Document
333 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
334 {
335     return notmuch->xapian_db->get_document (doc_id);
336 }
337
338 /* Generate a compressed version of 'message_id' of the form:
339  *
340  *      notmuch-sha1-<sha1_sum_of_message_id>
341  */
342 static char *
343 _message_id_compressed (void *ctx, const char *message_id)
344 {
345     char *sha1, *compressed;
346
347     sha1 = notmuch_sha1_of_string (message_id);
348
349     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
350     free (sha1);
351
352     return compressed;
353 }
354
355 notmuch_status_t
356 notmuch_database_find_message (notmuch_database_t *notmuch,
357                                const char *message_id,
358                                notmuch_message_t **message_ret)
359 {
360     notmuch_private_status_t status;
361     unsigned int doc_id;
362
363     if (message_ret == NULL)
364         return NOTMUCH_STATUS_NULL_POINTER;
365
366     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
367         message_id = _message_id_compressed (notmuch, message_id);
368
369     try {
370         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
371                                                        message_id, &doc_id);
372
373         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
374             *message_ret = NULL;
375         else {
376             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
377                                                     NULL);
378             if (*message_ret == NULL)
379                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
380         }
381
382         return NOTMUCH_STATUS_SUCCESS;
383     } catch (const Xapian::Error &error) {
384         fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
385                  error.get_msg().c_str());
386         notmuch->exception_reported = TRUE;
387         *message_ret = NULL;
388         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
389     }
390 }
391
392 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
393  * a (potentially nested) parenthesized sequence with '\' used to
394  * escape any character (including parentheses).
395  *
396  * If the sequence to be skipped continues to the end of the string,
397  * then 'str' will be left pointing at the final terminating '\0'
398  * character.
399  */
400 static void
401 skip_space_and_comments (const char **str)
402 {
403     const char *s;
404
405     s = *str;
406     while (*s && (isspace (*s) || *s == '(')) {
407         while (*s && isspace (*s))
408             s++;
409         if (*s == '(') {
410             int nesting = 1;
411             s++;
412             while (*s && nesting) {
413                 if (*s == '(') {
414                     nesting++;
415                 } else if (*s == ')') {
416                     nesting--;
417                 } else if (*s == '\\') {
418                     if (*(s+1))
419                         s++;
420                 }
421                 s++;
422             }
423         }
424     }
425
426     *str = s;
427 }
428
429 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
430  * comments, and the '<' and '>' delimiters.
431  *
432  * If not NULL, then *next will be made to point to the first character
433  * not parsed, (possibly pointing to the final '\0' terminator.
434  *
435  * Returns a newly talloc'ed string belonging to 'ctx'.
436  *
437  * Returns NULL if there is any error parsing the message-id. */
438 static char *
439 _parse_message_id (void *ctx, const char *message_id, const char **next)
440 {
441     const char *s, *end;
442     char *result;
443
444     if (message_id == NULL || *message_id == '\0')
445         return NULL;
446
447     s = message_id;
448
449     skip_space_and_comments (&s);
450
451     /* Skip any unstructured text as well. */
452     while (*s && *s != '<')
453         s++;
454
455     if (*s == '<') {
456         s++;
457     } else {
458         if (next)
459             *next = s;
460         return NULL;
461     }
462
463     skip_space_and_comments (&s);
464
465     end = s;
466     while (*end && *end != '>')
467         end++;
468     if (next) {
469         if (*end)
470             *next = end + 1;
471         else
472             *next = end;
473     }
474
475     if (end > s && *end == '>')
476         end--;
477     if (end <= s)
478         return NULL;
479
480     result = talloc_strndup (ctx, s, end - s + 1);
481
482     /* Finally, collapse any whitespace that is within the message-id
483      * itself. */
484     {
485         char *r;
486         int len;
487
488         for (r = result, len = strlen (r); *r; r++, len--)
489             if (*r == ' ' || *r == '\t')
490                 memmove (r, r+1, len);
491     }
492
493     return result;
494 }
495
496 /* Parse a References header value, putting a (talloc'ed under 'ctx')
497  * copy of each referenced message-id into 'hash'.
498  *
499  * We explicitly avoid including any reference identical to
500  * 'message_id' in the result (to avoid mass confusion when a single
501  * message references itself cyclically---and yes, mail messages are
502  * not infrequent in the wild that do this---don't ask me why).
503 */
504 static void
505 parse_references (void *ctx,
506                   const char *message_id,
507                   GHashTable *hash,
508                   const char *refs)
509 {
510     char *ref;
511
512     if (refs == NULL || *refs == '\0')
513         return;
514
515     while (*refs) {
516         ref = _parse_message_id (ctx, refs, &refs);
517
518         if (ref && strcmp (ref, message_id))
519             g_hash_table_insert (hash, ref, NULL);
520     }
521 }
522
523 notmuch_database_t *
524 notmuch_database_create (const char *path)
525 {
526     notmuch_database_t *notmuch = NULL;
527     char *notmuch_path = NULL;
528     struct stat st;
529     int err;
530
531     if (path == NULL) {
532         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
533         goto DONE;
534     }
535
536     err = stat (path, &st);
537     if (err) {
538         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
539                  path, strerror (errno));
540         goto DONE;
541     }
542
543     if (! S_ISDIR (st.st_mode)) {
544         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
545                  path);
546         goto DONE;
547     }
548
549     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
550
551     err = mkdir (notmuch_path, 0755);
552
553     if (err) {
554         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
555                  notmuch_path, strerror (errno));
556         goto DONE;
557     }
558
559     notmuch = notmuch_database_open (path,
560                                      NOTMUCH_DATABASE_MODE_READ_WRITE);
561     notmuch_database_upgrade (notmuch, NULL, NULL);
562
563   DONE:
564     if (notmuch_path)
565         talloc_free (notmuch_path);
566
567     return notmuch;
568 }
569
570 notmuch_status_t
571 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
572 {
573     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
574         fprintf (stderr, "Cannot write to a read-only database.\n");
575         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
576     }
577
578     return NOTMUCH_STATUS_SUCCESS;
579 }
580
581 notmuch_database_t *
582 notmuch_database_open (const char *path,
583                        notmuch_database_mode_t mode)
584 {
585     notmuch_database_t *notmuch = NULL;
586     char *notmuch_path = NULL, *xapian_path = NULL;
587     struct stat st;
588     int err;
589     unsigned int i, version;
590     static int initialized = 0;
591
592     if (asprintf (&notmuch_path, "%s/%s", path, ".notmuch") == -1) {
593         notmuch_path = NULL;
594         fprintf (stderr, "Out of memory\n");
595         goto DONE;
596     }
597
598     err = stat (notmuch_path, &st);
599     if (err) {
600         fprintf (stderr, "Error opening database at %s: %s\n",
601                  notmuch_path, strerror (errno));
602         goto DONE;
603     }
604
605     if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
606         xapian_path = NULL;
607         fprintf (stderr, "Out of memory\n");
608         goto DONE;
609     }
610
611     /* Initialize the GLib type system and threads */
612     g_type_init ();
613
614     /* Initialize gmime */
615     if (! initialized) {
616         g_mime_init (0);
617         initialized = 1;
618     }
619
620     notmuch = talloc (NULL, notmuch_database_t);
621     notmuch->exception_reported = FALSE;
622     notmuch->path = talloc_strdup (notmuch, path);
623
624     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
625         notmuch->path[strlen (notmuch->path) - 1] = '\0';
626
627     notmuch->needs_upgrade = FALSE;
628     notmuch->mode = mode;
629     notmuch->atomic_nesting = 0;
630     try {
631         string last_thread_id;
632
633         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
634             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
635                                                                Xapian::DB_CREATE_OR_OPEN);
636             version = notmuch_database_get_version (notmuch);
637
638             if (version > NOTMUCH_DATABASE_VERSION) {
639                 fprintf (stderr,
640                          "Error: Notmuch database at %s\n"
641                          "       has a newer database format version (%u) than supported by this\n"
642                          "       version of notmuch (%u). Refusing to open this database in\n"
643                          "       read-write mode.\n",
644                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
645                 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
646                 notmuch_database_close (notmuch);
647                 notmuch = NULL;
648                 goto DONE;
649             }
650
651             if (version < NOTMUCH_DATABASE_VERSION)
652                 notmuch->needs_upgrade = TRUE;
653         } else {
654             notmuch->xapian_db = new Xapian::Database (xapian_path);
655             version = notmuch_database_get_version (notmuch);
656             if (version > NOTMUCH_DATABASE_VERSION)
657             {
658                 fprintf (stderr,
659                          "Warning: Notmuch database at %s\n"
660                          "         has a newer database format version (%u) than supported by this\n"
661                          "         version of notmuch (%u). Some operations may behave incorrectly,\n"
662                          "         (but the database will not be harmed since it is being opened\n"
663                          "         in read-only mode).\n",
664                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
665             }
666         }
667
668         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
669         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
670         if (last_thread_id.empty ()) {
671             notmuch->last_thread_id = 0;
672         } else {
673             const char *str;
674             char *end;
675
676             str = last_thread_id.c_str ();
677             notmuch->last_thread_id = strtoull (str, &end, 16);
678             if (*end != '\0')
679                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
680         }
681
682         notmuch->query_parser = new Xapian::QueryParser;
683         notmuch->term_gen = new Xapian::TermGenerator;
684         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
685         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
686
687         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
688         notmuch->query_parser->set_database (*notmuch->xapian_db);
689         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
690         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
691         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
692
693         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
694             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
695             notmuch->query_parser->add_boolean_prefix (prefix->name,
696                                                        prefix->prefix);
697         }
698
699         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
700             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
701             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
702         }
703     } catch (const Xapian::Error &error) {
704         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
705                  error.get_msg().c_str());
706         notmuch = NULL;
707     }
708
709   DONE:
710     if (notmuch_path)
711         free (notmuch_path);
712     if (xapian_path)
713         free (xapian_path);
714
715     return notmuch;
716 }
717
718 void
719 notmuch_database_close (notmuch_database_t *notmuch)
720 {
721     try {
722         if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
723             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
724     } catch (const Xapian::Error &error) {
725         if (! notmuch->exception_reported) {
726             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
727                      error.get_msg().c_str());
728         }
729     }
730
731     delete notmuch->term_gen;
732     delete notmuch->query_parser;
733     delete notmuch->xapian_db;
734     delete notmuch->value_range_processor;
735     talloc_free (notmuch);
736 }
737
738 const char *
739 notmuch_database_get_path (notmuch_database_t *notmuch)
740 {
741     return notmuch->path;
742 }
743
744 unsigned int
745 notmuch_database_get_version (notmuch_database_t *notmuch)
746 {
747     unsigned int version;
748     string version_string;
749     const char *str;
750     char *end;
751
752     version_string = notmuch->xapian_db->get_metadata ("version");
753     if (version_string.empty ())
754         return 0;
755
756     str = version_string.c_str ();
757     if (str == NULL || *str == '\0')
758         return 0;
759
760     version = strtoul (str, &end, 10);
761     if (*end != '\0')
762         INTERNAL_ERROR ("Malformed database version: %s", str);
763
764     return version;
765 }
766
767 notmuch_bool_t
768 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
769 {
770     return notmuch->needs_upgrade;
771 }
772
773 static volatile sig_atomic_t do_progress_notify = 0;
774
775 static void
776 handle_sigalrm (unused (int signal))
777 {
778     do_progress_notify = 1;
779 }
780
781 /* Upgrade the current database.
782  *
783  * After opening a database in read-write mode, the client should
784  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
785  * if so, upgrade with this function before making any modifications.
786  *
787  * The optional progress_notify callback can be used by the caller to
788  * provide progress indication to the user. If non-NULL it will be
789  * called periodically with 'count' as the number of messages upgraded
790  * so far and 'total' the overall number of messages that will be
791  * converted.
792  */
793 notmuch_status_t
794 notmuch_database_upgrade (notmuch_database_t *notmuch,
795                           void (*progress_notify) (void *closure,
796                                                    double progress),
797                           void *closure)
798 {
799     Xapian::WritableDatabase *db;
800     struct sigaction action;
801     struct itimerval timerval;
802     notmuch_bool_t timer_is_active = FALSE;
803     unsigned int version;
804     notmuch_status_t status;
805     unsigned int count = 0, total = 0;
806
807     status = _notmuch_database_ensure_writable (notmuch);
808     if (status)
809         return status;
810
811     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
812
813     version = notmuch_database_get_version (notmuch);
814
815     if (version >= NOTMUCH_DATABASE_VERSION)
816         return NOTMUCH_STATUS_SUCCESS;
817
818     if (progress_notify) {
819         /* Setup our handler for SIGALRM */
820         memset (&action, 0, sizeof (struct sigaction));
821         action.sa_handler = handle_sigalrm;
822         sigemptyset (&action.sa_mask);
823         action.sa_flags = SA_RESTART;
824         sigaction (SIGALRM, &action, NULL);
825
826         /* Then start a timer to send SIGALRM once per second. */
827         timerval.it_interval.tv_sec = 1;
828         timerval.it_interval.tv_usec = 0;
829         timerval.it_value.tv_sec = 1;
830         timerval.it_value.tv_usec = 0;
831         setitimer (ITIMER_REAL, &timerval, NULL);
832
833         timer_is_active = TRUE;
834     }
835
836     /* Before version 1, each message document had its filename in the
837      * data field. Copy that into the new format by calling
838      * notmuch_message_add_filename.
839      */
840     if (version < 1) {
841         notmuch_query_t *query = notmuch_query_create (notmuch, "");
842         notmuch_messages_t *messages;
843         notmuch_message_t *message;
844         char *filename;
845         Xapian::TermIterator t, t_end;
846
847         total = notmuch_query_count_messages (query);
848
849         for (messages = notmuch_query_search_messages (query);
850              notmuch_messages_valid (messages);
851              notmuch_messages_move_to_next (messages))
852         {
853             if (do_progress_notify) {
854                 progress_notify (closure, (double) count / total);
855                 do_progress_notify = 0;
856             }
857
858             message = notmuch_messages_get (messages);
859
860             filename = _notmuch_message_talloc_copy_data (message);
861             if (filename && *filename != '\0') {
862                 _notmuch_message_add_filename (message, filename);
863                 _notmuch_message_sync (message);
864             }
865             talloc_free (filename);
866
867             notmuch_message_destroy (message);
868
869             count++;
870         }
871
872         notmuch_query_destroy (query);
873
874         /* Also, before version 1 we stored directory timestamps in
875          * XTIMESTAMP documents instead of the current XDIRECTORY
876          * documents. So copy those as well. */
877
878         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
879
880         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
881              t != t_end;
882              t++)
883         {
884             Xapian::PostingIterator p, p_end;
885             std::string term = *t;
886
887             p_end = notmuch->xapian_db->postlist_end (term);
888
889             for (p = notmuch->xapian_db->postlist_begin (term);
890                  p != p_end;
891                  p++)
892             {
893                 Xapian::Document document;
894                 time_t mtime;
895                 notmuch_directory_t *directory;
896
897                 if (do_progress_notify) {
898                     progress_notify (closure, (double) count / total);
899                     do_progress_notify = 0;
900                 }
901
902                 document = find_document_for_doc_id (notmuch, *p);
903                 mtime = Xapian::sortable_unserialise (
904                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
905
906                 directory = notmuch_database_get_directory (notmuch,
907                                                             term.c_str() + 10);
908                 notmuch_directory_set_mtime (directory, mtime);
909                 notmuch_directory_destroy (directory);
910             }
911         }
912     }
913
914     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
915     db->flush ();
916
917     /* Now that the upgrade is complete we can remove the old data
918      * and documents that are no longer needed. */
919     if (version < 1) {
920         notmuch_query_t *query = notmuch_query_create (notmuch, "");
921         notmuch_messages_t *messages;
922         notmuch_message_t *message;
923         char *filename;
924
925         for (messages = notmuch_query_search_messages (query);
926              notmuch_messages_valid (messages);
927              notmuch_messages_move_to_next (messages))
928         {
929             if (do_progress_notify) {
930                 progress_notify (closure, (double) count / total);
931                 do_progress_notify = 0;
932             }
933
934             message = notmuch_messages_get (messages);
935
936             filename = _notmuch_message_talloc_copy_data (message);
937             if (filename && *filename != '\0') {
938                 _notmuch_message_clear_data (message);
939                 _notmuch_message_sync (message);
940             }
941             talloc_free (filename);
942
943             notmuch_message_destroy (message);
944         }
945
946         notmuch_query_destroy (query);
947     }
948
949     if (version < 1) {
950         Xapian::TermIterator t, t_end;
951
952         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
953
954         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
955              t != t_end;
956              t++)
957         {
958             Xapian::PostingIterator p, p_end;
959             std::string term = *t;
960
961             p_end = notmuch->xapian_db->postlist_end (term);
962
963             for (p = notmuch->xapian_db->postlist_begin (term);
964                  p != p_end;
965                  p++)
966             {
967                 if (do_progress_notify) {
968                     progress_notify (closure, (double) count / total);
969                     do_progress_notify = 0;
970                 }
971
972                 db->delete_document (*p);
973             }
974         }
975     }
976
977     if (timer_is_active) {
978         /* Now stop the timer. */
979         timerval.it_interval.tv_sec = 0;
980         timerval.it_interval.tv_usec = 0;
981         timerval.it_value.tv_sec = 0;
982         timerval.it_value.tv_usec = 0;
983         setitimer (ITIMER_REAL, &timerval, NULL);
984
985         /* And disable the signal handler. */
986         action.sa_handler = SIG_IGN;
987         sigaction (SIGALRM, &action, NULL);
988     }
989
990     return NOTMUCH_STATUS_SUCCESS;
991 }
992
993 notmuch_status_t
994 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
995 {
996     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
997         notmuch->atomic_nesting > 0)
998         goto DONE;
999
1000     try {
1001         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1002     } catch (const Xapian::Error &error) {
1003         fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1004                  error.get_msg().c_str());
1005         notmuch->exception_reported = TRUE;
1006         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1007     }
1008
1009 DONE:
1010     notmuch->atomic_nesting++;
1011     return NOTMUCH_STATUS_SUCCESS;
1012 }
1013
1014 notmuch_status_t
1015 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1016 {
1017     Xapian::WritableDatabase *db;
1018
1019     if (notmuch->atomic_nesting == 0)
1020         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1021
1022     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1023         notmuch->atomic_nesting > 1)
1024         goto DONE;
1025
1026     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1027     try {
1028         db->commit_transaction ();
1029
1030         /* This is a hack for testing.  Xapian never flushes on a
1031          * non-flushed commit, even if the flush threshold is 1.
1032          * However, we rely on flushing to test atomicity. */
1033         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1034         if (thresh && atoi (thresh) == 1)
1035             db->flush ();
1036     } catch (const Xapian::Error &error) {
1037         fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1038                  error.get_msg().c_str());
1039         notmuch->exception_reported = TRUE;
1040         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1041     }
1042
1043 DONE:
1044     notmuch->atomic_nesting--;
1045     return NOTMUCH_STATUS_SUCCESS;
1046 }
1047
1048 /* We allow the user to use arbitrarily long paths for directories. But
1049  * we have a term-length limit. So if we exceed that, we'll use the
1050  * SHA-1 of the path for the database term.
1051  *
1052  * Note: This function may return the original value of 'path'. If it
1053  * does not, then the caller is responsible to free() the returned
1054  * value.
1055  */
1056 const char *
1057 _notmuch_database_get_directory_db_path (const char *path)
1058 {
1059     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1060
1061     if (term_len > NOTMUCH_TERM_MAX)
1062         return notmuch_sha1_of_string (path);
1063     else
1064         return path;
1065 }
1066
1067 /* Given a path, split it into two parts: the directory part is all
1068  * components except for the last, and the basename is that last
1069  * component. Getting the return-value for either part is optional
1070  * (the caller can pass NULL).
1071  *
1072  * The original 'path' can represent either a regular file or a
1073  * directory---the splitting will be carried out in the same way in
1074  * either case. Trailing slashes on 'path' will be ignored, and any
1075  * cases of multiple '/' characters appearing in series will be
1076  * treated as a single '/'.
1077  *
1078  * Allocation (if any) will have 'ctx' as the talloc owner. But
1079  * pointers will be returned within the original path string whenever
1080  * possible.
1081  *
1082  * Note: If 'path' is non-empty and contains no non-trailing slash,
1083  * (that is, consists of a filename with no parent directory), then
1084  * the directory returned will be an empty string. However, if 'path'
1085  * is an empty string, then both directory and basename will be
1086  * returned as NULL.
1087  */
1088 notmuch_status_t
1089 _notmuch_database_split_path (void *ctx,
1090                               const char *path,
1091                               const char **directory,
1092                               const char **basename)
1093 {
1094     const char *slash;
1095
1096     if (path == NULL || *path == '\0') {
1097         if (directory)
1098             *directory = NULL;
1099         if (basename)
1100             *basename = NULL;
1101         return NOTMUCH_STATUS_SUCCESS;
1102     }
1103
1104     /* Find the last slash (not counting a trailing slash), if any. */
1105
1106     slash = path + strlen (path) - 1;
1107
1108     /* First, skip trailing slashes. */
1109     while (slash != path) {
1110         if (*slash != '/')
1111             break;
1112
1113         --slash;
1114     }
1115
1116     /* Then, find a slash. */
1117     while (slash != path) {
1118         if (*slash == '/')
1119             break;
1120
1121         if (basename)
1122             *basename = slash;
1123
1124         --slash;
1125     }
1126
1127     /* Finally, skip multiple slashes. */
1128     while (slash != path) {
1129         if (*slash != '/')
1130             break;
1131
1132         --slash;
1133     }
1134
1135     if (slash == path) {
1136         if (directory)
1137             *directory = talloc_strdup (ctx, "");
1138         if (basename)
1139             *basename = path;
1140     } else {
1141         if (directory)
1142             *directory = talloc_strndup (ctx, path, slash - path + 1);
1143     }
1144
1145     return NOTMUCH_STATUS_SUCCESS;
1146 }
1147
1148 notmuch_status_t
1149 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1150                                      const char *path,
1151                                      unsigned int *directory_id)
1152 {
1153     notmuch_directory_t *directory;
1154     notmuch_status_t status;
1155
1156     if (path == NULL) {
1157         *directory_id = 0;
1158         return NOTMUCH_STATUS_SUCCESS;
1159     }
1160
1161     directory = _notmuch_directory_create (notmuch, path, &status);
1162     if (status) {
1163         *directory_id = -1;
1164         return status;
1165     }
1166
1167     *directory_id = _notmuch_directory_get_document_id (directory);
1168
1169     notmuch_directory_destroy (directory);
1170
1171     return NOTMUCH_STATUS_SUCCESS;
1172 }
1173
1174 const char *
1175 _notmuch_database_get_directory_path (void *ctx,
1176                                       notmuch_database_t *notmuch,
1177                                       unsigned int doc_id)
1178 {
1179     Xapian::Document document;
1180
1181     document = find_document_for_doc_id (notmuch, doc_id);
1182
1183     return talloc_strdup (ctx, document.get_data ().c_str ());
1184 }
1185
1186 /* Given a legal 'filename' for the database, (either relative to
1187  * database path or absolute with initial components identical to
1188  * database path), return a new string (with 'ctx' as the talloc
1189  * owner) suitable for use as a direntry term value.
1190  *
1191  * The necessary directory documents will be created in the database
1192  * as needed.
1193  */
1194 notmuch_status_t
1195 _notmuch_database_filename_to_direntry (void *ctx,
1196                                         notmuch_database_t *notmuch,
1197                                         const char *filename,
1198                                         char **direntry)
1199 {
1200     const char *relative, *directory, *basename;
1201     Xapian::docid directory_id;
1202     notmuch_status_t status;
1203
1204     relative = _notmuch_database_relative_path (notmuch, filename);
1205
1206     status = _notmuch_database_split_path (ctx, relative,
1207                                            &directory, &basename);
1208     if (status)
1209         return status;
1210
1211     status = _notmuch_database_find_directory_id (notmuch, directory,
1212                                                   &directory_id);
1213     if (status)
1214         return status;
1215
1216     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1217
1218     return NOTMUCH_STATUS_SUCCESS;
1219 }
1220
1221 /* Given a legal 'path' for the database, return the relative path.
1222  *
1223  * The return value will be a pointer to the original path contents,
1224  * and will be either the original string (if 'path' was relative) or
1225  * a portion of the string (if path was absolute and begins with the
1226  * database path).
1227  */
1228 const char *
1229 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1230                                  const char *path)
1231 {
1232     const char *db_path, *relative;
1233     unsigned int db_path_len;
1234
1235     db_path = notmuch_database_get_path (notmuch);
1236     db_path_len = strlen (db_path);
1237
1238     relative = path;
1239
1240     if (*relative == '/') {
1241         while (*relative == '/' && *(relative+1) == '/')
1242             relative++;
1243
1244         if (strncmp (relative, db_path, db_path_len) == 0)
1245         {
1246             relative += db_path_len;
1247             while (*relative == '/')
1248                 relative++;
1249         }
1250     }
1251
1252     return relative;
1253 }
1254
1255 notmuch_directory_t *
1256 notmuch_database_get_directory (notmuch_database_t *notmuch,
1257                                 const char *path)
1258 {
1259     notmuch_status_t status;
1260
1261     try {
1262         return _notmuch_directory_create (notmuch, path, &status);
1263     } catch (const Xapian::Error &error) {
1264         fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1265                  error.get_msg().c_str());
1266         notmuch->exception_reported = TRUE;
1267         return NULL;
1268     }
1269 }
1270
1271 /* Allocate a document ID that satisfies the following criteria:
1272  *
1273  * 1. The ID does not exist for any document in the Xapian database
1274  *
1275  * 2. The ID was not previously returned from this function
1276  *
1277  * 3. The ID is the smallest integer satisfying (1) and (2)
1278  *
1279  * This function will trigger an internal error if these constraints
1280  * cannot all be satisfied, (that is, the pool of available document
1281  * IDs has been exhausted).
1282  */
1283 unsigned int
1284 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1285 {
1286     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1287
1288     notmuch->last_doc_id++;
1289
1290     if (notmuch->last_doc_id == 0)
1291         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");        
1292
1293     return notmuch->last_doc_id;
1294 }
1295
1296 static const char *
1297 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1298 {
1299     /* 16 bytes (+ terminator) for hexadecimal representation of
1300      * a 64-bit integer. */
1301     static char thread_id[17];
1302     Xapian::WritableDatabase *db;
1303
1304     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1305
1306     notmuch->last_thread_id++;
1307
1308     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1309
1310     db->set_metadata ("last_thread_id", thread_id);
1311
1312     return thread_id;
1313 }
1314
1315 static char *
1316 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1317 {
1318     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1319         message_id = _message_id_compressed (ctx, message_id);
1320
1321     return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1322                             message_id);
1323 }
1324
1325 /* Find the thread ID to which the message with 'message_id' belongs.
1326  *
1327  * Note: 'thread_id_ret' must not be NULL!
1328  * On success '*thread_id_ret' is set to a newly talloced string belonging to
1329  * 'ctx'.
1330  *
1331  * Note: If there is no message in the database with the given
1332  * 'message_id' then a new thread_id will be allocated for this
1333  * message and stored in the database metadata, (where this same
1334  * thread ID can be looked up if the message is added to the database
1335  * later).
1336  */
1337 static notmuch_status_t
1338 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1339                                   void *ctx,
1340                                   const char *message_id,
1341                                   const char **thread_id_ret)
1342 {
1343     notmuch_status_t status;
1344     notmuch_message_t *message;
1345     string thread_id_string;
1346     char *metadata_key;
1347     Xapian::WritableDatabase *db;
1348
1349     status = notmuch_database_find_message (notmuch, message_id, &message);
1350
1351     if (status)
1352         return status;
1353
1354     if (message) {
1355         *thread_id_ret = talloc_steal (ctx,
1356                                        notmuch_message_get_thread_id (message));
1357
1358         notmuch_message_destroy (message);
1359
1360         return NOTMUCH_STATUS_SUCCESS;
1361     }
1362
1363     /* Message has not been seen yet.
1364      *
1365      * We may have seen a reference to it already, in which case, we
1366      * can return the thread ID stored in the metadata. Otherwise, we
1367      * generate a new thread ID and store it there.
1368      */
1369     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1370     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1371     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1372
1373     if (thread_id_string.empty()) {
1374         *thread_id_ret = talloc_strdup (ctx,
1375                                         _notmuch_database_generate_thread_id (notmuch));
1376         db->set_metadata (metadata_key, *thread_id_ret);
1377     } else {
1378         *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1379     }
1380
1381     talloc_free (metadata_key);
1382
1383     return NOTMUCH_STATUS_SUCCESS;
1384 }
1385
1386 static notmuch_status_t
1387 _merge_threads (notmuch_database_t *notmuch,
1388                 const char *winner_thread_id,
1389                 const char *loser_thread_id)
1390 {
1391     Xapian::PostingIterator loser, loser_end;
1392     notmuch_message_t *message = NULL;
1393     notmuch_private_status_t private_status;
1394     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1395
1396     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1397
1398     for ( ; loser != loser_end; loser++) {
1399         message = _notmuch_message_create (notmuch, notmuch,
1400                                            *loser, &private_status);
1401         if (message == NULL) {
1402             ret = COERCE_STATUS (private_status,
1403                                  "Cannot find document for doc_id from query");
1404             goto DONE;
1405         }
1406
1407         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1408         _notmuch_message_add_term (message, "thread", winner_thread_id);
1409         _notmuch_message_sync (message);
1410
1411         notmuch_message_destroy (message);
1412         message = NULL;
1413     }
1414
1415   DONE:
1416     if (message)
1417         notmuch_message_destroy (message);
1418
1419     return ret;
1420 }
1421
1422 static void
1423 _my_talloc_free_for_g_hash (void *ptr)
1424 {
1425     talloc_free (ptr);
1426 }
1427
1428 static notmuch_status_t
1429 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1430                                            notmuch_message_t *message,
1431                                            notmuch_message_file_t *message_file,
1432                                            const char **thread_id)
1433 {
1434     GHashTable *parents = NULL;
1435     const char *refs, *in_reply_to, *in_reply_to_message_id;
1436     GList *l, *keys = NULL;
1437     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1438
1439     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1440                                      _my_talloc_free_for_g_hash, NULL);
1441
1442     refs = notmuch_message_file_get_header (message_file, "references");
1443     parse_references (message, notmuch_message_get_message_id (message),
1444                       parents, refs);
1445
1446     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1447     parse_references (message, notmuch_message_get_message_id (message),
1448                       parents, in_reply_to);
1449
1450     /* Carefully avoid adding any self-referential in-reply-to term. */
1451     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1452     if (in_reply_to_message_id &&
1453         strcmp (in_reply_to_message_id,
1454                 notmuch_message_get_message_id (message)))
1455     {
1456         _notmuch_message_add_term (message, "replyto",
1457                              _parse_message_id (message, in_reply_to, NULL));
1458     }
1459
1460     keys = g_hash_table_get_keys (parents);
1461     for (l = keys; l; l = l->next) {
1462         char *parent_message_id;
1463         const char *parent_thread_id = NULL;
1464
1465         parent_message_id = (char *) l->data;
1466
1467         _notmuch_message_add_term (message, "reference",
1468                                    parent_message_id);
1469
1470         ret = _resolve_message_id_to_thread_id (notmuch,
1471                                                 message,
1472                                                 parent_message_id,
1473                                                 &parent_thread_id);
1474         if (ret)
1475             goto DONE;
1476
1477         if (*thread_id == NULL) {
1478             *thread_id = talloc_strdup (message, parent_thread_id);
1479             _notmuch_message_add_term (message, "thread", *thread_id);
1480         } else if (strcmp (*thread_id, parent_thread_id)) {
1481             ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1482             if (ret)
1483                 goto DONE;
1484         }
1485     }
1486
1487   DONE:
1488     if (keys)
1489         g_list_free (keys);
1490     if (parents)
1491         g_hash_table_unref (parents);
1492
1493     return ret;
1494 }
1495
1496 static notmuch_status_t
1497 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1498                                             notmuch_message_t *message,
1499                                             const char **thread_id)
1500 {
1501     const char *message_id = notmuch_message_get_message_id (message);
1502     Xapian::PostingIterator child, children_end;
1503     notmuch_message_t *child_message = NULL;
1504     const char *child_thread_id;
1505     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1506     notmuch_private_status_t private_status;
1507
1508     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1509
1510     for ( ; child != children_end; child++) {
1511
1512         child_message = _notmuch_message_create (message, notmuch,
1513                                                  *child, &private_status);
1514         if (child_message == NULL) {
1515             ret = COERCE_STATUS (private_status,
1516                                  "Cannot find document for doc_id from query");
1517             goto DONE;
1518         }
1519
1520         child_thread_id = notmuch_message_get_thread_id (child_message);
1521         if (*thread_id == NULL) {
1522             *thread_id = talloc_strdup (message, child_thread_id);
1523             _notmuch_message_add_term (message, "thread", *thread_id);
1524         } else if (strcmp (*thread_id, child_thread_id)) {
1525             _notmuch_message_remove_term (child_message, "reference",
1526                                           message_id);
1527             _notmuch_message_sync (child_message);
1528             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1529             if (ret)
1530                 goto DONE;
1531         }
1532
1533         notmuch_message_destroy (child_message);
1534         child_message = NULL;
1535     }
1536
1537   DONE:
1538     if (child_message)
1539         notmuch_message_destroy (child_message);
1540
1541     return ret;
1542 }
1543
1544 /* Given a (mostly empty) 'message' and its corresponding
1545  * 'message_file' link it to existing threads in the database.
1546  *
1547  * The first check is in the metadata of the database to see if we
1548  * have pre-allocated a thread_id in advance for this message, (which
1549  * would have happened if a message was previously added that
1550  * referenced this one).
1551  *
1552  * Second, we look at 'message_file' and its link-relevant headers
1553  * (References and In-Reply-To) for message IDs.
1554  *
1555  * Finally, we look in the database for existing message that
1556  * reference 'message'.
1557  *
1558  * In all cases, we assign to the current message the first thread_id
1559  * found (through either parent or child). We will also merge any
1560  * existing, distinct threads where this message belongs to both,
1561  * (which is not uncommon when messages are processed out of order).
1562  *
1563  * Finally, if no thread ID has been found through parent or child, we
1564  * call _notmuch_message_generate_thread_id to generate a new thread
1565  * ID. This should only happen for new, top-level messages, (no
1566  * References or In-Reply-To header in this message, and no previously
1567  * added message refers to this message).
1568  */
1569 static notmuch_status_t
1570 _notmuch_database_link_message (notmuch_database_t *notmuch,
1571                                 notmuch_message_t *message,
1572                                 notmuch_message_file_t *message_file)
1573 {
1574     notmuch_status_t status;
1575     const char *message_id, *thread_id = NULL;
1576     char *metadata_key;
1577     string stored_id;
1578
1579     message_id = notmuch_message_get_message_id (message);
1580     metadata_key = _get_metadata_thread_id_key (message, message_id);
1581
1582     /* Check if we have already seen related messages to this one.
1583      * If we have then use the thread_id that we stored at that time.
1584      */
1585     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1586     if (! stored_id.empty()) {
1587         Xapian::WritableDatabase *db;
1588
1589         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1590
1591         /* Clear the metadata for this message ID. We don't need it
1592          * anymore. */
1593         db->set_metadata (metadata_key, "");
1594         thread_id = stored_id.c_str();
1595
1596         _notmuch_message_add_term (message, "thread", thread_id);
1597     }
1598     talloc_free (metadata_key);
1599
1600     status = _notmuch_database_link_message_to_parents (notmuch, message,
1601                                                         message_file,
1602                                                         &thread_id);
1603     if (status)
1604         return status;
1605
1606     status = _notmuch_database_link_message_to_children (notmuch, message,
1607                                                          &thread_id);
1608     if (status)
1609         return status;
1610
1611     /* If not part of any existing thread, generate a new thread ID. */
1612     if (thread_id == NULL) {
1613         thread_id = _notmuch_database_generate_thread_id (notmuch);
1614
1615         _notmuch_message_add_term (message, "thread", thread_id);
1616     }
1617
1618     return NOTMUCH_STATUS_SUCCESS;
1619 }
1620
1621 notmuch_status_t
1622 notmuch_database_add_message (notmuch_database_t *notmuch,
1623                               const char *filename,
1624                               notmuch_message_t **message_ret)
1625 {
1626     notmuch_message_file_t *message_file;
1627     notmuch_message_t *message = NULL;
1628     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1629     notmuch_private_status_t private_status;
1630
1631     const char *date, *header;
1632     const char *from, *to, *subject;
1633     char *message_id = NULL;
1634
1635     if (message_ret)
1636         *message_ret = NULL;
1637
1638     ret = _notmuch_database_ensure_writable (notmuch);
1639     if (ret)
1640         return ret;
1641
1642     message_file = notmuch_message_file_open (filename);
1643     if (message_file == NULL)
1644         return NOTMUCH_STATUS_FILE_ERROR;
1645
1646     /* Adding a message may change many documents.  Do this all
1647      * atomically. */
1648     ret = notmuch_database_begin_atomic (notmuch);
1649     if (ret)
1650         goto DONE;
1651
1652     notmuch_message_file_restrict_headers (message_file,
1653                                            "date",
1654                                            "from",
1655                                            "in-reply-to",
1656                                            "message-id",
1657                                            "references",
1658                                            "subject",
1659                                            "to",
1660                                            (char *) NULL);
1661
1662     try {
1663         /* Before we do any real work, (especially before doing a
1664          * potential SHA-1 computation on the entire file's contents),
1665          * let's make sure that what we're looking at looks like an
1666          * actual email message.
1667          */
1668         from = notmuch_message_file_get_header (message_file, "from");
1669         subject = notmuch_message_file_get_header (message_file, "subject");
1670         to = notmuch_message_file_get_header (message_file, "to");
1671
1672         if ((from == NULL || *from == '\0') &&
1673             (subject == NULL || *subject == '\0') &&
1674             (to == NULL || *to == '\0'))
1675         {
1676             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1677             goto DONE;
1678         }
1679
1680         /* Now that we're sure it's mail, the first order of business
1681          * is to find a message ID (or else create one ourselves). */
1682
1683         header = notmuch_message_file_get_header (message_file, "message-id");
1684         if (header && *header != '\0') {
1685             message_id = _parse_message_id (message_file, header, NULL);
1686
1687             /* So the header value isn't RFC-compliant, but it's
1688              * better than no message-id at all. */
1689             if (message_id == NULL)
1690                 message_id = talloc_strdup (message_file, header);
1691
1692             /* If a message ID is too long, substitute its sha1 instead. */
1693             if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1694                 char *compressed = _message_id_compressed (message_file,
1695                                                            message_id);
1696                 talloc_free (message_id);
1697                 message_id = compressed;
1698             }
1699         }
1700
1701         if (message_id == NULL ) {
1702             /* No message-id at all, let's generate one by taking a
1703              * hash over the file's contents. */
1704             char *sha1 = notmuch_sha1_of_file (filename);
1705
1706             /* If that failed too, something is really wrong. Give up. */
1707             if (sha1 == NULL) {
1708                 ret = NOTMUCH_STATUS_FILE_ERROR;
1709                 goto DONE;
1710             }
1711
1712             message_id = talloc_asprintf (message_file,
1713                                           "notmuch-sha1-%s", sha1);
1714             free (sha1);
1715         }
1716
1717         /* Now that we have a message ID, we get a message object,
1718          * (which may or may not reference an existing document in the
1719          * database). */
1720
1721         message = _notmuch_message_create_for_message_id (notmuch,
1722                                                           message_id,
1723                                                           &private_status);
1724
1725         talloc_free (message_id);
1726
1727         if (message == NULL) {
1728             ret = COERCE_STATUS (private_status,
1729                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1730             goto DONE;
1731         }
1732
1733         _notmuch_message_add_filename (message, filename);
1734
1735         /* Is this a newly created message object? */
1736         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1737             _notmuch_message_add_term (message, "type", "mail");
1738
1739             ret = _notmuch_database_link_message (notmuch, message,
1740                                                   message_file);
1741             if (ret)
1742                 goto DONE;
1743
1744             date = notmuch_message_file_get_header (message_file, "date");
1745             _notmuch_message_set_header_values (message, date, from, subject);
1746
1747             _notmuch_message_index_file (message, filename);
1748         } else {
1749             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1750         }
1751
1752         _notmuch_message_sync (message);
1753     } catch (const Xapian::Error &error) {
1754         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1755                  error.get_msg().c_str());
1756         notmuch->exception_reported = TRUE;
1757         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1758         goto DONE;
1759     }
1760
1761   DONE:
1762     if (message) {
1763         if ((ret == NOTMUCH_STATUS_SUCCESS ||
1764              ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
1765             *message_ret = message;
1766         else
1767             notmuch_message_destroy (message);
1768     }
1769
1770     if (message_file)
1771         notmuch_message_file_close (message_file);
1772
1773     ret2 = notmuch_database_end_atomic (notmuch);
1774     if ((ret == NOTMUCH_STATUS_SUCCESS ||
1775          ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
1776         ret2 != NOTMUCH_STATUS_SUCCESS)
1777         ret = ret2;
1778
1779     return ret;
1780 }
1781
1782 notmuch_status_t
1783 notmuch_database_remove_message (notmuch_database_t *notmuch,
1784                                  const char *filename)
1785 {
1786     notmuch_status_t status;
1787     notmuch_message_t *message;
1788
1789     status = notmuch_database_find_message_by_filename (notmuch, filename,
1790                                                         &message);
1791
1792     if (status == NOTMUCH_STATUS_SUCCESS && message) {
1793             status = _notmuch_message_remove_filename (message, filename);
1794             if (status == NOTMUCH_STATUS_SUCCESS)
1795                 _notmuch_message_delete (message);
1796             else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1797                 _notmuch_message_sync (message);
1798
1799             notmuch_message_destroy (message);
1800     }
1801
1802     return status;
1803 }
1804
1805 notmuch_status_t
1806 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1807                                            const char *filename,
1808                                            notmuch_message_t **message_ret)
1809 {
1810     void *local;
1811     const char *prefix = _find_prefix ("file-direntry");
1812     char *direntry, *term;
1813     Xapian::PostingIterator i, end;
1814     notmuch_status_t status;
1815
1816     if (message_ret == NULL)
1817         return NOTMUCH_STATUS_NULL_POINTER;
1818
1819     local = talloc_new (notmuch);
1820
1821     try {
1822         status = _notmuch_database_filename_to_direntry (local, notmuch,
1823                                                          filename, &direntry);
1824         if (status)
1825             goto DONE;
1826
1827         term = talloc_asprintf (local, "%s%s", prefix, direntry);
1828
1829         find_doc_ids_for_term (notmuch, term, &i, &end);
1830
1831         if (i != end) {
1832             notmuch_private_status_t private_status;
1833
1834             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1835                                                     &private_status);
1836             if (*message_ret == NULL)
1837                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1838         }
1839     } catch (const Xapian::Error &error) {
1840         fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
1841                  error.get_msg().c_str());
1842         notmuch->exception_reported = TRUE;
1843         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1844     }
1845
1846   DONE:
1847     talloc_free (local);
1848
1849     if (status && *message_ret) {
1850         notmuch_message_destroy (*message_ret);
1851         *message_ret = NULL;
1852     }
1853     return status;
1854 }
1855
1856 notmuch_string_list_t *
1857 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1858                                          Xapian::TermIterator &end,
1859                                          const char *prefix)
1860 {
1861     int prefix_len = strlen (prefix);
1862     notmuch_string_list_t *list;
1863
1864     list = _notmuch_string_list_create (ctx);
1865     if (unlikely (list == NULL))
1866         return NULL;
1867
1868     for (i.skip_to (prefix); i != end; i++) {
1869         /* Terminate loop at first term without desired prefix. */
1870         if (strncmp ((*i).c_str (), prefix, prefix_len))
1871             break;
1872
1873         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1874     }
1875
1876     return list;
1877 }
1878
1879 notmuch_tags_t *
1880 notmuch_database_get_all_tags (notmuch_database_t *db)
1881 {
1882     Xapian::TermIterator i, end;
1883     notmuch_string_list_t *tags;
1884
1885     try {
1886         i = db->xapian_db->allterms_begin();
1887         end = db->xapian_db->allterms_end();
1888         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1889                                                         _find_prefix ("tag"));
1890         _notmuch_string_list_sort (tags);
1891         return _notmuch_tags_create (db, tags);
1892     } catch (const Xapian::Error &error) {
1893         fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1894                  error.get_msg().c_str());
1895         db->exception_reported = TRUE;
1896         return NULL;
1897     }
1898 }