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