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