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