]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
b7a64b1c3894c26224e78be165bf58ac445fa777
[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     _notmuch_message_ensure_metadata (message, message->thread_id);
608     if (! message->thread_id)
609         INTERNAL_ERROR ("Message with document ID of %u has no thread ID.\n",
610                         message->doc_id);
611     return message->thread_id;
612 }
613
614 void
615 _notmuch_message_add_reply (notmuch_message_t *message,
616                             notmuch_message_t *reply)
617 {
618     _notmuch_message_list_add_message (message->replies, reply);
619 }
620
621 size_t
622 _notmuch_message_get_thread_depth (notmuch_message_t *message)
623 {
624     return message->thread_depth;
625 }
626
627 void
628 _notmuch_message_label_depths (notmuch_message_t *message,
629                                size_t depth)
630 {
631     message->thread_depth = depth;
632
633     for (notmuch_messages_t *messages = _notmuch_messages_create (message->replies);
634          notmuch_messages_valid (messages);
635          notmuch_messages_move_to_next (messages)) {
636         notmuch_message_t *child = notmuch_messages_get (messages);
637         _notmuch_message_label_depths (child, depth + 1);
638     }
639 }
640
641 const notmuch_string_list_t *
642 _notmuch_message_get_references (notmuch_message_t *message)
643 {
644     _notmuch_message_ensure_metadata (message, message->reference_list);
645     return message->reference_list;
646 }
647
648 static int
649 _cmpmsg (const void *pa, const void *pb)
650 {
651     notmuch_message_t **a = (notmuch_message_t **) pa;
652     notmuch_message_t **b = (notmuch_message_t **) pb;
653     time_t time_a = notmuch_message_get_date (*a);
654     time_t time_b = notmuch_message_get_date (*b);
655
656     if (time_a == time_b)
657         return 0;
658     else if (time_a < time_b)
659         return -1;
660     else
661         return 1;
662 }
663
664 notmuch_message_list_t *
665 _notmuch_message_sort_subtrees (void *ctx, notmuch_message_list_t *list)
666 {
667
668     size_t count = 0;
669     size_t capacity = 16;
670
671     if (! list)
672         return list;
673
674     void *local = talloc_new (NULL);
675     notmuch_message_list_t *new_list = _notmuch_message_list_create (ctx);
676     notmuch_message_t **message_array = talloc_zero_array (local, notmuch_message_t *, capacity);
677
678     for (notmuch_messages_t *messages = _notmuch_messages_create (list);
679          notmuch_messages_valid (messages);
680          notmuch_messages_move_to_next (messages)) {
681         notmuch_message_t *root = notmuch_messages_get (messages);
682         if (count >= capacity) {
683             capacity *= 2;
684             message_array = talloc_realloc (local, message_array, notmuch_message_t *, capacity);
685         }
686         message_array[count++] = root;
687         root->replies = _notmuch_message_sort_subtrees (root, root->replies);
688     }
689
690     qsort (message_array, count, sizeof (notmuch_message_t *), _cmpmsg);
691     for (size_t i = 0; i < count; i++) {
692         _notmuch_message_list_add_message (new_list, message_array[i]);
693     }
694
695     talloc_free (local);
696     talloc_free (list);
697     return new_list;
698 }
699
700 notmuch_messages_t *
701 notmuch_message_get_replies (notmuch_message_t *message)
702 {
703     return _notmuch_messages_create (message->replies);
704 }
705
706 void
707 _notmuch_message_remove_terms (notmuch_message_t *message, const char *prefix)
708 {
709     Xapian::TermIterator i;
710     size_t prefix_len = 0;
711
712     prefix_len = strlen (prefix);
713
714     while (1) {
715         i = message->doc.termlist_begin ();
716         i.skip_to (prefix);
717
718         /* Terminate loop when no terms remain with desired prefix. */
719         if (i == message->doc.termlist_end () ||
720             strncmp ((*i).c_str (), prefix, prefix_len))
721             break;
722
723         try {
724             message->doc.remove_term ((*i));
725             message->modified = true;
726         } catch (const Xapian::InvalidArgumentError) {
727             /* Ignore failure to remove non-existent term. */
728         }
729     }
730 }
731
732
733 /* Remove all terms generated by indexing, i.e. not tags or
734  * properties, along with any automatic tags*/
735 /* According to Xapian API docs, none of these calls throw
736  * exceptions */
737 notmuch_private_status_t
738 _notmuch_message_remove_indexed_terms (notmuch_message_t *message)
739 {
740     Xapian::TermIterator i;
741
742     const std::string
743         id_prefix = _find_prefix ("id"),
744         property_prefix = _find_prefix ("property"),
745         tag_prefix = _find_prefix ("tag"),
746         type_prefix = _find_prefix ("type");
747
748     /* Make sure we have the data to restore to Xapian*/
749     _notmuch_message_ensure_metadata (message, NULL);
750
751     /* Empirically, it turns out to be faster to remove all the terms,
752      * and add back the ones we want. */
753     message->doc.clear_terms ();
754     message->modified = true;
755
756     /* still a mail message */
757     message->doc.add_term (type_prefix + "mail");
758
759     /* Put back message-id */
760     message->doc.add_term (id_prefix + message->message_id);
761
762     /* Put back non-automatic tags */
763     for (notmuch_tags_t *tags = notmuch_message_get_tags (message);
764          notmuch_tags_valid (tags);
765          notmuch_tags_move_to_next (tags)) {
766
767         const char *tag = notmuch_tags_get (tags);
768
769         if (strcmp (tag, "encrypted") != 0 &&
770             strcmp (tag, "signed") != 0 &&
771             strcmp (tag, "attachment") != 0) {
772             std::string term = tag_prefix + tag;
773             message->doc.add_term (term);
774         }
775     }
776
777     /* Put back properties */
778     notmuch_message_properties_t *list;
779
780     for (list = notmuch_message_get_properties (message, "", false);
781          notmuch_message_properties_valid (list); notmuch_message_properties_move_to_next (list)) {
782         std::string term = property_prefix +
783                            notmuch_message_properties_key (list) + "=" +
784                            notmuch_message_properties_value (list);
785
786         message->doc.add_term (term);
787     }
788
789     notmuch_message_properties_destroy (list);
790
791     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
792 }
793
794
795 /* Return true if p points at "new" or "cur". */
796 static bool
797 is_maildir (const char *p)
798 {
799     return strcmp (p, "cur") == 0 || strcmp (p, "new") == 0;
800 }
801
802 /* Add "folder:" term for directory. */
803 static notmuch_status_t
804 _notmuch_message_add_folder_terms (notmuch_message_t *message,
805                                    const char *directory)
806 {
807     char *folder, *last;
808
809     folder = talloc_strdup (NULL, directory);
810     if (! folder)
811         return NOTMUCH_STATUS_OUT_OF_MEMORY;
812
813     /*
814      * If the message file is in a leaf directory named "new" or
815      * "cur", presume maildir and index the parent directory. Thus a
816      * "folder:" prefix search matches messages in the specified
817      * maildir folder, i.e. in the specified directory and its "new"
818      * and "cur" subdirectories.
819      *
820      * Note that this means the "folder:" prefix can't be used for
821      * distinguishing between message files in "new" or "cur". The
822      * "path:" prefix needs to be used for that.
823      *
824      * Note the deliberate difference to _filename_is_in_maildir(). We
825      * don't want to index different things depending on the existence
826      * or non-existence of all maildir sibling directories "new",
827      * "cur", and "tmp". Doing so would be surprising, and difficult
828      * for the user to fix in case all subdirectories were not in
829      * place during indexing.
830      */
831     last = strrchr (folder, '/');
832     if (last) {
833         if (is_maildir (last + 1))
834             *last = '\0';
835     } else if (is_maildir (folder)) {
836         *folder = '\0';
837     }
838
839     _notmuch_message_add_term (message, "folder", folder);
840
841     talloc_free (folder);
842
843     message->modified = true;
844     return NOTMUCH_STATUS_SUCCESS;
845 }
846
847 #define RECURSIVE_SUFFIX "/**"
848
849 /* Add "path:" terms for directory. */
850 static notmuch_status_t
851 _notmuch_message_add_path_terms (notmuch_message_t *message,
852                                  const char *directory)
853 {
854     /* Add exact "path:" term. */
855     _notmuch_message_add_term (message, "path", directory);
856
857     if (strlen (directory)) {
858         char *path, *p;
859
860         path = talloc_asprintf (NULL, "%s%s", directory, RECURSIVE_SUFFIX);
861         if (! path)
862             return NOTMUCH_STATUS_OUT_OF_MEMORY;
863
864         /* Add recursive "path:" terms for directory and all parents. */
865         for (p = path + strlen (path) - 1; p > path; p--) {
866             if (*p == '/') {
867                 strcpy (p, RECURSIVE_SUFFIX);
868                 _notmuch_message_add_term (message, "path", path);
869             }
870         }
871
872         talloc_free (path);
873     }
874
875     /* Recursive all-matching path:** for consistency. */
876     _notmuch_message_add_term (message, "path", "**");
877
878     return NOTMUCH_STATUS_SUCCESS;
879 }
880
881 /* Add directory based terms for all filenames of the message. */
882 static notmuch_status_t
883 _notmuch_message_add_directory_terms (void *ctx, notmuch_message_t *message)
884 {
885     const char *direntry_prefix = _find_prefix ("file-direntry");
886     int direntry_prefix_len = strlen (direntry_prefix);
887     Xapian::TermIterator i = message->doc.termlist_begin ();
888     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
889
890     for (i.skip_to (direntry_prefix); i != message->doc.termlist_end (); i++) {
891         unsigned int directory_id;
892         const char *direntry, *directory;
893         char *colon;
894         const std::string &term = *i;
895
896         /* Terminate loop at first term without desired prefix. */
897         if (strncmp (term.c_str (), direntry_prefix, direntry_prefix_len))
898             break;
899
900         /* Indicate that there are filenames remaining. */
901         status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
902
903         direntry = term.c_str ();
904         direntry += direntry_prefix_len;
905
906         directory_id = strtol (direntry, &colon, 10);
907
908         if (colon == NULL || *colon != ':')
909             INTERNAL_ERROR ("malformed direntry");
910
911         directory = _notmuch_database_get_directory_path (ctx,
912                                                           message->notmuch,
913                                                           directory_id);
914
915         _notmuch_message_add_folder_terms (message, directory);
916         _notmuch_message_add_path_terms (message, directory);
917     }
918
919     return status;
920 }
921
922 /* Add an additional 'filename' for 'message'.
923  *
924  * This change will not be reflected in the database until the next
925  * call to _notmuch_message_sync. */
926 notmuch_status_t
927 _notmuch_message_add_filename (notmuch_message_t *message,
928                                const char *filename)
929 {
930     const char *relative, *directory;
931     notmuch_status_t status;
932     void *local = talloc_new (message);
933     char *direntry;
934
935     if (filename == NULL)
936         INTERNAL_ERROR ("Message filename cannot be NULL.");
937
938     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
939         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
940         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
941
942     relative = _notmuch_database_relative_path (message->notmuch, filename);
943
944     status = _notmuch_database_split_path (local, relative, &directory, NULL);
945     if (status)
946         return status;
947
948     status = _notmuch_database_filename_to_direntry (
949         local, message->notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
950     if (status)
951         return status;
952
953     /* New file-direntry allows navigating to this message with
954      * notmuch_directory_get_child_files() . */
955     _notmuch_message_add_term (message, "file-direntry", direntry);
956
957     _notmuch_message_add_folder_terms (message, directory);
958     _notmuch_message_add_path_terms (message, directory);
959
960     talloc_free (local);
961
962     return NOTMUCH_STATUS_SUCCESS;
963 }
964
965 /* Remove a particular 'filename' from 'message'.
966  *
967  * This change will not be reflected in the database until the next
968  * call to _notmuch_message_sync.
969  *
970  * If this message still has other filenames, returns
971  * NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID.
972  *
973  * Note: This function does not remove a document from the database,
974  * even if the specified filename is the only filename for this
975  * message. For that functionality, see
976  * notmuch_database_remove_message. */
977 notmuch_status_t
978 _notmuch_message_remove_filename (notmuch_message_t *message,
979                                   const char *filename)
980 {
981     void *local = talloc_new (message);
982     char *direntry;
983     notmuch_private_status_t private_status;
984     notmuch_status_t status;
985
986     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
987         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
988         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
989
990     status = _notmuch_database_filename_to_direntry (
991         local, message->notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
992     if (status || ! direntry)
993         return status;
994
995     /* Unlink this file from its parent directory. */
996     private_status = _notmuch_message_remove_term (message,
997                                                    "file-direntry", direntry);
998     status = COERCE_STATUS (private_status,
999                             "Unexpected error from _notmuch_message_remove_term");
1000     if (status)
1001         return status;
1002
1003     /* Re-synchronize "folder:" and "path:" terms for this message. */
1004
1005     /* Remove all "folder:" terms. */
1006     _notmuch_message_remove_terms (message, _find_prefix ("folder"));
1007
1008     /* Remove all "path:" terms. */
1009     _notmuch_message_remove_terms (message, _find_prefix ("path"));
1010
1011     /* Add back terms for all remaining filenames of the message. */
1012     status = _notmuch_message_add_directory_terms (local, message);
1013
1014     talloc_free (local);
1015
1016     return status;
1017 }
1018
1019 /* Upgrade the "folder:" prefix from V1 to V2. */
1020 #define FOLDER_PREFIX_V1       "XFOLDER"
1021 #define ZFOLDER_PREFIX_V1      "Z" FOLDER_PREFIX_V1
1022 void
1023 _notmuch_message_upgrade_folder (notmuch_message_t *message)
1024 {
1025     /* Remove all old "folder:" terms. */
1026     _notmuch_message_remove_terms (message, FOLDER_PREFIX_V1);
1027
1028     /* Remove all old "folder:" stemmed terms. */
1029     _notmuch_message_remove_terms (message, ZFOLDER_PREFIX_V1);
1030
1031     /* Add new boolean "folder:" and "path:" terms. */
1032     _notmuch_message_add_directory_terms (message, message);
1033 }
1034
1035 char *
1036 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
1037 {
1038     return talloc_strdup (message, message->doc.get_data ().c_str ());
1039 }
1040
1041 void
1042 _notmuch_message_clear_data (notmuch_message_t *message)
1043 {
1044     message->doc.set_data ("");
1045     message->modified = true;
1046 }
1047
1048 static void
1049 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
1050 {
1051     notmuch_string_node_t *node;
1052
1053     if (message->filename_list)
1054         return;
1055
1056     _notmuch_message_ensure_metadata (message, message->filename_term_list);
1057
1058     message->filename_list = _notmuch_string_list_create (message);
1059     node = message->filename_term_list->head;
1060
1061     if (! node) {
1062         /* A message document created by an old version of notmuch
1063          * (prior to rename support) will have the filename in the
1064          * data of the document rather than as a file-direntry term.
1065          *
1066          * It would be nice to do the upgrade of the document directly
1067          * here, but the database is likely open in read-only mode. */
1068
1069         std::string datastr = message->doc.get_data ();
1070         const char *data = datastr.c_str ();
1071
1072         if (data == NULL)
1073             INTERNAL_ERROR ("message with no filename");
1074
1075         _notmuch_string_list_append (message->filename_list, data);
1076
1077         return;
1078     }
1079
1080     for (; node; node = node->next) {
1081         void *local = talloc_new (message);
1082         const char *db_path, *directory, *basename, *filename;
1083         char *colon, *direntry = NULL;
1084         unsigned int directory_id;
1085
1086         direntry = node->string;
1087
1088         directory_id = strtol (direntry, &colon, 10);
1089
1090         if (colon == NULL || *colon != ':')
1091             INTERNAL_ERROR ("malformed direntry");
1092
1093         basename = colon + 1;
1094
1095         *colon = '\0';
1096
1097         db_path = notmuch_database_get_path (message->notmuch);
1098
1099         directory = _notmuch_database_get_directory_path (local,
1100                                                           message->notmuch,
1101                                                           directory_id);
1102
1103         if (strlen (directory))
1104             filename = talloc_asprintf (message, "%s/%s/%s",
1105                                         db_path, directory, basename);
1106         else
1107             filename = talloc_asprintf (message, "%s/%s",
1108                                         db_path, basename);
1109
1110         _notmuch_string_list_append (message->filename_list, filename);
1111
1112         talloc_free (local);
1113     }
1114
1115     talloc_free (message->filename_term_list);
1116     message->filename_term_list = NULL;
1117 }
1118
1119 const char *
1120 notmuch_message_get_filename (notmuch_message_t *message)
1121 {
1122     _notmuch_message_ensure_filename_list (message);
1123
1124     if (message->filename_list == NULL)
1125         return NULL;
1126
1127     if (message->filename_list->head == NULL ||
1128         message->filename_list->head->string == NULL) {
1129         INTERNAL_ERROR ("message with no filename");
1130     }
1131
1132     return message->filename_list->head->string;
1133 }
1134
1135 notmuch_filenames_t *
1136 notmuch_message_get_filenames (notmuch_message_t *message)
1137 {
1138     _notmuch_message_ensure_filename_list (message);
1139
1140     return _notmuch_filenames_create (message, message->filename_list);
1141 }
1142
1143 int
1144 notmuch_message_count_files (notmuch_message_t *message)
1145 {
1146     _notmuch_message_ensure_filename_list (message);
1147
1148     return _notmuch_string_list_length (message->filename_list);
1149 }
1150
1151 notmuch_bool_t
1152 notmuch_message_get_flag (notmuch_message_t *message,
1153                           notmuch_message_flag_t flag)
1154 {
1155     if (flag == NOTMUCH_MESSAGE_FLAG_GHOST &&
1156         ! NOTMUCH_TEST_BIT (message->lazy_flags, flag))
1157         _notmuch_message_ensure_metadata (message, NULL);
1158
1159     return NOTMUCH_TEST_BIT (message->flags, flag);
1160 }
1161
1162 void
1163 notmuch_message_set_flag (notmuch_message_t *message,
1164                           notmuch_message_flag_t flag, notmuch_bool_t enable)
1165 {
1166     if (enable)
1167         NOTMUCH_SET_BIT (&message->flags, flag);
1168     else
1169         NOTMUCH_CLEAR_BIT (&message->flags, flag);
1170     NOTMUCH_SET_BIT (&message->lazy_flags, flag);
1171 }
1172
1173 time_t
1174 notmuch_message_get_date (notmuch_message_t *message)
1175 {
1176     std::string value;
1177
1178     try {
1179         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
1180     } catch (Xapian::Error &error) {
1181         _notmuch_database_log (notmuch_message_get_database (message), "A Xapian exception occurred when reading date: %s\n",
1182                                error.get_msg ().c_str ());
1183         message->notmuch->exception_reported = true;
1184         return 0;
1185     }
1186
1187     if (value.empty ())
1188         /* sortable_unserialise is undefined on empty string */
1189         return 0;
1190     return Xapian::sortable_unserialise (value);
1191 }
1192
1193 notmuch_tags_t *
1194 notmuch_message_get_tags (notmuch_message_t *message)
1195 {
1196     notmuch_tags_t *tags;
1197
1198     _notmuch_message_ensure_metadata (message, message->tag_list);
1199
1200     tags = _notmuch_tags_create (message, message->tag_list);
1201     /* _notmuch_tags_create steals the reference to the tag_list, but
1202      * in this case it's still used by the message, so we add an
1203      * *additional* talloc reference to the list.  As a result, it's
1204      * possible to modify the message tags (which talloc_unlink's the
1205      * current list from the message) while still iterating because
1206      * the iterator will keep the current list alive. */
1207     if (! talloc_reference (message, message->tag_list))
1208         return NULL;
1209
1210     return tags;
1211 }
1212
1213 const char *
1214 _notmuch_message_get_author (notmuch_message_t *message)
1215 {
1216     return message->author;
1217 }
1218
1219 void
1220 _notmuch_message_set_author (notmuch_message_t *message,
1221                              const char *author)
1222 {
1223     if (message->author)
1224         talloc_free (message->author);
1225     message->author = talloc_strdup (message, author);
1226     return;
1227 }
1228
1229 void
1230 _notmuch_message_set_header_values (notmuch_message_t *message,
1231                                     const char *date,
1232                                     const char *from,
1233                                     const char *subject)
1234 {
1235     time_t time_value;
1236
1237     /* GMime really doesn't want to see a NULL date, so protect its
1238      * sensibilities. */
1239     if (date == NULL || *date == '\0') {
1240         time_value = 0;
1241     } else {
1242         time_value = g_mime_utils_header_decode_date_unix (date);
1243         /*
1244          * Workaround for https://bugzilla.gnome.org/show_bug.cgi?id=779923
1245          */
1246         if (time_value < 0)
1247             time_value = 0;
1248     }
1249
1250     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
1251                             Xapian::sortable_serialise (time_value));
1252     message->doc.add_value (NOTMUCH_VALUE_FROM, from);
1253     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
1254     message->modified = true;
1255 }
1256
1257 void
1258 _notmuch_message_update_subject (notmuch_message_t *message,
1259                                  const char *subject)
1260 {
1261     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
1262     message->modified = true;
1263 }
1264
1265 /* Upgrade a message to support NOTMUCH_FEATURE_LAST_MOD.  The caller
1266  * must call _notmuch_message_sync. */
1267 void
1268 _notmuch_message_upgrade_last_mod (notmuch_message_t *message)
1269 {
1270     /* _notmuch_message_sync will update the last modification
1271      * revision; we just have to ask it to. */
1272     message->modified = true;
1273 }
1274
1275 /* Synchronize changes made to message->doc out into the database. */
1276 void
1277 _notmuch_message_sync (notmuch_message_t *message)
1278 {
1279     Xapian::WritableDatabase *db;
1280
1281     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
1282         return;
1283
1284     if (! message->modified)
1285         return;
1286
1287     /* Update the last modification of this message. */
1288     if (message->notmuch->features & NOTMUCH_FEATURE_LAST_MOD)
1289         /* sortable_serialise gives a reasonably compact encoding,
1290          * which directly translates to reduced IO when scanning the
1291          * value stream.  Since it's built for doubles, we only get 53
1292          * effective bits, but that's still enough for the database to
1293          * last a few centuries at 1 million revisions per second. */
1294         message->doc.add_value (NOTMUCH_VALUE_LAST_MOD,
1295                                 Xapian::sortable_serialise (
1296                                     _notmuch_database_new_revision (
1297                                         message->notmuch)));
1298
1299     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
1300     db->replace_document (message->doc_id, message->doc);
1301     message->modified = false;
1302 }
1303
1304 /* Delete a message document from the database, leaving a ghost
1305  * message in its place */
1306 notmuch_status_t
1307 _notmuch_message_delete (notmuch_message_t *message)
1308 {
1309     notmuch_status_t status;
1310     Xapian::WritableDatabase *db;
1311     const char *mid, *tid, *query_string;
1312     notmuch_message_t *ghost;
1313     notmuch_private_status_t private_status;
1314     notmuch_database_t *notmuch;
1315     notmuch_query_t *query;
1316     unsigned int count = 0;
1317     bool is_ghost;
1318
1319     mid = notmuch_message_get_message_id (message);
1320     tid = notmuch_message_get_thread_id (message);
1321     notmuch = message->notmuch;
1322
1323     status = _notmuch_database_ensure_writable (message->notmuch);
1324     if (status)
1325         return status;
1326
1327     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1328     db->delete_document (message->doc_id);
1329
1330     /* if this was a ghost to begin with, we are done */
1331     private_status = _notmuch_message_has_term (message, "type", "ghost", &is_ghost);
1332     if (private_status)
1333         return COERCE_STATUS (private_status,
1334                               "Error trying to determine whether message was a ghost");
1335     if (is_ghost)
1336         return NOTMUCH_STATUS_SUCCESS;
1337
1338     query_string = talloc_asprintf (message, "thread:%s", tid);
1339     query = notmuch_query_create (notmuch, query_string);
1340     if (query == NULL)
1341         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1342     status = notmuch_query_count_messages (query, &count);
1343     if (status) {
1344         notmuch_query_destroy (query);
1345         return status;
1346     }
1347
1348     if (count > 0) {
1349         /* reintroduce a ghost in its place because there are still
1350          * other active messages in this thread: */
1351         ghost = _notmuch_message_create_for_message_id (notmuch, mid, &private_status);
1352         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1353             private_status = _notmuch_message_initialize_ghost (ghost, tid);
1354             if (! private_status)
1355                 _notmuch_message_sync (ghost);
1356         } else if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1357             /* this is deeply weird, and we should not have gotten
1358              * into this state.  is there a better error message to
1359              * return here? */
1360             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1361         }
1362
1363         notmuch_message_destroy (ghost);
1364         status = COERCE_STATUS (private_status, "Error converting to ghost message");
1365     } else {
1366         /* the thread is empty; drop all ghost messages from it */
1367         notmuch_messages_t *messages;
1368         status = _notmuch_query_search_documents (query,
1369                                                   "ghost",
1370                                                   &messages);
1371         if (status == NOTMUCH_STATUS_SUCCESS) {
1372             notmuch_status_t last_error = NOTMUCH_STATUS_SUCCESS;
1373             while (notmuch_messages_valid (messages)) {
1374                 message = notmuch_messages_get (messages);
1375                 status = _notmuch_message_delete (message);
1376                 if (status) /* we'll report the last failure we see;
1377                                          * if there is more than one failure, we
1378                                          * forget about previous ones */
1379                     last_error = status;
1380                 notmuch_message_destroy (message);
1381                 notmuch_messages_move_to_next (messages);
1382             }
1383             status = last_error;
1384         }
1385     }
1386     notmuch_query_destroy (query);
1387     return status;
1388 }
1389
1390 /* Transform a blank message into a ghost message.  The caller must
1391  * _notmuch_message_sync the message. */
1392 notmuch_private_status_t
1393 _notmuch_message_initialize_ghost (notmuch_message_t *message,
1394                                    const char *thread_id)
1395 {
1396     notmuch_private_status_t status;
1397
1398     status = _notmuch_message_add_term (message, "type", "ghost");
1399     if (status)
1400         return status;
1401     status = _notmuch_message_add_term (message, "thread", thread_id);
1402     if (status)
1403         return status;
1404
1405     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1406 }
1407
1408 /* Ensure that 'message' is not holding any file object open. Future
1409  * calls to various functions will still automatically open the
1410  * message file as needed.
1411  */
1412 void
1413 _notmuch_message_close (notmuch_message_t *message)
1414 {
1415     if (message->message_file) {
1416         _notmuch_message_file_close (message->message_file);
1417         message->message_file = NULL;
1418     }
1419 }
1420
1421 /* Add a name:value term to 'message', (the actual term will be
1422  * encoded by prefixing the value with a short prefix). See
1423  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1424  * names to prefix values.
1425  *
1426  * This change will not be reflected in the database until the next
1427  * call to _notmuch_message_sync. */
1428 notmuch_private_status_t
1429 _notmuch_message_add_term (notmuch_message_t *message,
1430                            const char *prefix_name,
1431                            const char *value)
1432 {
1433
1434     char *term;
1435
1436     if (value == NULL)
1437         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1438
1439     term = talloc_asprintf (message, "%s%s",
1440                             _find_prefix (prefix_name), value);
1441
1442     if (strlen (term) > NOTMUCH_TERM_MAX)
1443         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1444
1445     message->doc.add_term (term, 0);
1446     message->modified = true;
1447
1448     talloc_free (term);
1449
1450     _notmuch_message_invalidate_metadata (message, prefix_name);
1451
1452     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1453 }
1454
1455 /* Parse 'text' and add a term to 'message' for each parsed word. Each
1456  * term will be added with the appropriate prefix if prefix_name is
1457  * non-NULL.
1458  */
1459 notmuch_private_status_t
1460 _notmuch_message_gen_terms (notmuch_message_t *message,
1461                             const char *prefix_name,
1462                             const char *text)
1463 {
1464     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
1465
1466     if (text == NULL)
1467         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1468
1469     term_gen->set_document (message->doc);
1470     term_gen->set_termpos (message->termpos);
1471
1472     if (prefix_name) {
1473         const char *prefix = _notmuch_database_prefix (message->notmuch, prefix_name);
1474         if (prefix == NULL)
1475             return NOTMUCH_PRIVATE_STATUS_BAD_PREFIX;
1476
1477         _notmuch_message_invalidate_metadata (message, prefix_name);
1478         term_gen->index_text (text, 1, prefix);
1479     } else {
1480         term_gen->index_text (text);
1481     }
1482
1483     /* Create a gap between this an the next terms so they don't
1484      * appear to be a phrase. */
1485     message->termpos = term_gen->get_termpos () + 100;
1486
1487     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1488 }
1489
1490 /* Remove a name:value term from 'message', (the actual term will be
1491  * encoded by prefixing the value with a short prefix). See
1492  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1493  * names to prefix values.
1494  *
1495  * This change will not be reflected in the database until the next
1496  * call to _notmuch_message_sync. */
1497 notmuch_private_status_t
1498 _notmuch_message_remove_term (notmuch_message_t *message,
1499                               const char *prefix_name,
1500                               const char *value)
1501 {
1502     char *term;
1503
1504     if (value == NULL)
1505         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1506
1507     term = talloc_asprintf (message, "%s%s",
1508                             _find_prefix (prefix_name), value);
1509
1510     if (strlen (term) > NOTMUCH_TERM_MAX)
1511         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1512
1513     try {
1514         message->doc.remove_term (term);
1515         message->modified = true;
1516     } catch (const Xapian::InvalidArgumentError) {
1517         /* We'll let the philosophers try to wrestle with the
1518          * question of whether failing to remove that which was not
1519          * there in the first place is failure. For us, we'll silently
1520          * consider it all good. */
1521     }
1522
1523     talloc_free (term);
1524
1525     _notmuch_message_invalidate_metadata (message, prefix_name);
1526
1527     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1528 }
1529
1530 notmuch_private_status_t
1531 _notmuch_message_has_term (notmuch_message_t *message,
1532                            const char *prefix_name,
1533                            const char *value,
1534                            bool *result)
1535 {
1536     char *term;
1537     bool out = false;
1538     notmuch_private_status_t status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
1539
1540     if (value == NULL)
1541         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1542
1543     term = talloc_asprintf (message, "%s%s",
1544                             _find_prefix (prefix_name), value);
1545
1546     if (strlen (term) > NOTMUCH_TERM_MAX)
1547         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1548
1549     try {
1550         /* Look for the exact term */
1551         Xapian::TermIterator i = message->doc.termlist_begin ();
1552         i.skip_to (term);
1553         if (i != message->doc.termlist_end () &&
1554             ! strcmp ((*i).c_str (), term))
1555             out = true;
1556     } catch (Xapian::Error &error) {
1557         status = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
1558     }
1559     talloc_free (term);
1560
1561     *result = out;
1562     return status;
1563 }
1564
1565 notmuch_status_t
1566 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
1567 {
1568     notmuch_private_status_t private_status;
1569     notmuch_status_t status;
1570
1571     status = _notmuch_database_ensure_writable (message->notmuch);
1572     if (status)
1573         return status;
1574
1575     if (tag == NULL)
1576         return NOTMUCH_STATUS_NULL_POINTER;
1577
1578     if (strlen (tag) > NOTMUCH_TAG_MAX)
1579         return NOTMUCH_STATUS_TAG_TOO_LONG;
1580
1581     private_status = _notmuch_message_add_term (message, "tag", tag);
1582     if (private_status) {
1583         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
1584                         private_status);
1585     }
1586
1587     if (! message->frozen)
1588         _notmuch_message_sync (message);
1589
1590     return NOTMUCH_STATUS_SUCCESS;
1591 }
1592
1593 notmuch_status_t
1594 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1595 {
1596     notmuch_private_status_t private_status;
1597     notmuch_status_t status;
1598
1599     status = _notmuch_database_ensure_writable (message->notmuch);
1600     if (status)
1601         return status;
1602
1603     if (tag == NULL)
1604         return NOTMUCH_STATUS_NULL_POINTER;
1605
1606     if (strlen (tag) > NOTMUCH_TAG_MAX)
1607         return NOTMUCH_STATUS_TAG_TOO_LONG;
1608
1609     private_status = _notmuch_message_remove_term (message, "tag", tag);
1610     if (private_status) {
1611         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1612                         private_status);
1613     }
1614
1615     if (! message->frozen)
1616         _notmuch_message_sync (message);
1617
1618     return NOTMUCH_STATUS_SUCCESS;
1619 }
1620
1621 /* Is the given filename within a maildir directory?
1622  *
1623  * Specifically, is the final directory component of 'filename' either
1624  * "cur" or "new". If so, return a pointer to that final directory
1625  * component within 'filename'. If not, return NULL.
1626  *
1627  * A non-NULL return value is guaranteed to be a valid string pointer
1628  * pointing to the characters "new/" or "cur/", (but not
1629  * NUL-terminated).
1630  */
1631 static const char *
1632 _filename_is_in_maildir (const char *filename)
1633 {
1634     const char *slash, *dir = NULL;
1635
1636     /* Find the last '/' separating directory from filename. */
1637     slash = strrchr (filename, '/');
1638     if (slash == NULL)
1639         return NULL;
1640
1641     /* Jump back 4 characters to where the previous '/' will be if the
1642      * directory is named "cur" or "new". */
1643     if (slash - filename < 4)
1644         return NULL;
1645
1646     slash -= 4;
1647
1648     if (*slash != '/')
1649         return NULL;
1650
1651     dir = slash + 1;
1652
1653     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1654         STRNCMP_LITERAL (dir, "new/") == 0) {
1655         return dir;
1656     }
1657
1658     return NULL;
1659 }
1660
1661 static void
1662 _ensure_maildir_flags (notmuch_message_t *message, bool force)
1663 {
1664     const char *flags;
1665     notmuch_filenames_t *filenames;
1666     const char *filename, *dir;
1667     char *combined_flags = talloc_strdup (message, "");
1668     int seen_maildir_info = 0;
1669
1670     if (message->maildir_flags) {
1671         if (force) {
1672             talloc_free (message->maildir_flags);
1673             message->maildir_flags = NULL;
1674         }
1675     }
1676
1677     for (filenames = notmuch_message_get_filenames (message);
1678          notmuch_filenames_valid (filenames);
1679          notmuch_filenames_move_to_next (filenames)) {
1680         filename = notmuch_filenames_get (filenames);
1681         dir = _filename_is_in_maildir (filename);
1682
1683         if (! dir)
1684             continue;
1685
1686         flags = strstr (filename, ":2,");
1687         if (flags) {
1688             seen_maildir_info = 1;
1689             flags += 3;
1690             combined_flags = talloc_strdup_append (combined_flags, flags);
1691         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1692             /* Messages are delivered to new/ with no "info" part, but
1693              * they effectively have default maildir flags.  According
1694              * to the spec, we should ignore the info part for
1695              * messages in new/, but some MUAs (mutt) can set maildir
1696              * flags on messages in new/, so we're liberal in what we
1697              * accept. */
1698             seen_maildir_info = 1;
1699         }
1700     }
1701     if (seen_maildir_info)
1702         message->maildir_flags = combined_flags;
1703 }
1704
1705 notmuch_bool_t
1706 notmuch_message_has_maildir_flag (notmuch_message_t *message, char flag)
1707 {
1708     _ensure_maildir_flags (message, false);
1709     return message->maildir_flags && (strchr (message->maildir_flags, flag) != NULL);
1710 }
1711
1712 notmuch_status_t
1713 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1714 {
1715     notmuch_status_t status;
1716     unsigned i;
1717
1718     _ensure_maildir_flags (message, true);
1719     /* If none of the filenames have any maildir info field (not even
1720      * an empty info with no flags set) then there's no information to
1721      * go on, so do nothing. */
1722     if (! message->maildir_flags)
1723         return NOTMUCH_STATUS_SUCCESS;
1724
1725     status = notmuch_message_freeze (message);
1726     if (status)
1727         return status;
1728
1729     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1730         if ((strchr (message->maildir_flags, flag2tag[i].flag) != NULL)
1731             ^
1732             flag2tag[i].inverse) {
1733             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1734         } else {
1735             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1736         }
1737         if (status)
1738             return status;
1739     }
1740     status = notmuch_message_thaw (message);
1741
1742     return status;
1743 }
1744
1745 /* From the set of tags on 'message' and the flag2tag table, compute a
1746  * set of maildir-flag actions to be taken, (flags that should be
1747  * either set or cleared).
1748  *
1749  * The result is returned as two talloced strings: to_set, and to_clear
1750  */
1751 static void
1752 _get_maildir_flag_actions (notmuch_message_t *message,
1753                            char **to_set_ret,
1754                            char **to_clear_ret)
1755 {
1756     char *to_set, *to_clear;
1757     notmuch_tags_t *tags;
1758     const char *tag;
1759     unsigned i;
1760
1761     to_set = talloc_strdup (message, "");
1762     to_clear = talloc_strdup (message, "");
1763
1764     /* First, find flags for all set tags. */
1765     for (tags = notmuch_message_get_tags (message);
1766          notmuch_tags_valid (tags);
1767          notmuch_tags_move_to_next (tags)) {
1768         tag = notmuch_tags_get (tags);
1769
1770         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1771             if (strcmp (tag, flag2tag[i].tag) == 0) {
1772                 if (flag2tag[i].inverse)
1773                     to_clear = talloc_asprintf_append (to_clear,
1774                                                        "%c",
1775                                                        flag2tag[i].flag);
1776                 else
1777                     to_set = talloc_asprintf_append (to_set,
1778                                                      "%c",
1779                                                      flag2tag[i].flag);
1780             }
1781         }
1782     }
1783
1784     /* Then, find the flags for all tags not present. */
1785     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1786         if (flag2tag[i].inverse) {
1787             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1788                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1789         } else {
1790             if (strchr (to_set, flag2tag[i].flag) == NULL)
1791                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1792         }
1793     }
1794
1795     *to_set_ret = to_set;
1796     *to_clear_ret = to_clear;
1797 }
1798
1799 /* Given 'filename' and a set of maildir flags to set and to clear,
1800  * compute the new maildir filename.
1801  *
1802  * If the existing filename is in the directory "new", the new
1803  * filename will be in the directory "cur", except for the case when
1804  * no flags are changed and the existing filename does not contain
1805  * maildir info (starting with ",2:").
1806  *
1807  * After a sequence of ":2," in the filename, any subsequent
1808  * single-character flags will be added or removed according to the
1809  * characters in flags_to_set and flags_to_clear. Any existing flags
1810  * not mentioned in either string will remain. The final list of flags
1811  * will be in ASCII order.
1812  *
1813  * If the original flags seem invalid, (repeated characters or
1814  * non-ASCII ordering of flags), this function will return NULL
1815  * (meaning that renaming would not be safe and should not occur).
1816  */
1817 static char *
1818 _new_maildir_filename (void *ctx,
1819                        const char *filename,
1820                        const char *flags_to_set,
1821                        const char *flags_to_clear)
1822 {
1823     const char *info, *flags;
1824     unsigned int flag, last_flag;
1825     char *filename_new, *dir;
1826     char flag_map[128];
1827     int flags_in_map = 0;
1828     bool flags_changed = false;
1829     unsigned int i;
1830     char *s;
1831
1832     memset (flag_map, 0, sizeof (flag_map));
1833
1834     info = strstr (filename, ":2,");
1835
1836     if (info == NULL) {
1837         info = filename + strlen (filename);
1838     } else {
1839         /* Loop through existing flags in filename. */
1840         for (flags = info + 3, last_flag = 0;
1841              *flags;
1842              last_flag = flag, flags++) {
1843             flag = *flags;
1844
1845             /* Original flags not in ASCII order. Abort. */
1846             if (flag < last_flag)
1847                 return NULL;
1848
1849             /* Non-ASCII flag. Abort. */
1850             if (flag > sizeof (flag_map) - 1)
1851                 return NULL;
1852
1853             /* Repeated flag value. Abort. */
1854             if (flag_map[flag])
1855                 return NULL;
1856
1857             flag_map[flag] = 1;
1858             flags_in_map++;
1859         }
1860     }
1861
1862     /* Then set and clear our flags from tags. */
1863     for (flags = flags_to_set; *flags; flags++) {
1864         flag = *flags;
1865         if (flag_map[flag] == 0) {
1866             flag_map[flag] = 1;
1867             flags_in_map++;
1868             flags_changed = true;
1869         }
1870     }
1871
1872     for (flags = flags_to_clear; *flags; flags++) {
1873         flag = *flags;
1874         if (flag_map[flag]) {
1875             flag_map[flag] = 0;
1876             flags_in_map--;
1877             flags_changed = true;
1878         }
1879     }
1880
1881     /* Messages in new/ without maildir info can be kept in new/ if no
1882      * flags have changed. */
1883     dir = (char *) _filename_is_in_maildir (filename);
1884     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && ! *info && ! flags_changed)
1885         return talloc_strdup (ctx, filename);
1886
1887     filename_new = (char *) talloc_size (ctx,
1888                                          info - filename +
1889                                          strlen (":2,") + flags_in_map + 1);
1890     if (unlikely (filename_new == NULL))
1891         return NULL;
1892
1893     strncpy (filename_new, filename, info - filename);
1894     filename_new[info - filename] = '\0';
1895
1896     strcat (filename_new, ":2,");
1897
1898     s = filename_new + strlen (filename_new);
1899     for (i = 0; i < sizeof (flag_map); i++) {
1900         if (flag_map[i]) {
1901             *s = i;
1902             s++;
1903         }
1904     }
1905     *s = '\0';
1906
1907     /* If message is in new/ move it under cur/. */
1908     dir = (char *) _filename_is_in_maildir (filename_new);
1909     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1910         memcpy (dir, "cur/", 4);
1911
1912     return filename_new;
1913 }
1914
1915 notmuch_status_t
1916 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1917 {
1918     notmuch_filenames_t *filenames;
1919     const char *filename;
1920     char *filename_new;
1921     char *to_set, *to_clear;
1922     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1923
1924     _get_maildir_flag_actions (message, &to_set, &to_clear);
1925
1926     for (filenames = notmuch_message_get_filenames (message);
1927          notmuch_filenames_valid (filenames);
1928          notmuch_filenames_move_to_next (filenames)) {
1929         filename = notmuch_filenames_get (filenames);
1930
1931         if (! _filename_is_in_maildir (filename))
1932             continue;
1933
1934         filename_new = _new_maildir_filename (message, filename,
1935                                               to_set, to_clear);
1936         if (filename_new == NULL)
1937             continue;
1938
1939         if (strcmp (filename, filename_new)) {
1940             int err;
1941             notmuch_status_t new_status;
1942
1943             err = rename (filename, filename_new);
1944             if (err)
1945                 continue;
1946
1947             new_status = _notmuch_message_remove_filename (message,
1948                                                            filename);
1949             /* Hold on to only the first error. */
1950             if (! status && new_status
1951                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
1952                 status = new_status;
1953                 continue;
1954             }
1955
1956             new_status = _notmuch_message_add_filename (message,
1957                                                         filename_new);
1958             /* Hold on to only the first error. */
1959             if (! status && new_status) {
1960                 status = new_status;
1961                 continue;
1962             }
1963
1964             _notmuch_message_sync (message);
1965         }
1966
1967         talloc_free (filename_new);
1968     }
1969
1970     talloc_free (to_set);
1971     talloc_free (to_clear);
1972
1973     return status;
1974 }
1975
1976 notmuch_status_t
1977 notmuch_message_remove_all_tags (notmuch_message_t *message)
1978 {
1979     notmuch_private_status_t private_status;
1980     notmuch_status_t status;
1981     notmuch_tags_t *tags;
1982     const char *tag;
1983
1984     status = _notmuch_database_ensure_writable (message->notmuch);
1985     if (status)
1986         return status;
1987
1988     for (tags = notmuch_message_get_tags (message);
1989          notmuch_tags_valid (tags);
1990          notmuch_tags_move_to_next (tags)) {
1991         tag = notmuch_tags_get (tags);
1992
1993         private_status = _notmuch_message_remove_term (message, "tag", tag);
1994         if (private_status) {
1995             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1996                             private_status);
1997         }
1998     }
1999
2000     if (! message->frozen)
2001         _notmuch_message_sync (message);
2002
2003     talloc_free (tags);
2004     return NOTMUCH_STATUS_SUCCESS;
2005 }
2006
2007 notmuch_status_t
2008 notmuch_message_freeze (notmuch_message_t *message)
2009 {
2010     notmuch_status_t status;
2011
2012     status = _notmuch_database_ensure_writable (message->notmuch);
2013     if (status)
2014         return status;
2015
2016     message->frozen++;
2017
2018     return NOTMUCH_STATUS_SUCCESS;
2019 }
2020
2021 notmuch_status_t
2022 notmuch_message_thaw (notmuch_message_t *message)
2023 {
2024     notmuch_status_t status;
2025
2026     status = _notmuch_database_ensure_writable (message->notmuch);
2027     if (status)
2028         return status;
2029
2030     if (message->frozen > 0) {
2031         message->frozen--;
2032         if (message->frozen == 0)
2033             _notmuch_message_sync (message);
2034         return NOTMUCH_STATUS_SUCCESS;
2035     } else {
2036         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
2037     }
2038 }
2039
2040 void
2041 notmuch_message_destroy (notmuch_message_t *message)
2042 {
2043     talloc_free (message);
2044 }
2045
2046 notmuch_database_t *
2047 notmuch_message_get_database (const notmuch_message_t *message)
2048 {
2049     return message->notmuch;
2050 }
2051
2052 static void
2053 _notmuch_message_ensure_property_map (notmuch_message_t *message)
2054 {
2055     notmuch_string_node_t *node;
2056
2057     if (message->property_map)
2058         return;
2059
2060     _notmuch_message_ensure_metadata (message, message->property_term_list);
2061
2062     message->property_map = _notmuch_string_map_create (message);
2063
2064     for (node = message->property_term_list->head; node; node = node->next) {
2065         const char *key;
2066         char *value;
2067
2068         value = strchr (node->string, '=');
2069         if (! value)
2070             INTERNAL_ERROR ("malformed property term");
2071
2072         *value = '\0';
2073         value++;
2074         key = node->string;
2075
2076         _notmuch_string_map_append (message->property_map, key, value);
2077
2078     }
2079
2080     talloc_free (message->property_term_list);
2081     message->property_term_list = NULL;
2082 }
2083
2084 notmuch_string_map_t *
2085 _notmuch_message_property_map (notmuch_message_t *message)
2086 {
2087     _notmuch_message_ensure_property_map (message);
2088
2089     return message->property_map;
2090 }
2091
2092 bool
2093 _notmuch_message_frozen (notmuch_message_t *message)
2094 {
2095     return message->frozen;
2096 }
2097
2098 notmuch_status_t
2099 notmuch_message_reindex (notmuch_message_t *message,
2100                          notmuch_indexopts_t *indexopts)
2101 {
2102     notmuch_database_t *notmuch = NULL;
2103     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2104     notmuch_private_status_t private_status;
2105     notmuch_filenames_t *orig_filenames = NULL;
2106     const char *orig_thread_id = NULL;
2107     notmuch_message_file_t *message_file = NULL;
2108
2109     int found = 0;
2110
2111     if (message == NULL)
2112         return NOTMUCH_STATUS_NULL_POINTER;
2113
2114     /* Save in case we need to delete message */
2115     orig_thread_id = notmuch_message_get_thread_id (message);
2116     if (! orig_thread_id) {
2117         /* XXX TODO: make up new error return? */
2118         INTERNAL_ERROR ("message without thread-id");
2119     }
2120
2121     /* strdup it because the metadata may be invalidated */
2122     orig_thread_id = talloc_strdup (message, orig_thread_id);
2123
2124     notmuch = notmuch_message_get_database (message);
2125
2126     ret = _notmuch_database_ensure_writable (notmuch);
2127     if (ret)
2128         return ret;
2129
2130     orig_filenames = notmuch_message_get_filenames (message);
2131
2132     private_status = _notmuch_message_remove_indexed_terms (message);
2133     if (private_status) {
2134         ret = COERCE_STATUS (private_status, "error removing terms");
2135         goto DONE;
2136     }
2137
2138     ret = notmuch_message_remove_all_properties_with_prefix (message, "index.");
2139     if (ret)
2140         goto DONE; /* XXX TODO: distinguish from other error returns above? */
2141     if (indexopts && notmuch_indexopts_get_decrypt_policy (indexopts) == NOTMUCH_DECRYPT_FALSE) {
2142         ret = notmuch_message_remove_all_properties (message, "session-key");
2143         if (ret)
2144             goto DONE;
2145     }
2146
2147     /* re-add the filenames with the associated indexopts */
2148     for (; notmuch_filenames_valid (orig_filenames);
2149          notmuch_filenames_move_to_next (orig_filenames)) {
2150
2151         const char *date;
2152         const char *from, *to, *subject;
2153         char *message_id = NULL;
2154         const char *thread_id = NULL;
2155
2156         const char *filename = notmuch_filenames_get (orig_filenames);
2157
2158         message_file = _notmuch_message_file_open (notmuch, filename);
2159         if (message_file == NULL)
2160             continue;
2161
2162         ret = _notmuch_message_file_get_headers (message_file,
2163                                                  &from, &subject, &to, &date,
2164                                                  &message_id);
2165         if (ret)
2166             goto DONE;
2167
2168         /* XXX TODO: deal with changing message id? */
2169
2170         _notmuch_message_add_filename (message, filename);
2171
2172         ret = _notmuch_database_link_message_to_parents (notmuch, message,
2173                                                          message_file,
2174                                                          &thread_id);
2175         if (ret)
2176             goto DONE;
2177
2178         if (thread_id == NULL)
2179             thread_id = orig_thread_id;
2180
2181         _notmuch_message_add_term (message, "thread", thread_id);
2182         /* Take header values only from first filename */
2183         if (found == 0)
2184             _notmuch_message_set_header_values (message, date, from, subject);
2185
2186         ret = _notmuch_message_index_file (message, indexopts, message_file);
2187
2188         if (ret == NOTMUCH_STATUS_FILE_ERROR)
2189             continue;
2190         if (ret)
2191             goto DONE;
2192
2193         found++;
2194         _notmuch_message_file_close (message_file);
2195         message_file = NULL;
2196     }
2197     if (found == 0) {
2198         /* put back thread id to help cleanup */
2199         _notmuch_message_add_term (message, "thread", orig_thread_id);
2200         ret = _notmuch_message_delete (message);
2201     } else {
2202         _notmuch_message_sync (message);
2203     }
2204
2205   DONE:
2206     if (message_file)
2207         _notmuch_message_file_close (message_file);
2208
2209     /* XXX TODO destroy orig_filenames? */
2210     return ret;
2211 }