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