]> git.cworth.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 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
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,
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 static 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;
1360     notmuch_message_t *ghost;
1361     notmuch_private_status_t private_status;
1362     notmuch_database_t *notmuch;
1363     unsigned int count = 0;
1364     bool is_ghost;
1365
1366     mid = notmuch_message_get_message_id (message);
1367     tid = notmuch_message_get_thread_id (message);
1368     notmuch = message->notmuch;
1369
1370     status = _notmuch_database_ensure_writable (message->notmuch);
1371     if (status)
1372         return status;
1373
1374     message->notmuch->writable_xapian_db->delete_document (message->doc_id);
1375
1376     /* if this was a ghost to begin with, we are done */
1377     private_status = _notmuch_message_has_term (message, "type", "ghost", &is_ghost);
1378     if (private_status)
1379         return COERCE_STATUS (private_status,
1380                               "Error trying to determine whether message was a ghost");
1381     if (is_ghost)
1382         return NOTMUCH_STATUS_SUCCESS;
1383
1384     /* look for a non-ghost message in the same thread */
1385     try {
1386         Xapian::PostingIterator thread_doc, thread_doc_end;
1387         Xapian::PostingIterator mail_doc, mail_doc_end;
1388
1389         _notmuch_database_find_doc_ids (message->notmuch, "thread", tid, &thread_doc,
1390                                         &thread_doc_end);
1391         _notmuch_database_find_doc_ids (message->notmuch, "type", "mail", &mail_doc, &mail_doc_end);
1392
1393         while (count == 0 &&
1394                thread_doc != thread_doc_end &&
1395                mail_doc != mail_doc_end) {
1396             thread_doc.skip_to (*mail_doc);
1397             if (thread_doc != thread_doc_end) {
1398                 if (*thread_doc == *mail_doc) {
1399                     count++;
1400                 } else {
1401                     mail_doc.skip_to (*thread_doc);
1402                     if (mail_doc != mail_doc_end && *thread_doc == *mail_doc)
1403                         count++;
1404                 }
1405             }
1406         }
1407     } catch (Xapian::Error &error) {
1408         LOG_XAPIAN_EXCEPTION (message, error);
1409         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1410     }
1411     if (count > 0) {
1412         /* reintroduce a ghost in its place because there are still
1413          * other active messages in this thread: */
1414         ghost = _notmuch_message_create_for_message_id (notmuch, mid, &private_status);
1415         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1416             private_status = _notmuch_message_initialize_ghost (ghost, tid);
1417             if (! private_status)
1418                 _notmuch_message_sync (ghost);
1419         } else if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1420             /* this is deeply weird, and we should not have gotten
1421              * into this state.  is there a better error message to
1422              * return here? */
1423             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1424         }
1425
1426         notmuch_message_destroy (ghost);
1427         status = COERCE_STATUS (private_status, "Error converting to ghost message");
1428     } else {
1429         /* the thread now contains only ghosts: delete them */
1430         try {
1431             Xapian::PostingIterator doc, doc_end;
1432
1433             _notmuch_database_find_doc_ids (message->notmuch, "thread", tid, &doc, &doc_end);
1434
1435             for (; doc != doc_end; doc++) {
1436                 message->notmuch->writable_xapian_db->delete_document (*doc);
1437             }
1438         } catch (Xapian::Error &error) {
1439             LOG_XAPIAN_EXCEPTION (message, error);
1440             return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1441         }
1442
1443     }
1444     return status;
1445 }
1446
1447 /* Transform a blank message into a ghost message.  The caller must
1448  * _notmuch_message_sync the message. */
1449 notmuch_private_status_t
1450 _notmuch_message_initialize_ghost (notmuch_message_t *message,
1451                                    const char *thread_id)
1452 {
1453     notmuch_private_status_t status;
1454
1455     status = _notmuch_message_add_term (message, "type", "ghost");
1456     if (status)
1457         return status;
1458     status = _notmuch_message_add_term (message, "thread", thread_id);
1459     if (status)
1460         return status;
1461
1462     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1463 }
1464
1465 /* Ensure that 'message' is not holding any file object open. Future
1466  * calls to various functions will still automatically open the
1467  * message file as needed.
1468  */
1469 void
1470 _notmuch_message_close (notmuch_message_t *message)
1471 {
1472     if (message->message_file) {
1473         _notmuch_message_file_close (message->message_file);
1474         message->message_file = NULL;
1475     }
1476 }
1477
1478 /* Add a name:value term to 'message', (the actual term will be
1479  * encoded by prefixing the value with a short prefix). See
1480  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1481  * names to prefix values.
1482  *
1483  * This change will not be reflected in the database until the next
1484  * call to _notmuch_message_sync. */
1485 notmuch_private_status_t
1486 _notmuch_message_add_term (notmuch_message_t *message,
1487                            const char *prefix_name,
1488                            const char *value)
1489 {
1490
1491     char *term;
1492
1493     if (value == NULL)
1494         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1495
1496     term = talloc_asprintf (message, "%s%s",
1497                             _find_prefix (prefix_name), value);
1498
1499     if (strlen (term) > NOTMUCH_TERM_MAX)
1500         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1501
1502     message->doc.add_term (term, 0);
1503     message->modified = true;
1504
1505     talloc_free (term);
1506
1507     _notmuch_message_invalidate_metadata (message, prefix_name);
1508
1509     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1510 }
1511
1512 /* Parse 'text' and add a term to 'message' for each parsed word. Each
1513  * term will be added with the appropriate prefix if prefix_name is
1514  * non-NULL.
1515  */
1516 notmuch_private_status_t
1517 _notmuch_message_gen_terms (notmuch_message_t *message,
1518                             const char *prefix_name,
1519                             const char *text)
1520 {
1521     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
1522
1523     if (text == NULL)
1524         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1525
1526     term_gen->set_document (message->doc);
1527     term_gen->set_termpos (message->termpos);
1528
1529     if (prefix_name) {
1530         const char *prefix = _notmuch_database_prefix (message->notmuch, prefix_name);
1531         if (prefix == NULL)
1532             return NOTMUCH_PRIVATE_STATUS_BAD_PREFIX;
1533
1534         _notmuch_message_invalidate_metadata (message, prefix_name);
1535         term_gen->index_text (text, 1, prefix);
1536     } else {
1537         term_gen->index_text (text);
1538     }
1539
1540     /* Create a gap between this an the next terms so they don't
1541      * appear to be a phrase. */
1542     message->termpos = term_gen->get_termpos () + 100;
1543
1544     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1545 }
1546
1547 /* Remove a name:value term from 'message', (the actual term will be
1548  * encoded by prefixing the value with a short prefix). See
1549  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1550  * names to prefix values.
1551  *
1552  * This change will not be reflected in the database until the next
1553  * call to _notmuch_message_sync. */
1554 notmuch_private_status_t
1555 _notmuch_message_remove_term (notmuch_message_t *message,
1556                               const char *prefix_name,
1557                               const char *value)
1558 {
1559     char *term;
1560
1561     if (value == NULL)
1562         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1563
1564     term = talloc_asprintf (message, "%s%s",
1565                             _find_prefix (prefix_name), value);
1566
1567     if (strlen (term) > NOTMUCH_TERM_MAX)
1568         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1569
1570     try {
1571         message->doc.remove_term (term);
1572         message->modified = true;
1573     } catch (const Xapian::InvalidArgumentError) {
1574         /* We'll let the philosophers try to wrestle with the
1575          * question of whether failing to remove that which was not
1576          * there in the first place is failure. For us, we'll silently
1577          * consider it all good. */
1578     }
1579
1580     talloc_free (term);
1581
1582     _notmuch_message_invalidate_metadata (message, prefix_name);
1583
1584     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1585 }
1586
1587 notmuch_private_status_t
1588 _notmuch_message_has_term (notmuch_message_t *message,
1589                            const char *prefix_name,
1590                            const char *value,
1591                            bool *result)
1592 {
1593     char *term;
1594     bool out = false;
1595     notmuch_private_status_t status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
1596
1597     if (value == NULL)
1598         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1599
1600     term = talloc_asprintf (message, "%s%s",
1601                             _find_prefix (prefix_name), value);
1602
1603     if (strlen (term) > NOTMUCH_TERM_MAX)
1604         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1605
1606     try {
1607         /* Look for the exact term */
1608         Xapian::TermIterator i = message->doc.termlist_begin ();
1609         i.skip_to (term);
1610         if (i != message->doc.termlist_end () &&
1611             ! strcmp ((*i).c_str (), term))
1612             out = true;
1613     } catch (Xapian::Error &error) {
1614         status = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
1615     }
1616     talloc_free (term);
1617
1618     *result = out;
1619     return status;
1620 }
1621
1622 notmuch_status_t
1623 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
1624 {
1625     notmuch_private_status_t private_status;
1626     notmuch_status_t status;
1627
1628     try {
1629         status = _notmuch_database_ensure_writable (message->notmuch);
1630         if (status)
1631             return status;
1632
1633         if (tag == NULL)
1634             return NOTMUCH_STATUS_NULL_POINTER;
1635
1636         if (strlen (tag) > NOTMUCH_TAG_MAX)
1637             return NOTMUCH_STATUS_TAG_TOO_LONG;
1638
1639         private_status = _notmuch_message_add_term (message, "tag", tag);
1640         if (private_status) {
1641             return COERCE_STATUS (private_status,
1642                                   "_notmuch_message_remove_term return unexpected value: %d\n",
1643                                   private_status);
1644         }
1645
1646         if (! message->frozen)
1647             _notmuch_message_sync (message);
1648
1649     } catch (Xapian::Error &error) {
1650         LOG_XAPIAN_EXCEPTION (message, error);
1651         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1652     }
1653
1654     return NOTMUCH_STATUS_SUCCESS;
1655 }
1656
1657 notmuch_status_t
1658 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1659 {
1660     notmuch_private_status_t private_status;
1661     notmuch_status_t status;
1662
1663     try {
1664         status = _notmuch_database_ensure_writable (message->notmuch);
1665         if (status)
1666             return status;
1667
1668         if (tag == NULL)
1669             return NOTMUCH_STATUS_NULL_POINTER;
1670
1671         if (strlen (tag) > NOTMUCH_TAG_MAX)
1672             return NOTMUCH_STATUS_TAG_TOO_LONG;
1673
1674         private_status = _notmuch_message_remove_term (message, "tag", tag);
1675         if (private_status) {
1676             return COERCE_STATUS (private_status,
1677                                   "_notmuch_message_remove_term return unexpected value: %d\n",
1678                                   private_status);
1679         }
1680
1681         if (! message->frozen)
1682             _notmuch_message_sync (message);
1683     } catch (Xapian::Error &error) {
1684         LOG_XAPIAN_EXCEPTION (message, error);
1685         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1686     }
1687
1688     return NOTMUCH_STATUS_SUCCESS;
1689 }
1690
1691 /* Is the given filename within a maildir directory?
1692  *
1693  * Specifically, is the final directory component of 'filename' either
1694  * "cur" or "new". If so, return a pointer to that final directory
1695  * component within 'filename'. If not, return NULL.
1696  *
1697  * A non-NULL return value is guaranteed to be a valid string pointer
1698  * pointing to the characters "new/" or "cur/", (but not
1699  * NUL-terminated).
1700  */
1701 static const char *
1702 _filename_is_in_maildir (const char *filename)
1703 {
1704     const char *slash, *dir = NULL;
1705
1706     /* Find the last '/' separating directory from filename. */
1707     slash = strrchr (filename, '/');
1708     if (slash == NULL)
1709         return NULL;
1710
1711     /* Jump back 4 characters to where the previous '/' will be if the
1712      * directory is named "cur" or "new". */
1713     if (slash - filename < 4)
1714         return NULL;
1715
1716     slash -= 4;
1717
1718     if (*slash != '/')
1719         return NULL;
1720
1721     dir = slash + 1;
1722
1723     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1724         STRNCMP_LITERAL (dir, "new/") == 0) {
1725         return dir;
1726     }
1727
1728     return NULL;
1729 }
1730
1731 static notmuch_status_t
1732 _ensure_maildir_flags (notmuch_message_t *message, bool force)
1733 {
1734     const char *flags;
1735     notmuch_filenames_t *filenames;
1736     const char *filename, *dir;
1737     char *combined_flags = talloc_strdup (message, "");
1738     int seen_maildir_info = 0;
1739
1740     if (message->maildir_flags) {
1741         if (force) {
1742             talloc_free (message->maildir_flags);
1743             message->maildir_flags = NULL;
1744         }
1745     }
1746     filenames = notmuch_message_get_filenames (message);
1747     if (! filenames)
1748         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1749     for (;
1750          notmuch_filenames_valid (filenames);
1751          notmuch_filenames_move_to_next (filenames)) {
1752         filename = notmuch_filenames_get (filenames);
1753         dir = _filename_is_in_maildir (filename);
1754
1755         if (! dir)
1756             continue;
1757
1758         flags = strstr (filename, ":2,");
1759         if (flags) {
1760             seen_maildir_info = 1;
1761             flags += 3;
1762             combined_flags = talloc_strdup_append (combined_flags, flags);
1763         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1764             /* Messages are delivered to new/ with no "info" part, but
1765              * they effectively have default maildir flags.  According
1766              * to the spec, we should ignore the info part for
1767              * messages in new/, but some MUAs (mutt) can set maildir
1768              * flags on messages in new/, so we're liberal in what we
1769              * accept. */
1770             seen_maildir_info = 1;
1771         }
1772     }
1773     if (seen_maildir_info)
1774         message->maildir_flags = combined_flags;
1775     return NOTMUCH_STATUS_SUCCESS;
1776 }
1777
1778 notmuch_bool_t
1779 notmuch_message_has_maildir_flag (notmuch_message_t *message, char flag)
1780 {
1781     notmuch_status_t status;
1782     notmuch_bool_t ret;
1783
1784     status = notmuch_message_has_maildir_flag_st (message, flag, &ret);
1785     if (status)
1786         return FALSE;
1787
1788     return ret;
1789 }
1790
1791 notmuch_status_t
1792 notmuch_message_has_maildir_flag_st (notmuch_message_t *message,
1793                                      char flag,
1794                                      notmuch_bool_t *is_set)
1795 {
1796     notmuch_status_t status;
1797
1798     if (! is_set)
1799         return NOTMUCH_STATUS_NULL_POINTER;
1800
1801     status = _ensure_maildir_flags (message, false);
1802     if (status)
1803         return status;
1804
1805     *is_set =  message->maildir_flags && (strchr (message->maildir_flags, flag) != NULL);
1806     return NOTMUCH_STATUS_SUCCESS;
1807 }
1808
1809 notmuch_status_t
1810 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1811 {
1812     notmuch_status_t status;
1813     unsigned i;
1814
1815     status = _ensure_maildir_flags (message, true);
1816     if (status)
1817         return status;
1818     /* If none of the filenames have any maildir info field (not even
1819      * an empty info with no flags set) then there's no information to
1820      * go on, so do nothing. */
1821     if (! message->maildir_flags)
1822         return NOTMUCH_STATUS_SUCCESS;
1823
1824     status = notmuch_message_freeze (message);
1825     if (status)
1826         return status;
1827
1828     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1829         if ((strchr (message->maildir_flags, flag2tag[i].flag) != NULL)
1830             ^
1831             flag2tag[i].inverse) {
1832             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1833         } else {
1834             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1835         }
1836         if (status)
1837             return status;
1838     }
1839     status = notmuch_message_thaw (message);
1840
1841     return status;
1842 }
1843
1844 /* From the set of tags on 'message' and the flag2tag table, compute a
1845  * set of maildir-flag actions to be taken, (flags that should be
1846  * either set or cleared).
1847  *
1848  * The result is returned as two talloced strings: to_set, and to_clear
1849  */
1850 static void
1851 _get_maildir_flag_actions (notmuch_message_t *message,
1852                            char **to_set_ret,
1853                            char **to_clear_ret)
1854 {
1855     char *to_set, *to_clear;
1856     notmuch_tags_t *tags;
1857     const char *tag;
1858     unsigned i;
1859
1860     to_set = talloc_strdup (message, "");
1861     to_clear = talloc_strdup (message, "");
1862
1863     /* First, find flags for all set tags. */
1864     for (tags = notmuch_message_get_tags (message);
1865          notmuch_tags_valid (tags);
1866          notmuch_tags_move_to_next (tags)) {
1867         tag = notmuch_tags_get (tags);
1868
1869         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1870             if (strcmp (tag, flag2tag[i].tag) == 0) {
1871                 if (flag2tag[i].inverse)
1872                     to_clear = talloc_asprintf_append (to_clear,
1873                                                        "%c",
1874                                                        flag2tag[i].flag);
1875                 else
1876                     to_set = talloc_asprintf_append (to_set,
1877                                                      "%c",
1878                                                      flag2tag[i].flag);
1879             }
1880         }
1881     }
1882
1883     /* Then, find the flags for all tags not present. */
1884     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1885         if (flag2tag[i].inverse) {
1886             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1887                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1888         } else {
1889             if (strchr (to_set, flag2tag[i].flag) == NULL)
1890                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1891         }
1892     }
1893
1894     *to_set_ret = to_set;
1895     *to_clear_ret = to_clear;
1896 }
1897
1898 /* Given 'filename' and a set of maildir flags to set and to clear,
1899  * compute the new maildir filename.
1900  *
1901  * If the existing filename is in the directory "new", the new
1902  * filename will be in the directory "cur", except for the case when
1903  * no flags are changed and the existing filename does not contain
1904  * maildir info (starting with ",2:").
1905  *
1906  * After a sequence of ":2," in the filename, any subsequent
1907  * single-character flags will be added or removed according to the
1908  * characters in flags_to_set and flags_to_clear. Any existing flags
1909  * not mentioned in either string will remain. The final list of flags
1910  * will be in ASCII order.
1911  *
1912  * If the original flags seem invalid, (repeated characters or
1913  * non-ASCII ordering of flags), this function will return NULL
1914  * (meaning that renaming would not be safe and should not occur).
1915  */
1916 static char *
1917 _new_maildir_filename (void *ctx,
1918                        const char *filename,
1919                        const char *flags_to_set,
1920                        const char *flags_to_clear)
1921 {
1922     const char *info, *flags;
1923     unsigned int flag, last_flag;
1924     char *filename_new, *dir;
1925     char flag_map[128];
1926     int flags_in_map = 0;
1927     bool flags_changed = false;
1928     unsigned int i;
1929     char *s;
1930
1931     memset (flag_map, 0, sizeof (flag_map));
1932
1933     info = strstr (filename, ":2,");
1934
1935     if (info == NULL) {
1936         info = filename + strlen (filename);
1937     } else {
1938         /* Loop through existing flags in filename. */
1939         for (flags = info + 3, last_flag = 0;
1940              *flags;
1941              last_flag = flag, flags++) {
1942             flag = *flags;
1943
1944             /* Original flags not in ASCII order. Abort. */
1945             if (flag < last_flag)
1946                 return NULL;
1947
1948             /* Non-ASCII flag. Abort. */
1949             if (flag > sizeof (flag_map) - 1)
1950                 return NULL;
1951
1952             /* Repeated flag value. Abort. */
1953             if (flag_map[flag])
1954                 return NULL;
1955
1956             flag_map[flag] = 1;
1957             flags_in_map++;
1958         }
1959     }
1960
1961     /* Then set and clear our flags from tags. */
1962     for (flags = flags_to_set; *flags; flags++) {
1963         flag = *flags;
1964         if (flag_map[flag] == 0) {
1965             flag_map[flag] = 1;
1966             flags_in_map++;
1967             flags_changed = true;
1968         }
1969     }
1970
1971     for (flags = flags_to_clear; *flags; flags++) {
1972         flag = *flags;
1973         if (flag_map[flag]) {
1974             flag_map[flag] = 0;
1975             flags_in_map--;
1976             flags_changed = true;
1977         }
1978     }
1979
1980     /* Messages in new/ without maildir info can be kept in new/ if no
1981      * flags have changed. */
1982     dir = (char *) _filename_is_in_maildir (filename);
1983     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && ! *info && ! flags_changed)
1984         return talloc_strdup (ctx, filename);
1985
1986     filename_new = (char *) talloc_size (ctx,
1987                                          info - filename +
1988                                          strlen (":2,") + flags_in_map + 1);
1989     if (unlikely (filename_new == NULL))
1990         return NULL;
1991
1992     strncpy (filename_new, filename, info - filename);
1993     filename_new[info - filename] = '\0';
1994
1995     strcat (filename_new, ":2,");
1996
1997     s = filename_new + strlen (filename_new);
1998     for (i = 0; i < sizeof (flag_map); i++) {
1999         if (flag_map[i]) {
2000             *s = i;
2001             s++;
2002         }
2003     }
2004     *s = '\0';
2005
2006     /* If message is in new/ move it under cur/. */
2007     dir = (char *) _filename_is_in_maildir (filename_new);
2008     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
2009         memcpy (dir, "cur/", 4);
2010
2011     return filename_new;
2012 }
2013
2014 notmuch_status_t
2015 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
2016 {
2017     notmuch_filenames_t *filenames;
2018     const char *filename;
2019     char *filename_new;
2020     char *to_set, *to_clear;
2021     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
2022
2023     _get_maildir_flag_actions (message, &to_set, &to_clear);
2024
2025     for (filenames = notmuch_message_get_filenames (message);
2026          notmuch_filenames_valid (filenames);
2027          notmuch_filenames_move_to_next (filenames)) {
2028         filename = notmuch_filenames_get (filenames);
2029
2030         if (! _filename_is_in_maildir (filename))
2031             continue;
2032
2033         filename_new = _new_maildir_filename (message, filename,
2034                                               to_set, to_clear);
2035         if (filename_new == NULL)
2036             continue;
2037
2038         if (strcmp (filename, filename_new)) {
2039             int err;
2040             notmuch_status_t new_status;
2041
2042             err = rename (filename, filename_new);
2043             if (err)
2044                 continue;
2045
2046             new_status = _notmuch_message_remove_filename (message,
2047                                                            filename);
2048             /* Hold on to only the first error. */
2049             if (! status && new_status
2050                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
2051                 status = new_status;
2052                 continue;
2053             }
2054
2055             new_status = _notmuch_message_add_filename (message,
2056                                                         filename_new);
2057             /* Hold on to only the first error. */
2058             if (! status && new_status) {
2059                 status = new_status;
2060                 continue;
2061             }
2062
2063             _notmuch_message_sync (message);
2064         }
2065
2066         talloc_free (filename_new);
2067     }
2068
2069     talloc_free (to_set);
2070     talloc_free (to_clear);
2071
2072     return status;
2073 }
2074
2075 notmuch_status_t
2076 notmuch_message_remove_all_tags (notmuch_message_t *message)
2077 {
2078     notmuch_private_status_t private_status;
2079     notmuch_status_t status;
2080     notmuch_tags_t *tags;
2081     const char *tag;
2082
2083     status = _notmuch_database_ensure_writable (message->notmuch);
2084     if (status)
2085         return status;
2086     tags = notmuch_message_get_tags (message);
2087     if (! tags)
2088         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2089
2090     for (;
2091          notmuch_tags_valid (tags);
2092          notmuch_tags_move_to_next (tags)) {
2093         tag = notmuch_tags_get (tags);
2094
2095         private_status = _notmuch_message_remove_term (message, "tag", tag);
2096         if (private_status) {
2097             return COERCE_STATUS (private_status,
2098                                   "_notmuch_message_remove_term return unexpected value: %d\n",
2099                                   private_status);
2100         }
2101     }
2102
2103     if (! message->frozen)
2104         _notmuch_message_sync (message);
2105
2106     talloc_free (tags);
2107     return NOTMUCH_STATUS_SUCCESS;
2108 }
2109
2110 notmuch_status_t
2111 notmuch_message_freeze (notmuch_message_t *message)
2112 {
2113     notmuch_status_t status;
2114
2115     status = _notmuch_database_ensure_writable (message->notmuch);
2116     if (status)
2117         return status;
2118
2119     message->frozen++;
2120
2121     return NOTMUCH_STATUS_SUCCESS;
2122 }
2123
2124 notmuch_status_t
2125 notmuch_message_thaw (notmuch_message_t *message)
2126 {
2127     notmuch_status_t status;
2128
2129     status = _notmuch_database_ensure_writable (message->notmuch);
2130     if (status)
2131         return status;
2132
2133     if (message->frozen > 0) {
2134         message->frozen--;
2135         if (message->frozen == 0)
2136             _notmuch_message_sync (message);
2137         return NOTMUCH_STATUS_SUCCESS;
2138     } else {
2139         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
2140     }
2141 }
2142
2143 void
2144 notmuch_message_destroy (notmuch_message_t *message)
2145 {
2146     talloc_free (message);
2147 }
2148
2149 notmuch_database_t *
2150 notmuch_message_get_database (const notmuch_message_t *message)
2151 {
2152     return message->notmuch;
2153 }
2154
2155 static void
2156 _notmuch_message_ensure_property_map (notmuch_message_t *message)
2157 {
2158     notmuch_string_node_t *node;
2159
2160     if (message->property_map)
2161         return;
2162
2163     _notmuch_message_ensure_metadata (message, message->property_term_list);
2164
2165     message->property_map = _notmuch_string_map_create (message);
2166
2167     for (node = message->property_term_list->head; node; node = node->next) {
2168         const char *key;
2169         char *value;
2170
2171         value = strchr (node->string, '=');
2172         if (! value)
2173             INTERNAL_ERROR ("malformed property term");
2174
2175         *value = '\0';
2176         value++;
2177         key = node->string;
2178
2179         _notmuch_string_map_append (message->property_map, key, value);
2180
2181     }
2182
2183     talloc_free (message->property_term_list);
2184     message->property_term_list = NULL;
2185 }
2186
2187 notmuch_string_map_t *
2188 _notmuch_message_property_map (notmuch_message_t *message)
2189 {
2190     _notmuch_message_ensure_property_map (message);
2191
2192     return message->property_map;
2193 }
2194
2195 bool
2196 _notmuch_message_frozen (notmuch_message_t *message)
2197 {
2198     return message->frozen;
2199 }
2200
2201 notmuch_status_t
2202 notmuch_message_reindex (notmuch_message_t *message,
2203                          notmuch_indexopts_t *indexopts)
2204 {
2205     notmuch_database_t *notmuch = NULL;
2206     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
2207     notmuch_private_status_t private_status;
2208     notmuch_filenames_t *orig_filenames = NULL;
2209     const char *orig_thread_id = NULL;
2210     notmuch_message_file_t *message_file = NULL;
2211
2212     int found = 0;
2213
2214     if (message == NULL)
2215         return NOTMUCH_STATUS_NULL_POINTER;
2216
2217     /* Save in case we need to delete message */
2218     orig_thread_id = notmuch_message_get_thread_id (message);
2219     if (! orig_thread_id) {
2220         /* the following is correct as long as there is only one reason
2221          * n_m_get_thread_id returns NULL
2222          */
2223         return NOTMUCH_STATUS_XAPIAN_EXCEPTION;
2224     }
2225
2226     /* strdup it because the metadata may be invalidated */
2227     orig_thread_id = talloc_strdup (message, orig_thread_id);
2228
2229     notmuch = notmuch_message_get_database (message);
2230
2231     ret = _notmuch_database_ensure_writable (notmuch);
2232     if (ret)
2233         return ret;
2234
2235     orig_filenames = notmuch_message_get_filenames (message);
2236
2237     private_status = _notmuch_message_remove_indexed_terms (message);
2238     if (private_status) {
2239         ret = COERCE_STATUS (private_status, "error removing terms");
2240         goto DONE;
2241     }
2242
2243     ret = notmuch_message_remove_all_properties_with_prefix (message, "index.");
2244     if (ret)
2245         goto DONE; /* XXX TODO: distinguish from other error returns above? */
2246     if (indexopts && notmuch_indexopts_get_decrypt_policy (indexopts) == NOTMUCH_DECRYPT_FALSE) {
2247         ret = notmuch_message_remove_all_properties (message, "session-key");
2248         if (ret)
2249             goto DONE;
2250     }
2251
2252     /* re-add the filenames with the associated indexopts */
2253     for (; notmuch_filenames_valid (orig_filenames);
2254          notmuch_filenames_move_to_next (orig_filenames)) {
2255
2256         const char *date;
2257         const char *from, *to, *subject;
2258         char *message_id = NULL;
2259         const char *thread_id = NULL;
2260
2261         const char *filename = notmuch_filenames_get (orig_filenames);
2262
2263         message_file = _notmuch_message_file_open (notmuch, filename);
2264         if (message_file == NULL)
2265             continue;
2266
2267         ret = _notmuch_message_file_get_headers (message_file,
2268                                                  &from, &subject, &to, &date,
2269                                                  &message_id);
2270         if (ret)
2271             goto DONE;
2272
2273         /* XXX TODO: deal with changing message id? */
2274
2275         _notmuch_message_add_filename (message, filename);
2276
2277         ret = _notmuch_database_link_message_to_parents (notmuch, message,
2278                                                          message_file,
2279                                                          &thread_id);
2280         if (ret)
2281             goto DONE;
2282
2283         if (thread_id == NULL)
2284             thread_id = orig_thread_id;
2285
2286         _notmuch_message_add_term (message, "thread", thread_id);
2287         /* Take header values only from first filename */
2288         if (found == 0)
2289             _notmuch_message_set_header_values (message, date, from, subject);
2290
2291         ret = _notmuch_message_index_file (message, indexopts, message_file);
2292
2293         if (ret == NOTMUCH_STATUS_FILE_ERROR)
2294             continue;
2295         if (ret)
2296             goto DONE;
2297
2298         found++;
2299         _notmuch_message_file_close (message_file);
2300         message_file = NULL;
2301     }
2302     if (found == 0) {
2303         /* put back thread id to help cleanup */
2304         _notmuch_message_add_term (message, "thread", orig_thread_id);
2305         ret = _notmuch_message_delete (message);
2306     } else {
2307         _notmuch_message_sync (message);
2308     }
2309
2310   DONE:
2311     if (message_file)
2312         _notmuch_message_file_close (message_file);
2313
2314     /* XXX TODO destroy orig_filenames? */
2315     return ret;
2316 }