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