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