]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
Avoid database corruption by not adding partially-constructed mail documents.
[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         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
626         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
627         if (last_thread_id.empty ()) {
628             notmuch->last_thread_id = 0;
629         } else {
630             const char *str;
631             char *end;
632
633             str = last_thread_id.c_str ();
634             notmuch->last_thread_id = strtoull (str, &end, 16);
635             if (*end != '\0')
636                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
637         }
638
639         notmuch->query_parser = new Xapian::QueryParser;
640         notmuch->term_gen = new Xapian::TermGenerator;
641         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
642         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
643
644         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
645         notmuch->query_parser->set_database (*notmuch->xapian_db);
646         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
647         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
648         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
649
650         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
651             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
652             notmuch->query_parser->add_boolean_prefix (prefix->name,
653                                                        prefix->prefix);
654         }
655
656         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
657             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
658             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
659         }
660     } catch (const Xapian::Error &error) {
661         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
662                  error.get_msg().c_str());
663         notmuch = NULL;
664     }
665
666   DONE:
667     if (notmuch_path)
668         free (notmuch_path);
669     if (xapian_path)
670         free (xapian_path);
671
672     return notmuch;
673 }
674
675 void
676 notmuch_database_close (notmuch_database_t *notmuch)
677 {
678     try {
679         if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
680             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
681     } catch (const Xapian::Error &error) {
682         if (! notmuch->exception_reported) {
683             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
684                      error.get_msg().c_str());
685         }
686     }
687
688     delete notmuch->term_gen;
689     delete notmuch->query_parser;
690     delete notmuch->xapian_db;
691     delete notmuch->value_range_processor;
692     talloc_free (notmuch);
693 }
694
695 const char *
696 notmuch_database_get_path (notmuch_database_t *notmuch)
697 {
698     return notmuch->path;
699 }
700
701 unsigned int
702 notmuch_database_get_version (notmuch_database_t *notmuch)
703 {
704     unsigned int version;
705     string version_string;
706     const char *str;
707     char *end;
708
709     version_string = notmuch->xapian_db->get_metadata ("version");
710     if (version_string.empty ())
711         return 0;
712
713     str = version_string.c_str ();
714     if (str == NULL || *str == '\0')
715         return 0;
716
717     version = strtoul (str, &end, 10);
718     if (*end != '\0')
719         INTERNAL_ERROR ("Malformed database version: %s", str);
720
721     return version;
722 }
723
724 notmuch_bool_t
725 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
726 {
727     return notmuch->needs_upgrade;
728 }
729
730 static volatile sig_atomic_t do_progress_notify = 0;
731
732 static void
733 handle_sigalrm (unused (int signal))
734 {
735     do_progress_notify = 1;
736 }
737
738 /* Upgrade the current database.
739  *
740  * After opening a database in read-write mode, the client should
741  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
742  * if so, upgrade with this function before making any modifications.
743  *
744  * The optional progress_notify callback can be used by the caller to
745  * provide progress indication to the user. If non-NULL it will be
746  * called periodically with 'count' as the number of messages upgraded
747  * so far and 'total' the overall number of messages that will be
748  * converted.
749  */
750 notmuch_status_t
751 notmuch_database_upgrade (notmuch_database_t *notmuch,
752                           void (*progress_notify) (void *closure,
753                                                    double progress),
754                           void *closure)
755 {
756     Xapian::WritableDatabase *db;
757     struct sigaction action;
758     struct itimerval timerval;
759     notmuch_bool_t timer_is_active = FALSE;
760     unsigned int version;
761     notmuch_status_t status;
762     unsigned int count = 0, total = 0;
763
764     status = _notmuch_database_ensure_writable (notmuch);
765     if (status)
766         return status;
767
768     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
769
770     version = notmuch_database_get_version (notmuch);
771
772     if (version >= NOTMUCH_DATABASE_VERSION)
773         return NOTMUCH_STATUS_SUCCESS;
774
775     if (progress_notify) {
776         /* Setup our handler for SIGALRM */
777         memset (&action, 0, sizeof (struct sigaction));
778         action.sa_handler = handle_sigalrm;
779         sigemptyset (&action.sa_mask);
780         action.sa_flags = SA_RESTART;
781         sigaction (SIGALRM, &action, NULL);
782
783         /* Then start a timer to send SIGALRM once per second. */
784         timerval.it_interval.tv_sec = 1;
785         timerval.it_interval.tv_usec = 0;
786         timerval.it_value.tv_sec = 1;
787         timerval.it_value.tv_usec = 0;
788         setitimer (ITIMER_REAL, &timerval, NULL);
789
790         timer_is_active = TRUE;
791     }
792
793     /* Before version 1, each message document had its filename in the
794      * data field. Copy that into the new format by calling
795      * notmuch_message_add_filename.
796      */
797     if (version < 1) {
798         notmuch_query_t *query = notmuch_query_create (notmuch, "");
799         notmuch_messages_t *messages;
800         notmuch_message_t *message;
801         char *filename;
802         Xapian::TermIterator t, t_end;
803
804         total = notmuch_query_count_messages (query);
805
806         for (messages = notmuch_query_search_messages (query);
807              notmuch_messages_valid (messages);
808              notmuch_messages_move_to_next (messages))
809         {
810             if (do_progress_notify) {
811                 progress_notify (closure, (double) count / total);
812                 do_progress_notify = 0;
813             }
814
815             message = notmuch_messages_get (messages);
816
817             filename = _notmuch_message_talloc_copy_data (message);
818             if (filename && *filename != '\0') {
819                 _notmuch_message_add_filename (message, filename);
820                 _notmuch_message_sync (message);
821             }
822             talloc_free (filename);
823
824             notmuch_message_destroy (message);
825
826             count++;
827         }
828
829         notmuch_query_destroy (query);
830
831         /* Also, before version 1 we stored directory timestamps in
832          * XTIMESTAMP documents instead of the current XDIRECTORY
833          * documents. So copy those as well. */
834
835         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
836
837         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
838              t != t_end;
839              t++)
840         {
841             Xapian::PostingIterator p, p_end;
842             std::string term = *t;
843
844             p_end = notmuch->xapian_db->postlist_end (term);
845
846             for (p = notmuch->xapian_db->postlist_begin (term);
847                  p != p_end;
848                  p++)
849             {
850                 Xapian::Document document;
851                 time_t mtime;
852                 notmuch_directory_t *directory;
853
854                 if (do_progress_notify) {
855                     progress_notify (closure, (double) count / total);
856                     do_progress_notify = 0;
857                 }
858
859                 document = find_document_for_doc_id (notmuch, *p);
860                 mtime = Xapian::sortable_unserialise (
861                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
862
863                 directory = notmuch_database_get_directory (notmuch,
864                                                             term.c_str() + 10);
865                 notmuch_directory_set_mtime (directory, mtime);
866                 notmuch_directory_destroy (directory);
867             }
868         }
869     }
870
871     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
872     db->flush ();
873
874     /* Now that the upgrade is complete we can remove the old data
875      * and documents that are no longer needed. */
876     if (version < 1) {
877         notmuch_query_t *query = notmuch_query_create (notmuch, "");
878         notmuch_messages_t *messages;
879         notmuch_message_t *message;
880         char *filename;
881
882         for (messages = notmuch_query_search_messages (query);
883              notmuch_messages_valid (messages);
884              notmuch_messages_move_to_next (messages))
885         {
886             if (do_progress_notify) {
887                 progress_notify (closure, (double) count / total);
888                 do_progress_notify = 0;
889             }
890
891             message = notmuch_messages_get (messages);
892
893             filename = _notmuch_message_talloc_copy_data (message);
894             if (filename && *filename != '\0') {
895                 _notmuch_message_clear_data (message);
896                 _notmuch_message_sync (message);
897             }
898             talloc_free (filename);
899
900             notmuch_message_destroy (message);
901         }
902
903         notmuch_query_destroy (query);
904     }
905
906     if (version < 1) {
907         Xapian::TermIterator t, t_end;
908
909         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
910
911         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
912              t != t_end;
913              t++)
914         {
915             Xapian::PostingIterator p, p_end;
916             std::string term = *t;
917
918             p_end = notmuch->xapian_db->postlist_end (term);
919
920             for (p = notmuch->xapian_db->postlist_begin (term);
921                  p != p_end;
922                  p++)
923             {
924                 if (do_progress_notify) {
925                     progress_notify (closure, (double) count / total);
926                     do_progress_notify = 0;
927                 }
928
929                 db->delete_document (*p);
930             }
931         }
932     }
933
934     if (timer_is_active) {
935         /* Now stop the timer. */
936         timerval.it_interval.tv_sec = 0;
937         timerval.it_interval.tv_usec = 0;
938         timerval.it_value.tv_sec = 0;
939         timerval.it_value.tv_usec = 0;
940         setitimer (ITIMER_REAL, &timerval, NULL);
941
942         /* And disable the signal handler. */
943         action.sa_handler = SIG_IGN;
944         sigaction (SIGALRM, &action, NULL);
945     }
946
947     return NOTMUCH_STATUS_SUCCESS;
948 }
949
950 /* We allow the user to use arbitrarily long paths for directories. But
951  * we have a term-length limit. So if we exceed that, we'll use the
952  * SHA-1 of the path for the database term.
953  *
954  * Note: This function may return the original value of 'path'. If it
955  * does not, then the caller is responsible to free() the returned
956  * value.
957  */
958 const char *
959 _notmuch_database_get_directory_db_path (const char *path)
960 {
961     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
962
963     if (term_len > NOTMUCH_TERM_MAX)
964         return notmuch_sha1_of_string (path);
965     else
966         return path;
967 }
968
969 /* Given a path, split it into two parts: the directory part is all
970  * components except for the last, and the basename is that last
971  * component. Getting the return-value for either part is optional
972  * (the caller can pass NULL).
973  *
974  * The original 'path' can represent either a regular file or a
975  * directory---the splitting will be carried out in the same way in
976  * either case. Trailing slashes on 'path' will be ignored, and any
977  * cases of multiple '/' characters appearing in series will be
978  * treated as a single '/'.
979  *
980  * Allocation (if any) will have 'ctx' as the talloc owner. But
981  * pointers will be returned within the original path string whenever
982  * possible.
983  *
984  * Note: If 'path' is non-empty and contains no non-trailing slash,
985  * (that is, consists of a filename with no parent directory), then
986  * the directory returned will be an empty string. However, if 'path'
987  * is an empty string, then both directory and basename will be
988  * returned as NULL.
989  */
990 notmuch_status_t
991 _notmuch_database_split_path (void *ctx,
992                               const char *path,
993                               const char **directory,
994                               const char **basename)
995 {
996     const char *slash;
997
998     if (path == NULL || *path == '\0') {
999         if (directory)
1000             *directory = NULL;
1001         if (basename)
1002             *basename = NULL;
1003         return NOTMUCH_STATUS_SUCCESS;
1004     }
1005
1006     /* Find the last slash (not counting a trailing slash), if any. */
1007
1008     slash = path + strlen (path) - 1;
1009
1010     /* First, skip trailing slashes. */
1011     while (slash != path) {
1012         if (*slash != '/')
1013             break;
1014
1015         --slash;
1016     }
1017
1018     /* Then, find a slash. */
1019     while (slash != path) {
1020         if (*slash == '/')
1021             break;
1022
1023         if (basename)
1024             *basename = slash;
1025
1026         --slash;
1027     }
1028
1029     /* Finally, skip multiple slashes. */
1030     while (slash != path) {
1031         if (*slash != '/')
1032             break;
1033
1034         --slash;
1035     }
1036
1037     if (slash == path) {
1038         if (directory)
1039             *directory = talloc_strdup (ctx, "");
1040         if (basename)
1041             *basename = path;
1042     } else {
1043         if (directory)
1044             *directory = talloc_strndup (ctx, path, slash - path + 1);
1045     }
1046
1047     return NOTMUCH_STATUS_SUCCESS;
1048 }
1049
1050 notmuch_status_t
1051 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1052                                      const char *path,
1053                                      unsigned int *directory_id)
1054 {
1055     notmuch_directory_t *directory;
1056     notmuch_status_t status;
1057
1058     if (path == NULL) {
1059         *directory_id = 0;
1060         return NOTMUCH_STATUS_SUCCESS;
1061     }
1062
1063     directory = _notmuch_directory_create (notmuch, path, &status);
1064     if (status) {
1065         *directory_id = -1;
1066         return status;
1067     }
1068
1069     *directory_id = _notmuch_directory_get_document_id (directory);
1070
1071     notmuch_directory_destroy (directory);
1072
1073     return NOTMUCH_STATUS_SUCCESS;
1074 }
1075
1076 const char *
1077 _notmuch_database_get_directory_path (void *ctx,
1078                                       notmuch_database_t *notmuch,
1079                                       unsigned int doc_id)
1080 {
1081     Xapian::Document document;
1082
1083     document = find_document_for_doc_id (notmuch, doc_id);
1084
1085     return talloc_strdup (ctx, document.get_data ().c_str ());
1086 }
1087
1088 /* Given a legal 'filename' for the database, (either relative to
1089  * database path or absolute with initial components identical to
1090  * database path), return a new string (with 'ctx' as the talloc
1091  * owner) suitable for use as a direntry term value.
1092  *
1093  * The necessary directory documents will be created in the database
1094  * as needed.
1095  */
1096 notmuch_status_t
1097 _notmuch_database_filename_to_direntry (void *ctx,
1098                                         notmuch_database_t *notmuch,
1099                                         const char *filename,
1100                                         char **direntry)
1101 {
1102     const char *relative, *directory, *basename;
1103     Xapian::docid directory_id;
1104     notmuch_status_t status;
1105
1106     relative = _notmuch_database_relative_path (notmuch, filename);
1107
1108     status = _notmuch_database_split_path (ctx, relative,
1109                                            &directory, &basename);
1110     if (status)
1111         return status;
1112
1113     status = _notmuch_database_find_directory_id (notmuch, directory,
1114                                                   &directory_id);
1115     if (status)
1116         return status;
1117
1118     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1119
1120     return NOTMUCH_STATUS_SUCCESS;
1121 }
1122
1123 /* Given a legal 'path' for the database, return the relative path.
1124  *
1125  * The return value will be a pointer to the originl path contents,
1126  * and will be either the original string (if 'path' was relative) or
1127  * a portion of the string (if path was absolute and begins with the
1128  * database path).
1129  */
1130 const char *
1131 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1132                                  const char *path)
1133 {
1134     const char *db_path, *relative;
1135     unsigned int db_path_len;
1136
1137     db_path = notmuch_database_get_path (notmuch);
1138     db_path_len = strlen (db_path);
1139
1140     relative = path;
1141
1142     if (*relative == '/') {
1143         while (*relative == '/' && *(relative+1) == '/')
1144             relative++;
1145
1146         if (strncmp (relative, db_path, db_path_len) == 0)
1147         {
1148             relative += db_path_len;
1149             while (*relative == '/')
1150                 relative++;
1151         }
1152     }
1153
1154     return relative;
1155 }
1156
1157 notmuch_directory_t *
1158 notmuch_database_get_directory (notmuch_database_t *notmuch,
1159                                 const char *path)
1160 {
1161     notmuch_status_t status;
1162
1163     try {
1164         return _notmuch_directory_create (notmuch, path, &status);
1165     } catch (const Xapian::Error &error) {
1166         fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1167                  error.get_msg().c_str());
1168         notmuch->exception_reported = TRUE;
1169         return NULL;
1170     }
1171 }
1172
1173 /* Allocate a document ID that satisfies the following criteria:
1174  *
1175  * 1. The ID does not exist for any document in the Xapian database
1176  *
1177  * 2. The ID was not previously returned from this function
1178  *
1179  * 3. The ID is the smallest integer satisfying (1) and (2)
1180  *
1181  * This function will trigger an internal error if these constraints
1182  * cannot all be satisfied, (that is, the pool of available document
1183  * IDs has been exhausted).
1184  */
1185 unsigned int
1186 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1187 {
1188     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1189
1190     notmuch->last_doc_id++;
1191
1192     if (notmuch->last_doc_id == 0)
1193         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");        
1194
1195     return notmuch->last_doc_id;
1196 }
1197
1198 static const char *
1199 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1200 {
1201     /* 16 bytes (+ terminator) for hexadecimal representation of
1202      * a 64-bit integer. */
1203     static char thread_id[17];
1204     Xapian::WritableDatabase *db;
1205
1206     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1207
1208     notmuch->last_thread_id++;
1209
1210     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1211
1212     db->set_metadata ("last_thread_id", thread_id);
1213
1214     return thread_id;
1215 }
1216
1217 static char *
1218 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1219 {
1220     return talloc_asprintf (ctx, "thread_id_%s", message_id);
1221 }
1222
1223 /* Find the thread ID to which the message with 'message_id' belongs.
1224  *
1225  * Always returns a newly talloced string belonging to 'ctx'.
1226  *
1227  * Note: If there is no message in the database with the given
1228  * 'message_id' then a new thread_id will be allocated for this
1229  * message and stored in the database metadata, (where this same
1230  * thread ID can be looked up if the message is added to the database
1231  * later).
1232  */
1233 static const char *
1234 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1235                                   void *ctx,
1236                                   const char *message_id)
1237 {
1238     notmuch_message_t *message;
1239     string thread_id_string;
1240     const char *thread_id;
1241     char *metadata_key;
1242     Xapian::WritableDatabase *db;
1243
1244     message = notmuch_database_find_message (notmuch, message_id);
1245
1246     if (message) {
1247         thread_id = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1248
1249         notmuch_message_destroy (message);
1250
1251         return thread_id;
1252     }
1253
1254     /* Message has not been seen yet.
1255      *
1256      * We may have seen a reference to it already, in which case, we
1257      * can return the thread ID stored in the metadata. Otherwise, we
1258      * generate a new thread ID and store it there.
1259      */
1260     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1261     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1262     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1263
1264     if (thread_id_string.empty()) {
1265         thread_id = _notmuch_database_generate_thread_id (notmuch);
1266         db->set_metadata (metadata_key, thread_id);
1267     } else {
1268         thread_id = thread_id_string.c_str();
1269     }
1270
1271     talloc_free (metadata_key);
1272
1273     return thread_id;
1274 }
1275
1276 static notmuch_status_t
1277 _merge_threads (notmuch_database_t *notmuch,
1278                 const char *winner_thread_id,
1279                 const char *loser_thread_id)
1280 {
1281     Xapian::PostingIterator loser, loser_end;
1282     notmuch_message_t *message = NULL;
1283     notmuch_private_status_t private_status;
1284     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1285
1286     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1287
1288     for ( ; loser != loser_end; loser++) {
1289         message = _notmuch_message_create (notmuch, notmuch,
1290                                            *loser, &private_status);
1291         if (message == NULL) {
1292             ret = COERCE_STATUS (private_status,
1293                                  "Cannot find document for doc_id from query");
1294             goto DONE;
1295         }
1296
1297         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1298         _notmuch_message_add_term (message, "thread", winner_thread_id);
1299         _notmuch_message_sync (message);
1300
1301         notmuch_message_destroy (message);
1302         message = NULL;
1303     }
1304
1305   DONE:
1306     if (message)
1307         notmuch_message_destroy (message);
1308
1309     return ret;
1310 }
1311
1312 static void
1313 _my_talloc_free_for_g_hash (void *ptr)
1314 {
1315     talloc_free (ptr);
1316 }
1317
1318 static notmuch_status_t
1319 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1320                                            notmuch_message_t *message,
1321                                            notmuch_message_file_t *message_file,
1322                                            const char **thread_id)
1323 {
1324     GHashTable *parents = NULL;
1325     const char *refs, *in_reply_to, *in_reply_to_message_id;
1326     GList *l, *keys = NULL;
1327     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1328
1329     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1330                                      _my_talloc_free_for_g_hash, NULL);
1331
1332     refs = notmuch_message_file_get_header (message_file, "references");
1333     parse_references (message, notmuch_message_get_message_id (message),
1334                       parents, refs);
1335
1336     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1337     parse_references (message, notmuch_message_get_message_id (message),
1338                       parents, in_reply_to);
1339
1340     /* Carefully avoid adding any self-referential in-reply-to term. */
1341     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1342     if (in_reply_to_message_id &&
1343         strcmp (in_reply_to_message_id,
1344                 notmuch_message_get_message_id (message)))
1345     {
1346         _notmuch_message_add_term (message, "replyto",
1347                              _parse_message_id (message, in_reply_to, NULL));
1348     }
1349
1350     keys = g_hash_table_get_keys (parents);
1351     for (l = keys; l; l = l->next) {
1352         char *parent_message_id;
1353         const char *parent_thread_id;
1354
1355         parent_message_id = (char *) l->data;
1356
1357         _notmuch_message_add_term (message, "reference",
1358                                    parent_message_id);
1359
1360         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1361                                                              message,
1362                                                              parent_message_id);
1363
1364         if (*thread_id == NULL) {
1365             *thread_id = talloc_strdup (message, parent_thread_id);
1366             _notmuch_message_add_term (message, "thread", *thread_id);
1367         } else if (strcmp (*thread_id, parent_thread_id)) {
1368             ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1369             if (ret)
1370                 goto DONE;
1371         }
1372     }
1373
1374   DONE:
1375     if (keys)
1376         g_list_free (keys);
1377     if (parents)
1378         g_hash_table_unref (parents);
1379
1380     return ret;
1381 }
1382
1383 static notmuch_status_t
1384 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1385                                             notmuch_message_t *message,
1386                                             const char **thread_id)
1387 {
1388     const char *message_id = notmuch_message_get_message_id (message);
1389     Xapian::PostingIterator child, children_end;
1390     notmuch_message_t *child_message = NULL;
1391     const char *child_thread_id;
1392     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1393     notmuch_private_status_t private_status;
1394
1395     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1396
1397     for ( ; child != children_end; child++) {
1398
1399         child_message = _notmuch_message_create (message, notmuch,
1400                                                  *child, &private_status);
1401         if (child_message == NULL) {
1402             ret = COERCE_STATUS (private_status,
1403                                  "Cannot find document for doc_id from query");
1404             goto DONE;
1405         }
1406
1407         child_thread_id = notmuch_message_get_thread_id (child_message);
1408         if (*thread_id == NULL) {
1409             *thread_id = talloc_strdup (message, child_thread_id);
1410             _notmuch_message_add_term (message, "thread", *thread_id);
1411         } else if (strcmp (*thread_id, child_thread_id)) {
1412             _notmuch_message_remove_term (child_message, "reference",
1413                                           message_id);
1414             _notmuch_message_sync (child_message);
1415             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1416             if (ret)
1417                 goto DONE;
1418         }
1419
1420         notmuch_message_destroy (child_message);
1421         child_message = NULL;
1422     }
1423
1424   DONE:
1425     if (child_message)
1426         notmuch_message_destroy (child_message);
1427
1428     return ret;
1429 }
1430
1431 /* Given a (mostly empty) 'message' and its corresponding
1432  * 'message_file' link it to existing threads in the database.
1433  *
1434  * The first check is in the metadata of the database to see if we
1435  * have pre-allocated a thread_id in advance for this message, (which
1436  * would have happened if a message was previously added that
1437  * referenced this one).
1438  *
1439  * Second, we look at 'message_file' and its link-relevant headers
1440  * (References and In-Reply-To) for message IDs.
1441  *
1442  * Finally, we look in the database for existing message that
1443  * reference 'message'.
1444  *
1445  * In all cases, we assign to the current message the first thread_id
1446  * found (through either parent or child). We will also merge any
1447  * existing, distinct threads where this message belongs to both,
1448  * (which is not uncommon when mesages are processed out of order).
1449  *
1450  * Finally, if no thread ID has been found through parent or child, we
1451  * call _notmuch_message_generate_thread_id to generate a new thread
1452  * ID. This should only happen for new, top-level messages, (no
1453  * References or In-Reply-To header in this message, and no previously
1454  * added message refers to this message).
1455  */
1456 static notmuch_status_t
1457 _notmuch_database_link_message (notmuch_database_t *notmuch,
1458                                 notmuch_message_t *message,
1459                                 notmuch_message_file_t *message_file)
1460 {
1461     notmuch_status_t status;
1462     const char *message_id, *thread_id = NULL;
1463     char *metadata_key;
1464     string stored_id;
1465
1466     message_id = notmuch_message_get_message_id (message);
1467     metadata_key = _get_metadata_thread_id_key (message, message_id);
1468
1469     /* Check if we have already seen related messages to this one.
1470      * If we have then use the thread_id that we stored at that time.
1471      */
1472     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
1473     if (! stored_id.empty()) {
1474         Xapian::WritableDatabase *db;
1475
1476         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1477
1478         /* Clear the metadata for this message ID. We don't need it
1479          * anymore. */
1480         db->set_metadata (metadata_key, "");
1481         thread_id = stored_id.c_str();
1482
1483         _notmuch_message_add_term (message, "thread", thread_id);
1484     }
1485     talloc_free (metadata_key);
1486
1487     status = _notmuch_database_link_message_to_parents (notmuch, message,
1488                                                         message_file,
1489                                                         &thread_id);
1490     if (status)
1491         return status;
1492
1493     status = _notmuch_database_link_message_to_children (notmuch, message,
1494                                                          &thread_id);
1495     if (status)
1496         return status;
1497
1498     /* If not part of any existing thread, generate a new thread ID. */
1499     if (thread_id == NULL) {
1500         thread_id = _notmuch_database_generate_thread_id (notmuch);
1501
1502         _notmuch_message_add_term (message, "thread", thread_id);
1503     }
1504
1505     return NOTMUCH_STATUS_SUCCESS;
1506 }
1507
1508 notmuch_status_t
1509 notmuch_database_add_message (notmuch_database_t *notmuch,
1510                               const char *filename,
1511                               notmuch_message_t **message_ret)
1512 {
1513     notmuch_message_file_t *message_file;
1514     notmuch_message_t *message = NULL;
1515     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1516     notmuch_private_status_t private_status;
1517
1518     const char *date, *header;
1519     const char *from, *to, *subject;
1520     char *message_id = NULL;
1521
1522     if (message_ret)
1523         *message_ret = NULL;
1524
1525     ret = _notmuch_database_ensure_writable (notmuch);
1526     if (ret)
1527         return ret;
1528
1529     message_file = notmuch_message_file_open (filename);
1530     if (message_file == NULL)
1531         return NOTMUCH_STATUS_FILE_ERROR;
1532
1533     notmuch_message_file_restrict_headers (message_file,
1534                                            "date",
1535                                            "from",
1536                                            "in-reply-to",
1537                                            "message-id",
1538                                            "references",
1539                                            "subject",
1540                                            "to",
1541                                            (char *) NULL);
1542
1543     try {
1544         /* Before we do any real work, (especially before doing a
1545          * potential SHA-1 computation on the entire file's contents),
1546          * let's make sure that what we're looking at looks like an
1547          * actual email message.
1548          */
1549         from = notmuch_message_file_get_header (message_file, "from");
1550         subject = notmuch_message_file_get_header (message_file, "subject");
1551         to = notmuch_message_file_get_header (message_file, "to");
1552
1553         if ((from == NULL || *from == '\0') &&
1554             (subject == NULL || *subject == '\0') &&
1555             (to == NULL || *to == '\0'))
1556         {
1557             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1558             goto DONE;
1559         }
1560
1561         /* Now that we're sure it's mail, the first order of business
1562          * is to find a message ID (or else create one ourselves). */
1563
1564         header = notmuch_message_file_get_header (message_file, "message-id");
1565         if (header && *header != '\0') {
1566             message_id = _parse_message_id (message_file, header, NULL);
1567
1568             /* So the header value isn't RFC-compliant, but it's
1569              * better than no message-id at all. */
1570             if (message_id == NULL)
1571                 message_id = talloc_strdup (message_file, header);
1572
1573             /* Reject a Message ID that's too long. */
1574             if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1575                 talloc_free (message_id);
1576                 message_id = NULL;
1577             }
1578         }
1579
1580         if (message_id == NULL ) {
1581             /* No message-id at all, let's generate one by taking a
1582              * hash over the file's contents. */
1583             char *sha1 = notmuch_sha1_of_file (filename);
1584
1585             /* If that failed too, something is really wrong. Give up. */
1586             if (sha1 == NULL) {
1587                 ret = NOTMUCH_STATUS_FILE_ERROR;
1588                 goto DONE;
1589             }
1590
1591             message_id = talloc_asprintf (message_file,
1592                                           "notmuch-sha1-%s", sha1);
1593             free (sha1);
1594         }
1595
1596         /* Now that we have a message ID, we get a message object,
1597          * (which may or may not reference an existing document in the
1598          * database). */
1599
1600         message = _notmuch_message_create_for_message_id (notmuch,
1601                                                           message_id,
1602                                                           &private_status);
1603
1604         talloc_free (message_id);
1605
1606         if (message == NULL) {
1607             ret = COERCE_STATUS (private_status,
1608                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1609             goto DONE;
1610         }
1611
1612         _notmuch_message_add_filename (message, filename);
1613
1614         /* Is this a newly created message object? */
1615         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1616             _notmuch_message_add_term (message, "type", "mail");
1617
1618             ret = _notmuch_database_link_message (notmuch, message,
1619                                                   message_file);
1620             if (ret)
1621                 goto DONE;
1622
1623             date = notmuch_message_file_get_header (message_file, "date");
1624             _notmuch_message_set_date (message, date);
1625
1626             _notmuch_message_index_file (message, filename);
1627         } else {
1628             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1629         }
1630
1631         _notmuch_message_sync (message);
1632     } catch (const Xapian::Error &error) {
1633         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1634                  error.get_msg().c_str());
1635         notmuch->exception_reported = TRUE;
1636         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1637         goto DONE;
1638     }
1639
1640   DONE:
1641     if (message) {
1642         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1643             *message_ret = message;
1644         else
1645             notmuch_message_destroy (message);
1646     }
1647
1648     if (message_file)
1649         notmuch_message_file_close (message_file);
1650
1651     return ret;
1652 }
1653
1654 notmuch_status_t
1655 notmuch_database_remove_message (notmuch_database_t *notmuch,
1656                                  const char *filename)
1657 {
1658     Xapian::WritableDatabase *db;
1659     void *local;
1660     const char *prefix = _find_prefix ("file-direntry");
1661     char *direntry, *term;
1662     Xapian::PostingIterator i, end;
1663     Xapian::Document document;
1664     notmuch_status_t status;
1665
1666     status = _notmuch_database_ensure_writable (notmuch);
1667     if (status)
1668         return status;
1669
1670     local = talloc_new (notmuch);
1671
1672     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1673
1674     try {
1675
1676         status = _notmuch_database_filename_to_direntry (local, notmuch,
1677                                                          filename, &direntry);
1678         if (status)
1679             return status;
1680
1681         term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1682
1683         find_doc_ids_for_term (notmuch, term, &i, &end);
1684
1685         for ( ; i != end; i++) {
1686             Xapian::TermIterator j;
1687
1688             document = find_document_for_doc_id (notmuch, *i);
1689
1690             document.remove_term (term);
1691
1692             j = document.termlist_begin ();
1693             j.skip_to (prefix);
1694
1695             /* Was this the last file-direntry in the message? */
1696             if (j == document.termlist_end () ||
1697                 strncmp ((*j).c_str (), prefix, strlen (prefix)))
1698             {
1699                 db->delete_document (document.get_docid ());
1700                 status = NOTMUCH_STATUS_SUCCESS;
1701             } else {
1702                 db->replace_document (document.get_docid (), document);
1703                 status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1704             }
1705         }
1706     } catch (const Xapian::Error &error) {
1707         fprintf (stderr, "Error: A Xapian exception occurred removing message: %s\n",
1708                  error.get_msg().c_str());
1709         notmuch->exception_reported = TRUE;
1710         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1711     }
1712
1713     talloc_free (local);
1714
1715     return status;
1716 }
1717
1718 notmuch_tags_t *
1719 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1720                        Xapian::TermIterator &end)
1721 {
1722     const char *prefix = _find_prefix ("tag");
1723     notmuch_tags_t *tags;
1724     std::string tag;
1725
1726     /* Currently this iteration is written with the assumption that
1727      * "tag" has a single-character prefix. */
1728     assert (strlen (prefix) == 1);
1729
1730     tags = _notmuch_tags_create (ctx);
1731     if (unlikely (tags == NULL))
1732         return NULL;
1733
1734     i.skip_to (prefix);
1735
1736     while (i != end) {
1737         tag = *i;
1738
1739         if (tag.empty () || tag[0] != *prefix)
1740             break;
1741
1742         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1743
1744         i++;
1745     }
1746
1747     _notmuch_tags_prepare_iterator (tags);
1748
1749     return tags;
1750 }
1751
1752 notmuch_tags_t *
1753 notmuch_database_get_all_tags (notmuch_database_t *db)
1754 {
1755     Xapian::TermIterator i, end;
1756
1757     try {
1758         i = db->xapian_db->allterms_begin();
1759         end = db->xapian_db->allterms_end();
1760         return _notmuch_convert_tags(db, i, end);
1761     } catch (const Xapian::Error &error) {
1762         fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
1763                  error.get_msg().c_str());
1764         db->exception_reported = TRUE;
1765         return NULL;
1766     }
1767 }