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