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