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