]> git.notmuchmail.org Git - notmuch/blob - database.cc
0fd0bdadf8103366b4c2f95924926d1f532df0ca
[notmuch] / database.cc
1 /* database.cc - The database interfaces of the notmuch mail library
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "database-private.h"
22
23 #include <iostream>
24
25 #include <xapian.h>
26
27 #include <glib.h> /* g_free, GPtrArray, GHashTable */
28
29 using namespace std;
30
31 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
32
33 typedef struct {
34     const char *name;
35     const char *prefix;
36 } prefix_t;
37
38 /* Here's the current schema for our database:
39  *
40  * We currently have two different types of documents: mail and timestamps.
41  *
42  * Mail document
43  * -------------
44  * A mail document is associated with a particular email message file
45  * on disk. It is indexed with the following prefixed terms:
46  *
47  *    Single terms of given prefix:
48  *
49  *      type:   mail
50  *
51  *      id:     Unique ID of mail, (from Message-ID header or generated
52  *              as "notmuch-sha1-<sha1_sum_of_entire_file>.
53  *
54  *      thread: The ID of the thread to which the mail belongs
55  *
56  *    Multiple terms of given prefix:
57  *
58  *      ref:    All unresolved message IDs from In-Reply-To and
59  *              References headers in the message. (Once a referenced
60  *              message is added to the database and the thread IDs
61  *              are linked the corresponding "ref" term is dropped
62  *              from the message document.)
63  *
64  *      tag:    Any tags associated with this message by the user.
65  *
66  *    A mail document also has two values:
67  *
68  *      TIMESTAMP:      The time_t value corresponding to the message's
69  *                      Date header.
70  *
71  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
72  *
73  * Timestamp document
74  * ------------------
75  * A timestamp document is used by a client of the notmuch library to
76  * maintain data necessary to allow for efficient polling of mail
77  * directories. The notmuch library does no interpretation of
78  * timestamps, but merely allows the user to store and retrieve
79  * timestamps as name/value pairs.
80  *
81  * The timestamp document is indexed with a single prefixed term:
82  *
83  *      timestamp:      The user's key value (likely a directory name)
84  *
85  * and has a single value:
86  *
87  *      TIMETAMPS:      The time_t value from the user.
88  */
89
90 /* With these prefix values we follow the conventions published here:
91  *
92  * http://xapian.org/docs/omega/termprefixes.html
93  *
94  * as much as makes sense. Note that I took some liberty in matching
95  * the reserved prefix values to notmuch concepts, (for example, 'G'
96  * is documented as "newsGroup (or similar entity - e.g. a web forum
97  * name)", for which I think the thread is the closest analogue in
98  * notmuch. This in spite of the fact that we will eventually be
99  * storing mailing-list messages where 'G' for "mailing list name"
100  * might be even a closer analogue. I'm treating the single-character
101  * prefixes preferentially for core notmuch concepts (which will be
102  * nearly universal to all mail messages).
103  */
104
105 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
106     { "type", "T" },
107     { "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     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
170         return "Unblanced number of calls to notmuch_message_freeze/thaw";
171     default:
172     case NOTMUCH_STATUS_LAST_STATUS:
173         return "Unknown error status value";
174     }
175 }
176
177 static void
178 find_doc_ids (notmuch_database_t *notmuch,
179               const char *prefix_name,
180               const char *value,
181               Xapian::PostingIterator *begin,
182               Xapian::PostingIterator *end)
183 {
184     Xapian::PostingIterator i;
185     char *term;
186
187     term = talloc_asprintf (notmuch, "%s%s",
188                             _find_prefix (prefix_name), value);
189
190     *begin = notmuch->xapian_db->postlist_begin (term);
191
192     *end = notmuch->xapian_db->postlist_end (term);
193
194     talloc_free (term);
195 }
196
197 static notmuch_private_status_t
198 find_unique_doc_id (notmuch_database_t *notmuch,
199                     const char *prefix_name,
200                     const char *value,
201                     unsigned int *doc_id)
202 {
203     Xapian::PostingIterator i, end;
204
205     find_doc_ids (notmuch, prefix_name, value, &i, &end);
206
207     if (i == end) {
208         *doc_id = 0;
209         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
210     } else {
211         *doc_id = *i;
212         return NOTMUCH_PRIVATE_STATUS_SUCCESS;
213     }
214 }
215
216 static Xapian::Document
217 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
218 {
219     return notmuch->xapian_db->get_document (doc_id);
220 }
221
222 static notmuch_private_status_t
223 find_unique_document (notmuch_database_t *notmuch,
224                       const char *prefix_name,
225                       const char *value,
226                       Xapian::Document *document,
227                       unsigned int *doc_id)
228 {
229     notmuch_private_status_t status;
230
231     status = find_unique_doc_id (notmuch, prefix_name, value, doc_id);
232
233     if (status) {
234         *document = Xapian::Document ();
235         return status;
236     }
237
238     *document = find_document_for_doc_id (notmuch, *doc_id);
239     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
240 }
241
242 notmuch_message_t *
243 notmuch_database_find_message (notmuch_database_t *notmuch,
244                                const char *message_id)
245 {
246     notmuch_private_status_t status;
247     unsigned int doc_id;
248
249     status = find_unique_doc_id (notmuch, "id", message_id, &doc_id);
250
251     if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
252         return NULL;
253
254     return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
255 }
256
257 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
258  * a (potentially nested) parenthesized sequence with '\' used to
259  * escape any character (including parentheses).
260  *
261  * If the sequence to be skipped continues to the end of the string,
262  * then 'str' will be left pointing at the final terminating '\0'
263  * character.
264  */
265 static void
266 skip_space_and_comments (const char **str)
267 {
268     const char *s;
269
270     s = *str;
271     while (*s && (isspace (*s) || *s == '(')) {
272         while (*s && isspace (*s))
273             s++;
274         if (*s == '(') {
275             int nesting = 1;
276             s++;
277             while (*s && nesting) {
278                 if (*s == '(')
279                     nesting++;
280                 else if (*s == ')')
281                     nesting--;
282                 else if (*s == '\\')
283                     if (*(s+1))
284                         s++;
285                 s++;
286             }
287         }
288     }
289
290     *str = s;
291 }
292
293 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
294  * comments, and the '<' and '>' delimeters.
295  *
296  * If not NULL, then *next will be made to point to the first character
297  * not parsed, (possibly pointing to the final '\0' terminator.
298  *
299  * Returns a newly talloc'ed string belonging to 'ctx'.
300  *
301  * Returns NULL if there is any error parsing the message-id. */
302 static char *
303 parse_message_id (void *ctx, const char *message_id, const char **next)
304 {
305     const char *s, *end;
306     char *result;
307
308     if (message_id == NULL)
309         return NULL;
310
311     s = message_id;
312
313     skip_space_and_comments (&s);
314
315     /* Skip any unstructured text as well. */
316     while (*s && *s != '<')
317         s++;
318
319     if (*s == '<') {
320         s++;
321     } else {
322         if (next)
323             *next = s;
324         return NULL;
325     }
326
327     skip_space_and_comments (&s);
328
329     end = s;
330     while (*end && *end != '>')
331         end++;
332     if (next) {
333         if (*end)
334             *next = end + 1;
335         else
336             *next = end;
337     }
338
339     if (end > s && *end == '>')
340         end--;
341     if (end <= s)
342         return NULL;
343
344     result = talloc_strndup (ctx, s, end - s + 1);
345
346     /* Finally, collapse any whitespace that is within the message-id
347      * itself. */
348     {
349         char *r;
350         int len;
351
352         for (r = result, len = strlen (r); *r; r++, len--)
353             if (*r == ' ' || *r == '\t')
354                 memmove (r, r+1, len);
355     }
356
357     return result;
358 }
359
360 /* Parse a References header value, putting a (talloc'ed under 'ctx')
361  * copy of each referenced message-id into 'hash'. */
362 static void
363 parse_references (void *ctx,
364                   GHashTable *hash,
365                   const char *refs)
366 {
367     char *ref;
368
369     if (refs == NULL)
370         return;
371
372     while (*refs) {
373         ref = parse_message_id (ctx, refs, &refs);
374
375         if (ref)
376             g_hash_table_insert (hash, ref, NULL);
377     }
378 }
379
380 char *
381 notmuch_database_default_path (void)
382 {
383     char *path;
384
385     if (getenv ("NOTMUCH_BASE"))
386         return strdup (getenv ("NOTMUCH_BASE"));
387
388     if (asprintf (&path, "%s/mail", getenv ("HOME")) == -1) {
389         fprintf (stderr, "Out of memory.\n");
390         return xstrdup("");
391     }
392
393     return path;
394 }
395
396 notmuch_database_t *
397 notmuch_database_create (const char *path)
398 {
399     notmuch_database_t *notmuch = NULL;
400     char *notmuch_path = NULL;
401     struct stat st;
402     int err;
403     char *local_path = NULL;
404
405     if (path == NULL)
406         path = local_path = notmuch_database_default_path ();
407
408     err = stat (path, &st);
409     if (err) {
410         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
411                  path, strerror (errno));
412         goto DONE;
413     }
414
415     if (! S_ISDIR (st.st_mode)) {
416         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
417                  path);
418         goto DONE;
419     }
420
421     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
422
423     err = mkdir (notmuch_path, 0755);
424
425     if (err) {
426         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
427                  notmuch_path, strerror (errno));
428         goto DONE;
429     }
430
431     notmuch = notmuch_database_open (path);
432
433   DONE:
434     if (notmuch_path)
435         talloc_free (notmuch_path);
436     if (local_path)
437         free (local_path);
438
439     return notmuch;
440 }
441
442 notmuch_database_t *
443 notmuch_database_open (const char *path)
444 {
445     notmuch_database_t *notmuch = NULL;
446     char *notmuch_path = NULL, *xapian_path = NULL;
447     struct stat st;
448     int err;
449     char *local_path = NULL;
450     unsigned int i;
451
452     if (path == NULL)
453         path = local_path = notmuch_database_default_path ();
454
455     if (asprintf (&notmuch_path, "%s/%s", path, ".notmuch") == -1) {
456         notmuch_path = NULL;
457         fprintf (stderr, "Out of memory\n");
458         goto DONE;
459     }
460
461     err = stat (notmuch_path, &st);
462     if (err) {
463         fprintf (stderr, "Error opening database at %s: %s\n",
464                  notmuch_path, strerror (errno));
465         goto DONE;
466     }
467
468     if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
469         xapian_path = NULL;
470         fprintf (stderr, "Out of memory\n");
471         goto DONE;
472     }
473
474     notmuch = talloc (NULL, notmuch_database_t);
475     notmuch->path = talloc_strdup (notmuch, path);
476
477     try {
478         notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
479                                                            Xapian::DB_CREATE_OR_OPEN);
480         notmuch->query_parser = new Xapian::QueryParser;
481         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
482         notmuch->query_parser->set_database (*notmuch->xapian_db);
483
484         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
485             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
486             notmuch->query_parser->add_boolean_prefix (prefix->name,
487                                                        prefix->prefix);
488         }
489     } catch (const Xapian::Error &error) {
490         fprintf (stderr, "A Xapian exception occurred: %s\n",
491                  error.get_msg().c_str());
492     }
493     
494   DONE:
495     if (local_path)
496         free (local_path);
497     if (notmuch_path)
498         free (notmuch_path);
499     if (xapian_path)
500         free (xapian_path);
501
502     return notmuch;
503 }
504
505 void
506 notmuch_database_close (notmuch_database_t *notmuch)
507 {
508     notmuch->xapian_db->flush ();
509
510     delete notmuch->query_parser;
511     delete notmuch->xapian_db;
512     talloc_free (notmuch);
513 }
514
515 const char *
516 notmuch_database_get_path (notmuch_database_t *notmuch)
517 {
518     return notmuch->path;
519 }
520
521 static notmuch_private_status_t
522 find_timestamp_document (notmuch_database_t *notmuch, const char *db_key,
523                          Xapian::Document *doc, unsigned int *doc_id)
524 {
525     return find_unique_document (notmuch, "timestamp", db_key, doc, doc_id);
526 }
527
528 /* We allow the user to use arbitrarily long keys for timestamps,
529  * (they're for filesystem paths after all, which have no limit we
530  * know about). But we have a term-length limit. So if we exceed that,
531  * we'll use the SHA-1 of the user's key as the actual key for
532  * constructing a database term.
533  *
534  * Caution: This function returns a newly allocated string which the
535  * caller should free() when finished.
536  */
537 static char *
538 timestamp_db_key (const char *key)
539 {
540     int term_len = strlen (_find_prefix ("timestamp")) + strlen (key);
541
542     if (term_len > NOTMUCH_TERM_MAX)
543         return notmuch_sha1_of_string (key);
544     else
545         return strdup (key);
546 }
547
548 notmuch_status_t
549 notmuch_database_set_timestamp (notmuch_database_t *notmuch,
550                                 const char *key, time_t timestamp)
551 {
552     Xapian::Document doc;
553     unsigned int doc_id;
554     notmuch_private_status_t status;
555     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
556     char *db_key = NULL;
557
558     db_key = timestamp_db_key (key);
559
560     try {
561         status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
562
563         doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
564                        Xapian::sortable_serialise (timestamp));
565
566         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
567             char *term = talloc_asprintf (NULL, "%s%s",
568                                           _find_prefix ("timestamp"), db_key);
569             doc.add_term (term);
570             talloc_free (term);
571
572             notmuch->xapian_db->add_document (doc);
573         } else {
574             notmuch->xapian_db->replace_document (doc_id, doc);
575         }
576
577     } catch (Xapian::Error &error) {
578         fprintf (stderr, "A Xapian exception occurred: %s.\n",
579                  error.get_msg().c_str());
580         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
581     }
582
583     if (db_key)
584         free (db_key);
585
586     return ret;
587 }
588
589 time_t
590 notmuch_database_get_timestamp (notmuch_database_t *notmuch, const char *key)
591 {
592     Xapian::Document doc;
593     unsigned int doc_id;
594     notmuch_private_status_t status;
595     char *db_key = NULL;
596     time_t ret = 0;
597
598     db_key = timestamp_db_key (key);
599
600     try {
601         status = find_timestamp_document (notmuch, db_key, &doc, &doc_id);
602
603         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
604             goto DONE;
605
606         ret =  Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
607     } catch (Xapian::Error &error) {
608         goto DONE;
609     }
610
611   DONE:
612     if (db_key)
613         free (db_key);
614
615     return ret;
616 }
617
618 /* Find the thread ID to which the message with 'message_id' belongs.
619  *
620  * Returns NULL if no message with message ID 'message_id' is in the
621  * database.
622  *
623  * Otherwise, returns a newly talloced string belonging to 'ctx'.
624  */
625 static const char *
626 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
627                                   void *ctx,
628                                   const char *message_id)
629 {
630     notmuch_message_t *message;
631     const char *ret = NULL;
632
633     message = notmuch_database_find_message (notmuch, message_id);
634     if (message == NULL)
635         goto DONE;
636
637     ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
638
639   DONE:
640     if (message)
641         notmuch_message_destroy (message);
642
643     return ret;
644 }
645
646 static notmuch_status_t
647 _merge_threads (notmuch_database_t *notmuch,
648                 const char *winner_thread_id,
649                 const char *loser_thread_id)
650 {
651     Xapian::PostingIterator loser, loser_end;
652     notmuch_message_t *message = NULL;
653     notmuch_private_status_t private_status;
654     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
655
656     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
657
658     for ( ; loser != loser_end; loser++) {
659         message = _notmuch_message_create (notmuch, notmuch,
660                                            *loser, &private_status);
661         if (message == NULL) {
662             ret = COERCE_STATUS (private_status,
663                                  "Cannot find document for doc_id from query");
664             goto DONE;
665         }
666
667         _notmuch_message_remove_term (message, "thread", loser_thread_id);
668         _notmuch_message_add_term (message, "thread", winner_thread_id);
669         _notmuch_message_sync (message);
670
671         notmuch_message_destroy (message);
672         message = NULL;
673     }
674
675   DONE:
676     if (message)
677         notmuch_message_destroy (message);
678
679     return ret;
680 }
681
682 static void
683 _my_talloc_free_for_g_hash (void *ptr)
684 {
685     talloc_free (ptr);
686 }
687
688 static notmuch_status_t
689 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
690                                            notmuch_message_t *message,
691                                            notmuch_message_file_t *message_file,
692                                            const char **thread_id)
693 {
694     GHashTable *parents = NULL;
695     const char *refs, *in_reply_to;
696     GList *l, *keys = NULL;
697     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
698
699     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
700                                      _my_talloc_free_for_g_hash, NULL);
701
702     refs = notmuch_message_file_get_header (message_file, "references");
703     parse_references (message, parents, refs);
704
705     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
706     parse_references (message, parents, in_reply_to);
707
708     keys = g_hash_table_get_keys (parents);
709     for (l = keys; l; l = l->next) {
710         char *parent_message_id;
711         const char *parent_thread_id;
712
713         parent_message_id = (char *) l->data;
714         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
715                                                              message,
716                                                              parent_message_id);
717
718         if (parent_thread_id == NULL) {
719             _notmuch_message_add_term (message, "ref", parent_message_id);
720         } else {
721             if (*thread_id == NULL) {
722                 *thread_id = talloc_strdup (message, parent_thread_id);
723                 _notmuch_message_add_term (message, "thread", *thread_id);
724             } else if (strcmp (*thread_id, parent_thread_id)) {
725                 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
726                 if (ret)
727                     goto DONE;
728             }
729         }
730     }
731
732   DONE:
733     if (keys)
734         g_list_free (keys);
735     if (parents)
736         g_hash_table_unref (parents);
737
738     return ret;
739 }
740
741 static notmuch_status_t
742 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
743                                             notmuch_message_t *message,
744                                             const char **thread_id)
745 {
746     const char *message_id = notmuch_message_get_message_id (message);
747     Xapian::PostingIterator child, children_end;
748     notmuch_message_t *child_message = NULL;
749     const char *child_thread_id;
750     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
751     notmuch_private_status_t private_status;
752
753     find_doc_ids (notmuch, "ref", message_id, &child, &children_end);
754
755     for ( ; child != children_end; child++) {
756
757         child_message = _notmuch_message_create (message, notmuch,
758                                                  *child, &private_status);
759         if (child_message == NULL) {
760             ret = COERCE_STATUS (private_status,
761                                  "Cannot find document for doc_id from query");
762             goto DONE;
763         }
764
765         child_thread_id = notmuch_message_get_thread_id (child_message);
766         if (*thread_id == NULL) {
767             *thread_id = talloc_strdup (message, child_thread_id);
768             _notmuch_message_add_term (message, "thread", *thread_id);
769         } else if (strcmp (*thread_id, child_thread_id)) {
770             _notmuch_message_remove_term (child_message, "ref",
771                                           message_id);
772             _notmuch_message_sync (child_message);
773             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
774             if (ret)
775                 goto DONE;
776         }
777
778         notmuch_message_destroy (child_message);
779         child_message = NULL;
780     }
781
782   DONE:
783     if (child_message)
784         notmuch_message_destroy (child_message);
785
786     return ret;
787 }
788
789 /* Given a (mostly empty) 'message' and its corresponding
790  * 'message_file' link it to existing threads in the database.
791  *
792  * We first looke at 'message_file' and its link-relevant headers
793  * (References and In-Reply-To) for message IDs. We also look in the
794  * database for existing message that reference 'message'.p
795  *
796  * The end result is to call _notmuch_message_add_thread_id with one
797  * or more thread IDs to which this message belongs, (including
798  * generating a new thread ID if necessary if the message doesn't
799  * connect to any existing threads).
800  */
801 static notmuch_status_t
802 _notmuch_database_link_message (notmuch_database_t *notmuch,
803                                 notmuch_message_t *message,
804                                 notmuch_message_file_t *message_file)
805 {
806     notmuch_status_t status;
807     const char *thread_id = NULL;
808
809     status = _notmuch_database_link_message_to_parents (notmuch, message,
810                                                         message_file,
811                                                         &thread_id);
812     if (status)
813         return status;
814
815     status = _notmuch_database_link_message_to_children (notmuch, message,
816                                                          &thread_id);
817     if (status)
818         return status;
819
820     if (thread_id == NULL)
821         _notmuch_message_ensure_thread_id (message);
822
823     return NOTMUCH_STATUS_SUCCESS;
824 }
825
826 notmuch_status_t
827 notmuch_database_add_message (notmuch_database_t *notmuch,
828                               const char *filename,
829                               notmuch_message_t **message_ret)
830 {
831     notmuch_message_file_t *message_file;
832     notmuch_message_t *message;
833     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
834
835     const char *date, *header;
836     const char *from, *to, *subject, *old_filename;
837     char *message_id;
838
839     if (message_ret)
840         *message_ret = NULL;
841
842     message_file = notmuch_message_file_open (filename);
843     if (message_file == NULL) {
844         ret = NOTMUCH_STATUS_FILE_ERROR;
845         goto DONE;
846     }
847
848     notmuch_message_file_restrict_headers (message_file,
849                                            "date",
850                                            "from",
851                                            "in-reply-to",
852                                            "message-id",
853                                            "references",
854                                            "subject",
855                                            "to",
856                                            (char *) NULL);
857
858     try {
859         /* The first order of business is to find/create a message ID. */
860
861         header = notmuch_message_file_get_header (message_file, "message-id");
862         if (header) {
863             message_id = parse_message_id (message_file, header, NULL);
864             /* So the header value isn't RFC-compliant, but it's
865              * better than no message-id at all. */
866             if (message_id == NULL)
867                 message_id = talloc_strdup (message_file, header);
868         } else {
869             /* No message-id at all, let's generate one by taking a
870              * hash over the file's contents. */
871             char *sha1 = notmuch_sha1_of_file (filename);
872
873             /* If that failed too, something is really wrong. Give up. */
874             if (sha1 == NULL) {
875                 ret = NOTMUCH_STATUS_FILE_ERROR;
876                 goto DONE;
877             }
878
879             message_id = talloc_asprintf (message_file,
880                                           "notmuch-sha1-%s", sha1);
881             free (sha1);
882         }
883
884         /* Now that we have a message ID, we get a message object,
885          * (which may or may not reference an existing document in the
886          * database). */
887
888         /* Use NULL for owner since we want to free this locally. */
889         message = _notmuch_message_create_for_message_id (NULL,
890                                                           notmuch,
891                                                           message_id,
892                                                           &ret);
893
894         talloc_free (message_id);
895
896         if (message == NULL)
897             goto DONE;
898
899         /* Has a message previously been added with the same ID? */
900         old_filename = notmuch_message_get_filename (message);
901         if (old_filename && strlen (old_filename)) {
902             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
903             goto DONE;
904         } else {
905             _notmuch_message_set_filename (message, filename);
906             _notmuch_message_add_term (message, "type", "mail");
907         }
908
909         ret = _notmuch_database_link_message (notmuch, message, message_file);
910         if (ret)
911             goto DONE;
912
913         date = notmuch_message_file_get_header (message_file, "date");
914         _notmuch_message_set_date (message, date);
915
916         from = notmuch_message_file_get_header (message_file, "from");
917         subject = notmuch_message_file_get_header (message_file, "subject");
918         to = notmuch_message_file_get_header (message_file, "to");
919
920         if (from == NULL &&
921             subject == NULL &&
922             to == NULL)
923         {
924             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
925             goto DONE;
926         } else {
927             _notmuch_message_sync (message);
928         }
929     } catch (const Xapian::Error &error) {
930         fprintf (stderr, "A Xapian exception occurred: %s.\n",
931                  error.get_msg().c_str());
932         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
933         goto DONE;
934     }
935
936   DONE:
937     if (message) {
938         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
939             *message_ret = message;
940         else
941             notmuch_message_destroy (message);
942     }
943
944     if (message_file)
945         notmuch_message_file_close (message_file);
946
947     return ret;
948 }