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