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