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