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