]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
6afc8d938e382eb054d8088bd067d03193547ef0
[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 <sys/time.h>
26 #include <signal.h>
27 #include <xapian.h>
28
29 #include <glib.h> /* g_free, GPtrArray, GHashTable */
30
31 using namespace std;
32
33 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
34
35 typedef struct {
36     const char *name;
37     const char *prefix;
38 } prefix_t;
39
40 #define NOTMUCH_DATABASE_VERSION 1
41
42 #define STRINGIFY(s) _SUB_STRINGIFY(s)
43 #define _SUB_STRINGIFY(s) #s
44
45 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
46  *
47  * We currently have two different types of documents (mail and
48  * directory) and also some metadata.
49  *
50  * Mail document
51  * -------------
52  * A mail document is associated with a particular email message file
53  * on disk. It is indexed with the following prefixed terms which the
54  * database uses to construct threads, etc.:
55  *
56  *    Single terms of given prefix:
57  *
58  *      type:   mail
59  *
60  *      id:     Unique ID of mail, (from Message-ID header or generated
61  *              as "notmuch-sha1-<sha1_sum_of_entire_file>.
62  *
63  *      thread: The ID of the thread to which the mail belongs
64  *
65  *      replyto: The ID from the In-Reply-To header of the mail (if any).
66  *
67  *    Multiple terms of given prefix:
68  *
69  *      reference: All message IDs from In-Reply-To and Re ferences
70  *                 headers in the message.
71  *
72  *      tag:       Any tags associated with this message by the user.
73  *
74  *      file-direntry:  A colon-separated pair of values
75  *                      (INTEGER:STRING), where INTEGER is the
76  *                      document ID of a directory document, and
77  *                      STRING is the name of a file within that
78  *                      directory for this mail message.
79  *
80  *    A mail document also has two values:
81  *
82  *      TIMESTAMP:      The time_t value corresponding to the message's
83  *                      Date header.
84  *
85  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
86  *
87  * In addition, terms from the content of the message are added with
88  * "from", "to", "attachment", and "subject" prefixes for use by the
89  * user in searching. But the database doesn't really care itself
90  * about any of these.
91  *
92  * The data portion of a mail document is empty.
93  *
94  * Directory document
95  * ------------------
96  * A directory document is used by a client of the notmuch library to
97  * maintain data necessary to allow for efficient polling of mail
98  * directories.
99  *
100  * All directory documents contain one term:
101  *
102  *      directory:      The directory path (relative to the database path)
103  *                      Or the SHA1 sum of the directory path (if the
104  *                      path itself is too long to fit in a Xapian
105  *                      term).
106  *
107  * And all directory documents for directories other than top-level
108  * directories also contain the following term:
109  *
110  *      directory-direntry: A colon-separated pair of values
111  *                          (INTEGER:STRING), where INTEGER is the
112  *                          document ID of the parent directory
113  *                          document, and STRING is the name of this
114  *                          directory within that parent.
115  *
116  * All directory documents have a single value:
117  *
118  *      TIMESTAMP:      The mtime of the directory (at last scan)
119  *
120  * The data portion of a directory document contains the path of the
121  * directory (relative to the database path).
122  *
123  * Database metadata
124  * -----------------
125  * Xapian allows us to store arbitrary name-value pairs as
126  * "metadata". We currently use the following metadata names with the
127  * given meanings:
128  *
129  *      version         The database schema version, (which is distinct
130  *                      from both the notmuch package version (see
131  *                      notmuch --version) and the libnotmuch library
132  *                      version. The version is stored as an base-10
133  *                      ASCII integer. The initial database version
134  *                      was 1, (though a schema existed before that
135  *                      were no "version" database value existed at
136  *                      all). Succesive versions are allocated as
137  *                      changes are made to the database (such as by
138  *                      indexing new fields).
139  *
140  *      last_thread_id  The last thread ID generated. This is stored
141  *                      as a 16-byte hexadecimal ASCII representation
142  *                      of a 64-bit unsigned integer. The first ID
143  *                      generated is 1 and the value will be
144  *                      incremented for each thread ID.
145  *
146  *      thread_id_*     A pre-allocated thread ID for a particular
147  *                      message. This is actually an arbitarily large
148  *                      family of metadata name. Any particular name
149  *                      is formed by concatenating "thread_id_" with a
150  *                      message ID. The value stored is a thread ID.
151  *
152  *                      These thread ID metadata values are stored
153  *                      whenever a message references a parent message
154  *                      that does not yet exist in the database. A
155  *                      thread ID will be allocated and stored, and if
156  *                      the message is later added, the stored thread
157  *                      ID will be used (and the metadata value will
158  *                      be cleared).
159  *
160  *                      Even before a message is added, it's
161  *                      pre-allocated thread ID is useful so that all
162  *                      descendant messages that reference this common
163  *                      parent can be recognized as belonging to the
164  *                      same thread.
165  */
166
167 /* With these prefix values we follow the conventions published here:
168  *
169  * http://xapian.org/docs/omega/termprefixes.html
170  *
171  * as much as makes sense. Note that I took some liberty in matching
172  * the reserved prefix values to notmuch concepts, (for example, 'G'
173  * is documented as "newsGroup (or similar entity - e.g. a web forum
174  * name)", for which I think the thread is the closest analogue in
175  * notmuch. This in spite of the fact that we will eventually be
176  * storing mailing-list messages where 'G' for "mailing list name"
177  * might be even a closer analogue. I'm treating the single-character
178  * prefixes preferentially for core notmuch concepts (which will be
179  * nearly universal to all mail messages).
180  */
181
182 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
183     { "type",                   "T" },
184     { "reference",              "XREFERENCE" },
185     { "replyto",                "XREPLYTO" },
186     { "directory",              "XDIRECTORY" },
187     { "file-direntry",          "XFDIRENTRY" },
188     { "directory-direntry",     "XDDIRENTRY" },
189 };
190
191 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
192     { "thread",                 "G" },
193     { "tag",                    "K" },
194     { "is",                     "K" },
195     { "id",                     "Q" }
196 };
197
198 prefix_t PROBABILISTIC_PREFIX[]= {
199     { "from",                   "XFROM" },
200     { "to",                     "XTO" },
201     { "attachment",             "XATTACHMENT" },
202     { "subject",                "XSUBJECT"}
203 };
204
205 int
206 _internal_error (const char *format, ...)
207 {
208     va_list va_args;
209
210     va_start (va_args, format);
211
212     fprintf (stderr, "Internal error: ");
213     vfprintf (stderr, format, va_args);
214
215     exit (1);
216
217     return 1;
218 }
219
220 const char *
221 _find_prefix (const char *name)
222 {
223     unsigned int i;
224
225     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
226         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
227             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
228     }
229
230     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
231         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
232             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
233     }
234
235     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
236         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
237             return PROBABILISTIC_PREFIX[i].prefix;
238     }
239
240     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
241
242     return "";
243 }
244
245 const char *
246 notmuch_status_to_string (notmuch_status_t status)
247 {
248     switch (status) {
249     case NOTMUCH_STATUS_SUCCESS:
250         return "No error occurred";
251     case NOTMUCH_STATUS_OUT_OF_MEMORY:
252         return "Out of memory";
253     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
254         return "Attempt to write to a read-only database";
255     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
256         return "A Xapian exception occurred";
257     case NOTMUCH_STATUS_FILE_ERROR:
258         return "Something went wrong trying to read or write a file";
259     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
260         return "File is not an email";
261     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
262         return "Message ID is identical to a message in database";
263     case NOTMUCH_STATUS_NULL_POINTER:
264         return "Erroneous NULL pointer";
265     case NOTMUCH_STATUS_TAG_TOO_LONG:
266         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
267     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
268         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
269     default:
270     case NOTMUCH_STATUS_LAST_STATUS:
271         return "Unknown error status value";
272     }
273 }
274
275 static void
276 find_doc_ids_for_term (notmuch_database_t *notmuch,
277                        const char *term,
278                        Xapian::PostingIterator *begin,
279                        Xapian::PostingIterator *end)
280 {
281     *begin = notmuch->xapian_db->postlist_begin (term);
282
283     *end = notmuch->xapian_db->postlist_end (term);
284 }
285
286 static void
287 find_doc_ids (notmuch_database_t *notmuch,
288               const char *prefix_name,
289               const char *value,
290               Xapian::PostingIterator *begin,
291               Xapian::PostingIterator *end)
292 {
293     char *term;
294
295     term = talloc_asprintf (notmuch, "%s%s",
296                             _find_prefix (prefix_name), value);
297
298     find_doc_ids_for_term (notmuch, term, begin, end);
299
300     talloc_free (term);
301 }
302
303 notmuch_private_status_t
304 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
305                                       const char *prefix_name,
306                                       const char *value,
307                                       unsigned int *doc_id)
308 {
309     Xapian::PostingIterator i, end;
310
311     find_doc_ids (notmuch, prefix_name, value, &i, &end);
312
313     if (i == end) {
314         *doc_id = 0;
315         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
316     }
317
318     *doc_id = *i;
319
320 #if DEBUG_DATABASE_SANITY
321     i++;
322
323     if (i != end)
324         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
325                         prefix_name, value);
326 #endif
327
328     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
329 }
330
331 static Xapian::Document
332 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
333 {
334     return notmuch->xapian_db->get_document (doc_id);
335 }
336
337 notmuch_message_t *
338 notmuch_database_find_message (notmuch_database_t *notmuch,
339                                const char *message_id)
340 {
341     notmuch_private_status_t status;
342     unsigned int doc_id;
343
344     try {
345         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
346                                                        message_id, &doc_id);
347
348         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
349             return NULL;
350
351         return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
352     } catch (const Xapian::Error &error) {
353         fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
354                  error.get_msg().c_str());
355         notmuch->exception_reported = TRUE;
356         return NULL;
357     }
358 }
359
360 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
361  * a (potentially nested) parenthesized sequence with '\' used to
362  * escape any character (including parentheses).
363  *
364  * If the sequence to be skipped continues to the end of the string,
365  * then 'str' will be left pointing at the final terminating '\0'
366  * character.
367  */
368 static void
369 skip_space_and_comments (const char **str)
370 {
371     const char *s;
372
373     s = *str;
374     while (*s && (isspace (*s) || *s == '(')) {
375         while (*s && isspace (*s))
376             s++;
377         if (*s == '(') {
378             int nesting = 1;
379             s++;
380             while (*s && nesting) {
381                 if (*s == '(') {
382                     nesting++;
383                 } else if (*s == ')') {
384                     nesting--;
385                 } else if (*s == '\\') {
386                     if (*(s+1))
387                         s++;
388                 }
389                 s++;
390             }
391         }
392     }
393
394     *str = s;
395 }
396
397 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
398  * comments, and the '<' and '>' delimeters.
399  *
400  * If not NULL, then *next will be made to point to the first character
401  * not parsed, (possibly pointing to the final '\0' terminator.
402  *
403  * Returns a newly talloc'ed string belonging to 'ctx'.
404  *
405  * Returns NULL if there is any error parsing the message-id. */
406 static char *
407 _parse_message_id (void *ctx, const char *message_id, const char **next)
408 {
409     const char *s, *end;
410     char *result;
411
412     if (message_id == NULL || *message_id == '\0')
413         return NULL;
414
415     s = message_id;
416
417     skip_space_and_comments (&s);
418
419     /* Skip any unstructured text as well. */
420     while (*s && *s != '<')
421         s++;
422
423     if (*s == '<') {
424         s++;
425     } else {
426         if (next)
427             *next = s;
428         return NULL;
429     }
430
431     skip_space_and_comments (&s);
432
433     end = s;
434     while (*end && *end != '>')
435         end++;
436     if (next) {
437         if (*end)
438             *next = end + 1;
439         else
440             *next = end;
441     }
442
443     if (end > s && *end == '>')
444         end--;
445     if (end <= s)
446         return NULL;
447
448     result = talloc_strndup (ctx, s, end - s + 1);
449
450     /* Finally, collapse any whitespace that is within the message-id
451      * itself. */
452     {
453         char *r;
454         int len;
455
456         for (r = result, len = strlen (r); *r; r++, len--)
457             if (*r == ' ' || *r == '\t')
458                 memmove (r, r+1, len);
459     }
460
461     return result;
462 }
463
464 /* Parse a References header value, putting a (talloc'ed under 'ctx')
465  * copy of each referenced message-id into 'hash'.
466  *
467  * We explicitly avoid including any reference identical to
468  * 'message_id' in the result (to avoid mass confusion when a single
469  * message references itself cyclically---and yes, mail messages are
470  * not infrequent in the wild that do this---don't ask me why).
471 */
472 static void
473 parse_references (void *ctx,
474                   const char *message_id,
475                   GHashTable *hash,
476                   const char *refs)
477 {
478     char *ref;
479
480     if (refs == NULL || *refs == '\0')
481         return;
482
483     while (*refs) {
484         ref = _parse_message_id (ctx, refs, &refs);
485
486         if (ref && strcmp (ref, message_id))
487             g_hash_table_insert (hash, ref, NULL);
488     }
489 }
490
491 notmuch_database_t *
492 notmuch_database_create (const char *path)
493 {
494     notmuch_database_t *notmuch = NULL;
495     char *notmuch_path = NULL;
496     struct stat st;
497     int err;
498
499     if (path == NULL) {
500         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
501         goto DONE;
502     }
503
504     err = stat (path, &st);
505     if (err) {
506         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
507                  path, strerror (errno));
508         goto DONE;
509     }
510
511     if (! S_ISDIR (st.st_mode)) {
512         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
513                  path);
514         goto DONE;
515     }
516
517     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
518
519     err = mkdir (notmuch_path, 0755);
520
521     if (err) {
522         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
523                  notmuch_path, strerror (errno));
524         goto DONE;
525     }
526
527     notmuch = notmuch_database_open (path,
528                                      NOTMUCH_DATABASE_MODE_READ_WRITE);
529     notmuch_database_upgrade (notmuch, NULL, NULL);
530
531   DONE:
532     if (notmuch_path)
533         talloc_free (notmuch_path);
534
535     return notmuch;
536 }
537
538 notmuch_status_t
539 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
540 {
541     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
542         fprintf (stderr, "Cannot write to a read-only database.\n");
543         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
544     }
545
546     return NOTMUCH_STATUS_SUCCESS;
547 }
548
549 notmuch_database_t *
550 notmuch_database_open (const char *path,
551                        notmuch_database_mode_t mode)
552 {
553     notmuch_database_t *notmuch = NULL;
554     char *notmuch_path = NULL, *xapian_path = NULL;
555     struct stat st;
556     int err;
557     unsigned int i, version;
558
559     if (asprintf (&notmuch_path, "%s/%s", path, ".notmuch") == -1) {
560         notmuch_path = NULL;
561         fprintf (stderr, "Out of memory\n");
562         goto DONE;
563     }
564
565     err = stat (notmuch_path, &st);
566     if (err) {
567         fprintf (stderr, "Error opening database at %s: %s\n",
568                  notmuch_path, strerror (errno));
569         goto DONE;
570     }
571
572     if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
573         xapian_path = NULL;
574         fprintf (stderr, "Out of memory\n");
575         goto DONE;
576     }
577
578     notmuch = talloc (NULL, notmuch_database_t);
579     notmuch->exception_reported = FALSE;
580     notmuch->path = talloc_strdup (notmuch, path);
581
582     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
583         notmuch->path[strlen (notmuch->path) - 1] = '\0';
584
585     notmuch->needs_upgrade = FALSE;
586     notmuch->mode = mode;
587     try {
588         string last_thread_id;
589
590         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
591             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
592                                                                Xapian::DB_CREATE_OR_OPEN);
593             version = notmuch_database_get_version (notmuch);
594
595             if (version > NOTMUCH_DATABASE_VERSION) {
596                 fprintf (stderr,
597                          "Error: Notmuch database at %s\n"
598                          "       has a newer database format version (%u) than supported by this\n"
599                          "       version of notmuch (%u). Refusing to open this database in\n"
600                          "       read-write mode.\n",
601                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
602                 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
603                 notmuch_database_close (notmuch);
604                 notmuch = NULL;
605                 goto DONE;
606             }
607
608             if (version < NOTMUCH_DATABASE_VERSION)
609                 notmuch->needs_upgrade = TRUE;
610         } else {
611             notmuch->xapian_db = new Xapian::Database (xapian_path);
612             version = notmuch_database_get_version (notmuch);
613             if (version > NOTMUCH_DATABASE_VERSION)
614             {
615                 fprintf (stderr,
616                          "Warning: Notmuch database at %s\n"
617                          "         has a newer database format version (%u) than supported by this\n"
618                          "         version of notmuch (%u). Some operations may behave incorrectly,\n"
619                          "         (but the database will not be harmed since it is being opened\n"
620                          "         in read-only mode).\n",
621                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
622             }
623         }
624
625         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
626         if (last_thread_id.empty ()) {
627             notmuch->last_thread_id = 0;
628         } else {
629             const char *str;
630             char *end;
631
632             str = last_thread_id.c_str ();
633             notmuch->last_thread_id = strtoull (str, &end, 16);
634             if (*end != '\0')
635                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
636         }
637
638         notmuch->query_parser = new Xapian::QueryParser;
639         notmuch->term_gen = new Xapian::TermGenerator;
640         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
641         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
642
643         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
644         notmuch->query_parser->set_database (*notmuch->xapian_db);
645         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
646         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
647         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
648
649         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
650             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
651             notmuch->query_parser->add_boolean_prefix (prefix->name,
652                                                        prefix->prefix);
653         }
654
655         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
656             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
657             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
658         }
659     } catch (const Xapian::Error &error) {
660         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
661                  error.get_msg().c_str());
662         notmuch = NULL;
663     }
664
665   DONE:
666     if (notmuch_path)
667         free (notmuch_path);
668     if (xapian_path)
669         free (xapian_path);
670
671     return notmuch;
672 }
673
674 void
675 notmuch_database_close (notmuch_database_t *notmuch)
676 {
677     try {
678         if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
679             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
680     } catch (const Xapian::Error &error) {
681         if (! notmuch->exception_reported) {
682             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
683                      error.get_msg().c_str());
684         }
685     }
686
687     delete notmuch->term_gen;
688     delete notmuch->query_parser;
689     delete notmuch->xapian_db;
690     delete notmuch->value_range_processor;
691     talloc_free (notmuch);
692 }
693
694 const char *
695 notmuch_database_get_path (notmuch_database_t *notmuch)
696 {
697     return notmuch->path;
698 }
699
700 unsigned int
701 notmuch_database_get_version (notmuch_database_t *notmuch)
702 {
703     unsigned int version;
704     string version_string;
705     const char *str;
706     char *end;
707
708     version_string = notmuch->xapian_db->get_metadata ("version");
709     if (version_string.empty ())
710         return 0;
711
712     str = version_string.c_str ();
713     if (str == NULL || *str == '\0')
714         return 0;
715
716     version = strtoul (str, &end, 10);
717     if (*end != '\0')
718         INTERNAL_ERROR ("Malformed database version: %s", str);
719
720     return version;
721 }
722
723 notmuch_bool_t
724 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
725 {
726     return notmuch->needs_upgrade;
727 }
728
729 static volatile sig_atomic_t do_progress_notify = 0;
730
731 static void
732 handle_sigalrm (unused (int signal))
733 {
734     do_progress_notify = 1;
735 }
736
737 /* Upgrade the current database.
738  *
739  * After opening a database in read-write mode, the client should
740  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
741  * if so, upgrade with this function before making any modifications.
742  *
743  * The optional progress_notify callback can be used by the caller to
744  * provide progress indication to the user. If non-NULL it will be
745  * called periodically with 'count' as the number of messages upgraded
746  * so far and 'total' the overall number of messages that will be
747  * converted.
748  */
749 notmuch_status_t
750 notmuch_database_upgrade (notmuch_database_t *notmuch,
751                           void (*progress_notify) (void *closure,
752                                                    double progress),
753                           void *closure)
754 {
755     Xapian::WritableDatabase *db;
756     struct sigaction action;
757     struct itimerval timerval;
758     notmuch_bool_t timer_is_active = FALSE;
759     unsigned int version;
760     notmuch_status_t status;
761     unsigned int count = 0, total = 0;
762
763     status = _notmuch_database_ensure_writable (notmuch);
764     if (status)
765         return status;
766
767     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
768
769     version = notmuch_database_get_version (notmuch);
770
771     if (version >= NOTMUCH_DATABASE_VERSION)
772         return NOTMUCH_STATUS_SUCCESS;
773
774     if (progress_notify) {
775         /* Setup our handler for SIGALRM */
776         memset (&action, 0, sizeof (struct sigaction));
777         action.sa_handler = handle_sigalrm;
778         sigemptyset (&action.sa_mask);
779         action.sa_flags = SA_RESTART;
780         sigaction (SIGALRM, &action, NULL);
781
782         /* Then start a timer to send SIGALRM once per second. */
783         timerval.it_interval.tv_sec = 1;
784         timerval.it_interval.tv_usec = 0;
785         timerval.it_value.tv_sec = 1;
786         timerval.it_value.tv_usec = 0;
787         setitimer (ITIMER_REAL, &timerval, NULL);
788
789         timer_is_active = TRUE;
790     }
791
792     /* Before version 1, each message document had its filename in the
793      * data field. Copy that into the new format by calling
794      * notmuch_message_add_filename.
795      */
796     if (version < 1) {
797         notmuch_query_t *query = notmuch_query_create (notmuch, "");
798         notmuch_messages_t *messages;
799         notmuch_message_t *message;
800         char *filename;
801         Xapian::TermIterator t, t_end;
802
803         total = notmuch_query_count_messages (query);
804
805         for (messages = notmuch_query_search_messages (query);
806              notmuch_messages_valid (messages);
807              notmuch_messages_move_to_next (messages))
808         {
809             if (do_progress_notify) {
810                 progress_notify (closure, (double) count / total);
811                 do_progress_notify = 0;
812             }
813
814             message = notmuch_messages_get (messages);
815
816             filename = _notmuch_message_talloc_copy_data (message);
817             if (filename && *filename != '\0') {
818                 _notmuch_message_add_filename (message, filename);
819                 _notmuch_message_sync (message);
820             }
821             talloc_free (filename);
822
823             notmuch_message_destroy (message);
824
825             count++;
826         }
827
828         notmuch_query_destroy (query);
829
830         /* Also, before version 1 we stored directory timestamps in
831          * XTIMESTAMP documents instead of the current XDIRECTORY
832          * documents. So copy those as well. */
833
834         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
835
836         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
837              t != t_end;
838              t++)
839         {
840             Xapian::PostingIterator p, p_end;
841             std::string term = *t;
842
843             p_end = notmuch->xapian_db->postlist_end (term);
844
845             for (p = notmuch->xapian_db->postlist_begin (term);
846                  p != p_end;
847                  p++)
848             {
849                 Xapian::Document document;
850                 time_t mtime;
851                 notmuch_directory_t *directory;
852
853                 if (do_progress_notify) {
854                     progress_notify (closure, (double) count / total);
855                     do_progress_notify = 0;
856                 }
857
858                 document = find_document_for_doc_id (notmuch, *p);
859                 mtime = Xapian::sortable_unserialise (
860                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
861
862                 directory = notmuch_database_get_directory (notmuch,
863                                                             term.c_str() + 10);
864                 notmuch_directory_set_mtime (directory, mtime);
865                 notmuch_directory_destroy (directory);
866             }
867         }
868     }
869
870     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
871     db->flush ();
872
873     /* Now that the upgrade is complete we can remove the old data
874      * and documents that are no longer needed. */
875     if (version < 1) {
876         notmuch_query_t *query = notmuch_query_create (notmuch, "");
877         notmuch_messages_t *messages;
878         notmuch_message_t *message;
879         char *filename;
880
881         for (messages = notmuch_query_search_messages (query);
882              notmuch_messages_valid (messages);
883              notmuch_messages_move_to_next (messages))
884         {
885             if (do_progress_notify) {
886                 progress_notify (closure, (double) count / total);
887                 do_progress_notify = 0;
888             }
889
890             message = notmuch_messages_get (messages);
891
892             filename = _notmuch_message_talloc_copy_data (message);
893             if (filename && *filename != '\0') {
894                 _notmuch_message_clear_data (message);
895                 _notmuch_message_sync (message);
896             }
897             talloc_free (filename);
898
899             notmuch_message_destroy (message);
900         }
901
902         notmuch_query_destroy (query);
903     }
904
905     if (version < 1) {
906         Xapian::TermIterator t, t_end;
907
908         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
909
910         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
911              t != t_end;
912              t++)
913         {
914             Xapian::PostingIterator p, p_end;
915             std::string term = *t;
916
917             p_end = notmuch->xapian_db->postlist_end (term);
918
919             for (p = notmuch->xapian_db->postlist_begin (term);
920                  p != p_end;
921                  p++)
922             {
923                 if (do_progress_notify) {
924                     progress_notify (closure, (double) count / total);
925                     do_progress_notify = 0;
926                 }
927
928                 db->delete_document (*p);
929             }
930         }
931     }
932
933     if (timer_is_active) {
934         /* Now stop the timer. */
935         timerval.it_interval.tv_sec = 0;
936         timerval.it_interval.tv_usec = 0;
937         timerval.it_value.tv_sec = 0;
938         timerval.it_value.tv_usec = 0;
939         setitimer (ITIMER_REAL, &timerval, NULL);
940
941         /* And disable the signal handler. */
942         action.sa_handler = SIG_IGN;
943         sigaction (SIGALRM, &action, NULL);
944     }
945
946     return NOTMUCH_STATUS_SUCCESS;
947 }
948
949 /* We allow the user to use arbitrarily long paths for directories. But
950  * we have a term-length limit. So if we exceed that, we'll use the
951  * SHA-1 of the path for the database term.
952  *
953  * Note: This function may return the original value of 'path'. If it
954  * does not, then the caller is responsible to free() the returned
955  * value.
956  */
957 const char *
958 _notmuch_database_get_directory_db_path (const char *path)
959 {
960     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
961
962     if (term_len > NOTMUCH_TERM_MAX)
963         return notmuch_sha1_of_string (path);
964     else
965         return path;
966 }
967
968 /* Given a path, split it into two parts: the directory part is all
969  * components except for the last, and the basename is that last
970  * component. Getting the return-value for either part is optional
971  * (the caller can pass NULL).
972  *
973  * The original 'path' can represent either a regular file or a
974  * directory---the splitting will be carried out in the same way in
975  * either case. Trailing slashes on 'path' will be ignored, and any
976  * cases of multiple '/' characters appearing in series will be
977  * treated as a single '/'.
978  *
979  * Allocation (if any) will have 'ctx' as the talloc owner. But
980  * pointers will be returned within the original path string whenever
981  * possible.
982  *
983  * Note: If 'path' is non-empty and contains no non-trailing slash,
984  * (that is, consists of a filename with no parent directory), then
985  * the directory returned will be an empty string. However, if 'path'
986  * is an empty string, then both directory and basename will be
987  * returned as NULL.
988  */
989 notmuch_status_t
990 _notmuch_database_split_path (void *ctx,
991                               const char *path,
992                               const char **directory,
993                               const char **basename)
994 {
995     const char *slash;
996
997     if (path == NULL || *path == '\0') {
998         if (directory)
999             *directory = NULL;
1000         if (basename)
1001             *basename = NULL;
1002         return NOTMUCH_STATUS_SUCCESS;
1003     }
1004
1005     /* Find the last slash (not counting a trailing slash), if any. */
1006
1007     slash = path + strlen (path) - 1;
1008
1009     /* First, skip trailing slashes. */
1010     while (slash != path) {
1011         if (*slash != '/')
1012             break;
1013
1014         --slash;
1015     }
1016
1017     /* Then, find a slash. */
1018     while (slash != path) {
1019         if (*slash == '/')
1020             break;
1021
1022         if (basename)
1023             *basename = slash;
1024
1025         --slash;
1026     }
1027
1028     /* Finally, skip multiple slashes. */
1029     while (slash != path) {
1030         if (*slash != '/')
1031             break;
1032
1033         --slash;
1034     }
1035
1036     if (slash == path) {
1037         if (directory)
1038             *directory = talloc_strdup (ctx, "");
1039         if (basename)
1040             *basename = path;
1041     } else {
1042         if (directory)
1043             *directory = talloc_strndup (ctx, path, slash - path + 1);
1044     }
1045
1046     return NOTMUCH_STATUS_SUCCESS;
1047 }
1048
1049 notmuch_status_t
1050 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1051                                      const char *path,
1052                                      unsigned int *directory_id)
1053 {
1054     notmuch_directory_t *directory;
1055     notmuch_status_t status;
1056
1057     if (path == NULL) {
1058         *directory_id = 0;
1059         return NOTMUCH_STATUS_SUCCESS;
1060     }
1061
1062     directory = _notmuch_directory_create (notmuch, path, &status);
1063     if (status) {
1064         *directory_id = -1;
1065         return status;
1066     }
1067
1068     *directory_id = _notmuch_directory_get_document_id (directory);
1069
1070     notmuch_directory_destroy (directory);
1071
1072     return NOTMUCH_STATUS_SUCCESS;
1073 }
1074
1075 const char *
1076 _notmuch_database_get_directory_path (void *ctx,
1077                                       notmuch_database_t *notmuch,
1078                                       unsigned int doc_id)
1079 {
1080     Xapian::Document document;
1081
1082     document = find_document_for_doc_id (notmuch, doc_id);
1083
1084     return talloc_strdup (ctx, document.get_data ().c_str ());
1085 }
1086
1087 /* Given a legal 'filename' for the database, (either relative to
1088  * database path or absolute with initial components identical to
1089  * database path), return a new string (with 'ctx' as the talloc
1090  * owner) suitable for use as a direntry term value.
1091  *
1092  * The necessary directory documents will be created in the database
1093  * as needed.
1094  */
1095 notmuch_status_t
1096 _notmuch_database_filename_to_direntry (void *ctx,
1097                                         notmuch_database_t *notmuch,
1098                                         const char *filename,
1099                                         char **direntry)
1100 {
1101     const char *relative, *directory, *basename;
1102     Xapian::docid directory_id;
1103     notmuch_status_t status;
1104
1105     relative = _notmuch_database_relative_path (notmuch, filename);
1106
1107     status = _notmuch_database_split_path (ctx, relative,
1108                                            &directory, &basename);
1109     if (status)
1110         return status;
1111
1112     status = _notmuch_database_find_directory_id (notmuch, directory,
1113                                                   &directory_id);
1114     if (status)
1115         return status;
1116
1117     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1118
1119     return NOTMUCH_STATUS_SUCCESS;
1120 }
1121
1122 /* Given a legal 'path' for the database, return the relative path.
1123  *
1124  * The return value will be a pointer to the originl path contents,
1125  * and will be either the original string (if 'path' was relative) or
1126  * a portion of the string (if path was absolute and begins with the
1127  * database path).
1128  */
1129 const char *
1130 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1131                                  const char *path)
1132 {
1133     const char *db_path, *relative;
1134     unsigned int db_path_len;
1135
1136     db_path = notmuch_database_get_path (notmuch);
1137     db_path_len = strlen (db_path);
1138
1139     relative = path;
1140
1141     if (*relative == '/') {
1142         while (*relative == '/' && *(relative+1) == '/')
1143             relative++;
1144
1145         if (strncmp (relative, db_path, db_path_len) == 0)
1146         {
1147             relative += db_path_len;
1148             while (*relative == '/')
1149                 relative++;
1150         }
1151     }
1152
1153     return relative;
1154 }
1155
1156 notmuch_directory_t *
1157 notmuch_database_get_directory (notmuch_database_t *notmuch,
1158                                 const char *path)
1159 {
1160     notmuch_status_t status;
1161
1162     try {
1163         return _notmuch_directory_create (notmuch, path, &status);
1164     } catch (const Xapian::Error &error) {
1165         fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1166                  error.get_msg().c_str());
1167         notmuch->exception_reported = TRUE;
1168         return NULL;
1169     }
1170 }
1171
1172 static const char *
1173 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1174 {
1175     /* 16 bytes (+ terminator) for hexadecimal representation of
1176      * a 64-bit integer. */
1177     static char thread_id[17];
1178     Xapian::WritableDatabase *db;
1179
1180     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1181
1182     notmuch->last_thread_id++;
1183
1184     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1185
1186     db->set_metadata ("last_thread_id", thread_id);
1187
1188     return thread_id;
1189 }
1190
1191 static char *
1192 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1193 {
1194     return talloc_asprintf (ctx, "thread_id_%s", message_id);
1195 }
1196
1197 /* Find the thread ID to which the message with 'message_id' belongs.
1198  *
1199  * Always returns a newly talloced string belonging to 'ctx'.
1200  *
1201  * Note: If there is no message in the database with the given
1202  * 'message_id' then a new thread_id will be allocated for this
1203  * message and stored in the database metadata, (where this same
1204  * thread ID can be looked up if the message is added to the database
1205  * later).
1206  */
1207 static const char *
1208 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1209                                   void *ctx,
1210                                   const char *message_id)
1211 {
1212     notmuch_message_t *message;
1213     string thread_id_string;
1214     const char *thread_id;
1215     char *metadata_key;
1216     Xapian::WritableDatabase *db;
1217
1218     message = notmuch_database_find_message (notmuch, message_id);
1219
1220     if (message) {
1221         thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1222
1223         notmuch_message_destroy (message);
1224
1225         return thread_id;
1226     }
1227
1228     /* Message has not been seen yet.
1229      *
1230      * We may have seen a reference to it already, in which case, we
1231      * can return the thread ID stored in the metadata. Otherwise, we
1232      * generate a new thread ID and store it there.
1233      */
1234     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1235     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1236     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1237
1238     if (thread_id_string.empty()) {
1239         thread_id = _notmuch_database_generate_thread_id (notmuch);
1240         db->set_metadata (metadata_key, thread_id);
1241     } else {
1242         thread_id = thread_id_string.c_str();
1243     }
1244
1245     talloc_free (metadata_key);
1246
1247     return thread_id;
1248 }
1249
1250 static notmuch_status_t
1251 _merge_threads (notmuch_database_t *notmuch,
1252                 const char *winner_thread_id,
1253                 const char *loser_thread_id)
1254 {
1255     Xapian::PostingIterator loser, loser_end;
1256     notmuch_message_t *message = NULL;
1257     notmuch_private_status_t private_status;
1258     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1259
1260     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1261
1262     for ( ; loser != loser_end; loser++) {
1263         message = _notmuch_message_create (notmuch, notmuch,
1264                                            *loser, &private_status);
1265         if (message == NULL) {
1266             ret = COERCE_STATUS (private_status,
1267                                  "Cannot find document for doc_id from query");
1268             goto DONE;
1269         }
1270
1271         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1272         _notmuch_message_add_term (message, "thread", winner_thread_id);
1273         _notmuch_message_sync (message);
1274
1275         notmuch_message_destroy (message);
1276         message = NULL;
1277     }
1278
1279   DONE:
1280     if (message)
1281         notmuch_message_destroy (message);
1282
1283     return ret;
1284 }
1285
1286 static void
1287 _my_talloc_free_for_g_hash (void *ptr)
1288 {
1289     talloc_free (ptr);
1290 }
1291
1292 static notmuch_status_t
1293 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1294                                            notmuch_message_t *message,
1295                                            notmuch_message_file_t *message_file,
1296                                            const char **thread_id)
1297 {
1298     GHashTable *parents = NULL;
1299     const char *refs, *in_reply_to, *in_reply_to_message_id;
1300     GList *l, *keys = NULL;
1301     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1302
1303     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1304                                      _my_talloc_free_for_g_hash, NULL);
1305
1306     refs = notmuch_message_file_get_header (message_file, "references");
1307     parse_references (message, notmuch_message_get_message_id (message),
1308                       parents, refs);
1309
1310     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1311     parse_references (message, notmuch_message_get_message_id (message),
1312                       parents, in_reply_to);
1313
1314     /* Carefully avoid adding any self-referential in-reply-to term. */
1315     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1316     if (in_reply_to_message_id &&
1317         strcmp (in_reply_to_message_id,
1318                 notmuch_message_get_message_id (message)))
1319     {
1320         _notmuch_message_add_term (message, "replyto",
1321                              _parse_message_id (message, in_reply_to, NULL));
1322     }
1323
1324     keys = g_hash_table_get_keys (parents);
1325     for (l = keys; l; l = l->next) {
1326         char *parent_message_id;
1327         const char *parent_thread_id;
1328
1329         parent_message_id = (char *) l->data;
1330
1331         _notmuch_message_add_term (message, "reference",
1332                                    parent_message_id);
1333
1334         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1335                                                              message,
1336                                                              parent_message_id);
1337
1338         if (*thread_id == NULL) {
1339             *thread_id = talloc_strdup (message, parent_thread_id);
1340             _notmuch_message_add_term (message, "thread", *thread_id);
1341         } else if (strcmp (*thread_id, parent_thread_id)) {
1342             ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1343             if (ret)
1344                 goto DONE;
1345         }
1346     }
1347
1348   DONE:
1349     if (keys)
1350         g_list_free (keys);
1351     if (parents)
1352         g_hash_table_unref (parents);
1353
1354     return ret;
1355 }
1356
1357 static notmuch_status_t
1358 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1359                                             notmuch_message_t *message,
1360                                             const char **thread_id)
1361 {
1362     const char *message_id = notmuch_message_get_message_id (message);
1363     Xapian::PostingIterator child, children_end;
1364     notmuch_message_t *child_message = NULL;
1365     const char *child_thread_id;
1366     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1367     notmuch_private_status_t private_status;
1368
1369     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1370
1371     for ( ; child != children_end; child++) {
1372
1373         child_message = _notmuch_message_create (message, notmuch,
1374                                                  *child, &private_status);
1375         if (child_message == NULL) {
1376             ret = COERCE_STATUS (private_status,
1377                                  "Cannot find document for doc_id from query");
1378             goto DONE;
1379         }
1380
1381         child_thread_id = notmuch_message_get_thread_id (child_message);
1382         if (*thread_id == NULL) {
1383             *thread_id = talloc_strdup (message, child_thread_id);
1384             _notmuch_message_add_term (message, "thread", *thread_id);
1385         } else if (strcmp (*thread_id, child_thread_id)) {
1386             _notmuch_message_remove_term (child_message, "reference",
1387                                           message_id);
1388             _notmuch_message_sync (child_message);
1389             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1390             if (ret)
1391                 goto DONE;
1392         }
1393
1394         notmuch_message_destroy (child_message);
1395         child_message = NULL;
1396     }
1397
1398   DONE:
1399     if (child_message)
1400         notmuch_message_destroy (child_message);
1401
1402     return ret;
1403 }
1404
1405 /* Given a (mostly empty) 'message' and its corresponding
1406  * 'message_file' link it to existing threads in the database.
1407  *
1408  * The first check is in the metadata of the database to see if we
1409  * have pre-allocated a thread_id in advance for this message, (which
1410  * would have happened if a message was previously added that
1411  * referenced this one).
1412  *
1413  * Second, we look at 'message_file' and its link-relevant headers
1414  * (References and In-Reply-To) for message IDs.
1415  *
1416  * Finally, we look in the database for existing message that
1417  * reference 'message'.
1418  *
1419  * In all cases, we assign to the current message the first thread_id
1420  * found (through either parent or child). We will also merge any
1421  * existing, distinct threads where this message belongs to both,
1422  * (which is not uncommon when mesages are processed out of order).
1423  *
1424  * Finally, if no thread ID has been found through parent or child, we
1425  * call _notmuch_message_generate_thread_id to generate a new thread
1426  * ID. This should only happen for new, top-level messages, (no
1427  * References or In-Reply-To header in this message, and no previously
1428  * added message refers to this message).
1429  */
1430 static notmuch_status_t
1431 _notmuch_database_link_message (notmuch_database_t *notmuch,
1432                                 notmuch_message_t *message,
1433                                 notmuch_message_file_t *message_file)
1434 {
1435     notmuch_status_t status;
1436     const char *message_id, *thread_id = NULL;
1437     char *metadata_key;
1438     string stored_id;
1439
1440     message_id = notmuch_message_get_message_id (message);
1441     metadata_key = _get_metadata_thread_id_key (message, message_id);
1442
1443     /* Check if we have already seen related messages to this one.
1444      * If we have then use the thread_id that we stored at that time.
1445      */
1446     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1447     if (! stored_id.empty()) {
1448         Xapian::WritableDatabase *db;
1449
1450         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1451
1452         /* Clear the metadata for this message ID. We don't need it
1453          * anymore. */
1454         db->set_metadata (metadata_key, "");
1455         thread_id = stored_id.c_str();
1456
1457         _notmuch_message_add_term (message, "thread", thread_id);
1458     }
1459     talloc_free (metadata_key);
1460
1461     status = _notmuch_database_link_message_to_parents (notmuch, message,
1462                                                         message_file,
1463                                                         &thread_id);
1464     if (status)
1465         return status;
1466
1467     status = _notmuch_database_link_message_to_children (notmuch, message,
1468                                                          &thread_id);
1469     if (status)
1470         return status;
1471
1472     /* If not part of any existing thread, generate a new thread ID. */
1473     if (thread_id == NULL) {
1474         thread_id = _notmuch_database_generate_thread_id (notmuch);
1475
1476         _notmuch_message_add_term (message, "thread", thread_id);
1477     }
1478
1479     return NOTMUCH_STATUS_SUCCESS;
1480 }
1481
1482 notmuch_status_t
1483 notmuch_database_add_message (notmuch_database_t *notmuch,
1484                               const char *filename,
1485                               notmuch_message_t **message_ret)
1486 {
1487     notmuch_message_file_t *message_file;
1488     notmuch_message_t *message = NULL;
1489     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1490     notmuch_private_status_t private_status;
1491
1492     const char *date, *header;
1493     const char *from, *to, *subject;
1494     char *message_id = NULL;
1495
1496     if (message_ret)
1497         *message_ret = NULL;
1498
1499     ret = _notmuch_database_ensure_writable (notmuch);
1500     if (ret)
1501         return ret;
1502
1503     message_file = notmuch_message_file_open (filename);
1504     if (message_file == NULL)
1505         return NOTMUCH_STATUS_FILE_ERROR;
1506
1507     notmuch_message_file_restrict_headers (message_file,
1508                                            "date",
1509                                            "from",
1510                                            "in-reply-to",
1511                                            "message-id",
1512                                            "references",
1513                                            "subject",
1514                                            "to",
1515                                            (char *) NULL);
1516
1517     try {
1518         /* Before we do any real work, (especially before doing a
1519          * potential SHA-1 computation on the entire file's contents),
1520          * let's make sure that what we're looking at looks like an
1521          * actual email message.
1522          */
1523         from = notmuch_message_file_get_header (message_file, "from");
1524         subject = notmuch_message_file_get_header (message_file, "subject");
1525         to = notmuch_message_file_get_header (message_file, "to");
1526
1527         if ((from == NULL || *from == '\0') &&
1528             (subject == NULL || *subject == '\0') &&
1529             (to == NULL || *to == '\0'))
1530         {
1531             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1532             goto DONE;
1533         }
1534
1535         /* Now that we're sure it's mail, the first order of business
1536          * is to find a message ID (or else create one ourselves). */
1537
1538         header = notmuch_message_file_get_header (message_file, "message-id");
1539         if (header && *header != '\0') {
1540             message_id = _parse_message_id (message_file, header, NULL);
1541
1542             /* So the header value isn't RFC-compliant, but it's
1543              * better than no message-id at all. */
1544             if (message_id == NULL)
1545                 message_id = talloc_strdup (message_file, header);
1546
1547             /* Reject a Message ID that's too long. */
1548             if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1549                 talloc_free (message_id);
1550                 message_id = NULL;
1551             }
1552         }
1553
1554         if (message_id == NULL ) {
1555             /* No message-id at all, let's generate one by taking a
1556              * hash over the file's contents. */
1557             char *sha1 = notmuch_sha1_of_file (filename);
1558
1559             /* If that failed too, something is really wrong. Give up. */
1560             if (sha1 == NULL) {
1561                 ret = NOTMUCH_STATUS_FILE_ERROR;
1562                 goto DONE;
1563             }
1564
1565             message_id = talloc_asprintf (message_file,
1566                                           "notmuch-sha1-%s", sha1);
1567             free (sha1);
1568         }
1569
1570         /* Now that we have a message ID, we get a message object,
1571          * (which may or may not reference an existing document in the
1572          * database). */
1573
1574         message = _notmuch_message_create_for_message_id (notmuch,
1575                                                           message_id,
1576                                                           &private_status);
1577
1578         talloc_free (message_id);
1579
1580         if (message == NULL) {
1581             ret = COERCE_STATUS (private_status,
1582                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1583             goto DONE;
1584         }
1585
1586         _notmuch_message_add_filename (message, filename);
1587
1588         /* Is this a newly created message object? */
1589         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1590             _notmuch_message_add_term (message, "type", "mail");
1591
1592             ret = _notmuch_database_link_message (notmuch, message,
1593                                                   message_file);
1594             if (ret)
1595                 goto DONE;
1596
1597             date = notmuch_message_file_get_header (message_file, "date");
1598             _notmuch_message_set_date (message, date);
1599
1600             _notmuch_message_index_file (message, filename);
1601         } else {
1602             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1603         }
1604
1605         _notmuch_message_sync (message);
1606     } catch (const Xapian::Error &error) {
1607         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1608                  error.get_msg().c_str());
1609         notmuch->exception_reported = TRUE;
1610         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1611         goto DONE;
1612     }
1613
1614   DONE:
1615     if (message) {
1616         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1617             *message_ret = message;
1618         else
1619             notmuch_message_destroy (message);
1620     }
1621
1622     if (message_file)
1623         notmuch_message_file_close (message_file);
1624
1625     return ret;
1626 }
1627
1628 notmuch_status_t
1629 notmuch_database_remove_message (notmuch_database_t *notmuch,
1630                                  const char *filename)
1631 {
1632     Xapian::WritableDatabase *db;
1633     void *local;
1634     const char *prefix = _find_prefix ("file-direntry");
1635     char *direntry, *term;
1636     Xapian::PostingIterator i, end;
1637     Xapian::Document document;
1638     notmuch_status_t status;
1639
1640     status = _notmuch_database_ensure_writable (notmuch);
1641     if (status)
1642         return status;
1643
1644     local = talloc_new (notmuch);
1645
1646     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1647
1648     try {
1649
1650         status = _notmuch_database_filename_to_direntry (local, notmuch,
1651                                                          filename, &direntry);
1652         if (status)
1653             return status;
1654
1655         term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1656
1657         find_doc_ids_for_term (notmuch, term, &i, &end);
1658
1659         for ( ; i != end; i++) {
1660             Xapian::TermIterator j;
1661
1662             document = find_document_for_doc_id (notmuch, *i);
1663
1664             document.remove_term (term);
1665
1666             j = document.termlist_begin ();
1667             j.skip_to (prefix);
1668
1669             /* Was this the last file-direntry in the message? */
1670             if (j == document.termlist_end () ||
1671                 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1672             {
1673                 db->delete_document (document.get_docid ());
1674                 status = NOTMUCH_STATUS_SUCCESS;
1675             } else {
1676                 db->replace_document (document.get_docid (), document);
1677                 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1678             }
1679         }
1680     } catch (const Xapian::Error &error) {
1681         fprintf (stderr, "Error: A Xapian exception occurred removing message: %s\n",
1682                  error.get_msg().c_str());
1683         notmuch->exception_reported = TRUE;
1684         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1685     }
1686
1687     talloc_free (local);
1688
1689     return status;
1690 }
1691
1692 notmuch_tags_t *
1693 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1694                        Xapian::TermIterator &end)
1695 {
1696     const char *prefix = _find_prefix ("tag");
1697     notmuch_tags_t *tags;
1698     std::string tag;
1699
1700     /* Currently this iteration is written with the assumption that
1701      * "tag" has a single-character prefix. */
1702     assert (strlen (prefix) == 1);
1703
1704     tags = _notmuch_tags_create (ctx);
1705     if (unlikely (tags == NULL))
1706         return NULL;
1707
1708     i.skip_to (prefix);
1709
1710     while (i != end) {
1711         tag = *i;
1712
1713         if (tag.empty () || tag[0] != *prefix)
1714             break;
1715
1716         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1717
1718         i++;
1719     }
1720
1721     _notmuch_tags_prepare_iterator (tags);
1722
1723     return tags;
1724 }
1725
1726 notmuch_tags_t *
1727 notmuch_database_get_all_tags (notmuch_database_t *db)
1728 {
1729     Xapian::TermIterator i, end;
1730
1731     try {
1732         i = db->xapian_db->allterms_begin();
1733         end = db->xapian_db->allterms_end();
1734         return _notmuch_convert_tags(db, i, end);
1735     } catch (const Xapian::Error &error) {
1736         fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1737                  error.get_msg().c_str());
1738         db->exception_reported = TRUE;
1739         return NULL;
1740     }
1741 }