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