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