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