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