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