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