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