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