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