]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
notmuch_database_add_message: Add missing error-value propagation.
[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 <xapian.h>
26
27 #include <glib.h> /* g_free, GPtrArray, GHashTable */
28
29 using namespace std;
30
31 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
32
33 typedef struct {
34     const char *name;
35     const char *prefix;
36 } prefix_t;
37
38 /* Here's the current schema for our database:
39  *
40  * We currently have two different types of documents: mail and timestamps.
41  *
42  * Mail document
43  * -------------
44  * A mail document is associated with a particular email message file
45  * on disk. It is indexed with the following prefixed terms which the
46  * database uses to construct threads, etc.:
47  *
48  *    Single terms of given prefix:
49  *
50  *      type:   mail
51  *
52  *      id:     Unique ID of mail, (from Message-ID header or generated
53  *              as "notmuch-sha1-<sha1_sum_of_entire_file>.
54  *
55  *      thread: The ID of the thread to which the mail belongs
56  *
57  *      replyto: The ID from the In-Reply-To header of the mail (if any).
58  *
59  *    Multiple terms of given prefix:
60  *
61  *      reference: All message IDs from In-Reply-To and Re ferences
62  *                 headers in the message.
63  *
64  *      tag:       Any tags associated with this message by the user.
65  *
66  *    A mail document also has two values:
67  *
68  *      TIMESTAMP:      The time_t value corresponding to the message's
69  *                      Date header.
70  *
71  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
72  *
73  * In addition, terms from the content of the message are added with
74  * "from", "to", "attachment", and "subject" prefixes for use by the
75  * user in searching. But the database doesn't really care itself
76  * about any of these.
77  *
78  * Timestamp document
79  * ------------------
80  * A timestamp document is used by a client of the notmuch library to
81  * maintain data necessary to allow for efficient polling of mail
82  * directories. The notmuch library does no interpretation of
83  * timestamps, but merely allows the user to store and retrieve
84  * timestamps as name/value pairs.
85  *
86  * The timestamp document is indexed with a single prefixed term:
87  *
88  *      timestamp:      The user's key value (likely a directory name)
89  *
90  * and has a single value:
91  *
92  *      TIMESTAMP:      The time_t value from the user.
93  */
94
95 /* With these prefix values we follow the conventions published here:
96  *
97  * http://xapian.org/docs/omega/termprefixes.html
98  *
99  * as much as makes sense. Note that I took some liberty in matching
100  * the reserved prefix values to notmuch concepts, (for example, 'G'
101  * is documented as "newsGroup (or similar entity - e.g. a web forum
102  * name)", for which I think the thread is the closest analogue in
103  * notmuch. This in spite of the fact that we will eventually be
104  * storing mailing-list messages where 'G' for "mailing list name"
105  * might be even a closer analogue. I'm treating the single-character
106  * prefixes preferentially for core notmuch concepts (which will be
107  * nearly universal to all mail messages).
108  */
109
110 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
111     { "type", "T" },
112     { "reference", "XREFERENCE" },
113     { "replyto", "XREPLYTO" },
114     { "timestamp", "XTIMESTAMP" },
115 };
116
117 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
118     { "thread", "G" },
119     { "tag", "K" },
120     { "id", "Q" }
121 };
122
123 prefix_t PROBABILISTIC_PREFIX[]= {
124     { "from", "XFROM" },
125     { "to", "XTO" },
126     { "attachment", "XATTACHMENT" },
127     { "subject", "XSUBJECT"}
128 };
129
130 int
131 _internal_error (const char *format, ...)
132 {
133     va_list va_args;
134
135     va_start (va_args, format);
136
137     fprintf (stderr, "Internal error: ");
138     vfprintf (stderr, format, va_args);
139
140     exit (1);
141
142     return 1;
143 }
144
145 const char *
146 _find_prefix (const char *name)
147 {
148     unsigned int i;
149
150     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++)
151         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
152             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
153
154     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++)
155         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
156             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
157
158     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++)
159         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
160             return PROBABILISTIC_PREFIX[i].prefix;
161
162     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
163
164     return "";
165 }
166
167 const char *
168 notmuch_status_to_string (notmuch_status_t status)
169 {
170     switch (status) {
171     case NOTMUCH_STATUS_SUCCESS:
172         return "No error occurred";
173     case NOTMUCH_STATUS_OUT_OF_MEMORY:
174         return "Out of memory";
175     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
176         return "A Xapian exception occurred";
177     case NOTMUCH_STATUS_FILE_ERROR:
178         return "Something went wrong trying to read or write a file";
179     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
180         return "File is not an email";
181     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
182         return "Message ID is identical to a message in database";
183     case NOTMUCH_STATUS_NULL_POINTER:
184         return "Erroneous NULL pointer";
185     case NOTMUCH_STATUS_TAG_TOO_LONG:
186         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
187     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
188         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
189     default:
190     case NOTMUCH_STATUS_LAST_STATUS:
191         return "Unknown error status value";
192     }
193 }
194
195 static void
196 find_doc_ids (notmuch_database_t *notmuch,
197               const char *prefix_name,
198               const char *value,
199               Xapian::PostingIterator *begin,
200               Xapian::PostingIterator *end)
201 {
202     Xapian::PostingIterator i;
203     char *term;
204
205     term = talloc_asprintf (notmuch, "%s%s",
206                             _find_prefix (prefix_name), value);
207
208     *begin = notmuch->xapian_db->postlist_begin (term);
209
210     *end = notmuch->xapian_db->postlist_end (term);
211
212     talloc_free (term);
213 }
214
215 static notmuch_private_status_t
216 find_unique_doc_id (notmuch_database_t *notmuch,
217                     const char *prefix_name,
218                     const char *value,
219                     unsigned int *doc_id)
220 {
221     Xapian::PostingIterator i, end;
222
223     find_doc_ids (notmuch, prefix_name, value, &i, &end);
224
225     if (i == end) {
226         *doc_id = 0;
227         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
228     } else {
229         *doc_id = *i;
230         return NOTMUCH_PRIVATE_STATUS_SUCCESS;
231     }
232 }
233
234 static Xapian::Document
235 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
236 {
237     return notmuch->xapian_db->get_document (doc_id);
238 }
239
240 static notmuch_private_status_t
241 find_unique_document (notmuch_database_t *notmuch,
242                       const char *prefix_name,
243                       const char *value,
244                       Xapian::Document *document,
245                       unsigned int *doc_id)
246 {
247     notmuch_private_status_t status;
248
249     status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
250
251     if (status) {
252         *document = Xapian::Document ();
253         return status;
254     }
255
256     *document = find_document_for_doc_id (notmuch, *doc_id);
257     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
258 }
259
260 notmuch_message_t *
261 notmuch_database_find_message (notmuch_database_t *notmuch,
262                                const char *message_id)
263 {
264     notmuch_private_status_t status;
265     unsigned int doc_id;
266
267     status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
268
269     if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
270         return NULL;
271
272     return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
273 }
274
275 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
276  * a (potentially nested) parenthesized sequence with '\' used to
277  * escape any character (including parentheses).
278  *
279  * If the sequence to be skipped continues to the end of the string,
280  * then 'str' will be left pointing at the final terminating '\0'
281  * character.
282  */
283 static void
284 skip_space_and_comments (const char **str)
285 {
286     const char *s;
287
288     s = *str;
289     while (*s && (isspace (*s) || *s == '(')) {
290         while (*s && isspace (*s))
291             s++;
292         if (*s == '(') {
293             int nesting = 1;
294             s++;
295             while (*s && nesting) {
296                 if (*s == '(')
297                     nesting++;
298                 else if (*s == ')')
299                     nesting--;
300                 else if (*s == '\\')
301                     if (*(s+1))
302                         s++;
303                 s++;
304             }
305         }
306     }
307
308     *str = s;
309 }
310
311 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
312  * comments, and the '<' and '>' delimeters.
313  *
314  * If not NULL, then *next will be made to point to the first character
315  * not parsed, (possibly pointing to the final '\0' terminator.
316  *
317  * Returns a newly talloc'ed string belonging to 'ctx'.
318  *
319  * Returns NULL if there is any error parsing the message-id. */
320 static char *
321 _parse_message_id (void *ctx, const char *message_id, const char **next)
322 {
323     const char *s, *end;
324     char *result;
325
326     if (message_id == NULL)
327         return NULL;
328
329     s = message_id;
330
331     skip_space_and_comments (&s);
332
333     /* Skip any unstructured text as well. */
334     while (*s && *s != '<')
335         s++;
336
337     if (*s == '<') {
338         s++;
339     } else {
340         if (next)
341             *next = s;
342         return NULL;
343     }
344
345     skip_space_and_comments (&s);
346
347     end = s;
348     while (*end && *end != '>')
349         end++;
350     if (next) {
351         if (*end)
352             *next = end + 1;
353         else
354             *next = end;
355     }
356
357     if (end > s && *end == '>')
358         end--;
359     if (end <= s)
360         return NULL;
361
362     result = talloc_strndup (ctx, s, end - s + 1);
363
364     /* Finally, collapse any whitespace that is within the message-id
365      * itself. */
366     {
367         char *r;
368         int len;
369
370         for (r = result, len = strlen (r); *r; r++, len--)
371             if (*r == ' ' || *r == '\t')
372                 memmove (r, r+1, len);
373     }
374
375     return result;
376 }
377
378 /* Parse a References header value, putting a (talloc'ed under 'ctx')
379  * copy of each referenced message-id into 'hash'.
380  *
381  * We explicitly avoid including any reference identical to
382  * 'message_id' in the result (to avoid mass confusion when a single
383  * message references itself cyclically---and yes, mail messages are
384  * not infrequent in the wild that do this---don't ask me why).
385 */
386 static void
387 parse_references (void *ctx,
388                   const char *message_id,
389                   GHashTable *hash,
390                   const char *refs)
391 {
392     char *ref;
393
394     if (refs == NULL)
395         return;
396
397     while (*refs) {
398         ref = _parse_message_id (ctx, refs, &refs);
399
400         if (ref && strcmp (ref, message_id))
401             g_hash_table_insert (hash, ref, NULL);
402     }
403 }
404
405 notmuch_database_t *
406 notmuch_database_create (const char *path)
407 {
408     notmuch_database_t *notmuch = NULL;
409     char *notmuch_path = NULL;
410     struct stat st;
411     int err;
412
413     if (path == NULL) {
414         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
415         goto DONE;
416     }
417
418     err = stat (path, &st);
419     if (err) {
420         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
421                  path, strerror (errno));
422         goto DONE;
423     }
424
425     if (! S_ISDIR (st.st_mode)) {
426         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
427                  path);
428         goto DONE;
429     }
430
431     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
432
433     err = mkdir (notmuch_path, 0755);
434
435     if (err) {
436         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
437                  notmuch_path, strerror (errno));
438         goto DONE;
439     }
440
441     notmuch = notmuch_database_open (path);
442
443   DONE:
444     if (notmuch_path)
445         talloc_free (notmuch_path);
446
447     return notmuch;
448 }
449
450 notmuch_database_t *
451 notmuch_database_open (const char *path)
452 {
453     notmuch_database_t *notmuch = NULL;
454     char *notmuch_path = NULL, *xapian_path = NULL;
455     struct stat st;
456     int err;
457     unsigned int i;
458
459     if (asprintf (&notmuch_path, "%s/%s", path, ".notmuch") == -1) {
460         notmuch_path = NULL;
461         fprintf (stderr, "Out of memory\n");
462         goto DONE;
463     }
464
465     err = stat (notmuch_path, &st);
466     if (err) {
467         fprintf (stderr, "Error opening database at %s: %s\n",
468                  notmuch_path, strerror (errno));
469         goto DONE;
470     }
471
472     if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
473         xapian_path = NULL;
474         fprintf (stderr, "Out of memory\n");
475         goto DONE;
476     }
477
478     notmuch = talloc (NULL, notmuch_database_t);
479     notmuch->path = talloc_strdup (notmuch, path);
480
481     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
482         notmuch->path[strlen (notmuch->path) - 1] = '\0';
483
484     try {
485         notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
486                                                            Xapian::DB_CREATE_OR_OPEN);
487         notmuch->query_parser = new Xapian::QueryParser;
488         notmuch->term_gen = new Xapian::TermGenerator;
489         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
490
491         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
492         notmuch->query_parser->set_database (*notmuch->xapian_db);
493         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
494         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
495
496         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
497             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
498             notmuch->query_parser->add_boolean_prefix (prefix->name,
499                                                        prefix->prefix);
500         }
501
502         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
503             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
504             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
505         }
506     } catch (const Xapian::Error &error) {
507         fprintf (stderr, "A Xapian exception occurred: %s\n",
508                  error.get_msg().c_str());
509         notmuch = NULL;
510     }
511     
512   DONE:
513     if (notmuch_path)
514         free (notmuch_path);
515     if (xapian_path)
516         free (xapian_path);
517
518     return notmuch;
519 }
520
521 void
522 notmuch_database_close (notmuch_database_t *notmuch)
523 {
524     notmuch->xapian_db->flush ();
525
526     delete notmuch->term_gen;
527     delete notmuch->query_parser;
528     delete notmuch->xapian_db;
529     talloc_free (notmuch);
530 }
531
532 const char *
533 notmuch_database_get_path (notmuch_database_t *notmuch)
534 {
535     return notmuch->path;
536 }
537
538 static notmuch_private_status_t
539 find_timestamp_document (notmuch_database_t *notmuch, const char *db_key,
540                          Xapian::Document *doc, unsigned int *doc_id)
541 {
542     return find_unique_document (notmuch, "timestamp", db_key, doc, doc_id);
543 }
544
545 /* We allow the user to use arbitrarily long keys for timestamps,
546  * (they're for filesystem paths after all, which have no limit we
547  * know about). But we have a term-length limit. So if we exceed that,
548  * we'll use the SHA-1 of the user's key as the actual key for
549  * constructing a database term.
550  *
551  * Caution: This function returns a newly allocated string which the
552  * caller should free() when finished.
553  */
554 static char *
555 timestamp_db_key (const char *key)
556 {
557     int term_len = strlen (_find_prefix ("timestamp")) + strlen (key);
558
559     if (term_len > NOTMUCH_TERM_MAX)
560         return notmuch_sha1_of_string (key);
561     else
562         return strdup (key);
563 }
564
565 notmuch_status_t
566 notmuch_database_set_timestamp (notmuch_database_t *notmuch,
567                                 const char *key, time_t timestamp)
568 {
569     Xapian::Document doc;
570     unsigned int doc_id;
571     notmuch_private_status_t status;
572     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
573     char *db_key = NULL;
574
575     db_key = timestamp_db_key (key);
576
577     try {
578         status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
579
580         doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
581                        Xapian::sortable_serialise (timestamp));
582
583         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
584             char *term = talloc_asprintf (NULL, "%s%s",
585                                           _find_prefix ("timestamp"), db_key);
586             doc.add_term (term);
587             talloc_free (term);
588
589             notmuch->xapian_db->add_document (doc);
590         } else {
591             notmuch->xapian_db->replace_document (doc_id, doc);
592         }
593
594     } catch (Xapian::Error &error) {
595         fprintf (stderr, "A Xapian exception occurred: %s.\n",
596                  error.get_msg().c_str());
597         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
598     }
599
600     if (db_key)
601         free (db_key);
602
603     return ret;
604 }
605
606 time_t
607 notmuch_database_get_timestamp (notmuch_database_t *notmuch, const char *key)
608 {
609     Xapian::Document doc;
610     unsigned int doc_id;
611     notmuch_private_status_t status;
612     char *db_key = NULL;
613     time_t ret = 0;
614
615     db_key = timestamp_db_key (key);
616
617     try {
618         status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
619
620         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
621             goto DONE;
622
623         ret =  Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
624     } catch (Xapian::Error &error) {
625         goto DONE;
626     }
627
628   DONE:
629     if (db_key)
630         free (db_key);
631
632     return ret;
633 }
634
635 /* Find the thread ID to which the message with 'message_id' belongs.
636  *
637  * Returns NULL if no message with message ID 'message_id' is in the
638  * database.
639  *
640  * Otherwise, returns a newly talloced string belonging to 'ctx'.
641  */
642 static const char *
643 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
644                                   void *ctx,
645                                   const char *message_id)
646 {
647     notmuch_message_t *message;
648     const char *ret = NULL;
649
650     message = notmuch_database_find_message (notmuch, message_id);
651     if (message == NULL)
652         goto DONE;
653
654     ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
655
656   DONE:
657     if (message)
658         notmuch_message_destroy (message);
659
660     return ret;
661 }
662
663 static notmuch_status_t
664 _merge_threads (notmuch_database_t *notmuch,
665                 const char *winner_thread_id,
666                 const char *loser_thread_id)
667 {
668     Xapian::PostingIterator loser, loser_end;
669     notmuch_message_t *message = NULL;
670     notmuch_private_status_t private_status;
671     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
672
673     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
674
675     for ( ; loser != loser_end; loser++) {
676         message = _notmuch_message_create (notmuch, notmuch,
677                                            *loser, &private_status);
678         if (message == NULL) {
679             ret = COERCE_STATUS (private_status,
680                                  "Cannot find document for doc_id from query");
681             goto DONE;
682         }
683
684         _notmuch_message_remove_term (message, "thread", loser_thread_id);
685         _notmuch_message_add_term (message, "thread", winner_thread_id);
686         _notmuch_message_sync (message);
687
688         notmuch_message_destroy (message);
689         message = NULL;
690     }
691
692   DONE:
693     if (message)
694         notmuch_message_destroy (message);
695
696     return ret;
697 }
698
699 static void
700 _my_talloc_free_for_g_hash (void *ptr)
701 {
702     talloc_free (ptr);
703 }
704
705 static notmuch_status_t
706 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
707                                            notmuch_message_t *message,
708                                            notmuch_message_file_t *message_file,
709                                            const char **thread_id)
710 {
711     GHashTable *parents = NULL;
712     const char *refs, *in_reply_to, *in_reply_to_message_id;
713     GList *l, *keys = NULL;
714     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
715
716     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
717                                      _my_talloc_free_for_g_hash, NULL);
718
719     refs = notmuch_message_file_get_header (message_file, "references");
720     parse_references (message, notmuch_message_get_message_id (message),
721                       parents, refs);
722
723     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
724     parse_references (message, notmuch_message_get_message_id (message),
725                       parents, in_reply_to);
726
727     /* Carefully avoid adding any self-referential in-reply-to term. */
728     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
729     if (in_reply_to_message_id &&
730         strcmp (in_reply_to_message_id,
731                 notmuch_message_get_message_id (message)))
732     {
733         _notmuch_message_add_term (message, "replyto",
734                              _parse_message_id (message, in_reply_to, NULL));
735     }
736
737     keys = g_hash_table_get_keys (parents);
738     for (l = keys; l; l = l->next) {
739         char *parent_message_id;
740         const char *parent_thread_id;
741
742         parent_message_id = (char *) l->data;
743         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
744                                                              message,
745                                                              parent_message_id);
746
747         if (parent_thread_id == NULL) {
748             _notmuch_message_add_term (message, "reference",
749                                        parent_message_id);
750         } else {
751             if (*thread_id == NULL) {
752                 *thread_id = talloc_strdup (message, parent_thread_id);
753                 _notmuch_message_add_term (message, "thread", *thread_id);
754             } else if (strcmp (*thread_id, parent_thread_id)) {
755                 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
756                 if (ret)
757                     goto DONE;
758             }
759         }
760     }
761
762   DONE:
763     if (keys)
764         g_list_free (keys);
765     if (parents)
766         g_hash_table_unref (parents);
767
768     return ret;
769 }
770
771 static notmuch_status_t
772 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
773                                             notmuch_message_t *message,
774                                             const char **thread_id)
775 {
776     const char *message_id = notmuch_message_get_message_id (message);
777     Xapian::PostingIterator child, children_end;
778     notmuch_message_t *child_message = NULL;
779     const char *child_thread_id;
780     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
781     notmuch_private_status_t private_status;
782
783     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
784
785     for ( ; child != children_end; child++) {
786
787         child_message = _notmuch_message_create (message, notmuch,
788                                                  *child, &private_status);
789         if (child_message == NULL) {
790             ret = COERCE_STATUS (private_status,
791                                  "Cannot find document for doc_id from query");
792             goto DONE;
793         }
794
795         child_thread_id = notmuch_message_get_thread_id (child_message);
796         if (*thread_id == NULL) {
797             *thread_id = talloc_strdup (message, child_thread_id);
798             _notmuch_message_add_term (message, "thread", *thread_id);
799         } else if (strcmp (*thread_id, child_thread_id)) {
800             _notmuch_message_remove_term (child_message, "reference",
801                                           message_id);
802             _notmuch_message_sync (child_message);
803             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
804             if (ret)
805                 goto DONE;
806         }
807
808         notmuch_message_destroy (child_message);
809         child_message = NULL;
810     }
811
812   DONE:
813     if (child_message)
814         notmuch_message_destroy (child_message);
815
816     return ret;
817 }
818
819 /* Given a (mostly empty) 'message' and its corresponding
820  * 'message_file' link it to existing threads in the database.
821  *
822  * We first look at 'message_file' and its link-relevant headers
823  * (References and In-Reply-To) for message IDs. We also look in the
824  * database for existing message that reference 'message'.p
825  *
826  * The end result is to call _notmuch_message_add_thread_id with one
827  * or more thread IDs to which this message belongs, (including
828  * generating a new thread ID if necessary if the message doesn't
829  * connect to any existing threads).
830  */
831 static notmuch_status_t
832 _notmuch_database_link_message (notmuch_database_t *notmuch,
833                                 notmuch_message_t *message,
834                                 notmuch_message_file_t *message_file)
835 {
836     notmuch_status_t status;
837     const char *thread_id = NULL;
838
839     status = _notmuch_database_link_message_to_parents (notmuch, message,
840                                                         message_file,
841                                                         &thread_id);
842     if (status)
843         return status;
844
845     status = _notmuch_database_link_message_to_children (notmuch, message,
846                                                          &thread_id);
847     if (status)
848         return status;
849
850     if (thread_id == NULL)
851         _notmuch_message_ensure_thread_id (message);
852
853     return NOTMUCH_STATUS_SUCCESS;
854 }
855
856 notmuch_status_t
857 notmuch_database_add_message (notmuch_database_t *notmuch,
858                               const char *filename,
859                               notmuch_message_t **message_ret)
860 {
861     notmuch_message_file_t *message_file;
862     notmuch_message_t *message = NULL;
863     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
864     notmuch_private_status_t private_status;
865
866     const char *date, *header;
867     const char *from, *to, *subject;
868     char *message_id;
869
870     if (message_ret)
871         *message_ret = NULL;
872
873     message_file = notmuch_message_file_open (filename);
874     if (message_file == NULL) {
875         ret = NOTMUCH_STATUS_FILE_ERROR;
876         goto DONE;
877     }
878
879     notmuch_message_file_restrict_headers (message_file,
880                                            "date",
881                                            "from",
882                                            "in-reply-to",
883                                            "message-id",
884                                            "references",
885                                            "subject",
886                                            "to",
887                                            (char *) NULL);
888
889     try {
890         /* Before we do any real work, (especially before doing a
891          * potential SHA-1 computation on the entire file's contents),
892          * let's make sure that what we're looking at looks like an
893          * actual email message.
894          */
895         from = notmuch_message_file_get_header (message_file, "from");
896         subject = notmuch_message_file_get_header (message_file, "subject");
897         to = notmuch_message_file_get_header (message_file, "to");
898
899         if (from == NULL &&
900             subject == NULL &&
901             to == NULL)
902         {
903             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
904             goto DONE;
905         }
906
907         /* Now that we're sure it's mail, the first order of business
908          * is to find a message ID (or else create one ourselves). */
909
910         header = notmuch_message_file_get_header (message_file, "message-id");
911         if (header && *header != '\0') {
912             message_id = _parse_message_id (message_file, header, NULL);
913             /* So the header value isn't RFC-compliant, but it's
914              * better than no message-id at all. */
915             if (message_id == NULL)
916                 message_id = talloc_strdup (message_file, header);
917         } else {
918             /* No message-id at all, let's generate one by taking a
919              * hash over the file's contents. */
920             char *sha1 = notmuch_sha1_of_file (filename);
921
922             /* If that failed too, something is really wrong. Give up. */
923             if (sha1 == NULL) {
924                 ret = NOTMUCH_STATUS_FILE_ERROR;
925                 goto DONE;
926             }
927
928             message_id = talloc_asprintf (message_file,
929                                           "notmuch-sha1-%s", sha1);
930             free (sha1);
931         }
932
933         /* Now that we have a message ID, we get a message object,
934          * (which may or may not reference an existing document in the
935          * database). */
936
937         message = _notmuch_message_create_for_message_id (notmuch,
938                                                           message_id,
939                                                           &private_status);
940
941         talloc_free (message_id);
942
943         if (message == NULL) {
944             ret = COERCE_STATUS (private_status,
945                                  "Unexpected status value from _notmuch_message_create_for_message_id");
946             goto DONE;
947         }
948
949         /* Is this a newly created message object? */
950         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
951             _notmuch_message_set_filename (message, filename);
952             _notmuch_message_add_term (message, "type", "mail");
953         } else {
954             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
955             goto DONE;
956         }
957
958         ret = _notmuch_database_link_message (notmuch, message, message_file);
959         if (ret)
960             goto DONE;
961
962         date = notmuch_message_file_get_header (message_file, "date");
963         _notmuch_message_set_date (message, date);
964
965         _notmuch_message_index_file (message, filename);
966
967         _notmuch_message_sync (message);
968     } catch (const Xapian::Error &error) {
969         fprintf (stderr, "A Xapian exception occurred: %s.\n",
970                  error.get_msg().c_str());
971         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
972         goto DONE;
973     }
974
975   DONE:
976     if (message) {
977         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
978             *message_ret = message;
979         else
980             notmuch_message_destroy (message);
981     }
982
983     if (message_file)
984         notmuch_message_file_close (message_file);
985
986     return ret;
987 }