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