]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
lib/message: catch exception in n_m_get_thread_id
[notmuch] / lib / message.cc
1 /* message.cc - Results of message-based searches from a notmuch database
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 https://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-private.h"
22 #include "database-private.h"
23 #include "message-private.h"
24
25 #include <stdint.h>
26
27 #include <gmime/gmime.h>
28
29 struct _notmuch_message {
30     notmuch_database_t *notmuch;
31     Xapian::docid doc_id;
32     int frozen;
33     char *message_id;
34     char *thread_id;
35     size_t thread_depth;
36     char *in_reply_to;
37     notmuch_string_list_t *tag_list;
38     notmuch_string_list_t *filename_term_list;
39     notmuch_string_list_t *filename_list;
40     char *maildir_flags;
41     char *author;
42     notmuch_message_file_t *message_file;
43     notmuch_string_list_t *property_term_list;
44     notmuch_string_map_t *property_map;
45     notmuch_string_list_t *reference_list;
46     notmuch_message_list_t *replies;
47     unsigned long flags;
48     /* For flags that are initialized on-demand, lazy_flags indicates
49      * if each flag has been initialized. */
50     unsigned long lazy_flags;
51
52     /* Message document modified since last sync */
53     bool modified;
54
55     /* last view of database the struct is synced with */
56     unsigned long last_view;
57
58     Xapian::Document doc;
59     Xapian::termcount termpos;
60 };
61
62 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
63
64 struct maildir_flag_tag {
65     char flag;
66     const char *tag;
67     bool inverse;
68 };
69
70 /* ASCII ordered table of Maildir flags and associated tags */
71 static struct maildir_flag_tag flag2tag[] = {
72     { 'D', "draft",   false },
73     { 'F', "flagged", false },
74     { 'P', "passed",  false },
75     { 'R', "replied", false },
76     { 'S', "unread",  true }
77 };
78
79 /* We end up having to call the destructor explicitly because we had
80  * to use "placement new" in order to initialize C++ objects within a
81  * block that we allocated with talloc. So C++ is making talloc
82  * slightly less simple to use, (we wouldn't need
83  * talloc_set_destructor at all otherwise).
84  */
85 static int
86 _notmuch_message_destructor (notmuch_message_t *message)
87 {
88     message->doc.~Document ();
89
90     return 0;
91 }
92
93 #define LOG_XAPIAN_EXCEPTION(message, error) _log_xapian_exception (__location__, message, error)
94
95 static void
96 _log_xapian_exception (const char *where, notmuch_message_t *message,  const Xapian::Error error) {
97     notmuch_database_t *notmuch = notmuch_message_get_database (message);
98     _notmuch_database_log (notmuch,
99                            "A Xapian exception occurred %s retrieving %s : %s\n",
100                            where,
101                            error.get_msg ().c_str ());
102     notmuch->exception_reported = true;
103 }
104
105 static notmuch_message_t *
106 _notmuch_message_create_for_document (const void *talloc_owner,
107                                       notmuch_database_t *notmuch,
108                                       unsigned int doc_id,
109                                       Xapian::Document doc,
110                                       notmuch_private_status_t *status)
111 {
112     notmuch_message_t *message;
113
114     if (status)
115         *status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
116
117     message = talloc (talloc_owner, notmuch_message_t);
118     if (unlikely (message == NULL)) {
119         if (status)
120             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
121         return NULL;
122     }
123
124     message->notmuch = notmuch;
125     message->doc_id = doc_id;
126
127     message->frozen = 0;
128     message->flags = 0;
129     message->lazy_flags = 0;
130
131     /* the message is initially not synchronized with Xapian */
132     message->last_view = 0;
133
134     /* Calculated after the thread structure is computed */
135     message->thread_depth = 0;
136
137     /* Each of these will be lazily created as needed. */
138     message->message_id = NULL;
139     message->thread_id = NULL;
140     message->in_reply_to = NULL;
141     message->tag_list = NULL;
142     message->filename_term_list = NULL;
143     message->filename_list = NULL;
144     message->maildir_flags = NULL;
145     message->message_file = NULL;
146     message->author = NULL;
147     message->property_term_list = NULL;
148     message->property_map = NULL;
149     message->reference_list = NULL;
150
151     message->replies = _notmuch_message_list_create (message);
152     if (unlikely (message->replies == NULL)) {
153         if (status)
154             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
155         return NULL;
156     }
157
158     /* This is C++'s creepy "placement new", which is really just an
159      * ugly way to call a constructor for a pre-allocated object. So
160      * it's really not an error to not be checking for OUT_OF_MEMORY
161      * here, since this "new" isn't actually allocating memory. This
162      * is language-design comedy of the wrong kind. */
163
164     new (&message->doc) Xapian::Document;
165
166     talloc_set_destructor (message, _notmuch_message_destructor);
167
168     message->doc = doc;
169     message->termpos = 0;
170
171     return message;
172 }
173
174 /* Create a new notmuch_message_t object for an existing document in
175  * the database.
176  *
177  * Here, 'talloc owner' is an optional talloc context to which the new
178  * message will belong. This allows for the caller to not bother
179  * calling notmuch_message_destroy on the message, and know that all
180  * memory will be reclaimed when 'talloc_owner' is freed. The caller
181  * still can call notmuch_message_destroy when finished with the
182  * message if desired.
183  *
184  * The 'talloc_owner' argument can also be NULL, in which case the
185  * caller *is* responsible for calling notmuch_message_destroy.
186  *
187  * If no document exists in the database with document ID of 'doc_id'
188  * then this function returns NULL and optionally sets *status to
189  * NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND.
190  *
191  * This function can also fail to due lack of available memory,
192  * returning NULL and optionally setting *status to
193  * NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY.
194  *
195  * The caller can pass NULL for status if uninterested in
196  * distinguishing these two cases.
197  */
198 notmuch_message_t *
199 _notmuch_message_create (const void *talloc_owner,
200                          notmuch_database_t *notmuch,
201                          unsigned int doc_id,
202                          notmuch_private_status_t *status)
203 {
204     Xapian::Document doc;
205
206     try {
207         doc = notmuch->xapian_db->get_document (doc_id);
208     } catch (const Xapian::DocNotFoundError &error) {
209         if (status)
210             *status = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
211         return NULL;
212     }
213
214     return _notmuch_message_create_for_document (talloc_owner, notmuch,
215                                                  doc_id, doc, status);
216 }
217
218 /* Create a new notmuch_message_t object for a specific message ID,
219  * (which may or may not already exist in the database).
220  *
221  * The 'notmuch' database will be the talloc owner of the returned
222  * message.
223  *
224  * This function returns a valid notmuch_message_t whether or not
225  * there is already a document in the database with the given message
226  * ID. These two cases can be distinguished by the value of *status:
227  *
228  *
229  *   NOTMUCH_PRIVATE_STATUS_SUCCESS:
230  *
231  *     There is already a document with message ID 'message_id' in the
232  *     database. The returned message can be used to query/modify the
233  *     document. The message may be a ghost message.
234  *
235  *   NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND:
236  *
237  *     No document with 'message_id' exists in the database. The
238  *     returned message contains a newly created document (not yet
239  *     added to the database) and a document ID that is known not to
240  *     exist in the database.  This message is "blank"; that is, it
241  *     contains only a message ID and no other metadata. The caller
242  *     can modify the message, and a call to _notmuch_message_sync
243  *     will add the document to the database.
244  *
245  * If an error occurs, this function will return NULL and *status
246  * will be set as appropriate. (The status pointer argument must
247  * not be NULL.)
248  */
249 notmuch_message_t *
250 _notmuch_message_create_for_message_id (notmuch_database_t *notmuch,
251                                         const char *message_id,
252                                         notmuch_private_status_t *status_ret)
253 {
254     notmuch_message_t *message;
255     Xapian::Document doc;
256     unsigned int doc_id;
257     char *term;
258
259     *status_ret = (notmuch_private_status_t) notmuch_database_find_message (notmuch,
260                                                                             message_id,
261                                                                             &message);
262     if (message)
263         return talloc_steal (notmuch, message);
264     else if (*status_ret)
265         return NULL;
266
267     /* If the message ID is too long, substitute its sha1 instead. */
268     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
269         message_id = _notmuch_message_id_compressed (message, message_id);
270
271     term = talloc_asprintf (NULL, "%s%s",
272                             _find_prefix ("id"), message_id);
273     if (term == NULL) {
274         *status_ret = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
275         return NULL;
276     }
277
278     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
279         INTERNAL_ERROR ("Failure to ensure database is writable.");
280
281     try {
282         doc.add_term (term, 0);
283         talloc_free (term);
284
285         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
286
287         doc_id = _notmuch_database_generate_doc_id (notmuch);
288     } catch (const Xapian::Error &error) {
289         _notmuch_database_log (notmuch_message_get_database (message), "A Xapian exception occurred creating message: %s\n",
290                                error.get_msg ().c_str ());
291         notmuch->exception_reported = true;
292         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
293         return NULL;
294     }
295
296     message = _notmuch_message_create_for_document (notmuch, notmuch,
297                                                     doc_id, doc, status_ret);
298
299     /* We want to inform the caller that we had to create a new
300      * document. */
301     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
302         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
303
304     return message;
305 }
306
307 static char *
308 _notmuch_message_get_term (notmuch_message_t *message,
309                            Xapian::TermIterator &i, Xapian::TermIterator &end,
310                            const char *prefix)
311 {
312     int prefix_len = strlen (prefix);
313     char *value;
314
315     i.skip_to (prefix);
316
317     if (i == end)
318         return NULL;
319
320     const std::string &term = *i;
321     if (strncmp (term.c_str (), prefix, prefix_len))
322         return NULL;
323
324     value = talloc_strdup (message, term.c_str () + prefix_len);
325
326 #if DEBUG_DATABASE_SANITY
327     i++;
328
329     if (i != end && strncmp ((*i).c_str (), prefix, prefix_len) == 0) {
330         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate %s terms: %s and %s\n",
331                         message->doc_id, prefix, value,
332                         (*i).c_str () + prefix_len);
333     }
334 #endif
335
336     return value;
337 }
338
339 /*
340  * For special applications where we only want the thread id, reading
341  * in all metadata is a heavy I/O penalty.
342  */
343 const char *
344 _notmuch_message_get_thread_id_only (notmuch_message_t *message)
345 {
346
347     Xapian::TermIterator i = message->doc.termlist_begin ();
348     Xapian::TermIterator end = message->doc.termlist_end ();
349
350     message->thread_id = _notmuch_message_get_term (message, i, end,
351                                                     _find_prefix ("thread"));
352     return message->thread_id;
353 }
354
355
356 static void
357 _notmuch_message_ensure_metadata (notmuch_message_t *message, void *field)
358 {
359     Xapian::TermIterator i, end;
360
361     if (field && (message->last_view >= message->notmuch->view))
362         return;
363
364     const char *thread_prefix = _find_prefix ("thread"),
365                *tag_prefix = _find_prefix ("tag"),
366                *id_prefix = _find_prefix ("id"),
367                *type_prefix = _find_prefix ("type"),
368                *filename_prefix = _find_prefix ("file-direntry"),
369                *property_prefix = _find_prefix ("property"),
370                *reference_prefix = _find_prefix ("reference"),
371                *replyto_prefix = _find_prefix ("replyto");
372
373     /* We do this all in a single pass because Xapian decompresses the
374      * term list every time you iterate over it.  Thus, while this is
375      * slightly more costly than looking up individual fields if only
376      * one field of the message object is actually used, it's a huge
377      * win as more fields are used. */
378     for (int count = 0; count < 3; count++) {
379         try {
380             i = message->doc.termlist_begin ();
381             end = message->doc.termlist_end ();
382
383             /* Get thread */
384             if (! message->thread_id)
385                 message->thread_id =
386                     _notmuch_message_get_term (message, i, end, thread_prefix);
387
388             /* Get tags */
389             assert (strcmp (thread_prefix, tag_prefix) < 0);
390             if (! message->tag_list) {
391                 message->tag_list =
392                     _notmuch_database_get_terms_with_prefix (message, i, end,
393                                                              tag_prefix);
394                 _notmuch_string_list_sort (message->tag_list);
395             }
396
397             /* Get id */
398             assert (strcmp (tag_prefix, id_prefix) < 0);
399             if (! message->message_id)
400                 message->message_id =
401                     _notmuch_message_get_term (message, i, end, id_prefix);
402
403             /* Get document type */
404             assert (strcmp (id_prefix, type_prefix) < 0);
405             if (! NOTMUCH_TEST_BIT (message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST)) {
406                 i.skip_to (type_prefix);
407                 /* "T" is the prefix "type" fields.  See
408                  * BOOLEAN_PREFIX_INTERNAL. */
409                 if (*i == "Tmail")
410                     NOTMUCH_CLEAR_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
411                 else if (*i == "Tghost")
412                     NOTMUCH_SET_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
413                 else
414                     INTERNAL_ERROR ("Message without type term");
415                 NOTMUCH_SET_BIT (&message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST);
416             }
417
418             /* Get filename list.  Here we get only the terms.  We lazily
419              * expand them to full file names when needed in
420              * _notmuch_message_ensure_filename_list. */
421             assert (strcmp (type_prefix, filename_prefix) < 0);
422             if (! message->filename_term_list && ! message->filename_list)
423                 message->filename_term_list =
424                     _notmuch_database_get_terms_with_prefix (message, i, end,
425                                                              filename_prefix);
426
427
428             /* Get property terms. Mimic the setup with filenames above */
429             assert (strcmp (filename_prefix, property_prefix) < 0);
430             if (! message->property_map && ! message->property_term_list)
431                 message->property_term_list =
432                     _notmuch_database_get_terms_with_prefix (message, i, end,
433                                                              property_prefix);
434
435             /* get references */
436             assert (strcmp (property_prefix, reference_prefix) < 0);
437             if (! message->reference_list) {
438                 message->reference_list =
439                     _notmuch_database_get_terms_with_prefix (message, i, end,
440                                                              reference_prefix);
441             }
442
443             /* Get reply to */
444             assert (strcmp (property_prefix, replyto_prefix) < 0);
445             if (! message->in_reply_to)
446                 message->in_reply_to =
447                     _notmuch_message_get_term (message, i, end, replyto_prefix);
448
449
450             /* It's perfectly valid for a message to have no In-Reply-To
451              * header. For these cases, we return an empty string. */
452             if (! message->in_reply_to)
453                 message->in_reply_to = talloc_strdup (message, "");
454
455             /* all the way without an exception */
456             break;
457         } catch (const Xapian::DatabaseModifiedError &error) {
458             notmuch_status_t status = _notmuch_database_reopen (message->notmuch);
459             if (status != NOTMUCH_STATUS_SUCCESS)
460                 INTERNAL_ERROR ("unhandled error from notmuch_database_reopen: %s\n",
461                                 notmuch_status_to_string (status));
462         }
463     }
464     message->last_view = message->notmuch->view;
465 }
466
467 void
468 _notmuch_message_invalidate_metadata (notmuch_message_t *message,
469                                       const char *prefix_name)
470 {
471     if (strcmp ("thread", prefix_name) == 0) {
472         talloc_free (message->thread_id);
473         message->thread_id = NULL;
474     }
475
476     if (strcmp ("tag", prefix_name) == 0) {
477         talloc_unlink (message, message->tag_list);
478         message->tag_list = NULL;
479     }
480
481     if (strcmp ("type", prefix_name) == 0) {
482         NOTMUCH_CLEAR_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
483         NOTMUCH_CLEAR_BIT (&message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST);
484     }
485
486     if (strcmp ("file-direntry", prefix_name) == 0) {
487         talloc_free (message->filename_term_list);
488         talloc_free (message->filename_list);
489         message->filename_term_list = message->filename_list = NULL;
490     }
491
492     if (strcmp ("property", prefix_name) == 0) {
493
494         if (message->property_term_list)
495             talloc_free (message->property_term_list);
496         message->property_term_list = NULL;
497
498         if (message->property_map)
499             talloc_unlink (message, message->property_map);
500
501         message->property_map = NULL;
502     }
503
504     if (strcmp ("replyto", prefix_name) == 0) {
505         talloc_free (message->in_reply_to);
506         message->in_reply_to = NULL;
507     }
508 }
509
510 unsigned int
511 _notmuch_message_get_doc_id (notmuch_message_t *message)
512 {
513     return message->doc_id;
514 }
515
516 const char *
517 notmuch_message_get_message_id (notmuch_message_t *message)
518 {
519     try {
520         _notmuch_message_ensure_metadata (message, message->message_id);
521     } catch (const Xapian::Error &error) {
522         LOG_XAPIAN_EXCEPTION (message, error);
523         return NULL;
524     }
525
526     if (! message->message_id)
527         INTERNAL_ERROR ("Message with document ID of %u has no message ID.\n",
528                         message->doc_id);
529     return message->message_id;
530 }
531
532 static void
533 _notmuch_message_ensure_message_file (notmuch_message_t *message)
534 {
535     const char *filename;
536
537     if (message->message_file)
538         return;
539
540     filename = notmuch_message_get_filename (message);
541     if (unlikely (filename == NULL))
542         return;
543
544     message->message_file = _notmuch_message_file_open_ctx (
545         notmuch_message_get_database (message), message, filename);
546 }
547
548 const char *
549 notmuch_message_get_header (notmuch_message_t *message, const char *header)
550 {
551     Xapian::valueno slot = Xapian::BAD_VALUENO;
552
553     /* Fetch header from the appropriate xapian value field if
554      * available */
555     if (strcasecmp (header, "from") == 0)
556         slot = NOTMUCH_VALUE_FROM;
557     else if (strcasecmp (header, "subject") == 0)
558         slot = NOTMUCH_VALUE_SUBJECT;
559     else if (strcasecmp (header, "message-id") == 0)
560         slot = NOTMUCH_VALUE_MESSAGE_ID;
561
562     if (slot != Xapian::BAD_VALUENO) {
563         try {
564             std::string value = message->doc.get_value (slot);
565
566             /* If we have NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES, then
567              * empty values indicate empty headers.  If we don't, then
568              * it could just mean we didn't record the header. */
569             if ((message->notmuch->features &
570                  NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES) ||
571                 ! value.empty ())
572                 return talloc_strdup (message, value.c_str ());
573
574         } catch (Xapian::Error &error) {
575             _notmuch_database_log (notmuch_message_get_database (message), "A Xapian exception occurred when reading header: %s\n",
576                                    error.get_msg ().c_str ());
577             message->notmuch->exception_reported = true;
578             return NULL;
579         }
580     }
581
582     /* Otherwise fall back to parsing the file */
583     _notmuch_message_ensure_message_file (message);
584     if (message->message_file == NULL)
585         return NULL;
586
587     return _notmuch_message_file_get_header (message->message_file, header);
588 }
589
590 /* Return the message ID from the In-Reply-To header of 'message'.
591  *
592  * Returns an empty string ("") if 'message' has no In-Reply-To
593  * header.
594  *
595  * Returns NULL if any error occurs.
596  */
597 const char *
598 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
599 {
600     _notmuch_message_ensure_metadata (message, message->in_reply_to);
601     return message->in_reply_to;
602 }
603
604 const char *
605 notmuch_message_get_thread_id (notmuch_message_t *message)
606 {
607     try {
608         _notmuch_message_ensure_metadata (message, message->thread_id);
609     } catch (Xapian::Error &error) {
610         LOG_XAPIAN_EXCEPTION (message, error);
611         return NULL;
612     }
613     if (! message->thread_id)
614         INTERNAL_ERROR ("Message with document ID of %u has no thread ID.\n",
615                         message->doc_id);
616     return message->thread_id;
617 }
618
619 void
620 _notmuch_message_add_reply (notmuch_message_t *message,
621                             notmuch_message_t *reply)
622 {
623     _notmuch_message_list_add_message (message->replies, reply);
624 }
625
626 size_t
627 _notmuch_message_get_thread_depth (notmuch_message_t *message)
628 {
629     return message->thread_depth;
630 }
631
632 void
633 _notmuch_message_label_depths (notmuch_message_t *message,
634                                size_t depth)
635 {
636     message->thread_depth = depth;
637
638     for (notmuch_messages_t *messages = _notmuch_messages_create (message->replies);
639          notmuch_messages_valid (messages);
640          notmuch_messages_move_to_next (messages)) {
641         notmuch_message_t *child = notmuch_messages_get (messages);
642         _notmuch_message_label_depths (child, depth + 1);
643     }
644 }
645
646 const notmuch_string_list_t *
647 _notmuch_message_get_references (notmuch_message_t *message)
648 {
649     _notmuch_message_ensure_metadata (message, message->reference_list);
650     return message->reference_list;
651 }
652
653 static int
654 _cmpmsg (const void *pa, const void *pb)
655 {
656     notmuch_message_t **a = (notmuch_message_t **) pa;
657     notmuch_message_t **b = (notmuch_message_t **) pb;
658     time_t time_a = notmuch_message_get_date (*a);
659     time_t time_b = notmuch_message_get_date (*b);
660
661     if (time_a == time_b)
662         return 0;
663     else if (time_a < time_b)
664         return -1;
665     else
666         return 1;
667 }
668
669 notmuch_message_list_t *
670 _notmuch_message_sort_subtrees (void *ctx, notmuch_message_list_t *list)
671 {
672
673     size_t count = 0;
674     size_t capacity = 16;
675
676     if (! list)
677         return list;
678
679     void *local = talloc_new (NULL);
680     notmuch_message_list_t *new_list = _notmuch_message_list_create (ctx);
681     notmuch_message_t **message_array = talloc_zero_array (local, notmuch_message_t *, capacity);
682
683     for (notmuch_messages_t *messages = _notmuch_messages_create (list);
684          notmuch_messages_valid (messages);
685          notmuch_messages_move_to_next (messages)) {
686         notmuch_message_t *root = notmuch_messages_get (messages);
687         if (count >= capacity) {
688             capacity *= 2;
689             message_array = talloc_realloc (local, message_array, notmuch_message_t *, capacity);
690         }
691         message_array[count++] = root;
692         root->replies = _notmuch_message_sort_subtrees (root, root->replies);
693     }
694
695     qsort (message_array, count, sizeof (notmuch_message_t *), _cmpmsg);
696     for (size_t i = 0; i < count; i++) {
697         _notmuch_message_list_add_message (new_list, message_array[i]);
698     }
699
700     talloc_free (local);
701     talloc_free (list);
702     return new_list;
703 }
704
705 notmuch_messages_t *
706 notmuch_message_get_replies (notmuch_message_t *message)
707 {
708     return _notmuch_messages_create (message->replies);
709 }
710
711 void
712 _notmuch_message_remove_terms (notmuch_message_t *message, const char *prefix)
713 {
714     Xapian::TermIterator i;
715     size_t prefix_len = 0;
716
717     prefix_len = strlen (prefix);
718
719     while (1) {
720         i = message->doc.termlist_begin ();
721         i.skip_to (prefix);
722
723         /* Terminate loop when no terms remain with desired prefix. */
724         if (i == message->doc.termlist_end () ||
725             strncmp ((*i).c_str (), prefix, prefix_len))
726             break;
727
728         try {
729             message->doc.remove_term ((*i));
730             message->modified = true;
731         } catch (const Xapian::InvalidArgumentError) {
732             /* Ignore failure to remove non-existent term. */
733         }
734     }
735 }
736
737
738 /* Remove all terms generated by indexing, i.e. not tags or
739  * properties, along with any automatic tags*/
740 /* According to Xapian API docs, none of these calls throw
741  * exceptions */
742 notmuch_private_status_t
743 _notmuch_message_remove_indexed_terms (notmuch_message_t *message)
744 {
745     Xapian::TermIterator i;
746
747     const std::string
748         id_prefix = _find_prefix ("id"),
749         property_prefix = _find_prefix ("property"),
750         tag_prefix = _find_prefix ("tag"),
751         type_prefix = _find_prefix ("type");
752
753     /* Make sure we have the data to restore to Xapian*/
754     _notmuch_message_ensure_metadata (message, NULL);
755
756     /* Empirically, it turns out to be faster to remove all the terms,
757      * and add back the ones we want. */
758     message->doc.clear_terms ();
759     message->modified = true;
760
761     /* still a mail message */
762     message->doc.add_term (type_prefix + "mail");
763
764     /* Put back message-id */
765     message->doc.add_term (id_prefix + message->message_id);
766
767     /* Put back non-automatic tags */
768     for (notmuch_tags_t *tags = notmuch_message_get_tags (message);
769          notmuch_tags_valid (tags);
770          notmuch_tags_move_to_next (tags)) {
771
772         const char *tag = notmuch_tags_get (tags);
773
774         if (strcmp (tag, "encrypted") != 0 &&
775             strcmp (tag, "signed") != 0 &&
776             strcmp (tag, "attachment") != 0) {
777             std::string term = tag_prefix + tag;
778             message->doc.add_term (term);
779         }
780     }
781
782     /* Put back properties */
783     notmuch_message_properties_t *list;
784
785     for (list = notmuch_message_get_properties (message, "", false);
786          notmuch_message_properties_valid (list); notmuch_message_properties_move_to_next (list)) {
787         std::string term = property_prefix +
788                            notmuch_message_properties_key (list) + "=" +
789                            notmuch_message_properties_value (list);
790
791         message->doc.add_term (term);
792     }
793
794     notmuch_message_properties_destroy (list);
795
796     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
797 }
798
799
800 /* Return true if p points at "new" or "cur". */
801 static bool
802 is_maildir (const char *p)
803 {
804     return strcmp (p, "cur") == 0 || strcmp (p, "new") == 0;
805 }
806
807 /* Add "folder:" term for directory. */
808 static notmuch_status_t
809 _notmuch_message_add_folder_terms (notmuch_message_t *message,
810                                    const char *directory)
811 {
812     char *folder, *last;
813
814     folder = talloc_strdup (NULL, directory);
815     if (! folder)
816         return NOTMUCH_STATUS_OUT_OF_MEMORY;
817
818     /*
819      * If the message file is in a leaf directory named "new" or
820      * "cur", presume maildir and index the parent directory. Thus a
821      * "folder:" prefix search matches messages in the specified
822      * maildir folder, i.e. in the specified directory and its "new"
823      * and "cur" subdirectories.
824      *
825      * Note that this means the "folder:" prefix can't be used for
826      * distinguishing between message files in "new" or "cur". The
827      * "path:" prefix needs to be used for that.
828      *
829      * Note the deliberate difference to _filename_is_in_maildir(). We
830      * don't want to index different things depending on the existence
831      * or non-existence of all maildir sibling directories "new",
832      * "cur", and "tmp". Doing so would be surprising, and difficult
833      * for the user to fix in case all subdirectories were not in
834      * place during indexing.
835      */
836     last = strrchr (folder, '/');
837     if (last) {
838         if (is_maildir (last + 1))
839             *last = '\0';
840     } else if (is_maildir (folder)) {
841         *folder = '\0';
842     }
843
844     _notmuch_message_add_term (message, "folder", folder);
845
846     talloc_free (folder);
847
848     message->modified = true;
849     return NOTMUCH_STATUS_SUCCESS;
850 }
851
852 #define RECURSIVE_SUFFIX "/**"
853
854 /* Add "path:" terms for directory. */
855 static notmuch_status_t
856 _notmuch_message_add_path_terms (notmuch_message_t *message,
857                                  const char *directory)
858 {
859     /* Add exact "path:" term. */
860     _notmuch_message_add_term (message, "path", directory);
861
862     if (strlen (directory)) {
863         char *path, *p;
864
865         path = talloc_asprintf (NULL, "%s%s", directory, RECURSIVE_SUFFIX);
866         if (! path)
867             return NOTMUCH_STATUS_OUT_OF_MEMORY;
868
869         /* Add recursive "path:" terms for directory and all parents. */
870         for (p = path + strlen (path) - 1; p > path; p--) {
871             if (*p == '/') {
872                 strcpy (p, RECURSIVE_SUFFIX);
873                 _notmuch_message_add_term (message, "path", path);
874             }
875         }
876
877         talloc_free (path);
878     }
879
880     /* Recursive all-matching path:** for consistency. */
881     _notmuch_message_add_term (message, "path", "**");
882
883     return NOTMUCH_STATUS_SUCCESS;
884 }
885
886 /* Add directory based terms for all filenames of the message. */
887 static notmuch_status_t
888 _notmuch_message_add_directory_terms (void *ctx, notmuch_message_t *message)
889 {
890     const char *direntry_prefix = _find_prefix ("file-direntry");
891     int direntry_prefix_len = strlen (direntry_prefix);
892     Xapian::TermIterator i = message->doc.termlist_begin ();
893     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
894
895     for (i.skip_to (direntry_prefix); i != message->doc.termlist_end (); i++) {
896         unsigned int directory_id;
897         const char *direntry, *directory;
898         char *colon;
899         const std::string &term = *i;
900
901         /* Terminate loop at first term without desired prefix. */
902         if (strncmp (term.c_str (), direntry_prefix, direntry_prefix_len))
903             break;
904
905         /* Indicate that there are filenames remaining. */
906         status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
907
908         direntry = term.c_str ();
909         direntry += direntry_prefix_len;
910
911         directory_id = strtol (direntry, &colon, 10);
912
913         if (colon == NULL || *colon != ':')
914             INTERNAL_ERROR ("malformed direntry");
915
916         directory = _notmuch_database_get_directory_path (ctx,
917                                                           message->notmuch,
918                                                           directory_id);
919
920         _notmuch_message_add_folder_terms (message, directory);
921         _notmuch_message_add_path_terms (message, directory);
922     }
923
924     return status;
925 }
926
927 /* Add an additional 'filename' for 'message'.
928  *
929  * This change will not be reflected in the database until the next
930  * call to _notmuch_message_sync. */
931 notmuch_status_t
932 _notmuch_message_add_filename (notmuch_message_t *message,
933                                const char *filename)
934 {
935     const char *relative, *directory;
936     notmuch_status_t status;
937     void *local = talloc_new (message);
938     char *direntry;
939
940     if (filename == NULL)
941         INTERNAL_ERROR ("Message filename cannot be NULL.");
942
943     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
944         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
945         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
946
947     relative = _notmuch_database_relative_path (message->notmuch, filename);
948
949     status = _notmuch_database_split_path (local, relative, &directory, NULL);
950     if (status)
951         return status;
952
953     status = _notmuch_database_filename_to_direntry (
954         local, message->notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
955     if (status)
956         return status;
957
958     /* New file-direntry allows navigating to this message with
959      * notmuch_directory_get_child_files() . */
960     _notmuch_message_add_term (message, "file-direntry", direntry);
961
962     _notmuch_message_add_folder_terms (message, directory);
963     _notmuch_message_add_path_terms (message, directory);
964
965     talloc_free (local);
966
967     return NOTMUCH_STATUS_SUCCESS;
968 }
969
970 /* Remove a particular 'filename' from 'message'.
971  *
972  * This change will not be reflected in the database until the next
973  * call to _notmuch_message_sync.
974  *
975  * If this message still has other filenames, returns
976  * NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID.
977  *
978  * Note: This function does not remove a document from the database,
979  * even if the specified filename is the only filename for this
980  * message. For that functionality, see
981  * notmuch_database_remove_message. */
982 notmuch_status_t
983 _notmuch_message_remove_filename (notmuch_message_t *message,
984                                   const char *filename)
985 {
986     void *local = talloc_new (message);
987     char *direntry;
988     notmuch_private_status_t private_status;
989     notmuch_status_t status;
990
991     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
992         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
993         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
994
995     status = _notmuch_database_filename_to_direntry (
996         local, message->notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
997     if (status || ! direntry)
998         return status;
999
1000     /* Unlink this file from its parent directory. */
1001     private_status = _notmuch_message_remove_term (message,
1002                                                    "file-direntry", direntry);
1003     status = COERCE_STATUS (private_status,
1004                             "Unexpected error from _notmuch_message_remove_term");
1005     if (status)
1006         return status;
1007
1008     /* Re-synchronize "folder:" and "path:" terms for this message. */
1009
1010     /* Remove all "folder:" terms. */
1011     _notmuch_message_remove_terms (message, _find_prefix ("folder"));
1012
1013     /* Remove all "path:" terms. */
1014     _notmuch_message_remove_terms (message, _find_prefix ("path"));
1015
1016     /* Add back terms for all remaining filenames of the message. */
1017     status = _notmuch_message_add_directory_terms (local, message);
1018
1019     talloc_free (local);
1020
1021     return status;
1022 }
1023
1024 /* Upgrade the "folder:" prefix from V1 to V2. */
1025 #define FOLDER_PREFIX_V1       "XFOLDER"
1026 #define ZFOLDER_PREFIX_V1      "Z" FOLDER_PREFIX_V1
1027 void
1028 _notmuch_message_upgrade_folder (notmuch_message_t *message)
1029 {
1030     /* Remove all old "folder:" terms. */
1031     _notmuch_message_remove_terms (message, FOLDER_PREFIX_V1);
1032
1033     /* Remove all old "folder:" stemmed terms. */
1034     _notmuch_message_remove_terms (message, ZFOLDER_PREFIX_V1);
1035
1036     /* Add new boolean "folder:" and "path:" terms. */
1037     _notmuch_message_add_directory_terms (message, message);
1038 }
1039
1040 char *
1041 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
1042 {
1043     return talloc_strdup (message, message->doc.get_data ().c_str ());
1044 }
1045
1046 void
1047 _notmuch_message_clear_data (notmuch_message_t *message)
1048 {
1049     message->doc.set_data ("");
1050     message->modified = true;
1051 }
1052
1053 static void
1054 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
1055 {
1056     notmuch_string_node_t *node;
1057
1058     if (message->filename_list)
1059         return;
1060
1061     _notmuch_message_ensure_metadata (message, message->filename_term_list);
1062
1063     message->filename_list = _notmuch_string_list_create (message);
1064     node = message->filename_term_list->head;
1065
1066     if (! node) {
1067         /* A message document created by an old version of notmuch
1068          * (prior to rename support) will have the filename in the
1069          * data of the document rather than as a file-direntry term.
1070          *
1071          * It would be nice to do the upgrade of the document directly
1072          * here, but the database is likely open in read-only mode. */
1073
1074         std::string datastr = message->doc.get_data ();
1075         const char *data = datastr.c_str ();
1076
1077         if (data == NULL)
1078             INTERNAL_ERROR ("message with no filename");
1079
1080         _notmuch_string_list_append (message->filename_list, data);
1081
1082         return;
1083     }
1084
1085     for (; node; node = node->next) {
1086         void *local = talloc_new (message);
1087         const char *db_path, *directory, *basename, *filename;
1088         char *colon, *direntry = NULL;
1089         unsigned int directory_id;
1090
1091         direntry = node->string;
1092
1093         directory_id = strtol (direntry, &colon, 10);
1094
1095         if (colon == NULL || *colon != ':')
1096             INTERNAL_ERROR ("malformed direntry");
1097
1098         basename = colon + 1;
1099
1100         *colon = '\0';
1101
1102         db_path = notmuch_database_get_path (message->notmuch);
1103
1104         directory = _notmuch_database_get_directory_path (local,
1105                                                           message->notmuch,
1106                                                           directory_id);
1107
1108         if (strlen (directory))
1109             filename = talloc_asprintf (message, "%s/%s/%s",
1110                                         db_path, directory, basename);
1111         else
1112             filename = talloc_asprintf (message, "%s/%s",
1113                                         db_path, basename);
1114
1115         _notmuch_string_list_append (message->filename_list, filename);
1116
1117         talloc_free (local);
1118     }
1119
1120     talloc_free (message->filename_term_list);
1121     message->filename_term_list = NULL;
1122 }
1123
1124 const char *
1125 notmuch_message_get_filename (notmuch_message_t *message)
1126 {
1127     _notmuch_message_ensure_filename_list (message);
1128
1129     if (message->filename_list == NULL)
1130         return NULL;
1131
1132     if (message->filename_list->head == NULL ||
1133         message->filename_list->head->string == NULL) {
1134         INTERNAL_ERROR ("message with no filename");
1135     }
1136
1137     return message->filename_list->head->string;
1138 }
1139
1140 notmuch_filenames_t *
1141 notmuch_message_get_filenames (notmuch_message_t *message)
1142 {
1143     _notmuch_message_ensure_filename_list (message);
1144
1145     return _notmuch_filenames_create (message, message->filename_list);
1146 }
1147
1148 int
1149 notmuch_message_count_files (notmuch_message_t *message)
1150 {
1151     _notmuch_message_ensure_filename_list (message);
1152
1153     return _notmuch_string_list_length (message->filename_list);
1154 }
1155
1156 notmuch_bool_t
1157 notmuch_message_get_flag (notmuch_message_t *message,
1158                           notmuch_message_flag_t flag)
1159 {
1160     if (flag == NOTMUCH_MESSAGE_FLAG_GHOST &&
1161         ! NOTMUCH_TEST_BIT (message->lazy_flags, flag))
1162         _notmuch_message_ensure_metadata (message, NULL);
1163
1164     return NOTMUCH_TEST_BIT (message->flags, flag);
1165 }
1166
1167 void
1168 notmuch_message_set_flag (notmuch_message_t *message,
1169                           notmuch_message_flag_t flag, notmuch_bool_t enable)
1170 {
1171     if (enable)
1172         NOTMUCH_SET_BIT (&message->flags, flag);
1173     else
1174         NOTMUCH_CLEAR_BIT (&message->flags, flag);
1175     NOTMUCH_SET_BIT (&message->lazy_flags, flag);
1176 }
1177
1178 time_t
1179 notmuch_message_get_date (notmuch_message_t *message)
1180 {
1181     std::string value;
1182
1183     try {
1184         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
1185     } catch (Xapian::Error &error) {
1186         _notmuch_database_log (notmuch_message_get_database (message), "A Xapian exception occurred when reading date: %s\n",
1187                                error.get_msg ().c_str ());
1188         message->notmuch->exception_reported = true;
1189         return 0;
1190     }
1191
1192     if (value.empty ())
1193         /* sortable_unserialise is undefined on empty string */
1194         return 0;
1195     return Xapian::sortable_unserialise (value);
1196 }
1197
1198 notmuch_tags_t *
1199 notmuch_message_get_tags (notmuch_message_t *message)
1200 {
1201     notmuch_tags_t *tags;
1202
1203     _notmuch_message_ensure_metadata (message, message->tag_list);
1204
1205     tags = _notmuch_tags_create (message, message->tag_list);
1206     /* _notmuch_tags_create steals the reference to the tag_list, but
1207      * in this case it's still used by the message, so we add an
1208      * *additional* talloc reference to the list.  As a result, it's
1209      * possible to modify the message tags (which talloc_unlink's the
1210      * current list from the message) while still iterating because
1211      * the iterator will keep the current list alive. */
1212     if (! talloc_reference (message, message->tag_list))
1213         return NULL;
1214
1215     return tags;
1216 }
1217
1218 const char *
1219 _notmuch_message_get_author (notmuch_message_t *message)
1220 {
1221     return message->author;
1222 }
1223
1224 void
1225 _notmuch_message_set_author (notmuch_message_t *message,
1226                              const char *author)
1227 {
1228     if (message->author)
1229         talloc_free (message->author);
1230     message->author = talloc_strdup (message, author);
1231     return;
1232 }
1233
1234 void
1235 _notmuch_message_set_header_values (notmuch_message_t *message,
1236                                     const char *date,
1237                                     const char *from,
1238                                     const char *subject)
1239 {
1240     time_t time_value;
1241
1242     /* GMime really doesn't want to see a NULL date, so protect its
1243      * sensibilities. */
1244     if (date == NULL || *date == '\0') {
1245         time_value = 0;
1246     } else {
1247         time_value = g_mime_utils_header_decode_date_unix (date);
1248         /*
1249          * Workaround for https://bugzilla.gnome.org/show_bug.cgi?id=779923
1250          */
1251         if (time_value < 0)
1252             time_value = 0;
1253     }
1254
1255     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
1256                             Xapian::sortable_serialise (time_value));
1257     message->doc.add_value (NOTMUCH_VALUE_FROM, from);
1258     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
1259     message->modified = true;
1260 }
1261
1262 void
1263 _notmuch_message_update_subject (notmuch_message_t *message,
1264                                  const char *subject)
1265 {
1266     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
1267     message->modified = true;
1268 }
1269
1270 /* Upgrade a message to support NOTMUCH_FEATURE_LAST_MOD.  The caller
1271  * must call _notmuch_message_sync. */
1272 void
1273 _notmuch_message_upgrade_last_mod (notmuch_message_t *message)
1274 {
1275     /* _notmuch_message_sync will update the last modification
1276      * revision; we just have to ask it to. */
1277     message->modified = true;
1278 }
1279
1280 /* Synchronize changes made to message->doc out into the database. */
1281 void
1282 _notmuch_message_sync (notmuch_message_t *message)
1283 {
1284     Xapian::WritableDatabase *db;
1285
1286     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
1287         return;
1288
1289     if (! message->modified)
1290         return;
1291
1292     /* Update the last modification of this message. */
1293     if (message->notmuch->features & NOTMUCH_FEATURE_LAST_MOD)
1294         /* sortable_serialise gives a reasonably compact encoding,
1295          * which directly translates to reduced IO when scanning the
1296          * value stream.  Since it's built for doubles, we only get 53
1297          * effective bits, but that's still enough for the database to
1298          * last a few centuries at 1 million revisions per second. */
1299         message->doc.add_value (NOTMUCH_VALUE_LAST_MOD,
1300                                 Xapian::sortable_serialise (
1301                                     _notmuch_database_new_revision (
1302                                         message->notmuch)));
1303
1304     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
1305     db->replace_document (message->doc_id, message->doc);
1306     message->modified = false;
1307 }
1308
1309 /* Delete a message document from the database, leaving a ghost
1310  * message in its place */
1311 notmuch_status_t
1312 _notmuch_message_delete (notmuch_message_t *message)
1313 {
1314     notmuch_status_t status;
1315     Xapian::WritableDatabase *db;
1316     const char *mid, *tid, *query_string;
1317     notmuch_message_t *ghost;
1318     notmuch_private_status_t private_status;
1319     notmuch_database_t *notmuch;
1320     notmuch_query_t *query;
1321     unsigned int count = 0;
1322     bool is_ghost;
1323
1324     mid = notmuch_message_get_message_id (message);
1325     tid = notmuch_message_get_thread_id (message);
1326     notmuch = message->notmuch;
1327
1328     status = _notmuch_database_ensure_writable (message->notmuch);
1329     if (status)
1330         return status;
1331
1332     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1333     db->delete_document (message->doc_id);
1334
1335     /* if this was a ghost to begin with, we are done */
1336     private_status = _notmuch_message_has_term (message, "type", "ghost", &is_ghost);
1337     if (private_status)
1338         return COERCE_STATUS (private_status,
1339                               "Error trying to determine whether message was a ghost");
1340     if (is_ghost)
1341         return NOTMUCH_STATUS_SUCCESS;
1342
1343     query_string = talloc_asprintf (message, "thread:%s", tid);
1344     query = notmuch_query_create (notmuch, query_string);
1345     if (query == NULL)
1346         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1347     status = notmuch_query_count_messages (query, &count);
1348     if (status) {
1349         notmuch_query_destroy (query);
1350         return status;
1351     }
1352
1353     if (count > 0) {
1354         /* reintroduce a ghost in its place because there are still
1355          * other active messages in this thread: */
1356         ghost = _notmuch_message_create_for_message_id (notmuch, mid, &private_status);
1357         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1358             private_status = _notmuch_message_initialize_ghost (ghost, tid);
1359             if (! private_status)
1360                 _notmuch_message_sync (ghost);
1361         } else if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1362             /* this is deeply weird, and we should not have gotten
1363              * into this state.  is there a better error message to
1364              * return here? */
1365             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1366         }
1367
1368         notmuch_message_destroy (ghost);
1369         status = COERCE_STATUS (private_status, "Error converting to ghost message");
1370     } else {
1371         /* the thread is empty; drop all ghost messages from it */
1372         notmuch_messages_t *messages;
1373         status = _notmuch_query_search_documents (query,
1374                                                   "ghost",
1375                                                   &messages);
1376         if (status == NOTMUCH_STATUS_SUCCESS) {
1377             notmuch_status_t last_error = NOTMUCH_STATUS_SUCCESS;
1378             while (notmuch_messages_valid (messages)) {
1379                 message = notmuch_messages_get (messages);
1380                 status = _notmuch_message_delete (message);
1381                 if (status) /* we'll report the last failure we see;
1382                                          * if there is more than one failure, we
1383                                          * forget about previous ones */
1384                     last_error = status;
1385                 notmuch_message_destroy (message);
1386                 notmuch_messages_move_to_next (messages);
1387             }
1388             status = last_error;
1389         }
1390     }
1391     notmuch_query_destroy (query);
1392     return status;
1393 }
1394
1395 /* Transform a blank message into a ghost message.  The caller must
1396  * _notmuch_message_sync the message. */
1397 notmuch_private_status_t
1398 _notmuch_message_initialize_ghost (notmuch_message_t *message,
1399                                    const char *thread_id)
1400 {
1401     notmuch_private_status_t status;
1402
1403     status = _notmuch_message_add_term (message, "type", "ghost");
1404     if (status)
1405         return status;
1406     status = _notmuch_message_add_term (message, "thread", thread_id);
1407     if (status)
1408         return status;
1409
1410     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1411 }
1412
1413 /* Ensure that 'message' is not holding any file object open. Future
1414  * calls to various functions will still automatically open the
1415  * message file as needed.
1416  */
1417 void
1418 _notmuch_message_close (notmuch_message_t *message)
1419 {
1420     if (message->message_file) {
1421         _notmuch_message_file_close (message->message_file);
1422         message->message_file = NULL;
1423     }
1424 }
1425
1426 /* Add a name:value term to 'message', (the actual term will be
1427  * encoded by prefixing the value with a short prefix). See
1428  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1429  * names to prefix values.
1430  *
1431  * This change will not be reflected in the database until the next
1432  * call to _notmuch_message_sync. */
1433 notmuch_private_status_t
1434 _notmuch_message_add_term (notmuch_message_t *message,
1435                            const char *prefix_name,
1436                            const char *value)
1437 {
1438
1439     char *term;
1440
1441     if (value == NULL)
1442         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1443
1444     term = talloc_asprintf (message, "%s%s",
1445                             _find_prefix (prefix_name), value);
1446
1447     if (strlen (term) > NOTMUCH_TERM_MAX)
1448         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1449
1450     message->doc.add_term (term, 0);
1451     message->modified = true;
1452
1453     talloc_free (term);
1454
1455     _notmuch_message_invalidate_metadata (message, prefix_name);
1456
1457     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1458 }
1459
1460 /* Parse 'text' and add a term to 'message' for each parsed word. Each
1461  * term will be added with the appropriate prefix if prefix_name is
1462  * non-NULL.
1463  */
1464 notmuch_private_status_t
1465 _notmuch_message_gen_terms (notmuch_message_t *message,
1466                             const char *prefix_name,
1467                             const char *text)
1468 {
1469     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
1470
1471     if (text == NULL)
1472         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1473
1474     term_gen->set_document (message->doc);
1475     term_gen->set_termpos (message->termpos);
1476
1477     if (prefix_name) {
1478         const char *prefix = _notmuch_database_prefix (message->notmuch, prefix_name);
1479         if (prefix == NULL)
1480             return NOTMUCH_PRIVATE_STATUS_BAD_PREFIX;
1481
1482         _notmuch_message_invalidate_metadata (message, prefix_name);
1483         term_gen->index_text (text, 1, prefix);
1484     } else {
1485         term_gen->index_text (text);
1486     }
1487
1488     /* Create a gap between this an the next terms so they don't
1489      * appear to be a phrase. */
1490     message->termpos = term_gen->get_termpos () + 100;
1491
1492     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1493 }
1494
1495 /* Remove a name:value term from 'message', (the actual term will be
1496  * encoded by prefixing the value with a short prefix). See
1497  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1498  * names to prefix values.
1499  *
1500  * This change will not be reflected in the database until the next
1501  * call to _notmuch_message_sync. */
1502 notmuch_private_status_t
1503 _notmuch_message_remove_term (notmuch_message_t *message,
1504                               const char *prefix_name,
1505                               const char *value)
1506 {
1507     char *term;
1508
1509     if (value == NULL)
1510         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1511
1512     term = talloc_asprintf (message, "%s%s",
1513                             _find_prefix (prefix_name), value);
1514
1515     if (strlen (term) > NOTMUCH_TERM_MAX)
1516         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1517
1518     try {
1519         message->doc.remove_term (term);
1520         message->modified = true;
1521     } catch (const Xapian::InvalidArgumentError) {
1522         /* We'll let the philosophers try to wrestle with the
1523          * question of whether failing to remove that which was not
1524          * there in the first place is failure. For us, we'll silently
1525          * consider it all good. */
1526     }
1527
1528     talloc_free (term);
1529
1530     _notmuch_message_invalidate_metadata (message, prefix_name);
1531
1532     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1533 }
1534
1535 notmuch_private_status_t
1536 _notmuch_message_has_term (notmuch_message_t *message,
1537                            const char *prefix_name,
1538                            const char *value,
1539                            bool *result)
1540 {
1541     char *term;
1542     bool out = false;
1543     notmuch_private_status_t status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
1544
1545     if (value == NULL)
1546         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1547
1548     term = talloc_asprintf (message, "%s%s",
1549                             _find_prefix (prefix_name), value);
1550
1551     if (strlen (term) > NOTMUCH_TERM_MAX)
1552         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1553
1554     try {
1555         /* Look for the exact term */
1556         Xapian::TermIterator i = message->doc.termlist_begin ();
1557         i.skip_to (term);
1558         if (i != message->doc.termlist_end () &&
1559             ! strcmp ((*i).c_str (), term))
1560             out = true;
1561     } catch (Xapian::Error &error) {
1562         status = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
1563     }
1564     talloc_free (term);
1565
1566     *result = out;
1567     return status;
1568 }
1569
1570 notmuch_status_t
1571 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
1572 {
1573     notmuch_private_status_t private_status;
1574     notmuch_status_t status;
1575
1576     status = _notmuch_database_ensure_writable (message->notmuch);
1577     if (status)
1578         return status;
1579
1580     if (tag == NULL)
1581         return NOTMUCH_STATUS_NULL_POINTER;
1582
1583     if (strlen (tag) > NOTMUCH_TAG_MAX)
1584         return NOTMUCH_STATUS_TAG_TOO_LONG;
1585
1586     private_status = _notmuch_message_add_term (message, "tag", tag);
1587     if (private_status) {
1588         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
1589                         private_status);
1590     }
1591
1592     if (! message->frozen)
1593         _notmuch_message_sync (message);
1594
1595     return NOTMUCH_STATUS_SUCCESS;
1596 }
1597
1598 notmuch_status_t
1599 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1600 {
1601     notmuch_private_status_t private_status;
1602     notmuch_status_t status;
1603
1604     status = _notmuch_database_ensure_writable (message->notmuch);
1605     if (status)
1606         return status;
1607
1608     if (tag == NULL)
1609         return NOTMUCH_STATUS_NULL_POINTER;
1610
1611     if (strlen (tag) > NOTMUCH_TAG_MAX)
1612         return NOTMUCH_STATUS_TAG_TOO_LONG;
1613
1614     private_status = _notmuch_message_remove_term (message, "tag", tag);
1615     if (private_status) {
1616         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1617                         private_status);
1618     }
1619
1620     if (! message->frozen)
1621         _notmuch_message_sync (message);
1622
1623     return NOTMUCH_STATUS_SUCCESS;
1624 }
1625
1626 /* Is the given filename within a maildir directory?
1627  *
1628  * Specifically, is the final directory component of 'filename' either
1629  * "cur" or "new". If so, return a pointer to that final directory
1630  * component within 'filename'. If not, return NULL.
1631  *
1632  * A non-NULL return value is guaranteed to be a valid string pointer
1633  * pointing to the characters "new/" or "cur/", (but not
1634  * NUL-terminated).
1635  */
1636 static const char *
1637 _filename_is_in_maildir (const char *filename)
1638 {
1639     const char *slash, *dir = NULL;
1640
1641     /* Find the last '/' separating directory from filename. */
1642     slash = strrchr (filename, '/');
1643     if (slash == NULL)
1644         return NULL;
1645
1646     /* Jump back 4 characters to where the previous '/' will be if the
1647      * directory is named "cur" or "new". */
1648     if (slash - filename < 4)
1649         return NULL;
1650
1651     slash -= 4;
1652
1653     if (*slash != '/')
1654         return NULL;
1655
1656     dir = slash + 1;
1657
1658     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1659         STRNCMP_LITERAL (dir, "new/") == 0) {
1660         return dir;
1661     }
1662
1663     return NULL;
1664 }
1665
1666 static void
1667 _ensure_maildir_flags (notmuch_message_t *message, bool force)
1668 {
1669     const char *flags;
1670     notmuch_filenames_t *filenames;
1671     const char *filename, *dir;
1672     char *combined_flags = talloc_strdup (message, "");
1673     int seen_maildir_info = 0;
1674
1675     if (message->maildir_flags) {
1676         if (force) {
1677             talloc_free (message->maildir_flags);
1678             message->maildir_flags = NULL;
1679         }
1680     }
1681
1682     for (filenames = notmuch_message_get_filenames (message);
1683          notmuch_filenames_valid (filenames);
1684          notmuch_filenames_move_to_next (filenames)) {
1685         filename = notmuch_filenames_get (filenames);
1686         dir = _filename_is_in_maildir (filename);
1687
1688         if (! dir)
1689             continue;
1690
1691         flags = strstr (filename, ":2,");
1692         if (flags) {
1693             seen_maildir_info = 1;
1694             flags += 3;
1695             combined_flags = talloc_strdup_append (combined_flags, flags);
1696         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1697             /* Messages are delivered to new/ with no "info" part, but
1698              * they effectively have default maildir flags.  According
1699              * to the spec, we should ignore the info part for
1700              * messages in new/, but some MUAs (mutt) can set maildir
1701              * flags on messages in new/, so we're liberal in what we
1702              * accept. */
1703             seen_maildir_info = 1;
1704         }
1705     }
1706     if (seen_maildir_info)
1707         message->maildir_flags = combined_flags;
1708 }
1709
1710 notmuch_bool_t
1711 notmuch_message_has_maildir_flag (notmuch_message_t *message, char flag)
1712 {
1713     _ensure_maildir_flags (message, false);
1714     return message->maildir_flags && (strchr (message->maildir_flags, flag) != NULL);
1715 }
1716
1717 notmuch_status_t
1718 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1719 {
1720     notmuch_status_t status;
1721     unsigned i;
1722
1723     _ensure_maildir_flags (message, true);
1724     /* If none of the filenames have any maildir info field (not even
1725      * an empty info with no flags set) then there's no information to
1726      * go on, so do nothing. */
1727     if (! message->maildir_flags)
1728         return NOTMUCH_STATUS_SUCCESS;
1729
1730     status = notmuch_message_freeze (message);
1731     if (status)
1732         return status;
1733
1734     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1735         if ((strchr (message->maildir_flags, flag2tag[i].flag) != NULL)
1736             ^
1737             flag2tag[i].inverse) {
1738             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1739         } else {
1740             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1741         }
1742         if (status)
1743             return status;
1744     }
1745     status = notmuch_message_thaw (message);
1746
1747     return status;
1748 }
1749
1750 /* From the set of tags on 'message' and the flag2tag table, compute a
1751  * set of maildir-flag actions to be taken, (flags that should be
1752  * either set or cleared).
1753  *
1754  * The result is returned as two talloced strings: to_set, and to_clear
1755  */
1756 static void
1757 _get_maildir_flag_actions (notmuch_message_t *message,
1758                            char **to_set_ret,
1759                            char **to_clear_ret)
1760 {
1761     char *to_set, *to_clear;
1762     notmuch_tags_t *tags;
1763     const char *tag;
1764     unsigned i;
1765
1766     to_set = talloc_strdup (message, "");
1767     to_clear = talloc_strdup (message, "");
1768
1769     /* First, find flags for all set tags. */
1770     for (tags = notmuch_message_get_tags (message);
1771          notmuch_tags_valid (tags);
1772          notmuch_tags_move_to_next (tags)) {
1773         tag = notmuch_tags_get (tags);
1774
1775         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1776             if (strcmp (tag, flag2tag[i].tag) == 0) {
1777                 if (flag2tag[i].inverse)
1778                     to_clear = talloc_asprintf_append (to_clear,
1779                                                        "%c",
1780                                                        flag2tag[i].flag);
1781                 else
1782                     to_set = talloc_asprintf_append (to_set,
1783                                                      "%c",
1784                                                      flag2tag[i].flag);
1785             }
1786         }
1787     }
1788
1789     /* Then, find the flags for all tags not present. */
1790     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1791         if (flag2tag[i].inverse) {
1792             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1793                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1794         } else {
1795             if (strchr (to_set, flag2tag[i].flag) == NULL)
1796                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1797         }
1798     }
1799
1800     *to_set_ret = to_set;
1801     *to_clear_ret = to_clear;
1802 }
1803
1804 /* Given 'filename' and a set of maildir flags to set and to clear,
1805  * compute the new maildir filename.
1806  *
1807  * If the existing filename is in the directory "new", the new
1808  * filename will be in the directory "cur", except for the case when
1809  * no flags are changed and the existing filename does not contain
1810  * maildir info (starting with ",2:").
1811  *
1812  * After a sequence of ":2," in the filename, any subsequent
1813  * single-character flags will be added or removed according to the
1814  * characters in flags_to_set and flags_to_clear. Any existing flags
1815  * not mentioned in either string will remain. The final list of flags
1816  * will be in ASCII order.
1817  *
1818  * If the original flags seem invalid, (repeated characters or
1819  * non-ASCII ordering of flags), this function will return NULL
1820  * (meaning that renaming would not be safe and should not occur).
1821  */
1822 static char *
1823 _new_maildir_filename (void *ctx,
1824                        const char *filename,
1825                        const char *flags_to_set,
1826                        const char *flags_to_clear)
1827 {
1828     const char *info, *flags;
1829     unsigned int flag, last_flag;
1830     char *filename_new, *dir;
1831     char flag_map[128];
1832     int flags_in_map = 0;
1833     bool flags_changed = false;
1834     unsigned int i;
1835     char *s;
1836
1837     memset (flag_map, 0, sizeof (flag_map));
1838
1839     info = strstr (filename, ":2,");
1840
1841     if (info == NULL) {
1842         info = filename + strlen (filename);
1843     } else {
1844         /* Loop through existing flags in filename. */
1845         for (flags = info + 3, last_flag = 0;
1846              *flags;
1847              last_flag = flag, flags++) {
1848             flag = *flags;
1849
1850             /* Original flags not in ASCII order. Abort. */
1851             if (flag < last_flag)
1852                 return NULL;
1853
1854             /* Non-ASCII flag. Abort. */
1855             if (flag > sizeof (flag_map) - 1)
1856                 return NULL;
1857
1858             /* Repeated flag value. Abort. */
1859             if (flag_map[flag])
1860                 return NULL;
1861
1862             flag_map[flag] = 1;
1863             flags_in_map++;
1864         }
1865     }
1866
1867     /* Then set and clear our flags from tags. */
1868     for (flags = flags_to_set; *flags; flags++) {
1869         flag = *flags;
1870         if (flag_map[flag] == 0) {
1871             flag_map[flag] = 1;
1872             flags_in_map++;
1873             flags_changed = true;
1874         }
1875     }
1876
1877     for (flags = flags_to_clear; *flags; flags++) {
1878         flag = *flags;
1879         if (flag_map[flag]) {
1880             flag_map[flag] = 0;
1881             flags_in_map--;
1882             flags_changed = true;
1883         }
1884     }
1885
1886     /* Messages in new/ without maildir info can be kept in new/ if no
1887      * flags have changed. */
1888     dir = (char *) _filename_is_in_maildir (filename);
1889     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && ! *info && ! flags_changed)
1890         return talloc_strdup (ctx, filename);
1891
1892     filename_new = (char *) talloc_size (ctx,
1893                                          info - filename +
1894                                          strlen (":2,") + flags_in_map + 1);
1895     if (unlikely (filename_new == NULL))
1896         return NULL;
1897
1898     strncpy (filename_new, filename, info - filename);
1899     filename_new[info - filename] = '\0';
1900
1901     strcat (filename_new, ":2,");
1902
1903     s = filename_new + strlen (filename_new);
1904     for (i = 0; i < sizeof (flag_map); i++) {
1905         if (flag_map[i]) {
1906             *s = i;
1907             s++;
1908         }
1909     }
1910     *s = '\0';
1911
1912     /* If message is in new/ move it under cur/. */
1913     dir = (char *) _filename_is_in_maildir (filename_new);
1914     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1915         memcpy (dir, "cur/", 4);
1916
1917     return filename_new;
1918 }
1919
1920 notmuch_status_t
1921 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1922 {
1923     notmuch_filenames_t *filenames;
1924     const char *filename;
1925     char *filename_new;
1926     char *to_set, *to_clear;
1927     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1928
1929     _get_maildir_flag_actions (message, &to_set, &to_clear);
1930
1931     for (filenames = notmuch_message_get_filenames (message);
1932          notmuch_filenames_valid (filenames);
1933          notmuch_filenames_move_to_next (filenames)) {
1934         filename = notmuch_filenames_get (filenames);
1935
1936         if (! _filename_is_in_maildir (filename))
1937             continue;
1938
1939         filename_new = _new_maildir_filename (message, filename,
1940                                               to_set, to_clear);
1941         if (filename_new == NULL)
1942             continue;
1943
1944         if (strcmp (filename, filename_new)) {
1945             int err;
1946             notmuch_status_t new_status;
1947
1948             err = rename (filename, filename_new);
1949             if (err)
1950                 continue;
1951
1952             new_status = _notmuch_message_remove_filename (message,
1953                                                            filename);
1954             /* Hold on to only the first error. */
1955             if (! status && new_status
1956                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
1957                 status = new_status;
1958                 continue;
1959             }
1960
1961             new_status = _notmuch_message_add_filename (message,
1962                                                         filename_new);
1963             /* Hold on to only the first error. */
1964             if (! status && new_status) {
1965                 status = new_status;
1966                 continue;
1967             }
1968
1969             _notmuch_message_sync (message);
1970         }
1971
1972         talloc_free (filename_new);
1973     }
1974
1975     talloc_free (to_set);
1976     talloc_free (to_clear);
1977
1978     return status;
1979 }
1980
1981 notmuch_status_t
1982 notmuch_message_remove_all_tags (notmuch_message_t *message)
1983 {
1984     notmuch_private_status_t private_status;
1985     notmuch_status_t status;
1986     notmuch_tags_t *tags;
1987     const char *tag;
1988
1989     status = _notmuch_database_ensure_writable (message->notmuch);
1990     if (status)
1991         return status;
1992
1993     for (tags = notmuch_message_get_tags (message);
1994          notmuch_tags_valid (tags);
1995          notmuch_tags_move_to_next (tags)) {
1996         tag = notmuch_tags_get (tags);
1997
1998         private_status = _notmuch_message_remove_term (message, "tag", tag);
1999         if (private_status) {
2000             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
2001                             private_status);
2002         }
2003     }
2004
2005     if (! message->frozen)
2006         _notmuch_message_sync (message);
2007
2008     talloc_free (tags);
2009     return NOTMUCH_STATUS_SUCCESS;
2010 }
2011
2012 notmuch_status_t
2013 notmuch_message_freeze (notmuch_message_t *message)
2014 {
2015     notmuch_status_t status;
2016
2017     status = _notmuch_database_ensure_writable (message->notmuch);
2018     if (status)
2019         return status;
2020
2021     message->frozen++;
2022
2023     return NOTMUCH_STATUS_SUCCESS;
2024 }
2025
2026 notmuch_status_t
2027 notmuch_message_thaw (notmuch_message_t *message)
2028 {
2029     notmuch_status_t status;
2030
2031     status = _notmuch_database_ensure_writable (message->notmuch);
2032     if (status)
2033         return status;
2034
2035     if (message->frozen > 0) {
2036         message->frozen--;
2037         if (message->frozen == 0)
2038             _notmuch_message_sync (message);
2039         return NOTMUCH_STATUS_SUCCESS;
2040     } else {
2041         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
2042     }
2043 }
2044
2045 void
2046 notmuch_message_destroy (notmuch_message_t *message)
2047 {
2048     talloc_free (message);
2049 }
2050
2051 notmuch_database_t *
2052 notmuch_message_get_database (const notmuch_message_t *message)
2053 {
2054     return message->notmuch;
2055 }
2056
2057 static void
2058 _notmuch_message_ensure_property_map (notmuch_message_t *message)
2059 {
2060     notmuch_string_node_t *node;
2061
2062     if (message->property_map)
2063         return;
2064
2065     _notmuch_message_ensure_metadata (message, message->property_term_list);
2066
2067     message->property_map = _notmuch_string_map_create (message);
2068
2069     for (node = message->property_term_list->head; node; node = node->next) {
2070         const char *key;
2071         char *value;
2072
2073         value = strchr (node->string, '=');
2074         if (! value)
2075             INTERNAL_ERROR ("malformed property term");
2076
2077         *value = '\0';
2078         value++;
2079         key = node->string;
2080
2081         _notmuch_string_map_append (message->property_map, key, value);
2082
2083     }
2084
2085     talloc_free (message->property_term_list);
2086     message->property_term_list = NULL;
2087 }
2088
2089 notmuch_string_map_t *
2090 _notmuch_message_property_map (notmuch_message_t *message)
2091 {
2092     _notmuch_message_ensure_property_map (message);
2093
2094     return message->property_map;
2095 }
2096
2097 bool
2098 _notmuch_message_frozen (notmuch_message_t *message)
2099 {
2100     return message->frozen;
2101 }
2102
2103 notmuch_status_t
2104 notmuch_message_reindex (notmuch_message_t *message,
2105                          notmuch_indexopts_t *indexopts)
2106 {
2107     notmuch_database_t *notmuch = NULL;
2108     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2109     notmuch_private_status_t private_status;
2110     notmuch_filenames_t *orig_filenames = NULL;
2111     const char *orig_thread_id = NULL;
2112     notmuch_message_file_t *message_file = NULL;
2113
2114     int found = 0;
2115
2116     if (message == NULL)
2117         return NOTMUCH_STATUS_NULL_POINTER;
2118
2119     /* Save in case we need to delete message */
2120     orig_thread_id = notmuch_message_get_thread_id (message);
2121     if (! orig_thread_id) {
2122         /* XXX TODO: make up new error return? */
2123         INTERNAL_ERROR ("message without thread-id");
2124     }
2125
2126     /* strdup it because the metadata may be invalidated */
2127     orig_thread_id = talloc_strdup (message, orig_thread_id);
2128
2129     notmuch = notmuch_message_get_database (message);
2130
2131     ret = _notmuch_database_ensure_writable (notmuch);
2132     if (ret)
2133         return ret;
2134
2135     orig_filenames = notmuch_message_get_filenames (message);
2136
2137     private_status = _notmuch_message_remove_indexed_terms (message);
2138     if (private_status) {
2139         ret = COERCE_STATUS (private_status, "error removing terms");
2140         goto DONE;
2141     }
2142
2143     ret = notmuch_message_remove_all_properties_with_prefix (message, "index.");
2144     if (ret)
2145         goto DONE; /* XXX TODO: distinguish from other error returns above? */
2146     if (indexopts && notmuch_indexopts_get_decrypt_policy (indexopts) == NOTMUCH_DECRYPT_FALSE) {
2147         ret = notmuch_message_remove_all_properties (message, "session-key");
2148         if (ret)
2149             goto DONE;
2150     }
2151
2152     /* re-add the filenames with the associated indexopts */
2153     for (; notmuch_filenames_valid (orig_filenames);
2154          notmuch_filenames_move_to_next (orig_filenames)) {
2155
2156         const char *date;
2157         const char *from, *to, *subject;
2158         char *message_id = NULL;
2159         const char *thread_id = NULL;
2160
2161         const char *filename = notmuch_filenames_get (orig_filenames);
2162
2163         message_file = _notmuch_message_file_open (notmuch, filename);
2164         if (message_file == NULL)
2165             continue;
2166
2167         ret = _notmuch_message_file_get_headers (message_file,
2168                                                  &from, &subject, &to, &date,
2169                                                  &message_id);
2170         if (ret)
2171             goto DONE;
2172
2173         /* XXX TODO: deal with changing message id? */
2174
2175         _notmuch_message_add_filename (message, filename);
2176
2177         ret = _notmuch_database_link_message_to_parents (notmuch, message,
2178                                                          message_file,
2179                                                          &thread_id);
2180         if (ret)
2181             goto DONE;
2182
2183         if (thread_id == NULL)
2184             thread_id = orig_thread_id;
2185
2186         _notmuch_message_add_term (message, "thread", thread_id);
2187         /* Take header values only from first filename */
2188         if (found == 0)
2189             _notmuch_message_set_header_values (message, date, from, subject);
2190
2191         ret = _notmuch_message_index_file (message, indexopts, message_file);
2192
2193         if (ret == NOTMUCH_STATUS_FILE_ERROR)
2194             continue;
2195         if (ret)
2196             goto DONE;
2197
2198         found++;
2199         _notmuch_message_file_close (message_file);
2200         message_file = NULL;
2201     }
2202     if (found == 0) {
2203         /* put back thread id to help cleanup */
2204         _notmuch_message_add_term (message, "thread", orig_thread_id);
2205         ret = _notmuch_message_delete (message);
2206     } else {
2207         _notmuch_message_sync (message);
2208     }
2209
2210   DONE:
2211     if (message_file)
2212         _notmuch_message_file_close (message_file);
2213
2214     /* XXX TODO destroy orig_filenames? */
2215     return ret;
2216 }