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