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