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