]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib/cli: Make notmuch_database_create return a status code
[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_status_t
524 notmuch_database_create (const char *path, notmuch_database_t **database)
525 {
526     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
527     notmuch_database_t *notmuch = NULL;
528     char *notmuch_path = NULL;
529     struct stat st;
530     int err;
531
532     if (path == NULL) {
533         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
534         status = NOTMUCH_STATUS_NULL_POINTER;
535         goto DONE;
536     }
537
538     err = stat (path, &st);
539     if (err) {
540         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
541                  path, strerror (errno));
542         status = NOTMUCH_STATUS_FILE_ERROR;
543         goto DONE;
544     }
545
546     if (! S_ISDIR (st.st_mode)) {
547         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
548                  path);
549         status = NOTMUCH_STATUS_FILE_ERROR;
550         goto DONE;
551     }
552
553     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
554
555     err = mkdir (notmuch_path, 0755);
556
557     if (err) {
558         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
559                  notmuch_path, strerror (errno));
560         status = NOTMUCH_STATUS_FILE_ERROR;
561         goto DONE;
562     }
563
564     status = notmuch_database_open (path,
565                                     NOTMUCH_DATABASE_MODE_READ_WRITE,
566                                     &notmuch);
567     if (status)
568         goto DONE;
569     status = notmuch_database_upgrade (notmuch, NULL, NULL);
570     if (status) {
571         notmuch_database_close(notmuch);
572         notmuch = NULL;
573     }
574
575   DONE:
576     if (notmuch_path)
577         talloc_free (notmuch_path);
578
579     if (database)
580         *database = notmuch;
581     else
582         talloc_free (notmuch);
583     return status;
584 }
585
586 notmuch_status_t
587 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
588 {
589     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
590         fprintf (stderr, "Cannot write to a read-only database.\n");
591         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
592     }
593
594     return NOTMUCH_STATUS_SUCCESS;
595 }
596
597 notmuch_status_t
598 notmuch_database_open (const char *path,
599                        notmuch_database_mode_t mode,
600                        notmuch_database_t **database)
601 {
602     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
603     void *local = talloc_new (NULL);
604     notmuch_database_t *notmuch = NULL;
605     char *notmuch_path, *xapian_path;
606     struct stat st;
607     int err;
608     unsigned int i, version;
609     static int initialized = 0;
610
611     if (path == NULL) {
612         fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
613         status = NOTMUCH_STATUS_NULL_POINTER;
614         goto DONE;
615     }
616
617     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
618         fprintf (stderr, "Out of memory\n");
619         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
620         goto DONE;
621     }
622
623     err = stat (notmuch_path, &st);
624     if (err) {
625         fprintf (stderr, "Error opening database at %s: %s\n",
626                  notmuch_path, strerror (errno));
627         status = NOTMUCH_STATUS_FILE_ERROR;
628         goto DONE;
629     }
630
631     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
632         fprintf (stderr, "Out of memory\n");
633         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
634         goto DONE;
635     }
636
637     /* Initialize the GLib type system and threads */
638     g_type_init ();
639
640     /* Initialize gmime */
641     if (! initialized) {
642         g_mime_init (0);
643         initialized = 1;
644     }
645
646     notmuch = talloc_zero (NULL, notmuch_database_t);
647     notmuch->exception_reported = FALSE;
648     notmuch->path = talloc_strdup (notmuch, path);
649
650     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
651         notmuch->path[strlen (notmuch->path) - 1] = '\0';
652
653     notmuch->needs_upgrade = FALSE;
654     notmuch->mode = mode;
655     notmuch->atomic_nesting = 0;
656     try {
657         string last_thread_id;
658
659         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
660             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
661                                                                Xapian::DB_CREATE_OR_OPEN);
662             version = notmuch_database_get_version (notmuch);
663
664             if (version > NOTMUCH_DATABASE_VERSION) {
665                 fprintf (stderr,
666                          "Error: Notmuch database at %s\n"
667                          "       has a newer database format version (%u) than supported by this\n"
668                          "       version of notmuch (%u). Refusing to open this database in\n"
669                          "       read-write mode.\n",
670                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
671                 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
672                 notmuch_database_destroy (notmuch);
673                 notmuch = NULL;
674                 status = NOTMUCH_STATUS_FILE_ERROR;
675                 goto DONE;
676             }
677
678             if (version < NOTMUCH_DATABASE_VERSION)
679                 notmuch->needs_upgrade = TRUE;
680         } else {
681             notmuch->xapian_db = new Xapian::Database (xapian_path);
682             version = notmuch_database_get_version (notmuch);
683             if (version > NOTMUCH_DATABASE_VERSION)
684             {
685                 fprintf (stderr,
686                          "Warning: Notmuch database at %s\n"
687                          "         has a newer database format version (%u) than supported by this\n"
688                          "         version of notmuch (%u). Some operations may behave incorrectly,\n"
689                          "         (but the database will not be harmed since it is being opened\n"
690                          "         in read-only mode).\n",
691                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
692             }
693         }
694
695         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
696         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
697         if (last_thread_id.empty ()) {
698             notmuch->last_thread_id = 0;
699         } else {
700             const char *str;
701             char *end;
702
703             str = last_thread_id.c_str ();
704             notmuch->last_thread_id = strtoull (str, &end, 16);
705             if (*end != '\0')
706                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
707         }
708
709         notmuch->query_parser = new Xapian::QueryParser;
710         notmuch->term_gen = new Xapian::TermGenerator;
711         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
712         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
713
714         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
715         notmuch->query_parser->set_database (*notmuch->xapian_db);
716         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
717         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
718         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
719
720         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
721             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
722             notmuch->query_parser->add_boolean_prefix (prefix->name,
723                                                        prefix->prefix);
724         }
725
726         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
727             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
728             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
729         }
730     } catch (const Xapian::Error &error) {
731         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
732                  error.get_msg().c_str());
733         notmuch_database_destroy (notmuch);
734         notmuch = NULL;
735         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
736     }
737
738   DONE:
739     talloc_free (local);
740
741     if (database)
742         *database = notmuch;
743     else
744         talloc_free (notmuch);
745     return status;
746 }
747
748 void
749 notmuch_database_close (notmuch_database_t *notmuch)
750 {
751     try {
752         if (notmuch->xapian_db != NULL &&
753             notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
754             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
755     } catch (const Xapian::Error &error) {
756         if (! notmuch->exception_reported) {
757             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
758                      error.get_msg().c_str());
759         }
760     }
761
762     /* Many Xapian objects (and thus notmuch objects) hold references to
763      * the database, so merely deleting the database may not suffice to
764      * close it.  Thus, we explicitly close it here. */
765     if (notmuch->xapian_db != NULL) {
766         try {
767             notmuch->xapian_db->close();
768         } catch (const Xapian::Error &error) {
769             /* do nothing */
770         }
771     }
772
773     delete notmuch->term_gen;
774     notmuch->term_gen = NULL;
775     delete notmuch->query_parser;
776     notmuch->query_parser = NULL;
777     delete notmuch->xapian_db;
778     notmuch->xapian_db = NULL;
779     delete notmuch->value_range_processor;
780     notmuch->value_range_processor = NULL;
781 }
782
783 void
784 notmuch_database_destroy (notmuch_database_t *notmuch)
785 {
786     notmuch_database_close (notmuch);
787     talloc_free (notmuch);
788 }
789
790 const char *
791 notmuch_database_get_path (notmuch_database_t *notmuch)
792 {
793     return notmuch->path;
794 }
795
796 unsigned int
797 notmuch_database_get_version (notmuch_database_t *notmuch)
798 {
799     unsigned int version;
800     string version_string;
801     const char *str;
802     char *end;
803
804     version_string = notmuch->xapian_db->get_metadata ("version");
805     if (version_string.empty ())
806         return 0;
807
808     str = version_string.c_str ();
809     if (str == NULL || *str == '\0')
810         return 0;
811
812     version = strtoul (str, &end, 10);
813     if (*end != '\0')
814         INTERNAL_ERROR ("Malformed database version: %s", str);
815
816     return version;
817 }
818
819 notmuch_bool_t
820 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
821 {
822     return notmuch->needs_upgrade;
823 }
824
825 static volatile sig_atomic_t do_progress_notify = 0;
826
827 static void
828 handle_sigalrm (unused (int signal))
829 {
830     do_progress_notify = 1;
831 }
832
833 /* Upgrade the current database.
834  *
835  * After opening a database in read-write mode, the client should
836  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
837  * if so, upgrade with this function before making any modifications.
838  *
839  * The optional progress_notify callback can be used by the caller to
840  * provide progress indication to the user. If non-NULL it will be
841  * called periodically with 'count' as the number of messages upgraded
842  * so far and 'total' the overall number of messages that will be
843  * converted.
844  */
845 notmuch_status_t
846 notmuch_database_upgrade (notmuch_database_t *notmuch,
847                           void (*progress_notify) (void *closure,
848                                                    double progress),
849                           void *closure)
850 {
851     Xapian::WritableDatabase *db;
852     struct sigaction action;
853     struct itimerval timerval;
854     notmuch_bool_t timer_is_active = FALSE;
855     unsigned int version;
856     notmuch_status_t status;
857     unsigned int count = 0, total = 0;
858
859     status = _notmuch_database_ensure_writable (notmuch);
860     if (status)
861         return status;
862
863     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
864
865     version = notmuch_database_get_version (notmuch);
866
867     if (version >= NOTMUCH_DATABASE_VERSION)
868         return NOTMUCH_STATUS_SUCCESS;
869
870     if (progress_notify) {
871         /* Setup our handler for SIGALRM */
872         memset (&action, 0, sizeof (struct sigaction));
873         action.sa_handler = handle_sigalrm;
874         sigemptyset (&action.sa_mask);
875         action.sa_flags = SA_RESTART;
876         sigaction (SIGALRM, &action, NULL);
877
878         /* Then start a timer to send SIGALRM once per second. */
879         timerval.it_interval.tv_sec = 1;
880         timerval.it_interval.tv_usec = 0;
881         timerval.it_value.tv_sec = 1;
882         timerval.it_value.tv_usec = 0;
883         setitimer (ITIMER_REAL, &timerval, NULL);
884
885         timer_is_active = TRUE;
886     }
887
888     /* Before version 1, each message document had its filename in the
889      * data field. Copy that into the new format by calling
890      * notmuch_message_add_filename.
891      */
892     if (version < 1) {
893         notmuch_query_t *query = notmuch_query_create (notmuch, "");
894         notmuch_messages_t *messages;
895         notmuch_message_t *message;
896         char *filename;
897         Xapian::TermIterator t, t_end;
898
899         total = notmuch_query_count_messages (query);
900
901         for (messages = notmuch_query_search_messages (query);
902              notmuch_messages_valid (messages);
903              notmuch_messages_move_to_next (messages))
904         {
905             if (do_progress_notify) {
906                 progress_notify (closure, (double) count / total);
907                 do_progress_notify = 0;
908             }
909
910             message = notmuch_messages_get (messages);
911
912             filename = _notmuch_message_talloc_copy_data (message);
913             if (filename && *filename != '\0') {
914                 _notmuch_message_add_filename (message, filename);
915                 _notmuch_message_sync (message);
916             }
917             talloc_free (filename);
918
919             notmuch_message_destroy (message);
920
921             count++;
922         }
923
924         notmuch_query_destroy (query);
925
926         /* Also, before version 1 we stored directory timestamps in
927          * XTIMESTAMP documents instead of the current XDIRECTORY
928          * documents. So copy those as well. */
929
930         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
931
932         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
933              t != t_end;
934              t++)
935         {
936             Xapian::PostingIterator p, p_end;
937             std::string term = *t;
938
939             p_end = notmuch->xapian_db->postlist_end (term);
940
941             for (p = notmuch->xapian_db->postlist_begin (term);
942                  p != p_end;
943                  p++)
944             {
945                 Xapian::Document document;
946                 time_t mtime;
947                 notmuch_directory_t *directory;
948
949                 if (do_progress_notify) {
950                     progress_notify (closure, (double) count / total);
951                     do_progress_notify = 0;
952                 }
953
954                 document = find_document_for_doc_id (notmuch, *p);
955                 mtime = Xapian::sortable_unserialise (
956                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
957
958                 directory = notmuch_database_get_directory (notmuch,
959                                                             term.c_str() + 10);
960                 notmuch_directory_set_mtime (directory, mtime);
961                 notmuch_directory_destroy (directory);
962             }
963         }
964     }
965
966     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
967     db->flush ();
968
969     /* Now that the upgrade is complete we can remove the old data
970      * and documents that are no longer needed. */
971     if (version < 1) {
972         notmuch_query_t *query = notmuch_query_create (notmuch, "");
973         notmuch_messages_t *messages;
974         notmuch_message_t *message;
975         char *filename;
976
977         for (messages = notmuch_query_search_messages (query);
978              notmuch_messages_valid (messages);
979              notmuch_messages_move_to_next (messages))
980         {
981             if (do_progress_notify) {
982                 progress_notify (closure, (double) count / total);
983                 do_progress_notify = 0;
984             }
985
986             message = notmuch_messages_get (messages);
987
988             filename = _notmuch_message_talloc_copy_data (message);
989             if (filename && *filename != '\0') {
990                 _notmuch_message_clear_data (message);
991                 _notmuch_message_sync (message);
992             }
993             talloc_free (filename);
994
995             notmuch_message_destroy (message);
996         }
997
998         notmuch_query_destroy (query);
999     }
1000
1001     if (version < 1) {
1002         Xapian::TermIterator t, t_end;
1003
1004         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1005
1006         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1007              t != t_end;
1008              t++)
1009         {
1010             Xapian::PostingIterator p, p_end;
1011             std::string term = *t;
1012
1013             p_end = notmuch->xapian_db->postlist_end (term);
1014
1015             for (p = notmuch->xapian_db->postlist_begin (term);
1016                  p != p_end;
1017                  p++)
1018             {
1019                 if (do_progress_notify) {
1020                     progress_notify (closure, (double) count / total);
1021                     do_progress_notify = 0;
1022                 }
1023
1024                 db->delete_document (*p);
1025             }
1026         }
1027     }
1028
1029     if (timer_is_active) {
1030         /* Now stop the timer. */
1031         timerval.it_interval.tv_sec = 0;
1032         timerval.it_interval.tv_usec = 0;
1033         timerval.it_value.tv_sec = 0;
1034         timerval.it_value.tv_usec = 0;
1035         setitimer (ITIMER_REAL, &timerval, NULL);
1036
1037         /* And disable the signal handler. */
1038         action.sa_handler = SIG_IGN;
1039         sigaction (SIGALRM, &action, NULL);
1040     }
1041
1042     return NOTMUCH_STATUS_SUCCESS;
1043 }
1044
1045 notmuch_status_t
1046 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1047 {
1048     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1049         notmuch->atomic_nesting > 0)
1050         goto DONE;
1051
1052     try {
1053         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1054     } catch (const Xapian::Error &error) {
1055         fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1056                  error.get_msg().c_str());
1057         notmuch->exception_reported = TRUE;
1058         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1059     }
1060
1061 DONE:
1062     notmuch->atomic_nesting++;
1063     return NOTMUCH_STATUS_SUCCESS;
1064 }
1065
1066 notmuch_status_t
1067 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1068 {
1069     Xapian::WritableDatabase *db;
1070
1071     if (notmuch->atomic_nesting == 0)
1072         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1073
1074     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1075         notmuch->atomic_nesting > 1)
1076         goto DONE;
1077
1078     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1079     try {
1080         db->commit_transaction ();
1081
1082         /* This is a hack for testing.  Xapian never flushes on a
1083          * non-flushed commit, even if the flush threshold is 1.
1084          * However, we rely on flushing to test atomicity. */
1085         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1086         if (thresh && atoi (thresh) == 1)
1087             db->flush ();
1088     } catch (const Xapian::Error &error) {
1089         fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1090                  error.get_msg().c_str());
1091         notmuch->exception_reported = TRUE;
1092         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1093     }
1094
1095 DONE:
1096     notmuch->atomic_nesting--;
1097     return NOTMUCH_STATUS_SUCCESS;
1098 }
1099
1100 /* We allow the user to use arbitrarily long paths for directories. But
1101  * we have a term-length limit. So if we exceed that, we'll use the
1102  * SHA-1 of the path for the database term.
1103  *
1104  * Note: This function may return the original value of 'path'. If it
1105  * does not, then the caller is responsible to free() the returned
1106  * value.
1107  */
1108 const char *
1109 _notmuch_database_get_directory_db_path (const char *path)
1110 {
1111     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1112
1113     if (term_len > NOTMUCH_TERM_MAX)
1114         return notmuch_sha1_of_string (path);
1115     else
1116         return path;
1117 }
1118
1119 /* Given a path, split it into two parts: the directory part is all
1120  * components except for the last, and the basename is that last
1121  * component. Getting the return-value for either part is optional
1122  * (the caller can pass NULL).
1123  *
1124  * The original 'path' can represent either a regular file or a
1125  * directory---the splitting will be carried out in the same way in
1126  * either case. Trailing slashes on 'path' will be ignored, and any
1127  * cases of multiple '/' characters appearing in series will be
1128  * treated as a single '/'.
1129  *
1130  * Allocation (if any) will have 'ctx' as the talloc owner. But
1131  * pointers will be returned within the original path string whenever
1132  * possible.
1133  *
1134  * Note: If 'path' is non-empty and contains no non-trailing slash,
1135  * (that is, consists of a filename with no parent directory), then
1136  * the directory returned will be an empty string. However, if 'path'
1137  * is an empty string, then both directory and basename will be
1138  * returned as NULL.
1139  */
1140 notmuch_status_t
1141 _notmuch_database_split_path (void *ctx,
1142                               const char *path,
1143                               const char **directory,
1144                               const char **basename)
1145 {
1146     const char *slash;
1147
1148     if (path == NULL || *path == '\0') {
1149         if (directory)
1150             *directory = NULL;
1151         if (basename)
1152             *basename = NULL;
1153         return NOTMUCH_STATUS_SUCCESS;
1154     }
1155
1156     /* Find the last slash (not counting a trailing slash), if any. */
1157
1158     slash = path + strlen (path) - 1;
1159
1160     /* First, skip trailing slashes. */
1161     while (slash != path) {
1162         if (*slash != '/')
1163             break;
1164
1165         --slash;
1166     }
1167
1168     /* Then, find a slash. */
1169     while (slash != path) {
1170         if (*slash == '/')
1171             break;
1172
1173         if (basename)
1174             *basename = slash;
1175
1176         --slash;
1177     }
1178
1179     /* Finally, skip multiple slashes. */
1180     while (slash != path) {
1181         if (*slash != '/')
1182             break;
1183
1184         --slash;
1185     }
1186
1187     if (slash == path) {
1188         if (directory)
1189             *directory = talloc_strdup (ctx, "");
1190         if (basename)
1191             *basename = path;
1192     } else {
1193         if (directory)
1194             *directory = talloc_strndup (ctx, path, slash - path + 1);
1195     }
1196
1197     return NOTMUCH_STATUS_SUCCESS;
1198 }
1199
1200 notmuch_status_t
1201 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1202                                      const char *path,
1203                                      unsigned int *directory_id)
1204 {
1205     notmuch_directory_t *directory;
1206     notmuch_status_t status;
1207
1208     if (path == NULL) {
1209         *directory_id = 0;
1210         return NOTMUCH_STATUS_SUCCESS;
1211     }
1212
1213     directory = _notmuch_directory_create (notmuch, path, &status);
1214     if (status) {
1215         *directory_id = -1;
1216         return status;
1217     }
1218
1219     *directory_id = _notmuch_directory_get_document_id (directory);
1220
1221     notmuch_directory_destroy (directory);
1222
1223     return NOTMUCH_STATUS_SUCCESS;
1224 }
1225
1226 const char *
1227 _notmuch_database_get_directory_path (void *ctx,
1228                                       notmuch_database_t *notmuch,
1229                                       unsigned int doc_id)
1230 {
1231     Xapian::Document document;
1232
1233     document = find_document_for_doc_id (notmuch, doc_id);
1234
1235     return talloc_strdup (ctx, document.get_data ().c_str ());
1236 }
1237
1238 /* Given a legal 'filename' for the database, (either relative to
1239  * database path or absolute with initial components identical to
1240  * database path), return a new string (with 'ctx' as the talloc
1241  * owner) suitable for use as a direntry term value.
1242  *
1243  * The necessary directory documents will be created in the database
1244  * as needed.
1245  */
1246 notmuch_status_t
1247 _notmuch_database_filename_to_direntry (void *ctx,
1248                                         notmuch_database_t *notmuch,
1249                                         const char *filename,
1250                                         char **direntry)
1251 {
1252     const char *relative, *directory, *basename;
1253     Xapian::docid directory_id;
1254     notmuch_status_t status;
1255
1256     relative = _notmuch_database_relative_path (notmuch, filename);
1257
1258     status = _notmuch_database_split_path (ctx, relative,
1259                                            &directory, &basename);
1260     if (status)
1261         return status;
1262
1263     status = _notmuch_database_find_directory_id (notmuch, directory,
1264                                                   &directory_id);
1265     if (status)
1266         return status;
1267
1268     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1269
1270     return NOTMUCH_STATUS_SUCCESS;
1271 }
1272
1273 /* Given a legal 'path' for the database, return the relative path.
1274  *
1275  * The return value will be a pointer to the original path contents,
1276  * and will be either the original string (if 'path' was relative) or
1277  * a portion of the string (if path was absolute and begins with the
1278  * database path).
1279  */
1280 const char *
1281 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1282                                  const char *path)
1283 {
1284     const char *db_path, *relative;
1285     unsigned int db_path_len;
1286
1287     db_path = notmuch_database_get_path (notmuch);
1288     db_path_len = strlen (db_path);
1289
1290     relative = path;
1291
1292     if (*relative == '/') {
1293         while (*relative == '/' && *(relative+1) == '/')
1294             relative++;
1295
1296         if (strncmp (relative, db_path, db_path_len) == 0)
1297         {
1298             relative += db_path_len;
1299             while (*relative == '/')
1300                 relative++;
1301         }
1302     }
1303
1304     return relative;
1305 }
1306
1307 notmuch_directory_t *
1308 notmuch_database_get_directory (notmuch_database_t *notmuch,
1309                                 const char *path)
1310 {
1311     notmuch_status_t status;
1312
1313     try {
1314         return _notmuch_directory_create (notmuch, path, &status);
1315     } catch (const Xapian::Error &error) {
1316         fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1317                  error.get_msg().c_str());
1318         notmuch->exception_reported = TRUE;
1319         return NULL;
1320     }
1321 }
1322
1323 /* Allocate a document ID that satisfies the following criteria:
1324  *
1325  * 1. The ID does not exist for any document in the Xapian database
1326  *
1327  * 2. The ID was not previously returned from this function
1328  *
1329  * 3. The ID is the smallest integer satisfying (1) and (2)
1330  *
1331  * This function will trigger an internal error if these constraints
1332  * cannot all be satisfied, (that is, the pool of available document
1333  * IDs has been exhausted).
1334  */
1335 unsigned int
1336 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1337 {
1338     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1339
1340     notmuch->last_doc_id++;
1341
1342     if (notmuch->last_doc_id == 0)
1343         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");        
1344
1345     return notmuch->last_doc_id;
1346 }
1347
1348 static const char *
1349 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1350 {
1351     /* 16 bytes (+ terminator) for hexadecimal representation of
1352      * a 64-bit integer. */
1353     static char thread_id[17];
1354     Xapian::WritableDatabase *db;
1355
1356     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1357
1358     notmuch->last_thread_id++;
1359
1360     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1361
1362     db->set_metadata ("last_thread_id", thread_id);
1363
1364     return thread_id;
1365 }
1366
1367 static char *
1368 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1369 {
1370     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1371         message_id = _message_id_compressed (ctx, message_id);
1372
1373     return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1374                             message_id);
1375 }
1376
1377 /* Find the thread ID to which the message with 'message_id' belongs.
1378  *
1379  * Note: 'thread_id_ret' must not be NULL!
1380  * On success '*thread_id_ret' is set to a newly talloced string belonging to
1381  * 'ctx'.
1382  *
1383  * Note: If there is no message in the database with the given
1384  * 'message_id' then a new thread_id will be allocated for this
1385  * message and stored in the database metadata, (where this same
1386  * thread ID can be looked up if the message is added to the database
1387  * later).
1388  */
1389 static notmuch_status_t
1390 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1391                                   void *ctx,
1392                                   const char *message_id,
1393                                   const char **thread_id_ret)
1394 {
1395     notmuch_status_t status;
1396     notmuch_message_t *message;
1397     string thread_id_string;
1398     char *metadata_key;
1399     Xapian::WritableDatabase *db;
1400
1401     status = notmuch_database_find_message (notmuch, message_id, &message);
1402
1403     if (status)
1404         return status;
1405
1406     if (message) {
1407         *thread_id_ret = talloc_steal (ctx,
1408                                        notmuch_message_get_thread_id (message));
1409
1410         notmuch_message_destroy (message);
1411
1412         return NOTMUCH_STATUS_SUCCESS;
1413     }
1414
1415     /* Message has not been seen yet.
1416      *
1417      * We may have seen a reference to it already, in which case, we
1418      * can return the thread ID stored in the metadata. Otherwise, we
1419      * generate a new thread ID and store it there.
1420      */
1421     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1422     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1423     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1424
1425     if (thread_id_string.empty()) {
1426         *thread_id_ret = talloc_strdup (ctx,
1427                                         _notmuch_database_generate_thread_id (notmuch));
1428         db->set_metadata (metadata_key, *thread_id_ret);
1429     } else {
1430         *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1431     }
1432
1433     talloc_free (metadata_key);
1434
1435     return NOTMUCH_STATUS_SUCCESS;
1436 }
1437
1438 static notmuch_status_t
1439 _merge_threads (notmuch_database_t *notmuch,
1440                 const char *winner_thread_id,
1441                 const char *loser_thread_id)
1442 {
1443     Xapian::PostingIterator loser, loser_end;
1444     notmuch_message_t *message = NULL;
1445     notmuch_private_status_t private_status;
1446     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1447
1448     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1449
1450     for ( ; loser != loser_end; loser++) {
1451         message = _notmuch_message_create (notmuch, notmuch,
1452                                            *loser, &private_status);
1453         if (message == NULL) {
1454             ret = COERCE_STATUS (private_status,
1455                                  "Cannot find document for doc_id from query");
1456             goto DONE;
1457         }
1458
1459         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1460         _notmuch_message_add_term (message, "thread", winner_thread_id);
1461         _notmuch_message_sync (message);
1462
1463         notmuch_message_destroy (message);
1464         message = NULL;
1465     }
1466
1467   DONE:
1468     if (message)
1469         notmuch_message_destroy (message);
1470
1471     return ret;
1472 }
1473
1474 static void
1475 _my_talloc_free_for_g_hash (void *ptr)
1476 {
1477     talloc_free (ptr);
1478 }
1479
1480 static notmuch_status_t
1481 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1482                                            notmuch_message_t *message,
1483                                            notmuch_message_file_t *message_file,
1484                                            const char **thread_id)
1485 {
1486     GHashTable *parents = NULL;
1487     const char *refs, *in_reply_to, *in_reply_to_message_id;
1488     GList *l, *keys = NULL;
1489     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1490
1491     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1492                                      _my_talloc_free_for_g_hash, NULL);
1493
1494     refs = notmuch_message_file_get_header (message_file, "references");
1495     parse_references (message, notmuch_message_get_message_id (message),
1496                       parents, refs);
1497
1498     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1499     parse_references (message, notmuch_message_get_message_id (message),
1500                       parents, in_reply_to);
1501
1502     /* Carefully avoid adding any self-referential in-reply-to term. */
1503     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1504     if (in_reply_to_message_id &&
1505         strcmp (in_reply_to_message_id,
1506                 notmuch_message_get_message_id (message)))
1507     {
1508         _notmuch_message_add_term (message, "replyto",
1509                              _parse_message_id (message, in_reply_to, NULL));
1510     }
1511
1512     keys = g_hash_table_get_keys (parents);
1513     for (l = keys; l; l = l->next) {
1514         char *parent_message_id;
1515         const char *parent_thread_id = NULL;
1516
1517         parent_message_id = (char *) l->data;
1518
1519         _notmuch_message_add_term (message, "reference",
1520                                    parent_message_id);
1521
1522         ret = _resolve_message_id_to_thread_id (notmuch,
1523                                                 message,
1524                                                 parent_message_id,
1525                                                 &parent_thread_id);
1526         if (ret)
1527             goto DONE;
1528
1529         if (*thread_id == NULL) {
1530             *thread_id = talloc_strdup (message, parent_thread_id);
1531             _notmuch_message_add_term (message, "thread", *thread_id);
1532         } else if (strcmp (*thread_id, parent_thread_id)) {
1533             ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1534             if (ret)
1535                 goto DONE;
1536         }
1537     }
1538
1539   DONE:
1540     if (keys)
1541         g_list_free (keys);
1542     if (parents)
1543         g_hash_table_unref (parents);
1544
1545     return ret;
1546 }
1547
1548 static notmuch_status_t
1549 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1550                                             notmuch_message_t *message,
1551                                             const char **thread_id)
1552 {
1553     const char *message_id = notmuch_message_get_message_id (message);
1554     Xapian::PostingIterator child, children_end;
1555     notmuch_message_t *child_message = NULL;
1556     const char *child_thread_id;
1557     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1558     notmuch_private_status_t private_status;
1559
1560     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1561
1562     for ( ; child != children_end; child++) {
1563
1564         child_message = _notmuch_message_create (message, notmuch,
1565                                                  *child, &private_status);
1566         if (child_message == NULL) {
1567             ret = COERCE_STATUS (private_status,
1568                                  "Cannot find document for doc_id from query");
1569             goto DONE;
1570         }
1571
1572         child_thread_id = notmuch_message_get_thread_id (child_message);
1573         if (*thread_id == NULL) {
1574             *thread_id = talloc_strdup (message, child_thread_id);
1575             _notmuch_message_add_term (message, "thread", *thread_id);
1576         } else if (strcmp (*thread_id, child_thread_id)) {
1577             _notmuch_message_remove_term (child_message, "reference",
1578                                           message_id);
1579             _notmuch_message_sync (child_message);
1580             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1581             if (ret)
1582                 goto DONE;
1583         }
1584
1585         notmuch_message_destroy (child_message);
1586         child_message = NULL;
1587     }
1588
1589   DONE:
1590     if (child_message)
1591         notmuch_message_destroy (child_message);
1592
1593     return ret;
1594 }
1595
1596 /* Given a (mostly empty) 'message' and its corresponding
1597  * 'message_file' link it to existing threads in the database.
1598  *
1599  * The first check is in the metadata of the database to see if we
1600  * have pre-allocated a thread_id in advance for this message, (which
1601  * would have happened if a message was previously added that
1602  * referenced this one).
1603  *
1604  * Second, we look at 'message_file' and its link-relevant headers
1605  * (References and In-Reply-To) for message IDs.
1606  *
1607  * Finally, we look in the database for existing message that
1608  * reference 'message'.
1609  *
1610  * In all cases, we assign to the current message the first thread_id
1611  * found (through either parent or child). We will also merge any
1612  * existing, distinct threads where this message belongs to both,
1613  * (which is not uncommon when messages are processed out of order).
1614  *
1615  * Finally, if no thread ID has been found through parent or child, we
1616  * call _notmuch_message_generate_thread_id to generate a new thread
1617  * ID. This should only happen for new, top-level messages, (no
1618  * References or In-Reply-To header in this message, and no previously
1619  * added message refers to this message).
1620  */
1621 static notmuch_status_t
1622 _notmuch_database_link_message (notmuch_database_t *notmuch,
1623                                 notmuch_message_t *message,
1624                                 notmuch_message_file_t *message_file)
1625 {
1626     notmuch_status_t status;
1627     const char *message_id, *thread_id = NULL;
1628     char *metadata_key;
1629     string stored_id;
1630
1631     message_id = notmuch_message_get_message_id (message);
1632     metadata_key = _get_metadata_thread_id_key (message, message_id);
1633
1634     /* Check if we have already seen related messages to this one.
1635      * If we have then use the thread_id that we stored at that time.
1636      */
1637     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1638     if (! stored_id.empty()) {
1639         Xapian::WritableDatabase *db;
1640
1641         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1642
1643         /* Clear the metadata for this message ID. We don't need it
1644          * anymore. */
1645         db->set_metadata (metadata_key, "");
1646         thread_id = stored_id.c_str();
1647
1648         _notmuch_message_add_term (message, "thread", thread_id);
1649     }
1650     talloc_free (metadata_key);
1651
1652     status = _notmuch_database_link_message_to_parents (notmuch, message,
1653                                                         message_file,
1654                                                         &thread_id);
1655     if (status)
1656         return status;
1657
1658     status = _notmuch_database_link_message_to_children (notmuch, message,
1659                                                          &thread_id);
1660     if (status)
1661         return status;
1662
1663     /* If not part of any existing thread, generate a new thread ID. */
1664     if (thread_id == NULL) {
1665         thread_id = _notmuch_database_generate_thread_id (notmuch);
1666
1667         _notmuch_message_add_term (message, "thread", thread_id);
1668     }
1669
1670     return NOTMUCH_STATUS_SUCCESS;
1671 }
1672
1673 notmuch_status_t
1674 notmuch_database_add_message (notmuch_database_t *notmuch,
1675                               const char *filename,
1676                               notmuch_message_t **message_ret)
1677 {
1678     notmuch_message_file_t *message_file;
1679     notmuch_message_t *message = NULL;
1680     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
1681     notmuch_private_status_t private_status;
1682
1683     const char *date, *header;
1684     const char *from, *to, *subject;
1685     char *message_id = NULL;
1686
1687     if (message_ret)
1688         *message_ret = NULL;
1689
1690     ret = _notmuch_database_ensure_writable (notmuch);
1691     if (ret)
1692         return ret;
1693
1694     message_file = notmuch_message_file_open (filename);
1695     if (message_file == NULL)
1696         return NOTMUCH_STATUS_FILE_ERROR;
1697
1698     /* Adding a message may change many documents.  Do this all
1699      * atomically. */
1700     ret = notmuch_database_begin_atomic (notmuch);
1701     if (ret)
1702         goto DONE;
1703
1704     notmuch_message_file_restrict_headers (message_file,
1705                                            "date",
1706                                            "from",
1707                                            "in-reply-to",
1708                                            "message-id",
1709                                            "references",
1710                                            "subject",
1711                                            "to",
1712                                            (char *) NULL);
1713
1714     try {
1715         /* Before we do any real work, (especially before doing a
1716          * potential SHA-1 computation on the entire file's contents),
1717          * let's make sure that what we're looking at looks like an
1718          * actual email message.
1719          */
1720         from = notmuch_message_file_get_header (message_file, "from");
1721         subject = notmuch_message_file_get_header (message_file, "subject");
1722         to = notmuch_message_file_get_header (message_file, "to");
1723
1724         if ((from == NULL || *from == '\0') &&
1725             (subject == NULL || *subject == '\0') &&
1726             (to == NULL || *to == '\0'))
1727         {
1728             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1729             goto DONE;
1730         }
1731
1732         /* Now that we're sure it's mail, the first order of business
1733          * is to find a message ID (or else create one ourselves). */
1734
1735         header = notmuch_message_file_get_header (message_file, "message-id");
1736         if (header && *header != '\0') {
1737             message_id = _parse_message_id (message_file, header, NULL);
1738
1739             /* So the header value isn't RFC-compliant, but it's
1740              * better than no message-id at all. */
1741             if (message_id == NULL)
1742                 message_id = talloc_strdup (message_file, header);
1743
1744             /* If a message ID is too long, substitute its sha1 instead. */
1745             if (message_id && strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX) {
1746                 char *compressed = _message_id_compressed (message_file,
1747                                                            message_id);
1748                 talloc_free (message_id);
1749                 message_id = compressed;
1750             }
1751         }
1752
1753         if (message_id == NULL ) {
1754             /* No message-id at all, let's generate one by taking a
1755              * hash over the file's contents. */
1756             char *sha1 = notmuch_sha1_of_file (filename);
1757
1758             /* If that failed too, something is really wrong. Give up. */
1759             if (sha1 == NULL) {
1760                 ret = NOTMUCH_STATUS_FILE_ERROR;
1761                 goto DONE;
1762             }
1763
1764             message_id = talloc_asprintf (message_file,
1765                                           "notmuch-sha1-%s", sha1);
1766             free (sha1);
1767         }
1768
1769         /* Now that we have a message ID, we get a message object,
1770          * (which may or may not reference an existing document in the
1771          * database). */
1772
1773         message = _notmuch_message_create_for_message_id (notmuch,
1774                                                           message_id,
1775                                                           &private_status);
1776
1777         talloc_free (message_id);
1778
1779         if (message == NULL) {
1780             ret = COERCE_STATUS (private_status,
1781                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1782             goto DONE;
1783         }
1784
1785         _notmuch_message_add_filename (message, filename);
1786
1787         /* Is this a newly created message object? */
1788         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1789             _notmuch_message_add_term (message, "type", "mail");
1790
1791             ret = _notmuch_database_link_message (notmuch, message,
1792                                                   message_file);
1793             if (ret)
1794                 goto DONE;
1795
1796             date = notmuch_message_file_get_header (message_file, "date");
1797             _notmuch_message_set_header_values (message, date, from, subject);
1798
1799             _notmuch_message_index_file (message, filename);
1800         } else {
1801             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1802         }
1803
1804         _notmuch_message_sync (message);
1805     } catch (const Xapian::Error &error) {
1806         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1807                  error.get_msg().c_str());
1808         notmuch->exception_reported = TRUE;
1809         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1810         goto DONE;
1811     }
1812
1813   DONE:
1814     if (message) {
1815         if ((ret == NOTMUCH_STATUS_SUCCESS ||
1816              ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
1817             *message_ret = message;
1818         else
1819             notmuch_message_destroy (message);
1820     }
1821
1822     if (message_file)
1823         notmuch_message_file_close (message_file);
1824
1825     ret2 = notmuch_database_end_atomic (notmuch);
1826     if ((ret == NOTMUCH_STATUS_SUCCESS ||
1827          ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
1828         ret2 != NOTMUCH_STATUS_SUCCESS)
1829         ret = ret2;
1830
1831     return ret;
1832 }
1833
1834 notmuch_status_t
1835 notmuch_database_remove_message (notmuch_database_t *notmuch,
1836                                  const char *filename)
1837 {
1838     notmuch_status_t status;
1839     notmuch_message_t *message;
1840
1841     status = notmuch_database_find_message_by_filename (notmuch, filename,
1842                                                         &message);
1843
1844     if (status == NOTMUCH_STATUS_SUCCESS && message) {
1845             status = _notmuch_message_remove_filename (message, filename);
1846             if (status == NOTMUCH_STATUS_SUCCESS)
1847                 _notmuch_message_delete (message);
1848             else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
1849                 _notmuch_message_sync (message);
1850
1851             notmuch_message_destroy (message);
1852     }
1853
1854     return status;
1855 }
1856
1857 notmuch_status_t
1858 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
1859                                            const char *filename,
1860                                            notmuch_message_t **message_ret)
1861 {
1862     void *local;
1863     const char *prefix = _find_prefix ("file-direntry");
1864     char *direntry, *term;
1865     Xapian::PostingIterator i, end;
1866     notmuch_status_t status;
1867
1868     if (message_ret == NULL)
1869         return NOTMUCH_STATUS_NULL_POINTER;
1870
1871     /* return NULL on any failure */
1872     *message_ret = NULL;
1873
1874     local = talloc_new (notmuch);
1875
1876     try {
1877         status = _notmuch_database_filename_to_direntry (local, notmuch,
1878                                                          filename, &direntry);
1879         if (status)
1880             goto DONE;
1881
1882         term = talloc_asprintf (local, "%s%s", prefix, direntry);
1883
1884         find_doc_ids_for_term (notmuch, term, &i, &end);
1885
1886         if (i != end) {
1887             notmuch_private_status_t private_status;
1888
1889             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
1890                                                     &private_status);
1891             if (*message_ret == NULL)
1892                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
1893         }
1894     } catch (const Xapian::Error &error) {
1895         fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
1896                  error.get_msg().c_str());
1897         notmuch->exception_reported = TRUE;
1898         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1899     }
1900
1901   DONE:
1902     talloc_free (local);
1903
1904     if (status && *message_ret) {
1905         notmuch_message_destroy (*message_ret);
1906         *message_ret = NULL;
1907     }
1908     return status;
1909 }
1910
1911 notmuch_string_list_t *
1912 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
1913                                          Xapian::TermIterator &end,
1914                                          const char *prefix)
1915 {
1916     int prefix_len = strlen (prefix);
1917     notmuch_string_list_t *list;
1918
1919     list = _notmuch_string_list_create (ctx);
1920     if (unlikely (list == NULL))
1921         return NULL;
1922
1923     for (i.skip_to (prefix); i != end; i++) {
1924         /* Terminate loop at first term without desired prefix. */
1925         if (strncmp ((*i).c_str (), prefix, prefix_len))
1926             break;
1927
1928         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
1929     }
1930
1931     return list;
1932 }
1933
1934 notmuch_tags_t *
1935 notmuch_database_get_all_tags (notmuch_database_t *db)
1936 {
1937     Xapian::TermIterator i, end;
1938     notmuch_string_list_t *tags;
1939
1940     try {
1941         i = db->xapian_db->allterms_begin();
1942         end = db->xapian_db->allterms_end();
1943         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
1944                                                         _find_prefix ("tag"));
1945         _notmuch_string_list_sort (tags);
1946         return _notmuch_tags_create (db, tags);
1947     } catch (const Xapian::Error &error) {
1948         fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1949                  error.get_msg().c_str());
1950         db->exception_reported = TRUE;
1951         return NULL;
1952     }
1953 }