]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
b673718223aa448bf22e7fb01101e20daa8eac7a
[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 #include "parse-time-vrp.h"
23 #include "string-util.h"
24
25 #include <iostream>
26
27 #include <sys/time.h>
28 #include <sys/stat.h>
29 #include <signal.h>
30 #include <ftw.h>
31
32 #include <glib.h> /* g_free, GPtrArray, GHashTable */
33 #include <glib-object.h> /* g_type_init */
34
35 #include <gmime/gmime.h> /* g_mime_init */
36
37 using namespace std;
38
39 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
40
41 typedef struct {
42     const char *name;
43     const char *prefix;
44 } prefix_t;
45
46 #define NOTMUCH_DATABASE_VERSION 3
47
48 #define STRINGIFY(s) _SUB_STRINGIFY(s)
49 #define _SUB_STRINGIFY(s) #s
50
51 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
52  *
53  * We currently have three different types of documents (mail, ghost,
54  * and directory) and also some metadata.
55  *
56  * Mail document
57  * -------------
58  * A mail document is associated with a particular email message. It
59  * is stored in one or more files on disk (though only one has its
60  * content indexed) and is uniquely identified  by its "id" field
61  * (which is generally the message ID). It is indexed with the
62  * following prefixed terms which the database uses to construct
63  * threads, etc.:
64  *
65  *    Single terms of given prefix:
66  *
67  *      type:   mail
68  *
69  *      id:     Unique ID of mail. This is from the Message-ID header
70  *              if present and not too long (see NOTMUCH_MESSAGE_ID_MAX).
71  *              If it's present and too long, then we use
72  *              "notmuch-sha1-<sha1_sum_of_message_id>".
73  *              If this header is not present, we use
74  *              "notmuch-sha1-<sha1_sum_of_entire_file>".
75  *
76  *      thread: The ID of the thread to which the mail belongs
77  *
78  *      replyto: The ID from the In-Reply-To header of the mail (if any).
79  *
80  *    Multiple terms of given prefix:
81  *
82  *      reference: All message IDs from In-Reply-To and References
83  *                 headers in the message.
84  *
85  *      tag:       Any tags associated with this message by the user.
86  *
87  *      file-direntry:  A colon-separated pair of values
88  *                      (INTEGER:STRING), where INTEGER is the
89  *                      document ID of a directory document, and
90  *                      STRING is the name of a file within that
91  *                      directory for this mail message.
92  *
93  *    A mail document also has four values:
94  *
95  *      TIMESTAMP:      The time_t value corresponding to the message's
96  *                      Date header.
97  *
98  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
99  *
100  *      FROM:           The value of the "From" header
101  *
102  *      SUBJECT:        The value of the "Subject" header
103  *
104  * In addition, terms from the content of the message are added with
105  * "from", "to", "attachment", and "subject" prefixes for use by the
106  * user in searching. Similarly, terms from the path of the mail
107  * message are added with "folder" and "path" prefixes. But the
108  * database doesn't really care itself about any of these.
109  *
110  * The data portion of a mail document is empty.
111  *
112  * Ghost mail document [if NOTMUCH_FEATURE_GHOSTS]
113  * -----------------------------------------------
114  * A ghost mail document is like a mail document, but where we don't
115  * have the message content.  These are used to track thread reference
116  * information for messages we haven't received.
117  *
118  * A ghost mail document has type: ghost; id and thread fields that
119  * are identical to the mail document fields; and a MESSAGE_ID value.
120  *
121  * Directory document
122  * ------------------
123  * A directory document is used by a client of the notmuch library to
124  * maintain data necessary to allow for efficient polling of mail
125  * directories.
126  *
127  * All directory documents contain one term:
128  *
129  *      directory:      The directory path (relative to the database path)
130  *                      Or the SHA1 sum of the directory path (if the
131  *                      path itself is too long to fit in a Xapian
132  *                      term).
133  *
134  * And all directory documents for directories other than top-level
135  * directories also contain the following term:
136  *
137  *      directory-direntry: A colon-separated pair of values
138  *                          (INTEGER:STRING), where INTEGER is the
139  *                          document ID of the parent directory
140  *                          document, and STRING is the name of this
141  *                          directory within that parent.
142  *
143  * All directory documents have a single value:
144  *
145  *      TIMESTAMP:      The mtime of the directory (at last scan)
146  *
147  * The data portion of a directory document contains the path of the
148  * directory (relative to the database path).
149  *
150  * Database metadata
151  * -----------------
152  * Xapian allows us to store arbitrary name-value pairs as
153  * "metadata". We currently use the following metadata names with the
154  * given meanings:
155  *
156  *      version         The database schema version, (which is distinct
157  *                      from both the notmuch package version (see
158  *                      notmuch --version) and the libnotmuch library
159  *                      version. The version is stored as an base-10
160  *                      ASCII integer. The initial database version
161  *                      was 1, (though a schema existed before that
162  *                      were no "version" database value existed at
163  *                      all). Successive versions are allocated as
164  *                      changes are made to the database (such as by
165  *                      indexing new fields).
166  *
167  *      features        The set of features supported by this
168  *                      database. This consists of a set of
169  *                      '\n'-separated lines, where each is a feature
170  *                      name, a '\t', and compatibility flags.  If the
171  *                      compatibility flags contain 'w', then the
172  *                      opener must support this feature to safely
173  *                      write this database.  If the compatibility
174  *                      flags contain 'r', then the opener must
175  *                      support this feature to read this database.
176  *                      Introduced in database version 3.
177  *
178  *      last_thread_id  The last thread ID generated. This is stored
179  *                      as a 16-byte hexadecimal ASCII representation
180  *                      of a 64-bit unsigned integer. The first ID
181  *                      generated is 1 and the value will be
182  *                      incremented for each thread ID.
183  *
184  * Obsolete metadata
185  * -----------------
186  *
187  * If ! NOTMUCH_FEATURE_GHOSTS, there are no ghost mail documents.
188  * Instead, the database has the following additional database
189  * metadata:
190  *
191  *      thread_id_*     A pre-allocated thread ID for a particular
192  *                      message. This is actually an arbitrarily large
193  *                      family of metadata name. Any particular name is
194  *                      formed by concatenating "thread_id_" with a message
195  *                      ID (or the SHA1 sum of a message ID if it is very
196  *                      long---see description of 'id' in the mail
197  *                      document). The value stored is a thread ID.
198  *
199  *                      These thread ID metadata values are stored
200  *                      whenever a message references a parent message
201  *                      that does not yet exist in the database. A
202  *                      thread ID will be allocated and stored, and if
203  *                      the message is later added, the stored thread
204  *                      ID will be used (and the metadata value will
205  *                      be cleared).
206  *
207  *                      Even before a message is added, it's
208  *                      pre-allocated thread ID is useful so that all
209  *                      descendant messages that reference this common
210  *                      parent can be recognized as belonging to the
211  *                      same thread.
212  */
213
214 /* With these prefix values we follow the conventions published here:
215  *
216  * http://xapian.org/docs/omega/termprefixes.html
217  *
218  * as much as makes sense. Note that I took some liberty in matching
219  * the reserved prefix values to notmuch concepts, (for example, 'G'
220  * is documented as "newsGroup (or similar entity - e.g. a web forum
221  * name)", for which I think the thread is the closest analogue in
222  * notmuch. This in spite of the fact that we will eventually be
223  * storing mailing-list messages where 'G' for "mailing list name"
224  * might be even a closer analogue. I'm treating the single-character
225  * prefixes preferentially for core notmuch concepts (which will be
226  * nearly universal to all mail messages).
227  */
228
229 static prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
230     { "type",                   "T" },
231     { "reference",              "XREFERENCE" },
232     { "replyto",                "XREPLYTO" },
233     { "directory",              "XDIRECTORY" },
234     { "file-direntry",          "XFDIRENTRY" },
235     { "directory-direntry",     "XDDIRENTRY" },
236 };
237
238 static prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
239     { "thread",                 "G" },
240     { "tag",                    "K" },
241     { "is",                     "K" },
242     { "id",                     "Q" },
243     { "path",                   "P" },
244     /*
245      * Without the ":", since this is a multi-letter prefix, Xapian
246      * will add a colon itself if the first letter of the path is
247      * upper-case ASCII. Including the ":" forces there to always be a
248      * colon, which keeps our own logic simpler.
249      */
250     { "folder",                 "XFOLDER:" },
251 };
252
253 static prefix_t PROBABILISTIC_PREFIX[]= {
254     { "from",                   "XFROM" },
255     { "to",                     "XTO" },
256     { "attachment",             "XATTACHMENT" },
257     { "subject",                "XSUBJECT"},
258 };
259
260 const char *
261 _find_prefix (const char *name)
262 {
263     unsigned int i;
264
265     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
266         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
267             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
268     }
269
270     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
271         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
272             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
273     }
274
275     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
276         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
277             return PROBABILISTIC_PREFIX[i].prefix;
278     }
279
280     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
281
282     return "";
283 }
284
285 static const struct {
286     /* NOTMUCH_FEATURE_* value. */
287     _notmuch_features value;
288     /* Feature name as it appears in the database.  This name should
289      * be appropriate for displaying to the user if an older version
290      * of notmuch doesn't support this feature. */
291     const char *name;
292     /* Compatibility flags when this feature is declared. */
293     const char *flags;
294 } feature_names[] = {
295     { NOTMUCH_FEATURE_FILE_TERMS,
296       "multiple paths per message", "rw" },
297     { NOTMUCH_FEATURE_DIRECTORY_DOCS,
298       "relative directory paths", "rw" },
299     /* Header values are not required for reading a database because a
300      * reader can just refer to the message file. */
301     { NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES,
302       "from/subject/message-ID in database", "w" },
303     { NOTMUCH_FEATURE_BOOL_FOLDER,
304       "exact folder:/path: search", "rw" },
305     { NOTMUCH_FEATURE_GHOSTS,
306       "mail documents for missing messages", "w"},
307 };
308
309 const char *
310 notmuch_status_to_string (notmuch_status_t status)
311 {
312     switch (status) {
313     case NOTMUCH_STATUS_SUCCESS:
314         return "No error occurred";
315     case NOTMUCH_STATUS_OUT_OF_MEMORY:
316         return "Out of memory";
317     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
318         return "Attempt to write to a read-only database";
319     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
320         return "A Xapian exception occurred";
321     case NOTMUCH_STATUS_FILE_ERROR:
322         return "Something went wrong trying to read or write a file";
323     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
324         return "File is not an email";
325     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
326         return "Message ID is identical to a message in database";
327     case NOTMUCH_STATUS_NULL_POINTER:
328         return "Erroneous NULL pointer";
329     case NOTMUCH_STATUS_TAG_TOO_LONG:
330         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
331     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
332         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
333     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
334         return "Unbalanced number of calls to notmuch_database_begin_atomic/end_atomic";
335     case NOTMUCH_STATUS_UNSUPPORTED_OPERATION:
336         return "Unsupported operation";
337     case NOTMUCH_STATUS_UPGRADE_REQUIRED:
338         return "Operation requires a database upgrade";
339     default:
340     case NOTMUCH_STATUS_LAST_STATUS:
341         return "Unknown error status value";
342     }
343 }
344
345 static void
346 find_doc_ids_for_term (notmuch_database_t *notmuch,
347                        const char *term,
348                        Xapian::PostingIterator *begin,
349                        Xapian::PostingIterator *end)
350 {
351     *begin = notmuch->xapian_db->postlist_begin (term);
352
353     *end = notmuch->xapian_db->postlist_end (term);
354 }
355
356 static void
357 find_doc_ids (notmuch_database_t *notmuch,
358               const char *prefix_name,
359               const char *value,
360               Xapian::PostingIterator *begin,
361               Xapian::PostingIterator *end)
362 {
363     char *term;
364
365     term = talloc_asprintf (notmuch, "%s%s",
366                             _find_prefix (prefix_name), value);
367
368     find_doc_ids_for_term (notmuch, term, begin, end);
369
370     talloc_free (term);
371 }
372
373 notmuch_private_status_t
374 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
375                                       const char *prefix_name,
376                                       const char *value,
377                                       unsigned int *doc_id)
378 {
379     Xapian::PostingIterator i, end;
380
381     find_doc_ids (notmuch, prefix_name, value, &i, &end);
382
383     if (i == end) {
384         *doc_id = 0;
385         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
386     }
387
388     *doc_id = *i;
389
390 #if DEBUG_DATABASE_SANITY
391     i++;
392
393     if (i != end)
394         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
395                         prefix_name, value);
396 #endif
397
398     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
399 }
400
401 static Xapian::Document
402 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
403 {
404     return notmuch->xapian_db->get_document (doc_id);
405 }
406
407 /* Generate a compressed version of 'message_id' of the form:
408  *
409  *      notmuch-sha1-<sha1_sum_of_message_id>
410  */
411 char *
412 _notmuch_message_id_compressed (void *ctx, const char *message_id)
413 {
414     char *sha1, *compressed;
415
416     sha1 = _notmuch_sha1_of_string (message_id);
417
418     compressed = talloc_asprintf (ctx, "notmuch-sha1-%s", sha1);
419     free (sha1);
420
421     return compressed;
422 }
423
424 notmuch_status_t
425 notmuch_database_find_message (notmuch_database_t *notmuch,
426                                const char *message_id,
427                                notmuch_message_t **message_ret)
428 {
429     notmuch_private_status_t status;
430     unsigned int doc_id;
431
432     if (message_ret == NULL)
433         return NOTMUCH_STATUS_NULL_POINTER;
434
435     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
436         message_id = _notmuch_message_id_compressed (notmuch, message_id);
437
438     try {
439         status = _notmuch_database_find_unique_doc_id (notmuch, "id",
440                                                        message_id, &doc_id);
441
442         if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
443             *message_ret = NULL;
444         else {
445             *message_ret = _notmuch_message_create (notmuch, notmuch, doc_id,
446                                                     NULL);
447             if (*message_ret == NULL)
448                 return NOTMUCH_STATUS_OUT_OF_MEMORY;
449         }
450
451         return NOTMUCH_STATUS_SUCCESS;
452     } catch (const Xapian::Error &error) {
453         fprintf (stderr, "A Xapian exception occurred finding message: %s.\n",
454                  error.get_msg().c_str());
455         notmuch->exception_reported = TRUE;
456         *message_ret = NULL;
457         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
458     }
459 }
460
461 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
462  * a (potentially nested) parenthesized sequence with '\' used to
463  * escape any character (including parentheses).
464  *
465  * If the sequence to be skipped continues to the end of the string,
466  * then 'str' will be left pointing at the final terminating '\0'
467  * character.
468  */
469 static void
470 skip_space_and_comments (const char **str)
471 {
472     const char *s;
473
474     s = *str;
475     while (*s && (isspace (*s) || *s == '(')) {
476         while (*s && isspace (*s))
477             s++;
478         if (*s == '(') {
479             int nesting = 1;
480             s++;
481             while (*s && nesting) {
482                 if (*s == '(') {
483                     nesting++;
484                 } else if (*s == ')') {
485                     nesting--;
486                 } else if (*s == '\\') {
487                     if (*(s+1))
488                         s++;
489                 }
490                 s++;
491             }
492         }
493     }
494
495     *str = s;
496 }
497
498 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
499  * comments, and the '<' and '>' delimiters.
500  *
501  * If not NULL, then *next will be made to point to the first character
502  * not parsed, (possibly pointing to the final '\0' terminator.
503  *
504  * Returns a newly talloc'ed string belonging to 'ctx'.
505  *
506  * Returns NULL if there is any error parsing the message-id. */
507 static char *
508 _parse_message_id (void *ctx, const char *message_id, const char **next)
509 {
510     const char *s, *end;
511     char *result;
512
513     if (message_id == NULL || *message_id == '\0')
514         return NULL;
515
516     s = message_id;
517
518     skip_space_and_comments (&s);
519
520     /* Skip any unstructured text as well. */
521     while (*s && *s != '<')
522         s++;
523
524     if (*s == '<') {
525         s++;
526     } else {
527         if (next)
528             *next = s;
529         return NULL;
530     }
531
532     skip_space_and_comments (&s);
533
534     end = s;
535     while (*end && *end != '>')
536         end++;
537     if (next) {
538         if (*end)
539             *next = end + 1;
540         else
541             *next = end;
542     }
543
544     if (end > s && *end == '>')
545         end--;
546     if (end <= s)
547         return NULL;
548
549     result = talloc_strndup (ctx, s, end - s + 1);
550
551     /* Finally, collapse any whitespace that is within the message-id
552      * itself. */
553     {
554         char *r;
555         int len;
556
557         for (r = result, len = strlen (r); *r; r++, len--)
558             if (*r == ' ' || *r == '\t')
559                 memmove (r, r+1, len);
560     }
561
562     return result;
563 }
564
565 /* Parse a References header value, putting a (talloc'ed under 'ctx')
566  * copy of each referenced message-id into 'hash'.
567  *
568  * We explicitly avoid including any reference identical to
569  * 'message_id' in the result (to avoid mass confusion when a single
570  * message references itself cyclically---and yes, mail messages are
571  * not infrequent in the wild that do this---don't ask me why).
572  *
573  * Return the last reference parsed, if it is not equal to message_id.
574  */
575 static char *
576 parse_references (void *ctx,
577                   const char *message_id,
578                   GHashTable *hash,
579                   const char *refs)
580 {
581     char *ref, *last_ref = NULL;
582
583     if (refs == NULL || *refs == '\0')
584         return NULL;
585
586     while (*refs) {
587         ref = _parse_message_id (ctx, refs, &refs);
588
589         if (ref && strcmp (ref, message_id)) {
590             g_hash_table_insert (hash, ref, NULL);
591             last_ref = ref;
592         }
593     }
594
595     /* The return value of this function is used to add a parent
596      * reference to the database.  We should avoid making a message
597      * its own parent, thus the above check.
598      */
599     return last_ref;
600 }
601
602 notmuch_status_t
603 notmuch_database_create (const char *path, notmuch_database_t **database)
604 {
605     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
606     notmuch_database_t *notmuch = NULL;
607     char *notmuch_path = NULL;
608     struct stat st;
609     int err;
610
611     if (path == NULL) {
612         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
613         status = NOTMUCH_STATUS_NULL_POINTER;
614         goto DONE;
615     }
616
617     err = stat (path, &st);
618     if (err) {
619         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
620                  path, strerror (errno));
621         status = NOTMUCH_STATUS_FILE_ERROR;
622         goto DONE;
623     }
624
625     if (! S_ISDIR (st.st_mode)) {
626         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
627                  path);
628         status = NOTMUCH_STATUS_FILE_ERROR;
629         goto DONE;
630     }
631
632     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
633
634     err = mkdir (notmuch_path, 0755);
635
636     if (err) {
637         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
638                  notmuch_path, strerror (errno));
639         status = NOTMUCH_STATUS_FILE_ERROR;
640         goto DONE;
641     }
642
643     status = notmuch_database_open (path,
644                                     NOTMUCH_DATABASE_MODE_READ_WRITE,
645                                     &notmuch);
646     if (status)
647         goto DONE;
648
649     /* Upgrade doesn't add this feature to existing databases, but new
650      * databases have it. */
651     notmuch->features |= NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES;
652
653     status = notmuch_database_upgrade (notmuch, NULL, NULL);
654     if (status) {
655         notmuch_database_close(notmuch);
656         notmuch = NULL;
657     }
658
659   DONE:
660     if (notmuch_path)
661         talloc_free (notmuch_path);
662
663     if (database)
664         *database = notmuch;
665     else
666         talloc_free (notmuch);
667     return status;
668 }
669
670 notmuch_status_t
671 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
672 {
673     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
674         fprintf (stderr, "Cannot write to a read-only database.\n");
675         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
676     }
677
678     return NOTMUCH_STATUS_SUCCESS;
679 }
680
681 /* Parse a database features string from the given database version.
682  * Returns the feature bit set.
683  *
684  * For version < 3, this ignores the features string and returns a
685  * hard-coded set of features.
686  *
687  * If there are unrecognized features that are required to open the
688  * database in mode (which should be 'r' or 'w'), return a
689  * comma-separated list of unrecognized but required features in
690  * *incompat_out suitable for presenting to the user.  *incompat_out
691  * will be allocated from ctx.
692  */
693 static _notmuch_features
694 _parse_features (const void *ctx, const char *features, unsigned int version,
695                  char mode, char **incompat_out)
696 {
697     _notmuch_features res = static_cast<_notmuch_features>(0);
698     unsigned int namelen, i;
699     size_t llen = 0;
700     const char *flags;
701
702     /* Prior to database version 3, features were implied by the
703      * version number. */
704     if (version == 0)
705         return NOTMUCH_FEATURES_V0;
706     else if (version == 1)
707         return NOTMUCH_FEATURES_V1;
708     else if (version == 2)
709         return NOTMUCH_FEATURES_V2;
710
711     /* Parse the features string */
712     while ((features = strtok_len_c (features + llen, "\n", &llen)) != NULL) {
713         flags = strchr (features, '\t');
714         if (! flags || flags > features + llen)
715             continue;
716         namelen = flags - features;
717
718         for (i = 0; i < ARRAY_SIZE (feature_names); ++i) {
719             if (strlen (feature_names[i].name) == namelen &&
720                 strncmp (feature_names[i].name, features, namelen) == 0) {
721                 res |= feature_names[i].value;
722                 break;
723             }
724         }
725
726         if (i == ARRAY_SIZE (feature_names) && incompat_out) {
727             /* Unrecognized feature */
728             const char *have = strchr (flags, mode);
729             if (have && have < features + llen) {
730                 /* This feature is required to access this database in
731                  * 'mode', but we don't understand it. */
732                 if (! *incompat_out)
733                     *incompat_out = talloc_strdup (ctx, "");
734                 *incompat_out = talloc_asprintf_append_buffer (
735                     *incompat_out, "%s%.*s", **incompat_out ? ", " : "",
736                     namelen, features);
737             }
738         }
739     }
740
741     return res;
742 }
743
744 static char *
745 _print_features (const void *ctx, unsigned int features)
746 {
747     unsigned int i;
748     char *res = talloc_strdup (ctx, "");
749
750     for (i = 0; i < ARRAY_SIZE (feature_names); ++i)
751         if (features & feature_names[i].value)
752             res = talloc_asprintf_append_buffer (
753                 res, "%s\t%s\n", feature_names[i].name, feature_names[i].flags);
754
755     return res;
756 }
757
758 notmuch_status_t
759 notmuch_database_open (const char *path,
760                        notmuch_database_mode_t mode,
761                        notmuch_database_t **database)
762 {
763     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
764     void *local = talloc_new (NULL);
765     notmuch_database_t *notmuch = NULL;
766     char *notmuch_path, *xapian_path, *incompat_features;
767     struct stat st;
768     int err;
769     unsigned int i, version;
770     static int initialized = 0;
771
772     if (path == NULL) {
773         fprintf (stderr, "Error: Cannot open a database for a NULL path.\n");
774         status = NOTMUCH_STATUS_NULL_POINTER;
775         goto DONE;
776     }
777
778     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
779         fprintf (stderr, "Out of memory\n");
780         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
781         goto DONE;
782     }
783
784     err = stat (notmuch_path, &st);
785     if (err) {
786         fprintf (stderr, "Error opening database at %s: %s\n",
787                  notmuch_path, strerror (errno));
788         status = NOTMUCH_STATUS_FILE_ERROR;
789         goto DONE;
790     }
791
792     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
793         fprintf (stderr, "Out of memory\n");
794         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
795         goto DONE;
796     }
797
798     /* Initialize the GLib type system and threads */
799 #if !GLIB_CHECK_VERSION(2, 35, 1)
800     g_type_init ();
801 #endif
802
803     /* Initialize gmime */
804     if (! initialized) {
805         g_mime_init (GMIME_ENABLE_RFC2047_WORKAROUNDS);
806         initialized = 1;
807     }
808
809     notmuch = talloc_zero (NULL, notmuch_database_t);
810     notmuch->exception_reported = FALSE;
811     notmuch->path = talloc_strdup (notmuch, path);
812
813     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
814         notmuch->path[strlen (notmuch->path) - 1] = '\0';
815
816     notmuch->mode = mode;
817     notmuch->atomic_nesting = 0;
818     try {
819         string last_thread_id;
820
821         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
822             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
823                                                                Xapian::DB_CREATE_OR_OPEN);
824         } else {
825             notmuch->xapian_db = new Xapian::Database (xapian_path);
826         }
827
828         /* Check version.  As of database version 3, we represent
829          * changes in terms of features, so assume a version bump
830          * means a dramatically incompatible change. */
831         version = notmuch_database_get_version (notmuch);
832         if (version > NOTMUCH_DATABASE_VERSION) {
833             fprintf (stderr,
834                      "Error: Notmuch database at %s\n"
835                      "       has a newer database format version (%u) than supported by this\n"
836                      "       version of notmuch (%u).\n",
837                      notmuch_path, version, NOTMUCH_DATABASE_VERSION);
838             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
839             notmuch_database_destroy (notmuch);
840             notmuch = NULL;
841             status = NOTMUCH_STATUS_FILE_ERROR;
842             goto DONE;
843         }
844
845         /* Check features. */
846         incompat_features = NULL;
847         notmuch->features = _parse_features (
848             local, notmuch->xapian_db->get_metadata ("features").c_str (),
849             version, mode == NOTMUCH_DATABASE_MODE_READ_WRITE ? 'w' : 'r',
850             &incompat_features);
851         if (incompat_features) {
852             fprintf (stderr,
853                      "Error: Notmuch database at %s\n"
854                      "       requires features (%s)\n"
855                      "       not supported by this version of notmuch.\n",
856                      notmuch_path, incompat_features);
857             notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
858             notmuch_database_destroy (notmuch);
859             notmuch = NULL;
860             status = NOTMUCH_STATUS_FILE_ERROR;
861             goto DONE;
862         }
863
864         notmuch->last_doc_id = notmuch->xapian_db->get_lastdocid ();
865         last_thread_id = notmuch->xapian_db->get_metadata ("last_thread_id");
866         if (last_thread_id.empty ()) {
867             notmuch->last_thread_id = 0;
868         } else {
869             const char *str;
870             char *end;
871
872             str = last_thread_id.c_str ();
873             notmuch->last_thread_id = strtoull (str, &end, 16);
874             if (*end != '\0')
875                 INTERNAL_ERROR ("Malformed database last_thread_id: %s", str);
876         }
877
878         notmuch->query_parser = new Xapian::QueryParser;
879         notmuch->term_gen = new Xapian::TermGenerator;
880         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
881         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
882         notmuch->date_range_processor = new ParseTimeValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
883
884         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
885         notmuch->query_parser->set_database (*notmuch->xapian_db);
886         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
887         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
888         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
889         notmuch->query_parser->add_valuerangeprocessor (notmuch->date_range_processor);
890
891         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
892             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
893             notmuch->query_parser->add_boolean_prefix (prefix->name,
894                                                        prefix->prefix);
895         }
896
897         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
898             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
899             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
900         }
901     } catch (const Xapian::Error &error) {
902         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
903                  error.get_msg().c_str());
904         notmuch_database_destroy (notmuch);
905         notmuch = NULL;
906         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
907     }
908
909   DONE:
910     talloc_free (local);
911
912     if (database)
913         *database = notmuch;
914     else
915         talloc_free (notmuch);
916     return status;
917 }
918
919 notmuch_status_t
920 notmuch_database_close (notmuch_database_t *notmuch)
921 {
922     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
923
924     /* Many Xapian objects (and thus notmuch objects) hold references to
925      * the database, so merely deleting the database may not suffice to
926      * close it.  Thus, we explicitly close it here. */
927     if (notmuch->xapian_db != NULL) {
928         try {
929             /* If there's an outstanding transaction, it's unclear if
930              * closing the Xapian database commits everything up to
931              * that transaction, or may discard committed (but
932              * unflushed) transactions.  To be certain, explicitly
933              * cancel any outstanding transaction before closing. */
934             if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
935                 notmuch->atomic_nesting)
936                 (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))
937                     ->cancel_transaction ();
938
939             /* Close the database.  This implicitly flushes
940              * outstanding changes. */
941             notmuch->xapian_db->close();
942         } catch (const Xapian::Error &error) {
943             status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
944             if (! notmuch->exception_reported) {
945                 fprintf (stderr, "Error: A Xapian exception occurred closing database: %s\n",
946                          error.get_msg().c_str());
947             }
948         }
949     }
950
951     delete notmuch->term_gen;
952     notmuch->term_gen = NULL;
953     delete notmuch->query_parser;
954     notmuch->query_parser = NULL;
955     delete notmuch->xapian_db;
956     notmuch->xapian_db = NULL;
957     delete notmuch->value_range_processor;
958     notmuch->value_range_processor = NULL;
959     delete notmuch->date_range_processor;
960     notmuch->date_range_processor = NULL;
961
962     return status;
963 }
964
965 #if HAVE_XAPIAN_COMPACT
966 static int
967 unlink_cb (const char *path,
968            unused (const struct stat *sb),
969            unused (int type),
970            unused (struct FTW *ftw))
971 {
972     return remove (path);
973 }
974
975 static int
976 rmtree (const char *path)
977 {
978     return nftw (path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
979 }
980
981 class NotmuchCompactor : public Xapian::Compactor
982 {
983     notmuch_compact_status_cb_t status_cb;
984     void *status_closure;
985
986 public:
987     NotmuchCompactor(notmuch_compact_status_cb_t cb, void *closure) :
988         status_cb (cb), status_closure (closure) { }
989
990     virtual void
991     set_status (const std::string &table, const std::string &status)
992     {
993         char *msg;
994
995         if (status_cb == NULL)
996             return;
997
998         if (status.length () == 0)
999             msg = talloc_asprintf (NULL, "compacting table %s", table.c_str());
1000         else
1001             msg = talloc_asprintf (NULL, "     %s", status.c_str());
1002
1003         if (msg == NULL) {
1004             return;
1005         }
1006
1007         status_cb (msg, status_closure);
1008         talloc_free (msg);
1009     }
1010 };
1011
1012 /* Compacts the given database, optionally saving the original database
1013  * in backup_path. Additionally, a callback function can be provided to
1014  * give the user feedback on the progress of the (likely long-lived)
1015  * compaction process.
1016  *
1017  * The backup path must point to a directory on the same volume as the
1018  * original database. Passing a NULL backup_path will result in the
1019  * uncompacted database being deleted after compaction has finished.
1020  * Note that the database write lock will be held during the
1021  * compaction process to protect data integrity.
1022  */
1023 notmuch_status_t
1024 notmuch_database_compact (const char *path,
1025                           const char *backup_path,
1026                           notmuch_compact_status_cb_t status_cb,
1027                           void *closure)
1028 {
1029     void *local;
1030     char *notmuch_path, *xapian_path, *compact_xapian_path;
1031     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1032     notmuch_database_t *notmuch = NULL;
1033     struct stat statbuf;
1034     notmuch_bool_t keep_backup;
1035
1036     local = talloc_new (NULL);
1037     if (! local)
1038         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1039
1040     ret = notmuch_database_open (path, NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch);
1041     if (ret) {
1042         goto DONE;
1043     }
1044
1045     if (! (notmuch_path = talloc_asprintf (local, "%s/%s", path, ".notmuch"))) {
1046         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1047         goto DONE;
1048     }
1049
1050     if (! (xapian_path = talloc_asprintf (local, "%s/%s", notmuch_path, "xapian"))) {
1051         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1052         goto DONE;
1053     }
1054
1055     if (! (compact_xapian_path = talloc_asprintf (local, "%s.compact", xapian_path))) {
1056         ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1057         goto DONE;
1058     }
1059
1060     if (backup_path == NULL) {
1061         if (! (backup_path = talloc_asprintf (local, "%s.old", xapian_path))) {
1062             ret = NOTMUCH_STATUS_OUT_OF_MEMORY;
1063             goto DONE;
1064         }
1065         keep_backup = FALSE;
1066     }
1067     else {
1068         keep_backup = TRUE;
1069     }
1070
1071     if (stat (backup_path, &statbuf) != -1) {
1072         fprintf (stderr, "Path already exists: %s\n", backup_path);
1073         ret = NOTMUCH_STATUS_FILE_ERROR;
1074         goto DONE;
1075     }
1076     if (errno != ENOENT) {
1077         fprintf (stderr, "Unknown error while stat()ing path: %s\n",
1078                  strerror (errno));
1079         ret = NOTMUCH_STATUS_FILE_ERROR;
1080         goto DONE;
1081     }
1082
1083     /* Unconditionally attempt to remove old work-in-progress database (if
1084      * any). This is "protected" by database lock. If this fails due to write
1085      * errors (etc), the following code will fail and provide error message.
1086      */
1087     (void) rmtree (compact_xapian_path);
1088
1089     try {
1090         NotmuchCompactor compactor (status_cb, closure);
1091
1092         compactor.set_renumber (false);
1093         compactor.add_source (xapian_path);
1094         compactor.set_destdir (compact_xapian_path);
1095         compactor.compact ();
1096     } catch (const Xapian::Error &error) {
1097         fprintf (stderr, "Error while compacting: %s\n", error.get_msg().c_str());
1098         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1099         goto DONE;
1100     }
1101
1102     if (rename (xapian_path, backup_path)) {
1103         fprintf (stderr, "Error moving %s to %s: %s\n",
1104                  xapian_path, backup_path, strerror (errno));
1105         ret = NOTMUCH_STATUS_FILE_ERROR;
1106         goto DONE;
1107     }
1108
1109     if (rename (compact_xapian_path, xapian_path)) {
1110         fprintf (stderr, "Error moving %s to %s: %s\n",
1111                  compact_xapian_path, xapian_path, strerror (errno));
1112         ret = NOTMUCH_STATUS_FILE_ERROR;
1113         goto DONE;
1114     }
1115
1116     if (! keep_backup) {
1117         if (rmtree (backup_path)) {
1118             fprintf (stderr, "Error removing old database %s: %s\n",
1119                      backup_path, strerror (errno));
1120             ret = NOTMUCH_STATUS_FILE_ERROR;
1121             goto DONE;
1122         }
1123     }
1124
1125   DONE:
1126     if (notmuch) {
1127         notmuch_status_t ret2;
1128
1129         ret2 = notmuch_database_destroy (notmuch);
1130
1131         /* don't clobber previous error status */
1132         if (ret == NOTMUCH_STATUS_SUCCESS && ret2 != NOTMUCH_STATUS_SUCCESS)
1133             ret = ret2;
1134     }
1135
1136     talloc_free (local);
1137
1138     return ret;
1139 }
1140 #else
1141 notmuch_status_t
1142 notmuch_database_compact (unused (const char *path),
1143                           unused (const char *backup_path),
1144                           unused (notmuch_compact_status_cb_t status_cb),
1145                           unused (void *closure))
1146 {
1147     fprintf (stderr, "notmuch was compiled against a xapian version lacking compaction support.\n");
1148     return NOTMUCH_STATUS_UNSUPPORTED_OPERATION;
1149 }
1150 #endif
1151
1152 notmuch_status_t
1153 notmuch_database_destroy (notmuch_database_t *notmuch)
1154 {
1155     notmuch_status_t status;
1156
1157     status = notmuch_database_close (notmuch);
1158     talloc_free (notmuch);
1159
1160     return status;
1161 }
1162
1163 const char *
1164 notmuch_database_get_path (notmuch_database_t *notmuch)
1165 {
1166     return notmuch->path;
1167 }
1168
1169 unsigned int
1170 notmuch_database_get_version (notmuch_database_t *notmuch)
1171 {
1172     unsigned int version;
1173     string version_string;
1174     const char *str;
1175     char *end;
1176
1177     version_string = notmuch->xapian_db->get_metadata ("version");
1178     if (version_string.empty ())
1179         return 0;
1180
1181     str = version_string.c_str ();
1182     if (str == NULL || *str == '\0')
1183         return 0;
1184
1185     version = strtoul (str, &end, 10);
1186     if (*end != '\0')
1187         INTERNAL_ERROR ("Malformed database version: %s", str);
1188
1189     return version;
1190 }
1191
1192 notmuch_bool_t
1193 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
1194 {
1195     return notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE &&
1196         ((NOTMUCH_FEATURES_CURRENT & ~notmuch->features) ||
1197          (notmuch_database_get_version (notmuch) < NOTMUCH_DATABASE_VERSION));
1198 }
1199
1200 static volatile sig_atomic_t do_progress_notify = 0;
1201
1202 static void
1203 handle_sigalrm (unused (int signal))
1204 {
1205     do_progress_notify = 1;
1206 }
1207
1208 /* Upgrade the current database.
1209  *
1210  * After opening a database in read-write mode, the client should
1211  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
1212  * if so, upgrade with this function before making any modifications.
1213  *
1214  * The optional progress_notify callback can be used by the caller to
1215  * provide progress indication to the user. If non-NULL it will be
1216  * called periodically with 'count' as the number of messages upgraded
1217  * so far and 'total' the overall number of messages that will be
1218  * converted.
1219  */
1220 notmuch_status_t
1221 notmuch_database_upgrade (notmuch_database_t *notmuch,
1222                           void (*progress_notify) (void *closure,
1223                                                    double progress),
1224                           void *closure)
1225 {
1226     void *local = talloc_new (NULL);
1227     Xapian::TermIterator t, t_end;
1228     Xapian::WritableDatabase *db;
1229     struct sigaction action;
1230     struct itimerval timerval;
1231     notmuch_bool_t timer_is_active = FALSE;
1232     enum _notmuch_features target_features, new_features;
1233     notmuch_status_t status;
1234     notmuch_private_status_t private_status;
1235     unsigned int count = 0, total = 0;
1236
1237     status = _notmuch_database_ensure_writable (notmuch);
1238     if (status)
1239         return status;
1240
1241     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1242
1243     target_features = notmuch->features | NOTMUCH_FEATURES_CURRENT;
1244     new_features = NOTMUCH_FEATURES_CURRENT & ~notmuch->features;
1245
1246     if (! notmuch_database_needs_upgrade (notmuch))
1247         return NOTMUCH_STATUS_SUCCESS;
1248
1249     if (progress_notify) {
1250         /* Setup our handler for SIGALRM */
1251         memset (&action, 0, sizeof (struct sigaction));
1252         action.sa_handler = handle_sigalrm;
1253         sigemptyset (&action.sa_mask);
1254         action.sa_flags = SA_RESTART;
1255         sigaction (SIGALRM, &action, NULL);
1256
1257         /* Then start a timer to send SIGALRM once per second. */
1258         timerval.it_interval.tv_sec = 1;
1259         timerval.it_interval.tv_usec = 0;
1260         timerval.it_value.tv_sec = 1;
1261         timerval.it_value.tv_usec = 0;
1262         setitimer (ITIMER_REAL, &timerval, NULL);
1263
1264         timer_is_active = TRUE;
1265     }
1266
1267     /* Figure out how much total work we need to do. */
1268     if (new_features &
1269         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1270         notmuch_query_t *query = notmuch_query_create (notmuch, "");
1271         total += notmuch_query_count_messages (query);
1272         notmuch_query_destroy (query);
1273     }
1274     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1275         t_end = db->allterms_end ("XTIMESTAMP");
1276         for (t = db->allterms_begin ("XTIMESTAMP"); t != t_end; t++)
1277             ++total;
1278     }
1279     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1280         /* The ghost message upgrade converts all thread_id_*
1281          * metadata values into ghost message documents. */
1282         t_end = db->metadata_keys_end ("thread_id_");
1283         for (t = db->metadata_keys_begin ("thread_id_"); t != t_end; ++t)
1284             ++total;
1285     }
1286
1287     /* Perform the upgrade in a transaction. */
1288     db->begin_transaction (true);
1289
1290     /* Set the target features so we write out changes in the desired
1291      * format. */
1292     notmuch->features = target_features;
1293
1294     /* Perform per-message upgrades. */
1295     if (new_features &
1296         (NOTMUCH_FEATURE_FILE_TERMS | NOTMUCH_FEATURE_BOOL_FOLDER)) {
1297         notmuch_query_t *query = notmuch_query_create (notmuch, "");
1298         notmuch_messages_t *messages;
1299         notmuch_message_t *message;
1300         char *filename;
1301
1302         for (messages = notmuch_query_search_messages (query);
1303              notmuch_messages_valid (messages);
1304              notmuch_messages_move_to_next (messages))
1305         {
1306             if (do_progress_notify) {
1307                 progress_notify (closure, (double) count / total);
1308                 do_progress_notify = 0;
1309             }
1310
1311             message = notmuch_messages_get (messages);
1312
1313             /* Before version 1, each message document had its
1314              * filename in the data field. Copy that into the new
1315              * format by calling notmuch_message_add_filename.
1316              */
1317             if (new_features & NOTMUCH_FEATURE_FILE_TERMS) {
1318                 filename = _notmuch_message_talloc_copy_data (message);
1319                 if (filename && *filename != '\0') {
1320                     _notmuch_message_add_filename (message, filename);
1321                     _notmuch_message_clear_data (message);
1322                 }
1323                 talloc_free (filename);
1324             }
1325
1326             /* Prior to version 2, the "folder:" prefix was
1327              * probabilistic and stemmed. Change it to the current
1328              * boolean prefix. Add "path:" prefixes while at it.
1329              */
1330             if (new_features & NOTMUCH_FEATURE_BOOL_FOLDER)
1331                 _notmuch_message_upgrade_folder (message);
1332
1333             _notmuch_message_sync (message);
1334
1335             notmuch_message_destroy (message);
1336
1337             count++;
1338         }
1339
1340         notmuch_query_destroy (query);
1341     }
1342
1343     /* Perform per-directory upgrades. */
1344
1345     /* Before version 1 we stored directory timestamps in
1346      * XTIMESTAMP documents instead of the current XDIRECTORY
1347      * documents. So copy those as well. */
1348     if (new_features & NOTMUCH_FEATURE_DIRECTORY_DOCS) {
1349         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
1350
1351         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
1352              t != t_end;
1353              t++)
1354         {
1355             Xapian::PostingIterator p, p_end;
1356             std::string term = *t;
1357
1358             p_end = notmuch->xapian_db->postlist_end (term);
1359
1360             for (p = notmuch->xapian_db->postlist_begin (term);
1361                  p != p_end;
1362                  p++)
1363             {
1364                 Xapian::Document document;
1365                 time_t mtime;
1366                 notmuch_directory_t *directory;
1367
1368                 if (do_progress_notify) {
1369                     progress_notify (closure, (double) count / total);
1370                     do_progress_notify = 0;
1371                 }
1372
1373                 document = find_document_for_doc_id (notmuch, *p);
1374                 mtime = Xapian::sortable_unserialise (
1375                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
1376
1377                 directory = _notmuch_directory_create (notmuch, term.c_str() + 10,
1378                                                        NOTMUCH_FIND_CREATE, &status);
1379                 notmuch_directory_set_mtime (directory, mtime);
1380                 notmuch_directory_destroy (directory);
1381
1382                 db->delete_document (*p);
1383             }
1384
1385             ++count;
1386         }
1387     }
1388
1389     /* Perform metadata upgrades. */
1390
1391     /* Prior to NOTMUCH_FEATURE_GHOSTS, thread IDs for missing
1392      * messages were stored as database metadata. Change these to
1393      * ghost messages.
1394      */
1395     if (new_features & NOTMUCH_FEATURE_GHOSTS) {
1396         notmuch_message_t *message;
1397         std::string message_id, thread_id;
1398
1399         t_end = db->metadata_keys_end (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1400         for (t = db->metadata_keys_begin (NOTMUCH_METADATA_THREAD_ID_PREFIX);
1401              t != t_end; ++t) {
1402             if (do_progress_notify) {
1403                 progress_notify (closure, (double) count / total);
1404                 do_progress_notify = 0;
1405             }
1406
1407             message_id = (*t).substr (
1408                 strlen (NOTMUCH_METADATA_THREAD_ID_PREFIX));
1409             thread_id = db->get_metadata (*t);
1410
1411             /* Create ghost message */
1412             message = _notmuch_message_create_for_message_id (
1413                 notmuch, message_id.c_str (), &private_status);
1414             if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1415                 /* Document already exists; ignore the stored thread ID */
1416             } else if (private_status ==
1417                        NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1418                 private_status = _notmuch_message_initialize_ghost (
1419                     message, thread_id.c_str ());
1420                 if (! private_status)
1421                     _notmuch_message_sync (message);
1422             }
1423
1424             if (private_status) {
1425                 fprintf (stderr,
1426                          "Upgrade failed while creating ghost messages.\n");
1427                 status = COERCE_STATUS (private_status, "Unexpected status from _notmuch_message_initialize_ghost");
1428                 goto DONE;
1429             }
1430
1431             /* Clear saved metadata thread ID */
1432             db->set_metadata (*t, "");
1433
1434             ++count;
1435         }
1436     }
1437
1438     status = NOTMUCH_STATUS_SUCCESS;
1439     db->set_metadata ("features", _print_features (local, notmuch->features));
1440     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
1441
1442  DONE:
1443     if (status == NOTMUCH_STATUS_SUCCESS)
1444         db->commit_transaction ();
1445     else
1446         db->cancel_transaction ();
1447
1448     if (timer_is_active) {
1449         /* Now stop the timer. */
1450         timerval.it_interval.tv_sec = 0;
1451         timerval.it_interval.tv_usec = 0;
1452         timerval.it_value.tv_sec = 0;
1453         timerval.it_value.tv_usec = 0;
1454         setitimer (ITIMER_REAL, &timerval, NULL);
1455
1456         /* And disable the signal handler. */
1457         action.sa_handler = SIG_IGN;
1458         sigaction (SIGALRM, &action, NULL);
1459     }
1460
1461     talloc_free (local);
1462     return status;
1463 }
1464
1465 notmuch_status_t
1466 notmuch_database_begin_atomic (notmuch_database_t *notmuch)
1467 {
1468     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1469         notmuch->atomic_nesting > 0)
1470         goto DONE;
1471
1472     try {
1473         (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->begin_transaction (false);
1474     } catch (const Xapian::Error &error) {
1475         fprintf (stderr, "A Xapian exception occurred beginning transaction: %s.\n",
1476                  error.get_msg().c_str());
1477         notmuch->exception_reported = TRUE;
1478         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1479     }
1480
1481 DONE:
1482     notmuch->atomic_nesting++;
1483     return NOTMUCH_STATUS_SUCCESS;
1484 }
1485
1486 notmuch_status_t
1487 notmuch_database_end_atomic (notmuch_database_t *notmuch)
1488 {
1489     Xapian::WritableDatabase *db;
1490
1491     if (notmuch->atomic_nesting == 0)
1492         return NOTMUCH_STATUS_UNBALANCED_ATOMIC;
1493
1494     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY ||
1495         notmuch->atomic_nesting > 1)
1496         goto DONE;
1497
1498     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1499     try {
1500         db->commit_transaction ();
1501
1502         /* This is a hack for testing.  Xapian never flushes on a
1503          * non-flushed commit, even if the flush threshold is 1.
1504          * However, we rely on flushing to test atomicity. */
1505         const char *thresh = getenv ("XAPIAN_FLUSH_THRESHOLD");
1506         if (thresh && atoi (thresh) == 1)
1507             db->flush ();
1508     } catch (const Xapian::Error &error) {
1509         fprintf (stderr, "A Xapian exception occurred committing transaction: %s.\n",
1510                  error.get_msg().c_str());
1511         notmuch->exception_reported = TRUE;
1512         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1513     }
1514
1515 DONE:
1516     notmuch->atomic_nesting--;
1517     return NOTMUCH_STATUS_SUCCESS;
1518 }
1519
1520 /* We allow the user to use arbitrarily long paths for directories. But
1521  * we have a term-length limit. So if we exceed that, we'll use the
1522  * SHA-1 of the path for the database term.
1523  *
1524  * Note: This function may return the original value of 'path'. If it
1525  * does not, then the caller is responsible to free() the returned
1526  * value.
1527  */
1528 const char *
1529 _notmuch_database_get_directory_db_path (const char *path)
1530 {
1531     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
1532
1533     if (term_len > NOTMUCH_TERM_MAX)
1534         return _notmuch_sha1_of_string (path);
1535     else
1536         return path;
1537 }
1538
1539 /* Given a path, split it into two parts: the directory part is all
1540  * components except for the last, and the basename is that last
1541  * component. Getting the return-value for either part is optional
1542  * (the caller can pass NULL).
1543  *
1544  * The original 'path' can represent either a regular file or a
1545  * directory---the splitting will be carried out in the same way in
1546  * either case. Trailing slashes on 'path' will be ignored, and any
1547  * cases of multiple '/' characters appearing in series will be
1548  * treated as a single '/'.
1549  *
1550  * Allocation (if any) will have 'ctx' as the talloc owner. But
1551  * pointers will be returned within the original path string whenever
1552  * possible.
1553  *
1554  * Note: If 'path' is non-empty and contains no non-trailing slash,
1555  * (that is, consists of a filename with no parent directory), then
1556  * the directory returned will be an empty string. However, if 'path'
1557  * is an empty string, then both directory and basename will be
1558  * returned as NULL.
1559  */
1560 notmuch_status_t
1561 _notmuch_database_split_path (void *ctx,
1562                               const char *path,
1563                               const char **directory,
1564                               const char **basename)
1565 {
1566     const char *slash;
1567
1568     if (path == NULL || *path == '\0') {
1569         if (directory)
1570             *directory = NULL;
1571         if (basename)
1572             *basename = NULL;
1573         return NOTMUCH_STATUS_SUCCESS;
1574     }
1575
1576     /* Find the last slash (not counting a trailing slash), if any. */
1577
1578     slash = path + strlen (path) - 1;
1579
1580     /* First, skip trailing slashes. */
1581     while (slash != path) {
1582         if (*slash != '/')
1583             break;
1584
1585         --slash;
1586     }
1587
1588     /* Then, find a slash. */
1589     while (slash != path) {
1590         if (*slash == '/')
1591             break;
1592
1593         if (basename)
1594             *basename = slash;
1595
1596         --slash;
1597     }
1598
1599     /* Finally, skip multiple slashes. */
1600     while (slash != path) {
1601         if (*slash != '/')
1602             break;
1603
1604         --slash;
1605     }
1606
1607     if (slash == path) {
1608         if (directory)
1609             *directory = talloc_strdup (ctx, "");
1610         if (basename)
1611             *basename = path;
1612     } else {
1613         if (directory)
1614             *directory = talloc_strndup (ctx, path, slash - path + 1);
1615     }
1616
1617     return NOTMUCH_STATUS_SUCCESS;
1618 }
1619
1620 /* Find the document ID of the specified directory.
1621  *
1622  * If (flags & NOTMUCH_FIND_CREATE), a new directory document will be
1623  * created if one does not exist for 'path'.  Otherwise, if the
1624  * directory document does not exist, this sets *directory_id to
1625  * ((unsigned int)-1) and returns NOTMUCH_STATUS_SUCCESS.
1626  */
1627 notmuch_status_t
1628 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
1629                                      const char *path,
1630                                      notmuch_find_flags_t flags,
1631                                      unsigned int *directory_id)
1632 {
1633     notmuch_directory_t *directory;
1634     notmuch_status_t status;
1635
1636     if (path == NULL) {
1637         *directory_id = 0;
1638         return NOTMUCH_STATUS_SUCCESS;
1639     }
1640
1641     directory = _notmuch_directory_create (notmuch, path, flags, &status);
1642     if (status || !directory) {
1643         *directory_id = -1;
1644         return status;
1645     }
1646
1647     *directory_id = _notmuch_directory_get_document_id (directory);
1648
1649     notmuch_directory_destroy (directory);
1650
1651     return NOTMUCH_STATUS_SUCCESS;
1652 }
1653
1654 const char *
1655 _notmuch_database_get_directory_path (void *ctx,
1656                                       notmuch_database_t *notmuch,
1657                                       unsigned int doc_id)
1658 {
1659     Xapian::Document document;
1660
1661     document = find_document_for_doc_id (notmuch, doc_id);
1662
1663     return talloc_strdup (ctx, document.get_data ().c_str ());
1664 }
1665
1666 /* Given a legal 'filename' for the database, (either relative to
1667  * database path or absolute with initial components identical to
1668  * database path), return a new string (with 'ctx' as the talloc
1669  * owner) suitable for use as a direntry term value.
1670  *
1671  * If (flags & NOTMUCH_FIND_CREATE), the necessary directory documents
1672  * will be created in the database as needed.  Otherwise, if the
1673  * necessary directory documents do not exist, this sets
1674  * *direntry to NULL and returns NOTMUCH_STATUS_SUCCESS.
1675  */
1676 notmuch_status_t
1677 _notmuch_database_filename_to_direntry (void *ctx,
1678                                         notmuch_database_t *notmuch,
1679                                         const char *filename,
1680                                         notmuch_find_flags_t flags,
1681                                         char **direntry)
1682 {
1683     const char *relative, *directory, *basename;
1684     Xapian::docid directory_id;
1685     notmuch_status_t status;
1686
1687     relative = _notmuch_database_relative_path (notmuch, filename);
1688
1689     status = _notmuch_database_split_path (ctx, relative,
1690                                            &directory, &basename);
1691     if (status)
1692         return status;
1693
1694     status = _notmuch_database_find_directory_id (notmuch, directory, flags,
1695                                                   &directory_id);
1696     if (status || directory_id == (unsigned int)-1) {
1697         *direntry = NULL;
1698         return status;
1699     }
1700
1701     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
1702
1703     return NOTMUCH_STATUS_SUCCESS;
1704 }
1705
1706 /* Given a legal 'path' for the database, return the relative path.
1707  *
1708  * The return value will be a pointer to the original path contents,
1709  * and will be either the original string (if 'path' was relative) or
1710  * a portion of the string (if path was absolute and begins with the
1711  * database path).
1712  */
1713 const char *
1714 _notmuch_database_relative_path (notmuch_database_t *notmuch,
1715                                  const char *path)
1716 {
1717     const char *db_path, *relative;
1718     unsigned int db_path_len;
1719
1720     db_path = notmuch_database_get_path (notmuch);
1721     db_path_len = strlen (db_path);
1722
1723     relative = path;
1724
1725     if (*relative == '/') {
1726         while (*relative == '/' && *(relative+1) == '/')
1727             relative++;
1728
1729         if (strncmp (relative, db_path, db_path_len) == 0)
1730         {
1731             relative += db_path_len;
1732             while (*relative == '/')
1733                 relative++;
1734         }
1735     }
1736
1737     return relative;
1738 }
1739
1740 notmuch_status_t
1741 notmuch_database_get_directory (notmuch_database_t *notmuch,
1742                                 const char *path,
1743                                 notmuch_directory_t **directory)
1744 {
1745     notmuch_status_t status;
1746
1747     if (directory == NULL)
1748         return NOTMUCH_STATUS_NULL_POINTER;
1749     *directory = NULL;
1750
1751     try {
1752         *directory = _notmuch_directory_create (notmuch, path,
1753                                                 NOTMUCH_FIND_LOOKUP, &status);
1754     } catch (const Xapian::Error &error) {
1755         fprintf (stderr, "A Xapian exception occurred getting directory: %s.\n",
1756                  error.get_msg().c_str());
1757         notmuch->exception_reported = TRUE;
1758         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1759     }
1760     return status;
1761 }
1762
1763 /* Allocate a document ID that satisfies the following criteria:
1764  *
1765  * 1. The ID does not exist for any document in the Xapian database
1766  *
1767  * 2. The ID was not previously returned from this function
1768  *
1769  * 3. The ID is the smallest integer satisfying (1) and (2)
1770  *
1771  * This function will trigger an internal error if these constraints
1772  * cannot all be satisfied, (that is, the pool of available document
1773  * IDs has been exhausted).
1774  */
1775 unsigned int
1776 _notmuch_database_generate_doc_id (notmuch_database_t *notmuch)
1777 {
1778     assert (notmuch->last_doc_id >= notmuch->xapian_db->get_lastdocid ());
1779
1780     notmuch->last_doc_id++;
1781
1782     if (notmuch->last_doc_id == 0)
1783         INTERNAL_ERROR ("Xapian document IDs are exhausted.\n");
1784
1785     return notmuch->last_doc_id;
1786 }
1787
1788 static const char *
1789 _notmuch_database_generate_thread_id (notmuch_database_t *notmuch)
1790 {
1791     /* 16 bytes (+ terminator) for hexadecimal representation of
1792      * a 64-bit integer. */
1793     static char thread_id[17];
1794     Xapian::WritableDatabase *db;
1795
1796     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1797
1798     notmuch->last_thread_id++;
1799
1800     sprintf (thread_id, "%016" PRIx64, notmuch->last_thread_id);
1801
1802     db->set_metadata ("last_thread_id", thread_id);
1803
1804     return thread_id;
1805 }
1806
1807 static char *
1808 _get_metadata_thread_id_key (void *ctx, const char *message_id)
1809 {
1810     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
1811         message_id = _notmuch_message_id_compressed (ctx, message_id);
1812
1813     return talloc_asprintf (ctx, NOTMUCH_METADATA_THREAD_ID_PREFIX "%s",
1814                             message_id);
1815 }
1816
1817 static notmuch_status_t
1818 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1819                                       void *ctx,
1820                                       const char *message_id,
1821                                       const char **thread_id_ret);
1822
1823 /* Find the thread ID to which the message with 'message_id' belongs.
1824  *
1825  * Note: 'thread_id_ret' must not be NULL!
1826  * On success '*thread_id_ret' is set to a newly talloced string belonging to
1827  * 'ctx'.
1828  *
1829  * Note: If there is no message in the database with the given
1830  * 'message_id' then a new thread_id will be allocated for this
1831  * message ID and stored in the database metadata so that the
1832  * thread ID can be looked up if the message is added to the database
1833  * later.
1834  */
1835 static notmuch_status_t
1836 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1837                                   void *ctx,
1838                                   const char *message_id,
1839                                   const char **thread_id_ret)
1840 {
1841     notmuch_private_status_t status;
1842     notmuch_message_t *message;
1843
1844     if (! (notmuch->features & NOTMUCH_FEATURE_GHOSTS))
1845         return _resolve_message_id_to_thread_id_old (notmuch, ctx, message_id,
1846                                                      thread_id_ret);
1847
1848     /* Look for this message (regular or ghost) */
1849     message = _notmuch_message_create_for_message_id (
1850         notmuch, message_id, &status);
1851     if (status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1852         /* Message exists */
1853         *thread_id_ret = talloc_steal (
1854             ctx, notmuch_message_get_thread_id (message));
1855     } else if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1856         /* Message did not exist.  Give it a fresh thread ID and
1857          * populate this message as a ghost message. */
1858         *thread_id_ret = talloc_strdup (
1859             ctx, _notmuch_database_generate_thread_id (notmuch));
1860         if (! *thread_id_ret) {
1861             status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
1862         } else {
1863             status = _notmuch_message_initialize_ghost (message, *thread_id_ret);
1864             if (status == 0)
1865                 /* Commit the new ghost message */
1866                 _notmuch_message_sync (message);
1867         }
1868     } else {
1869         /* Create failed. Fall through. */
1870     }
1871
1872     notmuch_message_destroy (message);
1873
1874     return COERCE_STATUS (status, "Error creating ghost message");
1875 }
1876
1877 /* Pre-ghost messages _resolve_message_id_to_thread_id */
1878 static notmuch_status_t
1879 _resolve_message_id_to_thread_id_old (notmuch_database_t *notmuch,
1880                                       void *ctx,
1881                                       const char *message_id,
1882                                       const char **thread_id_ret)
1883 {
1884     notmuch_status_t status;
1885     notmuch_message_t *message;
1886     string thread_id_string;
1887     char *metadata_key;
1888     Xapian::WritableDatabase *db;
1889
1890     status = notmuch_database_find_message (notmuch, message_id, &message);
1891
1892     if (status)
1893         return status;
1894
1895     if (message) {
1896         *thread_id_ret = talloc_steal (ctx,
1897                                        notmuch_message_get_thread_id (message));
1898
1899         notmuch_message_destroy (message);
1900
1901         return NOTMUCH_STATUS_SUCCESS;
1902     }
1903
1904     /* Message has not been seen yet.
1905      *
1906      * We may have seen a reference to it already, in which case, we
1907      * can return the thread ID stored in the metadata. Otherwise, we
1908      * generate a new thread ID and store it there.
1909      */
1910     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1911     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
1912     thread_id_string = notmuch->xapian_db->get_metadata (metadata_key);
1913
1914     if (thread_id_string.empty()) {
1915         *thread_id_ret = talloc_strdup (ctx,
1916                                         _notmuch_database_generate_thread_id (notmuch));
1917         db->set_metadata (metadata_key, *thread_id_ret);
1918     } else {
1919         *thread_id_ret = talloc_strdup (ctx, thread_id_string.c_str());
1920     }
1921
1922     talloc_free (metadata_key);
1923
1924     return NOTMUCH_STATUS_SUCCESS;
1925 }
1926
1927 static notmuch_status_t
1928 _merge_threads (notmuch_database_t *notmuch,
1929                 const char *winner_thread_id,
1930                 const char *loser_thread_id)
1931 {
1932     Xapian::PostingIterator loser, loser_end;
1933     notmuch_message_t *message = NULL;
1934     notmuch_private_status_t private_status;
1935     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1936
1937     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1938
1939     for ( ; loser != loser_end; loser++) {
1940         message = _notmuch_message_create (notmuch, notmuch,
1941                                            *loser, &private_status);
1942         if (message == NULL) {
1943             ret = COERCE_STATUS (private_status,
1944                                  "Cannot find document for doc_id from query");
1945             goto DONE;
1946         }
1947
1948         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1949         _notmuch_message_add_term (message, "thread", winner_thread_id);
1950         _notmuch_message_sync (message);
1951
1952         notmuch_message_destroy (message);
1953         message = NULL;
1954     }
1955
1956   DONE:
1957     if (message)
1958         notmuch_message_destroy (message);
1959
1960     return ret;
1961 }
1962
1963 static void
1964 _my_talloc_free_for_g_hash (void *ptr)
1965 {
1966     talloc_free (ptr);
1967 }
1968
1969 static notmuch_status_t
1970 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1971                                            notmuch_message_t *message,
1972                                            notmuch_message_file_t *message_file,
1973                                            const char **thread_id)
1974 {
1975     GHashTable *parents = NULL;
1976     const char *refs, *in_reply_to, *in_reply_to_message_id;
1977     const char *last_ref_message_id, *this_message_id;
1978     GList *l, *keys = NULL;
1979     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1980
1981     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1982                                      _my_talloc_free_for_g_hash, NULL);
1983     this_message_id = notmuch_message_get_message_id (message);
1984
1985     refs = _notmuch_message_file_get_header (message_file, "references");
1986     last_ref_message_id = parse_references (message,
1987                                             this_message_id,
1988                                             parents, refs);
1989
1990     in_reply_to = _notmuch_message_file_get_header (message_file, "in-reply-to");
1991     in_reply_to_message_id = parse_references (message,
1992                                                this_message_id,
1993                                                parents, in_reply_to);
1994
1995     /* For the parent of this message, use the last message ID of the
1996      * References header, if available.  If not, fall back to the
1997      * first message ID in the In-Reply-To header. */
1998     if (last_ref_message_id) {
1999         _notmuch_message_add_term (message, "replyto",
2000                                    last_ref_message_id);
2001     } else if (in_reply_to_message_id) {
2002         _notmuch_message_add_term (message, "replyto",
2003                              in_reply_to_message_id);
2004     }
2005
2006     keys = g_hash_table_get_keys (parents);
2007     for (l = keys; l; l = l->next) {
2008         char *parent_message_id;
2009         const char *parent_thread_id = NULL;
2010
2011         parent_message_id = (char *) l->data;
2012
2013         _notmuch_message_add_term (message, "reference",
2014                                    parent_message_id);
2015
2016         ret = _resolve_message_id_to_thread_id (notmuch,
2017                                                 message,
2018                                                 parent_message_id,
2019                                                 &parent_thread_id);
2020         if (ret)
2021             goto DONE;
2022
2023         if (*thread_id == NULL) {
2024             *thread_id = talloc_strdup (message, parent_thread_id);
2025             _notmuch_message_add_term (message, "thread", *thread_id);
2026         } else if (strcmp (*thread_id, parent_thread_id)) {
2027             ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
2028             if (ret)
2029                 goto DONE;
2030         }
2031     }
2032
2033   DONE:
2034     if (keys)
2035         g_list_free (keys);
2036     if (parents)
2037         g_hash_table_unref (parents);
2038
2039     return ret;
2040 }
2041
2042 static notmuch_status_t
2043 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
2044                                             notmuch_message_t *message,
2045                                             const char **thread_id)
2046 {
2047     const char *message_id = notmuch_message_get_message_id (message);
2048     Xapian::PostingIterator child, children_end;
2049     notmuch_message_t *child_message = NULL;
2050     const char *child_thread_id;
2051     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2052     notmuch_private_status_t private_status;
2053
2054     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
2055
2056     for ( ; child != children_end; child++) {
2057
2058         child_message = _notmuch_message_create (message, notmuch,
2059                                                  *child, &private_status);
2060         if (child_message == NULL) {
2061             ret = COERCE_STATUS (private_status,
2062                                  "Cannot find document for doc_id from query");
2063             goto DONE;
2064         }
2065
2066         child_thread_id = notmuch_message_get_thread_id (child_message);
2067         if (*thread_id == NULL) {
2068             *thread_id = talloc_strdup (message, child_thread_id);
2069             _notmuch_message_add_term (message, "thread", *thread_id);
2070         } else if (strcmp (*thread_id, child_thread_id)) {
2071             _notmuch_message_remove_term (child_message, "reference",
2072                                           message_id);
2073             _notmuch_message_sync (child_message);
2074             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
2075             if (ret)
2076                 goto DONE;
2077         }
2078
2079         notmuch_message_destroy (child_message);
2080         child_message = NULL;
2081     }
2082
2083   DONE:
2084     if (child_message)
2085         notmuch_message_destroy (child_message);
2086
2087     return ret;
2088 }
2089
2090 /* Fetch and clear the stored thread_id for message, or NULL if none. */
2091 static char *
2092 _consume_metadata_thread_id (void *ctx, notmuch_database_t *notmuch,
2093                              notmuch_message_t *message)
2094 {
2095     const char *message_id;
2096     string stored_id;
2097     char *metadata_key;
2098
2099     message_id = notmuch_message_get_message_id (message);
2100     metadata_key = _get_metadata_thread_id_key (ctx, message_id);
2101
2102     /* Check if we have already seen related messages to this one.
2103      * If we have then use the thread_id that we stored at that time.
2104      */
2105     stored_id = notmuch->xapian_db->get_metadata (metadata_key);
2106     if (stored_id.empty ()) {
2107         return NULL;
2108     } else {
2109         Xapian::WritableDatabase *db;
2110
2111         db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
2112
2113         /* Clear the metadata for this message ID. We don't need it
2114          * anymore. */
2115         db->set_metadata (metadata_key, "");
2116
2117         return talloc_strdup (ctx, stored_id.c_str ());
2118     }
2119 }
2120
2121 /* Given a blank or ghost 'message' and its corresponding
2122  * 'message_file' link it to existing threads in the database.
2123  *
2124  * First, if is_ghost, this retrieves the thread ID already stored in
2125  * the message (which will be the case if a message was previously
2126  * added that referenced this one).  If the message is blank
2127  * (!is_ghost), it doesn't have a thread ID yet (we'll generate one
2128  * later in this function).  If the database does not support ghost
2129  * messages, this checks for a thread ID stored in database metadata
2130  * for this message ID.
2131  *
2132  * Second, we look at 'message_file' and its link-relevant headers
2133  * (References and In-Reply-To) for message IDs.
2134  *
2135  * Finally, we look in the database for existing message that
2136  * reference 'message'.
2137  *
2138  * In all cases, we assign to the current message the first thread ID
2139  * found (through either parent or child). We will also merge any
2140  * existing, distinct threads where this message belongs to both,
2141  * (which is not uncommon when messages are processed out of order).
2142  *
2143  * Finally, if no thread ID has been found through parent or child, we
2144  * call _notmuch_message_generate_thread_id to generate a new thread
2145  * ID. This should only happen for new, top-level messages, (no
2146  * References or In-Reply-To header in this message, and no previously
2147  * added message refers to this message).
2148  */
2149 static notmuch_status_t
2150 _notmuch_database_link_message (notmuch_database_t *notmuch,
2151                                 notmuch_message_t *message,
2152                                 notmuch_message_file_t *message_file,
2153                                 notmuch_bool_t is_ghost)
2154 {
2155     void *local = talloc_new (NULL);
2156     notmuch_status_t status;
2157     const char *thread_id = NULL;
2158
2159     /* Check if the message already had a thread ID */
2160     if (notmuch->features & NOTMUCH_FEATURE_GHOSTS) {
2161         if (is_ghost)
2162             thread_id = notmuch_message_get_thread_id (message);
2163     } else {
2164         thread_id = _consume_metadata_thread_id (local, notmuch, message);
2165         if (thread_id)
2166             _notmuch_message_add_term (message, "thread", thread_id);
2167     }
2168
2169     status = _notmuch_database_link_message_to_parents (notmuch, message,
2170                                                         message_file,
2171                                                         &thread_id);
2172     if (status)
2173         goto DONE;
2174
2175     status = _notmuch_database_link_message_to_children (notmuch, message,
2176                                                          &thread_id);
2177     if (status)
2178         goto DONE;
2179
2180     /* If not part of any existing thread, generate a new thread ID. */
2181     if (thread_id == NULL) {
2182         thread_id = _notmuch_database_generate_thread_id (notmuch);
2183
2184         _notmuch_message_add_term (message, "thread", thread_id);
2185     }
2186
2187  DONE:
2188     talloc_free (local);
2189
2190     return status;
2191 }
2192
2193 notmuch_status_t
2194 notmuch_database_add_message (notmuch_database_t *notmuch,
2195                               const char *filename,
2196                               notmuch_message_t **message_ret)
2197 {
2198     notmuch_message_file_t *message_file;
2199     notmuch_message_t *message = NULL;
2200     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS, ret2;
2201     notmuch_private_status_t private_status;
2202     notmuch_bool_t is_ghost = false;
2203
2204     const char *date, *header;
2205     const char *from, *to, *subject;
2206     char *message_id = NULL;
2207
2208     if (message_ret)
2209         *message_ret = NULL;
2210
2211     ret = _notmuch_database_ensure_writable (notmuch);
2212     if (ret)
2213         return ret;
2214
2215     message_file = _notmuch_message_file_open (filename);
2216     if (message_file == NULL)
2217         return NOTMUCH_STATUS_FILE_ERROR;
2218
2219     /* Adding a message may change many documents.  Do this all
2220      * atomically. */
2221     ret = notmuch_database_begin_atomic (notmuch);
2222     if (ret)
2223         goto DONE;
2224
2225     /* Parse message up front to get better error status. */
2226     ret = _notmuch_message_file_parse (message_file);
2227     if (ret)
2228         goto DONE;
2229
2230     try {
2231         /* Before we do any real work, (especially before doing a
2232          * potential SHA-1 computation on the entire file's contents),
2233          * let's make sure that what we're looking at looks like an
2234          * actual email message.
2235          */
2236         from = _notmuch_message_file_get_header (message_file, "from");
2237         subject = _notmuch_message_file_get_header (message_file, "subject");
2238         to = _notmuch_message_file_get_header (message_file, "to");
2239
2240         if ((from == NULL || *from == '\0') &&
2241             (subject == NULL || *subject == '\0') &&
2242             (to == NULL || *to == '\0'))
2243         {
2244             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
2245             goto DONE;
2246         }
2247
2248         /* Now that we're sure it's mail, the first order of business
2249          * is to find a message ID (or else create one ourselves). */
2250
2251         header = _notmuch_message_file_get_header (message_file, "message-id");
2252         if (header && *header != '\0') {
2253             message_id = _parse_message_id (message_file, header, NULL);
2254
2255             /* So the header value isn't RFC-compliant, but it's
2256              * better than no message-id at all. */
2257             if (message_id == NULL)
2258                 message_id = talloc_strdup (message_file, header);
2259         }
2260
2261         if (message_id == NULL ) {
2262             /* No message-id at all, let's generate one by taking a
2263              * hash over the file's contents. */
2264             char *sha1 = _notmuch_sha1_of_file (filename);
2265
2266             /* If that failed too, something is really wrong. Give up. */
2267             if (sha1 == NULL) {
2268                 ret = NOTMUCH_STATUS_FILE_ERROR;
2269                 goto DONE;
2270             }
2271
2272             message_id = talloc_asprintf (message_file,
2273                                           "notmuch-sha1-%s", sha1);
2274             free (sha1);
2275         }
2276
2277         /* Now that we have a message ID, we get a message object,
2278          * (which may or may not reference an existing document in the
2279          * database). */
2280
2281         message = _notmuch_message_create_for_message_id (notmuch,
2282                                                           message_id,
2283                                                           &private_status);
2284
2285         talloc_free (message_id);
2286
2287         if (message == NULL) {
2288             ret = COERCE_STATUS (private_status,
2289                                  "Unexpected status value from _notmuch_message_create_for_message_id");
2290             goto DONE;
2291         }
2292
2293         _notmuch_message_add_filename (message, filename);
2294
2295         /* Is this a newly created message object or a ghost
2296          * message?  We have to be slightly careful: if this is a
2297          * blank message, it's not safe to call
2298          * notmuch_message_get_flag yet. */
2299         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND ||
2300             (is_ghost = notmuch_message_get_flag (
2301                 message, NOTMUCH_MESSAGE_FLAG_GHOST))) {
2302             _notmuch_message_add_term (message, "type", "mail");
2303             if (is_ghost)
2304                 /* Convert ghost message to a regular message */
2305                 _notmuch_message_remove_term (message, "type", "ghost");
2306
2307             ret = _notmuch_database_link_message (notmuch, message,
2308                                                   message_file, is_ghost);
2309             if (ret)
2310                 goto DONE;
2311
2312             date = _notmuch_message_file_get_header (message_file, "date");
2313             _notmuch_message_set_header_values (message, date, from, subject);
2314
2315             ret = _notmuch_message_index_file (message, message_file);
2316             if (ret)
2317                 goto DONE;
2318         } else {
2319             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
2320         }
2321
2322         _notmuch_message_sync (message);
2323     } catch (const Xapian::Error &error) {
2324         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
2325                  error.get_msg().c_str());
2326         notmuch->exception_reported = TRUE;
2327         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2328         goto DONE;
2329     }
2330
2331   DONE:
2332     if (message) {
2333         if ((ret == NOTMUCH_STATUS_SUCCESS ||
2334              ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) && message_ret)
2335             *message_ret = message;
2336         else
2337             notmuch_message_destroy (message);
2338     }
2339
2340     if (message_file)
2341         _notmuch_message_file_close (message_file);
2342
2343     ret2 = notmuch_database_end_atomic (notmuch);
2344     if ((ret == NOTMUCH_STATUS_SUCCESS ||
2345          ret == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) &&
2346         ret2 != NOTMUCH_STATUS_SUCCESS)
2347         ret = ret2;
2348
2349     return ret;
2350 }
2351
2352 notmuch_status_t
2353 notmuch_database_remove_message (notmuch_database_t *notmuch,
2354                                  const char *filename)
2355 {
2356     notmuch_status_t status;
2357     notmuch_message_t *message;
2358
2359     status = notmuch_database_find_message_by_filename (notmuch, filename,
2360                                                         &message);
2361
2362     if (status == NOTMUCH_STATUS_SUCCESS && message) {
2363             status = _notmuch_message_remove_filename (message, filename);
2364             if (status == NOTMUCH_STATUS_SUCCESS)
2365                 _notmuch_message_delete (message);
2366             else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
2367                 _notmuch_message_sync (message);
2368
2369             notmuch_message_destroy (message);
2370     }
2371
2372     return status;
2373 }
2374
2375 notmuch_status_t
2376 notmuch_database_find_message_by_filename (notmuch_database_t *notmuch,
2377                                            const char *filename,
2378                                            notmuch_message_t **message_ret)
2379 {
2380     void *local;
2381     const char *prefix = _find_prefix ("file-direntry");
2382     char *direntry, *term;
2383     Xapian::PostingIterator i, end;
2384     notmuch_status_t status;
2385
2386     if (message_ret == NULL)
2387         return NOTMUCH_STATUS_NULL_POINTER;
2388
2389     if (! (notmuch->features & NOTMUCH_FEATURE_FILE_TERMS))
2390         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
2391
2392     /* return NULL on any failure */
2393     *message_ret = NULL;
2394
2395     local = talloc_new (notmuch);
2396
2397     try {
2398         status = _notmuch_database_filename_to_direntry (
2399             local, notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
2400         if (status || !direntry)
2401             goto DONE;
2402
2403         term = talloc_asprintf (local, "%s%s", prefix, direntry);
2404
2405         find_doc_ids_for_term (notmuch, term, &i, &end);
2406
2407         if (i != end) {
2408             notmuch_private_status_t private_status;
2409
2410             *message_ret = _notmuch_message_create (notmuch, notmuch, *i,
2411                                                     &private_status);
2412             if (*message_ret == NULL)
2413                 status = NOTMUCH_STATUS_OUT_OF_MEMORY;
2414         }
2415     } catch (const Xapian::Error &error) {
2416         fprintf (stderr, "Error: A Xapian exception occurred finding message by filename: %s\n",
2417                  error.get_msg().c_str());
2418         notmuch->exception_reported = TRUE;
2419         status = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2420     }
2421
2422   DONE:
2423     talloc_free (local);
2424
2425     if (status && *message_ret) {
2426         notmuch_message_destroy (*message_ret);
2427         *message_ret = NULL;
2428     }
2429     return status;
2430 }
2431
2432 notmuch_string_list_t *
2433 _notmuch_database_get_terms_with_prefix (void *ctx, Xapian::TermIterator &i,
2434                                          Xapian::TermIterator &end,
2435                                          const char *prefix)
2436 {
2437     int prefix_len = strlen (prefix);
2438     notmuch_string_list_t *list;
2439
2440     list = _notmuch_string_list_create (ctx);
2441     if (unlikely (list == NULL))
2442         return NULL;
2443
2444     for (i.skip_to (prefix); i != end; i++) {
2445         /* Terminate loop at first term without desired prefix. */
2446         if (strncmp ((*i).c_str (), prefix, prefix_len))
2447             break;
2448
2449         _notmuch_string_list_append (list, (*i).c_str () + prefix_len);
2450     }
2451
2452     return list;
2453 }
2454
2455 notmuch_tags_t *
2456 notmuch_database_get_all_tags (notmuch_database_t *db)
2457 {
2458     Xapian::TermIterator i, end;
2459     notmuch_string_list_t *tags;
2460
2461     try {
2462         i = db->xapian_db->allterms_begin();
2463         end = db->xapian_db->allterms_end();
2464         tags = _notmuch_database_get_terms_with_prefix (db, i, end,
2465                                                         _find_prefix ("tag"));
2466         _notmuch_string_list_sort (tags);
2467         return _notmuch_tags_create (db, tags);
2468     } catch (const Xapian::Error &error) {
2469         fprintf (stderr, "A Xapian exception occurred getting tags: %s.\n",
2470                  error.get_msg().c_str());
2471         db->exception_reported = TRUE;
2472         return NULL;
2473     }
2474 }