]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
Make maildir synchronization configurable
[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 Re ferences
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. But the database doesn't really care itself
93  * about any of these.
94  *
95  * The data portion of a mail document is empty.
96  *
97  * Directory document
98  * ------------------
99  * A directory document is used by a client of the notmuch library to
100  * maintain data necessary to allow for efficient polling of mail
101  * directories.
102  *
103  * All directory documents contain one term:
104  *
105  *      directory:      The directory path (relative to the database path)
106  *                      Or the SHA1 sum of the directory path (if the
107  *                      path itself is too long to fit in a Xapian
108  *                      term).
109  *
110  * And all directory documents for directories other than top-level
111  * directories also contain the following term:
112  *
113  *      directory-direntry: A colon-separated pair of values
114  *                          (INTEGER:STRING), where INTEGER is the
115  *                          document ID of the parent directory
116  *                          document, and STRING is the name of this
117  *                          directory within that parent.
118  *
119  * All directory documents have a single value:
120  *
121  *      TIMESTAMP:      The mtime of the directory (at last scan)
122  *
123  * The data portion of a directory document contains the path of the
124  * directory (relative to the database path).
125  *
126  * Database metadata
127  * -----------------
128  * Xapian allows us to store arbitrary name-value pairs as
129  * "metadata". We currently use the following metadata names with the
130  * given meanings:
131  *
132  *      version         The database schema version, (which is distinct
133  *                      from both the notmuch package version (see
134  *                      notmuch --version) and the libnotmuch library
135  *                      version. The version is stored as an base-10
136  *                      ASCII integer. The initial database version
137  *                      was 1, (though a schema existed before that
138  *                      were no "version" database value existed at
139  *                      all). Succesive versions are allocated as
140  *                      changes are made to the database (such as by
141  *                      indexing new fields).
142  *
143  *      last_thread_id  The last thread ID generated. This is stored
144  *                      as a 16-byte hexadecimal ASCII representation
145  *                      of a 64-bit unsigned integer. The first ID
146  *                      generated is 1 and the value will be
147  *                      incremented for each thread ID.
148  *
149  *      thread_id_*     A pre-allocated thread ID for a particular
150  *                      message. This is actually an arbitarily large
151  *                      family of metadata name. Any particular name is
152  *                      formed by concatenating "thread_id_" with a message
153  *                      ID (or the SHA1 sum of a message ID if it is very
154  *                      long---see description of 'id' in the mail
155  *                      document). The value stored is a thread ID.
156  *
157  *                      These thread ID metadata values are stored
158  *                      whenever a message references a parent message
159  *                      that does not yet exist in the database. A
160  *                      thread ID will be allocated and stored, and if
161  *                      the message is later added, the stored thread
162  *                      ID will be used (and the metadata value will
163  *                      be cleared).
164  *
165  *                      Even before a message is added, it's
166  *                      pre-allocated thread ID is useful so that all
167  *                      descendant messages that reference this common
168  *                      parent can be recognized as belonging to the
169  *                      same thread.
170  */
171
172 /* With these prefix values we follow the conventions published here:
173  *
174  * http://xapian.org/docs/omega/termprefixes.html
175  *
176  * as much as makes sense. Note that I took some liberty in matching
177  * the reserved prefix values to notmuch concepts, (for example, 'G'
178  * is documented as "newsGroup (or similar entity - e.g. a web forum
179  * name)", for which I think the thread is the closest analogue in
180  * notmuch. This in spite of the fact that we will eventually be
181  * storing mailing-list messages where 'G' for "mailing list name"
182  * might be even a closer analogue. I'm treating the single-character
183  * prefixes preferentially for core notmuch concepts (which will be
184  * nearly universal to all mail messages).
185  */
186
187 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
188     { "type",                   "T" },
189     { "reference",              "XREFERENCE" },
190     { "replyto",                "XREPLYTO" },
191     { "directory",              "XDIRECTORY" },
192     { "file-direntry",          "XFDIRENTRY" },
193     { "directory-direntry",     "XDDIRENTRY" },
194 };
195
196 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
197     { "thread",                 "G" },
198     { "tag",                    "K" },
199     { "is",                     "K" },
200     { "id",                     "Q" }
201 };
202
203 static prefix_t PROBABILISTIC_PREFIX[]= {
204     { "from",                   "XFROM" },
205     { "to",                     "XTO" },
206     { "attachment",             "XATTACHMENT" },
207     { "subject",                "XSUBJECT"}
208 };
209
210 int
211 _internal_error (const char *format, ...)
212 {
213     va_list va_args;
214
215     va_start (va_args, format);
216
217     fprintf (stderr, "Internal error: ");
218     vfprintf (stderr, format, va_args);
219
220     exit (1);
221
222     return 1;
223 }
224
225 const char *
226 _find_prefix (const char *name)
227 {
228     unsigned int i;
229
230     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
231         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
232             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
233     }
234
235     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
236         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
237             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
238     }
239
240     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
241         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
242             return PROBABILISTIC_PREFIX[i].prefix;
243     }
244
245     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
246
247     return "";
248 }
249
250 const char *
251 notmuch_status_to_string (notmuch_status_t status)
252 {
253     switch (status) {
254     case NOTMUCH_STATUS_SUCCESS:
255         return "No error occurred";
256     case NOTMUCH_STATUS_OUT_OF_MEMORY:
257         return "Out of memory";
258     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
259         return "Attempt to write to a read-only database";
260     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
261         return "A Xapian exception occurred";
262     case NOTMUCH_STATUS_FILE_ERROR:
263         return "Something went wrong trying to read or write a file";
264     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
265         return "File is not an email";
266     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
267         return "Message ID is identical to a message in database";
268     case NOTMUCH_STATUS_NULL_POINTER:
269         return "Erroneous NULL pointer";
270     case NOTMUCH_STATUS_TAG_TOO_LONG:
271         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
272     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
273         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
274     default:
275     case NOTMUCH_STATUS_LAST_STATUS:
276         return "Unknown error status value";
277     }
278 }
279
280 static void
281 find_doc_ids_for_term (notmuch_database_t *notmuch,
282                        const char *term,
283                        Xapian::PostingIterator *begin,
284                        Xapian::PostingIterator *end)
285 {
286     *begin = notmuch->xapian_db->postlist_begin (term);
287
288     *end = notmuch->xapian_db->postlist_end (term);
289 }
290
291 static void
292 find_doc_ids (notmuch_database_t *notmuch,
293               const char *prefix_name,
294               const char *value,
295               Xapian::PostingIterator *begin,
296               Xapian::PostingIterator *end)
297 {
298     char *term;
299
300     term = talloc_asprintf (notmuch, "%s%s",
301                             _find_prefix (prefix_name), value);
302
303     find_doc_ids_for_term (notmuch, term, begin, end);
304
305     talloc_free (term);
306 }
307
308 notmuch_private_status_t
309 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
310                                       const char *prefix_name,
311                                       const char *value,
312                                       unsigned int *doc_id)
313 {
314     Xapian::PostingIterator i, end;
315
316     find_doc_ids (notmuch, prefix_name, value, &i, &end);
317
318     if (i == end) {
319         *doc_id = 0;
320         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
321     }
322
323     *doc_id = *i;
324
325 #if DEBUG_DATABASE_SANITY
326     i++;
327
328     if (i != end)
329         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
330                         prefix_name, value);
331 #endif
332
333     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
334 }
335
336 static Xapian::Document
337 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
338 {
339     return notmuch->xapian_db->get_document (doc_id);
340 }
341
342 /* Generate a compressed version of 'message_id' of the form:
343  *
344  *      notmuch-sha1-<sha1_sum_of_message_id>
345  */
346 static char *
347 _message_id_compressed (void *ctx, const char *message_id)
348 {
349     char *sha1, *compressed;
350
351     sha1 = notmuch_sha1_of_string (message_id);
352
353     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
354     free (sha1);
355
356     return compressed;
357 }
358
359 notmuch_message_t *
360 notmuch_database_find_message (notmuch_database_t *notmuch,
361                                const char *message_id)
362 {
363     notmuch_private_status_t status;
364     unsigned int doc_id;
365
366     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
367         message_id = _message_id_compressed (notmuch, message_id);
368
369     try {
370         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
371                                                        message_id, &doc_id);
372
373         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
374             return NULL;
375
376         return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
377     } catch (const Xapian::Error &error) {
378         fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
379                  error.get_msg().c_str());
380         notmuch->exception_reported = TRUE;
381         return NULL;
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 '>' delimeters.
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     try {
613         string last_thread_id;
614
615         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
616             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
617                                                                Xapian::DB_CREATE_OR_OPEN);
618             version = notmuch_database_get_version (notmuch);
619
620             if (version > NOTMUCH_DATABASE_VERSION) {
621                 fprintf (stderr,
622                          "Error: Notmuch database at %s\n"
623                          "       has a newer database format version (%u) than supported by this\n"
624                          "       version of notmuch (%u). Refusing to open this database in\n"
625                          "       read-write mode.\n",
626                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
627                 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
628                 notmuch_database_close (notmuch);
629                 notmuch = NULL;
630                 goto DONE;
631             }
632
633             if (version < NOTMUCH_DATABASE_VERSION)
634                 notmuch->needs_upgrade = TRUE;
635         } else {
636             notmuch->xapian_db = new Xapian::Database (xapian_path);
637             version = notmuch_database_get_version (notmuch);
638             if (version > NOTMUCH_DATABASE_VERSION)
639             {
640                 fprintf (stderr,
641                          "Warning: Notmuch database at %s\n"
642                          "         has a newer database format version (%u) than supported by this\n"
643                          "         version of notmuch (%u). Some operations may behave incorrectly,\n"
644                          "         (but the database will not be harmed since it is being opened\n"
645                          "         in read-only mode).\n",
646                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
647             }
648         }
649
650         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
651         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
652         if (last_thread_id.empty ()) {
653             notmuch->last_thread_id = 0;
654         } else {
655             const char *str;
656             char *end;
657
658             str = last_thread_id.c_str ();
659             notmuch->last_thread_id = strtoull (str, &end, 16);
660             if (*end != '\0')
661                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
662         }
663
664         notmuch->query_parser = new Xapian::QueryParser;
665         notmuch->term_gen = new Xapian::TermGenerator;
666         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
667         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
668
669         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
670         notmuch->query_parser->set_database (*notmuch->xapian_db);
671         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
672         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
673         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
674
675         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
676             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
677             notmuch->query_parser->add_boolean_prefix (prefix->name,
678                                                        prefix->prefix);
679         }
680
681         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
682             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
683             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
684         }
685     } catch (const Xapian::Error &error) {
686         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
687                  error.get_msg().c_str());
688         notmuch = NULL;
689     }
690
691     notmuch_database_set_maildir_sync (notmuch, FALSE);
692
693   DONE:
694     if (notmuch_path)
695         free (notmuch_path);
696     if (xapian_path)
697         free (xapian_path);
698
699     return notmuch;
700 }
701
702 void
703 notmuch_database_close (notmuch_database_t *notmuch)
704 {
705     try {
706         if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
707             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
708     } catch (const Xapian::Error &error) {
709         if (! notmuch->exception_reported) {
710             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
711                      error.get_msg().c_str());
712         }
713     }
714
715     delete notmuch->term_gen;
716     delete notmuch->query_parser;
717     delete notmuch->xapian_db;
718     delete notmuch->value_range_processor;
719     talloc_free (notmuch);
720 }
721
722 void
723 notmuch_database_set_maildir_sync (notmuch_database_t *database,
724                                    notmuch_bool_t maildir_sync)
725 {
726     database->maildir_sync = maildir_sync;
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 /* We allow the user to use arbitrarily long paths for directories. But
985  * we have a term-length limit. So if we exceed that, we'll use the
986  * SHA-1 of the path for the database term.
987  *
988  * Note: This function may return the original value of 'path'. If it
989  * does not, then the caller is responsible to free() the returned
990  * value.
991  */
992 const char *
993 _notmuch_database_get_directory_db_path (const char *path)
994 {
995     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
996
997     if (term_len > NOTMUCH_TERM_MAX)
998         return notmuch_sha1_of_string (path);
999     else
1000         return path;
1001 }
1002
1003 /* Given a path, split it into two parts: the directory part is all
1004  * components except for the last, and the basename is that last
1005  * component. Getting the return-value for either part is optional
1006  * (the caller can pass NULL).
1007  *
1008  * The original 'path' can represent either a regular file or a
1009  * directory---the splitting will be carried out in the same way in
1010  * either case. Trailing slashes on 'path' will be ignored, and any
1011  * cases of multiple '/' characters appearing in series will be
1012  * treated as a single '/'.
1013  *
1014  * Allocation (if any) will have 'ctx' as the talloc owner. But
1015  * pointers will be returned within the original path string whenever
1016  * possible.
1017  *
1018  * Note: If 'path' is non-empty and contains no non-trailing slash,
1019  * (that is, consists of a filename with no parent directory), then
1020  * the directory returned will be an empty string. However, if 'path'
1021  * is an empty string, then both directory and basename will be
1022  * returned as NULL.
1023  */
1024 notmuch_status_t
1025 _notmuch_database_split_path (void *ctx,
1026                               const char *path,
1027                               const char **directory,
1028                               const char **basename)
1029 {
1030     const char *slash;
1031
1032     if (path == NULL || *path == '\0') {
1033         if (directory)
1034             *directory = NULL;
1035         if (basename)
1036             *basename = NULL;
1037         return NOTMUCH_STATUS_SUCCESS;
1038     }
1039
1040     /* Find the last slash (not counting a trailing slash), if any. */
1041
1042     slash = path + strlen (path) - 1;
1043
1044     /* First, skip trailing slashes. */
1045     while (slash != path) {
1046         if (*slash != '/')
1047             break;
1048
1049         --slash;
1050     }
1051
1052     /* Then, find a slash. */
1053     while (slash != path) {
1054         if (*slash == '/')
1055             break;
1056
1057         if (basename)
1058             *basename = slash;
1059
1060         --slash;
1061     }
1062
1063     /* Finally, skip multiple slashes. */
1064     while (slash != path) {
1065         if (*slash != '/')
1066             break;
1067
1068         --slash;
1069     }
1070
1071     if (slash == path) {
1072         if (directory)
1073             *directory = talloc_strdup (ctx, "");
1074         if (basename)
1075             *basename = path;
1076     } else {
1077         if (directory)
1078             *directory = talloc_strndup (ctx, path, slash - path + 1);
1079     }
1080
1081     return NOTMUCH_STATUS_SUCCESS;
1082 }
1083
1084 notmuch_status_t
1085 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1086                                      const char *path,
1087                                      unsigned int *directory_id)
1088 {
1089     notmuch_directory_t *directory;
1090     notmuch_status_t status;
1091
1092     if (path == NULL) {
1093         *directory_id = 0;
1094         return NOTMUCH_STATUS_SUCCESS;
1095     }
1096
1097     directory = _notmuch_directory_create (notmuch, path, &status);
1098     if (status) {
1099         *directory_id = -1;
1100         return status;
1101     }
1102
1103     *directory_id = _notmuch_directory_get_document_id (directory);
1104
1105     notmuch_directory_destroy (directory);
1106
1107     return NOTMUCH_STATUS_SUCCESS;
1108 }
1109
1110 const char *
1111 _notmuch_database_get_directory_path (void *ctx,
1112                                       notmuch_database_t *notmuch,
1113                                       unsigned int doc_id)
1114 {
1115     Xapian::Document document;
1116
1117     document = find_document_for_doc_id (notmuch, doc_id);
1118
1119     return talloc_strdup (ctx, document.get_data ().c_str ());
1120 }
1121
1122 /* Given a legal 'filename' for the database, (either relative to
1123  * database path or absolute with initial components identical to
1124  * database path), return a new string (with 'ctx' as the talloc
1125  * owner) suitable for use as a direntry term value.
1126  *
1127  * The necessary directory documents will be created in the database
1128  * as needed.
1129  */
1130 notmuch_status_t
1131 _notmuch_database_filename_to_direntry (void *ctx,
1132                                         notmuch_database_t *notmuch,
1133                                         const char *filename,
1134                                         char **direntry)
1135 {
1136     const char *relative, *directory, *basename;
1137     Xapian::docid directory_id;
1138     notmuch_status_t status;
1139
1140     relative = _notmuch_database_relative_path (notmuch, filename);
1141
1142     status = _notmuch_database_split_path (ctx, relative,
1143                                            &directory, &basename);
1144     if (status)
1145         return status;
1146
1147     status = _notmuch_database_find_directory_id (notmuch, directory,
1148                                                   &directory_id);
1149     if (status)
1150         return status;
1151
1152     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1153
1154     return NOTMUCH_STATUS_SUCCESS;
1155 }
1156
1157 /* Given a legal 'path' for the database, return the relative path.
1158  *
1159  * The return value will be a pointer to the originl path contents,
1160  * and will be either the original string (if 'path' was relative) or
1161  * a portion of the string (if path was absolute and begins with the
1162  * database path).
1163  */
1164 const char *
1165 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1166                                  const char *path)
1167 {
1168     const char *db_path, *relative;
1169     unsigned int db_path_len;
1170
1171     db_path = notmuch_database_get_path (notmuch);
1172     db_path_len = strlen (db_path);
1173
1174     relative = path;
1175
1176     if (*relative == '/') {
1177         while (*relative == '/' && *(relative+1) == '/')
1178             relative++;
1179
1180         if (strncmp (relative, db_path, db_path_len) == 0)
1181         {
1182             relative += db_path_len;
1183             while (*relative == '/')
1184                 relative++;
1185         }
1186     }
1187
1188     return relative;
1189 }
1190
1191 notmuch_directory_t *
1192 notmuch_database_get_directory (notmuch_database_t *notmuch,
1193                                 const char *path)
1194 {
1195     notmuch_status_t status;
1196
1197     try {
1198         return _notmuch_directory_create (notmuch, path, &status);
1199     } catch (const Xapian::Error &error) {
1200         fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1201                  error.get_msg().c_str());
1202         notmuch->exception_reported = TRUE;
1203         return NULL;
1204     }
1205 }
1206
1207 /* Allocate a document ID that satisfies the following criteria:
1208  *
1209  * 1. The ID does not exist for any document in the Xapian database
1210  *
1211  * 2. The ID was not previously returned from this function
1212  *
1213  * 3. The ID is the smallest integer satisfying (1) and (2)
1214  *
1215  * This function will trigger an internal error if these constraints
1216  * cannot all be satisfied, (that is, the pool of available document
1217  * IDs has been exhausted).
1218  */
1219 unsigned int
1220 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1221 {
1222     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1223
1224     notmuch->last_doc_id++;
1225
1226     if (notmuch->last_doc_id == 0)
1227         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");        
1228
1229     return notmuch->last_doc_id;
1230 }
1231
1232 static const char *
1233 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1234 {
1235     /* 16 bytes (+ terminator) for hexadecimal representation of
1236      * a 64-bit integer. */
1237     static char thread_id[17];
1238     Xapian::WritableDatabase *db;
1239
1240     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1241
1242     notmuch->last_thread_id++;
1243
1244     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1245
1246     db->set_metadata ("last_thread_id", thread_id);
1247
1248     return thread_id;
1249 }
1250
1251 static char *
1252 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1253 {
1254     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1255         message_id = _message_id_compressed (ctx, message_id);
1256
1257     return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1258                             message_id);
1259 }
1260
1261 /* Find the thread ID to which the message with 'message_id' belongs.
1262  *
1263  * Always returns a newly talloced string belonging to 'ctx'.
1264  *
1265  * Note: If there is no message in the database with the given
1266  * 'message_id' then a new thread_id will be allocated for this
1267  * message and stored in the database metadata, (where this same
1268  * thread ID can be looked up if the message is added to the database
1269  * later).
1270  */
1271 static const char *
1272 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1273                                   void *ctx,
1274                                   const char *message_id)
1275 {
1276     notmuch_message_t *message;
1277     string thread_id_string;
1278     const char *thread_id;
1279     char *metadata_key;
1280     Xapian::WritableDatabase *db;
1281
1282     message = notmuch_database_find_message (notmuch, message_id);
1283
1284     if (message) {
1285         thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1286
1287         notmuch_message_destroy (message);
1288
1289         return thread_id;
1290     }
1291
1292     /* Message has not been seen yet.
1293      *
1294      * We may have seen a reference to it already, in which case, we
1295      * can return the thread ID stored in the metadata. Otherwise, we
1296      * generate a new thread ID and store it there.
1297      */
1298     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1299     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1300     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1301
1302     if (thread_id_string.empty()) {
1303         thread_id = _notmuch_database_generate_thread_id (notmuch);
1304         db->set_metadata (metadata_key, thread_id);
1305     } else {
1306         thread_id = thread_id_string.c_str();
1307     }
1308
1309     talloc_free (metadata_key);
1310
1311     return talloc_strdup (ctx, thread_id);
1312 }
1313
1314 static notmuch_status_t
1315 _merge_threads (notmuch_database_t *notmuch,
1316                 const char *winner_thread_id,
1317                 const char *loser_thread_id)
1318 {
1319     Xapian::PostingIterator loser, loser_end;
1320     notmuch_message_t *message = NULL;
1321     notmuch_private_status_t private_status;
1322     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1323
1324     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1325
1326     for ( ; loser != loser_end; loser++) {
1327         message = _notmuch_message_create (notmuch, notmuch,
1328                                            *loser, &private_status);
1329         if (message == NULL) {
1330             ret = COERCE_STATUS (private_status,
1331                                  "Cannot find document for doc_id from query");
1332             goto DONE;
1333         }
1334
1335         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1336         _notmuch_message_add_term (message, "thread", winner_thread_id);
1337         _notmuch_message_sync (message);
1338
1339         notmuch_message_destroy (message);
1340         message = NULL;
1341     }
1342
1343   DONE:
1344     if (message)
1345         notmuch_message_destroy (message);
1346
1347     return ret;
1348 }
1349
1350 static void
1351 _my_talloc_free_for_g_hash (void *ptr)
1352 {
1353     talloc_free (ptr);
1354 }
1355
1356 static notmuch_status_t
1357 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1358                                            notmuch_message_t *message,
1359                                            notmuch_message_file_t *message_file,
1360                                            const char **thread_id)
1361 {
1362     GHashTable *parents = NULL;
1363     const char *refs, *in_reply_to, *in_reply_to_message_id;
1364     GList *l, *keys = NULL;
1365     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1366
1367     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1368                                      _my_talloc_free_for_g_hash, NULL);
1369
1370     refs = notmuch_message_file_get_header (message_file, "references");
1371     parse_references (message, notmuch_message_get_message_id (message),
1372                       parents, refs);
1373
1374     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1375     parse_references (message, notmuch_message_get_message_id (message),
1376                       parents, in_reply_to);
1377
1378     /* Carefully avoid adding any self-referential in-reply-to term. */
1379     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1380     if (in_reply_to_message_id &&
1381         strcmp (in_reply_to_message_id,
1382                 notmuch_message_get_message_id (message)))
1383     {
1384         _notmuch_message_add_term (message, "replyto",
1385                              _parse_message_id (message, in_reply_to, NULL));
1386     }
1387
1388     keys = g_hash_table_get_keys (parents);
1389     for (l = keys; l; l = l->next) {
1390         char *parent_message_id;
1391         const char *parent_thread_id;
1392
1393         parent_message_id = (char *) l->data;
1394
1395         _notmuch_message_add_term (message, "reference",
1396                                    parent_message_id);
1397
1398         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1399                                                              message,
1400                                                              parent_message_id);
1401
1402         if (*thread_id == NULL) {
1403             *thread_id = talloc_strdup (message, parent_thread_id);
1404             _notmuch_message_add_term (message, "thread", *thread_id);
1405         } else if (strcmp (*thread_id, parent_thread_id)) {
1406             ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1407             if (ret)
1408                 goto DONE;
1409         }
1410     }
1411
1412   DONE:
1413     if (keys)
1414         g_list_free (keys);
1415     if (parents)
1416         g_hash_table_unref (parents);
1417
1418     return ret;
1419 }
1420
1421 static notmuch_status_t
1422 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1423                                             notmuch_message_t *message,
1424                                             const char **thread_id)
1425 {
1426     const char *message_id = notmuch_message_get_message_id (message);
1427     Xapian::PostingIterator child, children_end;
1428     notmuch_message_t *child_message = NULL;
1429     const char *child_thread_id;
1430     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1431     notmuch_private_status_t private_status;
1432
1433     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1434
1435     for ( ; child != children_end; child++) {
1436
1437         child_message = _notmuch_message_create (message, notmuch,
1438                                                  *child, &private_status);
1439         if (child_message == NULL) {
1440             ret = COERCE_STATUS (private_status,
1441                                  "Cannot find document for doc_id from query");
1442             goto DONE;
1443         }
1444
1445         child_thread_id = notmuch_message_get_thread_id (child_message);
1446         if (*thread_id == NULL) {
1447             *thread_id = talloc_strdup (message, child_thread_id);
1448             _notmuch_message_add_term (message, "thread", *thread_id);
1449         } else if (strcmp (*thread_id, child_thread_id)) {
1450             _notmuch_message_remove_term (child_message, "reference",
1451                                           message_id);
1452             _notmuch_message_sync (child_message);
1453             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1454             if (ret)
1455                 goto DONE;
1456         }
1457
1458         notmuch_message_destroy (child_message);
1459         child_message = NULL;
1460     }
1461
1462   DONE:
1463     if (child_message)
1464         notmuch_message_destroy (child_message);
1465
1466     return ret;
1467 }
1468
1469 /* Given a (mostly empty) 'message' and its corresponding
1470  * 'message_file' link it to existing threads in the database.
1471  *
1472  * The first check is in the metadata of the database to see if we
1473  * have pre-allocated a thread_id in advance for this message, (which
1474  * would have happened if a message was previously added that
1475  * referenced this one).
1476  *
1477  * Second, we look at 'message_file' and its link-relevant headers
1478  * (References and In-Reply-To) for message IDs.
1479  *
1480  * Finally, we look in the database for existing message that
1481  * reference 'message'.
1482  *
1483  * In all cases, we assign to the current message the first thread_id
1484  * found (through either parent or child). We will also merge any
1485  * existing, distinct threads where this message belongs to both,
1486  * (which is not uncommon when mesages are processed out of order).
1487  *
1488  * Finally, if no thread ID has been found through parent or child, we
1489  * call _notmuch_message_generate_thread_id to generate a new thread
1490  * ID. This should only happen for new, top-level messages, (no
1491  * References or In-Reply-To header in this message, and no previously
1492  * added message refers to this message).
1493  */
1494 static notmuch_status_t
1495 _notmuch_database_link_message (notmuch_database_t *notmuch,
1496                                 notmuch_message_t *message,
1497                                 notmuch_message_file_t *message_file)
1498 {
1499     notmuch_status_t status;
1500     const char *message_id, *thread_id = NULL;
1501     char *metadata_key;
1502     string stored_id;
1503
1504     message_id = notmuch_message_get_message_id (message);
1505     metadata_key = _get_metadata_thread_id_key (message, message_id);
1506
1507     /* Check if we have already seen related messages to this one.
1508      * If we have then use the thread_id that we stored at that time.
1509      */
1510     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1511     if (! stored_id.empty()) {
1512         Xapian::WritableDatabase *db;
1513
1514         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1515
1516         /* Clear the metadata for this message ID. We don't need it
1517          * anymore. */
1518         db->set_metadata (metadata_key, "");
1519         thread_id = stored_id.c_str();
1520
1521         _notmuch_message_add_term (message, "thread", thread_id);
1522     }
1523     talloc_free (metadata_key);
1524
1525     status = _notmuch_database_link_message_to_parents (notmuch, message,
1526                                                         message_file,
1527                                                         &thread_id);
1528     if (status)
1529         return status;
1530
1531     status = _notmuch_database_link_message_to_children (notmuch, message,
1532                                                          &thread_id);
1533     if (status)
1534         return status;
1535
1536     /* If not part of any existing thread, generate a new thread ID. */
1537     if (thread_id == NULL) {
1538         thread_id = _notmuch_database_generate_thread_id (notmuch);
1539
1540         _notmuch_message_add_term (message, "thread", thread_id);
1541     }
1542
1543     return NOTMUCH_STATUS_SUCCESS;
1544 }
1545
1546 notmuch_status_t
1547 notmuch_database_add_message (notmuch_database_t *notmuch,
1548                               const char *filename,
1549                               notmuch_message_t **message_ret)
1550 {
1551     notmuch_message_file_t *message_file;
1552     notmuch_message_t *message = NULL;
1553     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1554     notmuch_private_status_t private_status;
1555
1556     const char *date, *header;
1557     const char *from, *to, *subject;
1558     char *message_id = NULL;
1559
1560     if (message_ret)
1561         *message_ret = NULL;
1562
1563     ret = _notmuch_database_ensure_writable (notmuch);
1564     if (ret)
1565         return ret;
1566
1567     message_file = notmuch_message_file_open (filename);
1568     if (message_file == NULL)
1569         return NOTMUCH_STATUS_FILE_ERROR;
1570
1571     notmuch_message_file_restrict_headers (message_file,
1572                                            "date",
1573                                            "from",
1574                                            "in-reply-to",
1575                                            "message-id",
1576                                            "references",
1577                                            "subject",
1578                                            "to",
1579                                            (char *) NULL);
1580
1581     try {
1582         /* Before we do any real work, (especially before doing a
1583          * potential SHA-1 computation on the entire file's contents),
1584          * let's make sure that what we're looking at looks like an
1585          * actual email message.
1586          */
1587         from = notmuch_message_file_get_header (message_file, "from");
1588         subject = notmuch_message_file_get_header (message_file, "subject");
1589         to = notmuch_message_file_get_header (message_file, "to");
1590
1591         if ((from == NULL || *from == '\0') &&
1592             (subject == NULL || *subject == '\0') &&
1593             (to == NULL || *to == '\0'))
1594         {
1595             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1596             goto DONE;
1597         }
1598
1599         /* Now that we're sure it's mail, the first order of business
1600          * is to find a message ID (or else create one ourselves). */
1601
1602         header = notmuch_message_file_get_header (message_file, "message-id");
1603         if (header && *header != '\0') {
1604             message_id = _parse_message_id (message_file, header, NULL);
1605
1606             /* So the header value isn't RFC-compliant, but it's
1607              * better than no message-id at all. */
1608             if (message_id == NULL)
1609                 message_id = talloc_strdup (message_file, header);
1610
1611             /* If a message ID is too long, substitute its sha1 instead. */
1612             if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1613                 char *compressed = _message_id_compressed (message_file,
1614                                                            message_id);
1615                 talloc_free (message_id);
1616                 message_id = compressed;
1617             }
1618         }
1619
1620         if (message_id == NULL ) {
1621             /* No message-id at all, let's generate one by taking a
1622              * hash over the file's contents. */
1623             char *sha1 = notmuch_sha1_of_file (filename);
1624
1625             /* If that failed too, something is really wrong. Give up. */
1626             if (sha1 == NULL) {
1627                 ret = NOTMUCH_STATUS_FILE_ERROR;
1628                 goto DONE;
1629             }
1630
1631             message_id = talloc_asprintf (message_file,
1632                                           "notmuch-sha1-%s", sha1);
1633             free (sha1);
1634         }
1635
1636         /* Now that we have a message ID, we get a message object,
1637          * (which may or may not reference an existing document in the
1638          * database). */
1639
1640         message = _notmuch_message_create_for_message_id (notmuch,
1641                                                           message_id,
1642                                                           &private_status);
1643
1644         talloc_free (message_id);
1645
1646         if (message == NULL) {
1647             ret = COERCE_STATUS (private_status,
1648                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1649             goto DONE;
1650         }
1651
1652         _notmuch_message_add_filename (message, filename);
1653
1654         /* This is a new message or it has a new filename and as such,
1655          * its tags in database either do not exists or might be out
1656          * of date. We assign the tags later in notmuch new, but until
1657          * then we should not synchronize the tags back to the maildir
1658          * flags (if notmuch is configured to do so). */
1659         notmuch_message_set_flag(message, NOTMUCH_MESSAGE_FLAG_TAGS_INVALID, TRUE);
1660
1661         /* Is this a newly created message object? */
1662         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1663             _notmuch_message_add_term (message, "type", "mail");
1664
1665             ret = _notmuch_database_link_message (notmuch, message,
1666                                                   message_file);
1667             if (ret)
1668                 goto DONE;
1669
1670             date = notmuch_message_file_get_header (message_file, "date");
1671             _notmuch_message_set_date (message, date);
1672
1673             _notmuch_message_index_file (message, filename);
1674         } else {
1675             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1676         }
1677
1678         _notmuch_message_sync (message);
1679     } catch (const Xapian::Error &error) {
1680         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1681                  error.get_msg().c_str());
1682         notmuch->exception_reported = TRUE;
1683         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1684         goto DONE;
1685     }
1686
1687   DONE:
1688     if (message) {
1689         if ((ret == NOTMUCH_STATUS_SUCCESS ||
1690              ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
1691             *message_ret = message;
1692         else
1693             notmuch_message_destroy (message);
1694     }
1695
1696     if (message_file)
1697         notmuch_message_file_close (message_file);
1698
1699     return ret;
1700 }
1701
1702 notmuch_status_t
1703 notmuch_database_remove_message (notmuch_database_t *notmuch,
1704                                  const char *filename)
1705 {
1706     Xapian::WritableDatabase *db;
1707     void *local;
1708     const char *prefix = _find_prefix ("file-direntry");
1709     char *direntry, *term;
1710     Xapian::PostingIterator i, end;
1711     Xapian::Document document;
1712     notmuch_status_t status;
1713
1714     status = _notmuch_database_ensure_writable (notmuch);
1715     if (status)
1716         return status;
1717
1718     local = talloc_new (notmuch);
1719
1720     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1721
1722     try {
1723
1724         status = _notmuch_database_filename_to_direntry (local, notmuch,
1725                                                          filename, &direntry);
1726         if (status)
1727             return status;
1728
1729         term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1730
1731         find_doc_ids_for_term (notmuch, term, &i, &end);
1732
1733         for ( ; i != end; i++) {
1734             Xapian::TermIterator j;
1735
1736             document = find_document_for_doc_id (notmuch, *i);
1737
1738             document.remove_term (term);
1739
1740             j = document.termlist_begin ();
1741             j.skip_to (prefix);
1742
1743             /* Was this the last file-direntry in the message? */
1744             if (j == document.termlist_end () ||
1745                 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1746             {
1747                 db->delete_document (document.get_docid ());
1748                 status = NOTMUCH_STATUS_SUCCESS;
1749             } else {
1750                 db->replace_document (document.get_docid (), document);
1751                 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1752             }
1753         }
1754     } catch (const Xapian::Error &error) {
1755         fprintf (stderr, "Error: A Xapian exception occurred removing message: %s\n",
1756                  error.get_msg().c_str());
1757         notmuch->exception_reported = TRUE;
1758         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1759     }
1760
1761     talloc_free (local);
1762
1763     return status;
1764 }
1765
1766 notmuch_tags_t *
1767 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1768                        Xapian::TermIterator &end)
1769 {
1770     const char *prefix = _find_prefix ("tag");
1771     notmuch_tags_t *tags;
1772     std::string tag;
1773
1774     /* Currently this iteration is written with the assumption that
1775      * "tag" has a single-character prefix. */
1776     assert (strlen (prefix) == 1);
1777
1778     tags = _notmuch_tags_create (ctx);
1779     if (unlikely (tags == NULL))
1780         return NULL;
1781
1782     i.skip_to (prefix);
1783
1784     while (i != end) {
1785         tag = *i;
1786
1787         if (tag.empty () || tag[0] != *prefix)
1788             break;
1789
1790         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1791
1792         i++;
1793     }
1794
1795     _notmuch_tags_prepare_iterator (tags);
1796
1797     return tags;
1798 }
1799
1800 notmuch_tags_t *
1801 notmuch_database_get_all_tags (notmuch_database_t *db)
1802 {
1803     Xapian::TermIterator i, end;
1804
1805     try {
1806         i = db->xapian_db->allterms_begin();
1807         end = db->xapian_db->allterms_end();
1808         return _notmuch_convert_tags(db, i, end);
1809     } catch (const Xapian::Error &error) {
1810         fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1811                  error.get_msg().c_str());
1812         db->exception_reported = TRUE;
1813         return NULL;
1814     }
1815 }