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