]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
lib: Document that the filename is stored in the 'data' of a mail document
[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 (an absolute 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     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
643     db_path = directory_db_path (path);
644
645     try {
646         status = find_directory_document (notmuch, db_path, &doc, &doc_id);
647
648         doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
649                        Xapian::sortable_serialise (mtime));
650
651         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
652             char *term = talloc_asprintf (NULL, "%s%s",
653                                           _find_prefix ("directory"), db_path);
654             doc.add_term (term);
655             talloc_free (term);
656
657             db->add_document (doc);
658         } else {
659             db->replace_document (doc_id, doc);
660         }
661
662     } catch (const Xapian::Error &error) {
663         fprintf (stderr, "A Xapian exception occurred setting directory mtime: %s.\n",
664                  error.get_msg().c_str());
665         notmuch->exception_reported = TRUE;
666         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
667     }
668
669     if (db_path != path)
670         free ((char *) db_path);
671
672     return ret;
673 }
674
675 time_t
676 notmuch_database_get_directory_mtime (notmuch_database_t *notmuch,
677                                       const char *path)
678 {
679     Xapian::Document doc;
680     unsigned int doc_id;
681     notmuch_private_status_t status;
682     const char *db_path = NULL;
683     time_t ret = 0;
684
685     db_path = directory_db_path (path);
686
687     try {
688         status = find_directory_document (notmuch, db_path, &doc, &doc_id);
689
690         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
691             goto DONE;
692
693         ret =  Xapian::sortable_unserialise (doc.get_value (NOTMUCH_VALUE_TIMESTAMP));
694     } catch (Xapian::Error &error) {
695         ret = 0;
696         goto DONE;
697     }
698
699   DONE:
700     if (db_path != path)
701         free ((char *) db_path);
702
703     return ret;
704 }
705
706 /* Find the thread ID to which the message with 'message_id' belongs.
707  *
708  * Returns NULL if no message with message ID 'message_id' is in the
709  * database.
710  *
711  * Otherwise, returns a newly talloced string belonging to 'ctx'.
712  */
713 static const char *
714 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
715                                   void *ctx,
716                                   const char *message_id)
717 {
718     notmuch_message_t *message;
719     const char *ret = NULL;
720
721     message = notmuch_database_find_message (notmuch, message_id);
722     if (message == NULL)
723         goto DONE;
724
725     ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
726
727   DONE:
728     if (message)
729         notmuch_message_destroy (message);
730
731     return ret;
732 }
733
734 static notmuch_status_t
735 _merge_threads (notmuch_database_t *notmuch,
736                 const char *winner_thread_id,
737                 const char *loser_thread_id)
738 {
739     Xapian::PostingIterator loser, loser_end;
740     notmuch_message_t *message = NULL;
741     notmuch_private_status_t private_status;
742     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
743
744     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
745
746     for ( ; loser != loser_end; loser++) {
747         message = _notmuch_message_create (notmuch, notmuch,
748                                            *loser, &private_status);
749         if (message == NULL) {
750             ret = COERCE_STATUS (private_status,
751                                  "Cannot find document for doc_id from query");
752             goto DONE;
753         }
754
755         _notmuch_message_remove_term (message, "thread", loser_thread_id);
756         _notmuch_message_add_term (message, "thread", winner_thread_id);
757         _notmuch_message_sync (message);
758
759         notmuch_message_destroy (message);
760         message = NULL;
761     }
762
763   DONE:
764     if (message)
765         notmuch_message_destroy (message);
766
767     return ret;
768 }
769
770 static void
771 _my_talloc_free_for_g_hash (void *ptr)
772 {
773     talloc_free (ptr);
774 }
775
776 static notmuch_status_t
777 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
778                                            notmuch_message_t *message,
779                                            notmuch_message_file_t *message_file,
780                                            const char **thread_id)
781 {
782     GHashTable *parents = NULL;
783     const char *refs, *in_reply_to, *in_reply_to_message_id;
784     GList *l, *keys = NULL;
785     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
786
787     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
788                                      _my_talloc_free_for_g_hash, NULL);
789
790     refs = notmuch_message_file_get_header (message_file, "references");
791     parse_references (message, notmuch_message_get_message_id (message),
792                       parents, refs);
793
794     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
795     parse_references (message, notmuch_message_get_message_id (message),
796                       parents, in_reply_to);
797
798     /* Carefully avoid adding any self-referential in-reply-to term. */
799     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
800     if (in_reply_to_message_id &&
801         strcmp (in_reply_to_message_id,
802                 notmuch_message_get_message_id (message)))
803     {
804         _notmuch_message_add_term (message, "replyto",
805                              _parse_message_id (message, in_reply_to, NULL));
806     }
807
808     keys = g_hash_table_get_keys (parents);
809     for (l = keys; l; l = l->next) {
810         char *parent_message_id;
811         const char *parent_thread_id;
812
813         parent_message_id = (char *) l->data;
814         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
815                                                              message,
816                                                              parent_message_id);
817
818         if (parent_thread_id == NULL) {
819             _notmuch_message_add_term (message, "reference",
820                                        parent_message_id);
821         } else {
822             if (*thread_id == NULL) {
823                 *thread_id = talloc_strdup (message, parent_thread_id);
824                 _notmuch_message_add_term (message, "thread", *thread_id);
825             } else if (strcmp (*thread_id, parent_thread_id)) {
826                 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
827                 if (ret)
828                     goto DONE;
829             }
830         }
831     }
832
833   DONE:
834     if (keys)
835         g_list_free (keys);
836     if (parents)
837         g_hash_table_unref (parents);
838
839     return ret;
840 }
841
842 static notmuch_status_t
843 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
844                                             notmuch_message_t *message,
845                                             const char **thread_id)
846 {
847     const char *message_id = notmuch_message_get_message_id (message);
848     Xapian::PostingIterator child, children_end;
849     notmuch_message_t *child_message = NULL;
850     const char *child_thread_id;
851     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
852     notmuch_private_status_t private_status;
853
854     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
855
856     for ( ; child != children_end; child++) {
857
858         child_message = _notmuch_message_create (message, notmuch,
859                                                  *child, &private_status);
860         if (child_message == NULL) {
861             ret = COERCE_STATUS (private_status,
862                                  "Cannot find document for doc_id from query");
863             goto DONE;
864         }
865
866         child_thread_id = notmuch_message_get_thread_id (child_message);
867         if (*thread_id == NULL) {
868             *thread_id = talloc_strdup (message, child_thread_id);
869             _notmuch_message_add_term (message, "thread", *thread_id);
870         } else if (strcmp (*thread_id, child_thread_id)) {
871             _notmuch_message_remove_term (child_message, "reference",
872                                           message_id);
873             _notmuch_message_sync (child_message);
874             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
875             if (ret)
876                 goto DONE;
877         }
878
879         notmuch_message_destroy (child_message);
880         child_message = NULL;
881     }
882
883   DONE:
884     if (child_message)
885         notmuch_message_destroy (child_message);
886
887     return ret;
888 }
889
890 /* Given a (mostly empty) 'message' and its corresponding
891  * 'message_file' link it to existing threads in the database.
892  *
893  * We first look at 'message_file' and its link-relevant headers
894  * (References and In-Reply-To) for message IDs. We also look in the
895  * database for existing message that reference 'message'.
896  *
897  * The end result is to call _notmuch_message_ensure_thread_id which
898  * generates a new thread ID if the message doesn't connect to any
899  * existing threads.
900  */
901 static notmuch_status_t
902 _notmuch_database_link_message (notmuch_database_t *notmuch,
903                                 notmuch_message_t *message,
904                                 notmuch_message_file_t *message_file)
905 {
906     notmuch_status_t status;
907     const char *thread_id = NULL;
908
909     status = _notmuch_database_link_message_to_parents (notmuch, message,
910                                                         message_file,
911                                                         &thread_id);
912     if (status)
913         return status;
914
915     status = _notmuch_database_link_message_to_children (notmuch, message,
916                                                          &thread_id);
917     if (status)
918         return status;
919
920     if (thread_id == NULL)
921         _notmuch_message_ensure_thread_id (message);
922
923     return NOTMUCH_STATUS_SUCCESS;
924 }
925
926 notmuch_status_t
927 notmuch_database_add_message (notmuch_database_t *notmuch,
928                               const char *filename,
929                               notmuch_message_t **message_ret)
930 {
931     notmuch_message_file_t *message_file;
932     notmuch_message_t *message = NULL;
933     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
934     notmuch_private_status_t private_status;
935
936     const char *date, *header;
937     const char *from, *to, *subject;
938     char *message_id = NULL;
939
940     if (message_ret)
941         *message_ret = NULL;
942
943     message_file = notmuch_message_file_open (filename);
944     if (message_file == NULL) {
945         ret = NOTMUCH_STATUS_FILE_ERROR;
946         goto DONE;
947     }
948
949     notmuch_message_file_restrict_headers (message_file,
950                                            "date",
951                                            "from",
952                                            "in-reply-to",
953                                            "message-id",
954                                            "references",
955                                            "subject",
956                                            "to",
957                                            (char *) NULL);
958
959     try {
960         /* Before we do any real work, (especially before doing a
961          * potential SHA-1 computation on the entire file's contents),
962          * let's make sure that what we're looking at looks like an
963          * actual email message.
964          */
965         from = notmuch_message_file_get_header (message_file, "from");
966         subject = notmuch_message_file_get_header (message_file, "subject");
967         to = notmuch_message_file_get_header (message_file, "to");
968
969         if ((from == NULL || *from == '\0') &&
970             (subject == NULL || *subject == '\0') &&
971             (to == NULL || *to == '\0'))
972         {
973             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
974             goto DONE;
975         }
976
977         /* Now that we're sure it's mail, the first order of business
978          * is to find a message ID (or else create one ourselves). */
979
980         header = notmuch_message_file_get_header (message_file, "message-id");
981         if (header && *header != '\0') {
982             message_id = _parse_message_id (message_file, header, NULL);
983
984             /* So the header value isn't RFC-compliant, but it's
985              * better than no message-id at all. */
986             if (message_id == NULL)
987                 message_id = talloc_strdup (message_file, header);
988
989             /* Reject a Message ID that's too long. */
990             if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
991                 talloc_free (message_id);
992                 message_id = NULL;
993             }
994         }
995
996         if (message_id == NULL ) {
997             /* No message-id at all, let's generate one by taking a
998              * hash over the file's contents. */
999             char *sha1 = notmuch_sha1_of_file (filename);
1000
1001             /* If that failed too, something is really wrong. Give up. */
1002             if (sha1 == NULL) {
1003                 ret = NOTMUCH_STATUS_FILE_ERROR;
1004                 goto DONE;
1005             }
1006
1007             message_id = talloc_asprintf (message_file,
1008                                           "notmuch-sha1-%s", sha1);
1009             free (sha1);
1010         }
1011
1012         /* Now that we have a message ID, we get a message object,
1013          * (which may or may not reference an existing document in the
1014          * database). */
1015
1016         message = _notmuch_message_create_for_message_id (notmuch,
1017                                                           message_id,
1018                                                           &private_status);
1019
1020         talloc_free (message_id);
1021
1022         if (message == NULL) {
1023             ret = COERCE_STATUS (private_status,
1024                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1025             goto DONE;
1026         }
1027
1028         /* Is this a newly created message object? */
1029         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1030             _notmuch_message_set_filename (message, filename);
1031             _notmuch_message_add_term (message, "type", "mail");
1032         } else {
1033             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1034             goto DONE;
1035         }
1036
1037         ret = _notmuch_database_link_message (notmuch, message, message_file);
1038         if (ret)
1039             goto DONE;
1040
1041         date = notmuch_message_file_get_header (message_file, "date");
1042         _notmuch_message_set_date (message, date);
1043
1044         _notmuch_message_index_file (message, filename);
1045
1046         _notmuch_message_sync (message);
1047     } catch (const Xapian::Error &error) {
1048         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1049                  error.get_description().c_str());
1050         notmuch->exception_reported = TRUE;
1051         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1052         goto DONE;
1053     }
1054
1055   DONE:
1056     if (message) {
1057         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1058             *message_ret = message;
1059         else
1060             notmuch_message_destroy (message);
1061     }
1062
1063     if (message_file)
1064         notmuch_message_file_close (message_file);
1065
1066     return ret;
1067 }
1068
1069 notmuch_tags_t *
1070 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1071                        Xapian::TermIterator &end)
1072 {
1073     const char *prefix = _find_prefix ("tag");
1074     notmuch_tags_t *tags;
1075     std::string tag;
1076
1077     /* Currently this iteration is written with the assumption that
1078      * "tag" has a single-character prefix. */
1079     assert (strlen (prefix) == 1);
1080
1081     tags = _notmuch_tags_create (ctx);
1082     if (unlikely (tags == NULL))
1083         return NULL;
1084
1085     i.skip_to (prefix);
1086
1087     while (i != end) {
1088         tag = *i;
1089
1090         if (tag.empty () || tag[0] != *prefix)
1091             break;
1092
1093         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1094
1095         i++;
1096     }
1097
1098     _notmuch_tags_prepare_iterator (tags);
1099
1100     return tags;
1101 }
1102
1103 notmuch_tags_t *
1104 notmuch_database_get_all_tags (notmuch_database_t *db)
1105 {
1106     Xapian::TermIterator i, end;
1107     i = db->xapian_db->allterms_begin();
1108     end = db->xapian_db->allterms_end();
1109     return _notmuch_convert_tags(db, i, end);
1110 }