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