]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
ed8c59e9b072795aec252b99def49a5d4b14e20e
[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 http://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
24 #include <stdint.h>
25
26 #include <gmime/gmime.h>
27
28 struct visible _notmuch_message {
29     notmuch_database_t *notmuch;
30     Xapian::docid doc_id;
31     int frozen;
32     char *message_id;
33     char *thread_id;
34     char *in_reply_to;
35     notmuch_string_list_t *tag_list;
36     notmuch_string_list_t *filename_term_list;
37     notmuch_string_list_t *filename_list;
38     char *author;
39     notmuch_message_file_t *message_file;
40     notmuch_message_list_t *replies;
41     unsigned long flags;
42
43     Xapian::Document doc;
44     Xapian::termcount termpos;
45 };
46
47 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
48
49 struct maildir_flag_tag {
50     char flag;
51     const char *tag;
52     notmuch_bool_t inverse;
53 };
54
55 /* ASCII ordered table of Maildir flags and associated tags */
56 static struct maildir_flag_tag flag2tag[] = {
57     { 'D', "draft",   FALSE},
58     { 'F', "flagged", FALSE},
59     { 'P', "passed",  FALSE},
60     { 'R', "replied", FALSE},
61     { 'S', "unread",  TRUE }
62 };
63
64 /* We end up having to call the destructor explicitly because we had
65  * to use "placement new" in order to initialize C++ objects within a
66  * block that we allocated with talloc. So C++ is making talloc
67  * slightly less simple to use, (we wouldn't need
68  * talloc_set_destructor at all otherwise).
69  */
70 static int
71 _notmuch_message_destructor (notmuch_message_t *message)
72 {
73     message->doc.~Document ();
74
75     return 0;
76 }
77
78 static notmuch_message_t *
79 _notmuch_message_create_for_document (const void *talloc_owner,
80                                       notmuch_database_t *notmuch,
81                                       unsigned int doc_id,
82                                       Xapian::Document doc,
83                                       notmuch_private_status_t *status)
84 {
85     notmuch_message_t *message;
86
87     if (status)
88         *status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
89
90     message = talloc (talloc_owner, notmuch_message_t);
91     if (unlikely (message == NULL)) {
92         if (status)
93             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
94         return NULL;
95     }
96
97     message->notmuch = notmuch;
98     message->doc_id = doc_id;
99
100     message->frozen = 0;
101     message->flags = 0;
102
103     /* Each of these will be lazily created as needed. */
104     message->message_id = NULL;
105     message->thread_id = NULL;
106     message->in_reply_to = NULL;
107     message->tag_list = NULL;
108     message->filename_term_list = NULL;
109     message->filename_list = NULL;
110     message->message_file = NULL;
111     message->author = NULL;
112
113     message->replies = _notmuch_message_list_create (message);
114     if (unlikely (message->replies == NULL)) {
115         if (status)
116             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
117         return NULL;
118     }
119
120     /* This is C++'s creepy "placement new", which is really just an
121      * ugly way to call a constructor for a pre-allocated object. So
122      * it's really not an error to not be checking for OUT_OF_MEMORY
123      * here, since this "new" isn't actually allocating memory. This
124      * is language-design comedy of the wrong kind. */
125
126     new (&message->doc) Xapian::Document;
127
128     talloc_set_destructor (message, _notmuch_message_destructor);
129
130     message->doc = doc;
131     message->termpos = 0;
132
133     return message;
134 }
135
136 /* Create a new notmuch_message_t object for an existing document in
137  * the database.
138  *
139  * Here, 'talloc owner' is an optional talloc context to which the new
140  * message will belong. This allows for the caller to not bother
141  * calling notmuch_message_destroy on the message, and know that all
142  * memory will be reclaimed when 'talloc_owner' is freed. The caller
143  * still can call notmuch_message_destroy when finished with the
144  * message if desired.
145  *
146  * The 'talloc_owner' argument can also be NULL, in which case the
147  * caller *is* responsible for calling notmuch_message_destroy.
148  *
149  * If no document exists in the database with document ID of 'doc_id'
150  * then this function returns NULL and optionally sets *status to
151  * NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND.
152  *
153  * This function can also fail to due lack of available memory,
154  * returning NULL and optionally setting *status to
155  * NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY.
156  *
157  * The caller can pass NULL for status if uninterested in
158  * distinguishing these two cases.
159  */
160 notmuch_message_t *
161 _notmuch_message_create (const void *talloc_owner,
162                          notmuch_database_t *notmuch,
163                          unsigned int doc_id,
164                          notmuch_private_status_t *status)
165 {
166     Xapian::Document doc;
167
168     try {
169         doc = notmuch->xapian_db->get_document (doc_id);
170     } catch (const Xapian::DocNotFoundError &error) {
171         if (status)
172             *status = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
173         return NULL;
174     }
175
176     return _notmuch_message_create_for_document (talloc_owner, notmuch,
177                                                  doc_id, doc, status);
178 }
179
180 /* Create a new notmuch_message_t object for a specific message ID,
181  * (which may or may not already exist in the database).
182  *
183  * The 'notmuch' database will be the talloc owner of the returned
184  * message.
185  *
186  * This function returns a valid notmuch_message_t whether or not
187  * there is already a document in the database with the given message
188  * ID. These two cases can be distinguished by the value of *status:
189  *
190  *
191  *   NOTMUCH_PRIVATE_STATUS_SUCCESS:
192  *
193  *     There is already a document with message ID 'message_id' in the
194  *     database. The returned message can be used to query/modify the
195  *     document.
196  *
197  *   NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND:
198  *
199  *     No document with 'message_id' exists in the database. The
200  *     returned message contains a newly created document (not yet
201  *     added to the database) and a document ID that is known not to
202  *     exist in the database.  This message is "blank"; that is, it
203  *     contains only a message ID and no other metadata. The caller
204  *     can modify the message, and a call to _notmuch_message_sync
205  *     will add the document to the database.
206  *
207  * If an error occurs, this function will return NULL and *status
208  * will be set as appropriate. (The status pointer argument must
209  * not be NULL.)
210  */
211 notmuch_message_t *
212 _notmuch_message_create_for_message_id (notmuch_database_t *notmuch,
213                                         const char *message_id,
214                                         notmuch_private_status_t *status_ret)
215 {
216     notmuch_message_t *message;
217     Xapian::Document doc;
218     unsigned int doc_id;
219     char *term;
220
221     *status_ret = (notmuch_private_status_t) notmuch_database_find_message (notmuch,
222                                                                             message_id,
223                                                                             &message);
224     if (message)
225         return talloc_steal (notmuch, message);
226     else if (*status_ret)
227         return NULL;
228
229     term = talloc_asprintf (NULL, "%s%s",
230                             _find_prefix ("id"), message_id);
231     if (term == NULL) {
232         *status_ret = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
233         return NULL;
234     }
235
236     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
237         INTERNAL_ERROR ("Failure to ensure database is writable.");
238
239     try {
240         doc.add_term (term, 0);
241         talloc_free (term);
242
243         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
244
245         doc_id = _notmuch_database_generate_doc_id (notmuch);
246     } catch (const Xapian::Error &error) {
247         fprintf (stderr, "A Xapian exception occurred creating message: %s\n",
248                  error.get_msg().c_str());
249         notmuch->exception_reported = TRUE;
250         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
251         return NULL;
252     }
253
254     message = _notmuch_message_create_for_document (notmuch, notmuch,
255                                                     doc_id, doc, status_ret);
256
257     /* We want to inform the caller that we had to create a new
258      * document. */
259     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
260         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
261
262     return message;
263 }
264
265 static char *
266 _notmuch_message_get_term (notmuch_message_t *message,
267                            Xapian::TermIterator &i, Xapian::TermIterator &end,
268                            const char *prefix)
269 {
270     int prefix_len = strlen (prefix);
271     char *value;
272
273     i.skip_to (prefix);
274
275     if (i == end)
276         return NULL;
277
278     std::string term = *i;
279     if (strncmp (term.c_str(), prefix, prefix_len))
280         return NULL;
281
282     value = talloc_strdup (message, term.c_str() + prefix_len);
283
284 #if DEBUG_DATABASE_SANITY
285     i++;
286
287     if (i != end && strncmp ((*i).c_str (), prefix, prefix_len) == 0) {
288         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate %s terms: %s and %s\n",
289                         message->doc_id, prefix, value,
290                         (*i).c_str () + prefix_len);
291     }
292 #endif
293
294     return value;
295 }
296
297 void
298 _notmuch_message_ensure_metadata (notmuch_message_t *message)
299 {
300     Xapian::TermIterator i, end;
301     const char *thread_prefix = _find_prefix ("thread"),
302         *tag_prefix = _find_prefix ("tag"),
303         *id_prefix = _find_prefix ("id"),
304         *filename_prefix = _find_prefix ("file-direntry"),
305         *replyto_prefix = _find_prefix ("replyto");
306
307     /* We do this all in a single pass because Xapian decompresses the
308      * term list every time you iterate over it.  Thus, while this is
309      * slightly more costly than looking up individual fields if only
310      * one field of the message object is actually used, it's a huge
311      * win as more fields are used. */
312
313     i = message->doc.termlist_begin ();
314     end = message->doc.termlist_end ();
315
316     /* Get thread */
317     if (!message->thread_id)
318         message->thread_id =
319             _notmuch_message_get_term (message, i, end, thread_prefix);
320
321     /* Get tags */
322     assert (strcmp (thread_prefix, tag_prefix) < 0);
323     if (!message->tag_list) {
324         message->tag_list =
325             _notmuch_database_get_terms_with_prefix (message, i, end,
326                                                      tag_prefix);
327         _notmuch_string_list_sort (message->tag_list);
328     }
329
330     /* Get id */
331     assert (strcmp (tag_prefix, id_prefix) < 0);
332     if (!message->message_id)
333         message->message_id =
334             _notmuch_message_get_term (message, i, end, id_prefix);
335
336     /* Get filename list.  Here we get only the terms.  We lazily
337      * expand them to full file names when needed in
338      * _notmuch_message_ensure_filename_list. */
339     assert (strcmp (id_prefix, filename_prefix) < 0);
340     if (!message->filename_term_list && !message->filename_list)
341         message->filename_term_list =
342             _notmuch_database_get_terms_with_prefix (message, i, end,
343                                                      filename_prefix);
344
345     /* Get reply to */
346     assert (strcmp (filename_prefix, replyto_prefix) < 0);
347     if (!message->in_reply_to)
348         message->in_reply_to =
349             _notmuch_message_get_term (message, i, end, replyto_prefix);
350     /* It's perfectly valid for a message to have no In-Reply-To
351      * header. For these cases, we return an empty string. */
352     if (!message->in_reply_to)
353         message->in_reply_to = talloc_strdup (message, "");
354 }
355
356 static void
357 _notmuch_message_invalidate_metadata (notmuch_message_t *message,
358                                       const char *prefix_name)
359 {
360     if (strcmp ("thread", prefix_name) == 0) {
361         talloc_free (message->thread_id);
362         message->thread_id = NULL;
363     }
364
365     if (strcmp ("tag", prefix_name) == 0) {
366         talloc_unlink (message, message->tag_list);
367         message->tag_list = NULL;
368     }
369
370     if (strcmp ("file-direntry", prefix_name) == 0) {
371         talloc_free (message->filename_term_list);
372         talloc_free (message->filename_list);
373         message->filename_term_list = message->filename_list = NULL;
374     }
375
376     if (strcmp ("replyto", prefix_name) == 0) {
377         talloc_free (message->in_reply_to);
378         message->in_reply_to = NULL;
379     }
380 }
381
382 unsigned int
383 _notmuch_message_get_doc_id (notmuch_message_t *message)
384 {
385     return message->doc_id;
386 }
387
388 const char *
389 notmuch_message_get_message_id (notmuch_message_t *message)
390 {
391     if (!message->message_id)
392         _notmuch_message_ensure_metadata (message);
393     if (!message->message_id)
394         INTERNAL_ERROR ("Message with document ID of %u has no message ID.\n",
395                         message->doc_id);
396     return message->message_id;
397 }
398
399 static void
400 _notmuch_message_ensure_message_file (notmuch_message_t *message)
401 {
402     const char *filename;
403
404     if (message->message_file)
405         return;
406
407     filename = notmuch_message_get_filename (message);
408     if (unlikely (filename == NULL))
409         return;
410
411     message->message_file = _notmuch_message_file_open_ctx (message, filename);
412 }
413
414 const char *
415 notmuch_message_get_header (notmuch_message_t *message, const char *header)
416 {
417     Xapian::valueno slot = Xapian::BAD_VALUENO;
418
419     /* Fetch header from the appropriate xapian value field if
420      * available */
421     if (strcasecmp (header, "from") == 0)
422         slot = NOTMUCH_VALUE_FROM;
423     else if (strcasecmp (header, "subject") == 0)
424         slot = NOTMUCH_VALUE_SUBJECT;
425     else if (strcasecmp (header, "message-id") == 0)
426         slot = NOTMUCH_VALUE_MESSAGE_ID;
427
428     if (slot != Xapian::BAD_VALUENO) {
429         try {
430             std::string value = message->doc.get_value (slot);
431
432             /* If we have NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES, then
433              * empty values indicate empty headers.  If we don't, then
434              * it could just mean we didn't record the header. */
435             if ((message->notmuch->features &
436                  NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES) ||
437                 ! value.empty())
438                 return talloc_strdup (message, value.c_str ());
439
440         } catch (Xapian::Error &error) {
441             fprintf (stderr, "A Xapian exception occurred when reading header: %s\n",
442                      error.get_msg().c_str());
443             message->notmuch->exception_reported = TRUE;
444             return NULL;
445         }
446     }
447
448     /* Otherwise fall back to parsing the file */
449     _notmuch_message_ensure_message_file (message);
450     if (message->message_file == NULL)
451         return NULL;
452
453     return _notmuch_message_file_get_header (message->message_file, header);
454 }
455
456 /* Return the message ID from the In-Reply-To header of 'message'.
457  *
458  * Returns an empty string ("") if 'message' has no In-Reply-To
459  * header.
460  *
461  * Returns NULL if any error occurs.
462  */
463 const char *
464 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
465 {
466     if (!message->in_reply_to)
467         _notmuch_message_ensure_metadata (message);
468     return message->in_reply_to;
469 }
470
471 const char *
472 notmuch_message_get_thread_id (notmuch_message_t *message)
473 {
474     if (!message->thread_id)
475         _notmuch_message_ensure_metadata (message);
476     if (!message->thread_id)
477         INTERNAL_ERROR ("Message with document ID of %u has no thread ID.\n",
478                         message->doc_id);
479     return message->thread_id;
480 }
481
482 void
483 _notmuch_message_add_reply (notmuch_message_t *message,
484                             notmuch_message_t *reply)
485 {
486     _notmuch_message_list_add_message (message->replies, reply);
487 }
488
489 notmuch_messages_t *
490 notmuch_message_get_replies (notmuch_message_t *message)
491 {
492     return _notmuch_messages_create (message->replies);
493 }
494
495 static void
496 _notmuch_message_remove_terms (notmuch_message_t *message, const char *prefix)
497 {
498     Xapian::TermIterator i;
499     size_t prefix_len = strlen (prefix);
500
501     while (1) {
502         i = message->doc.termlist_begin ();
503         i.skip_to (prefix);
504
505         /* Terminate loop when no terms remain with desired prefix. */
506         if (i == message->doc.termlist_end () ||
507             strncmp ((*i).c_str (), prefix, prefix_len))
508             break;
509
510         try {
511             message->doc.remove_term ((*i));
512         } catch (const Xapian::InvalidArgumentError) {
513             /* Ignore failure to remove non-existent term. */
514         }
515     }
516 }
517
518 /* Return true if p points at "new" or "cur". */
519 static bool is_maildir (const char *p)
520 {
521     return strcmp (p, "cur") == 0 || strcmp (p, "new") == 0;
522 }
523
524 /* Add "folder:" term for directory. */
525 static notmuch_status_t
526 _notmuch_message_add_folder_terms (notmuch_message_t *message,
527                                    const char *directory)
528 {
529     char *folder, *last;
530
531     folder = talloc_strdup (NULL, directory);
532     if (! folder)
533         return NOTMUCH_STATUS_OUT_OF_MEMORY;
534
535     /*
536      * If the message file is in a leaf directory named "new" or
537      * "cur", presume maildir and index the parent directory. Thus a
538      * "folder:" prefix search matches messages in the specified
539      * maildir folder, i.e. in the specified directory and its "new"
540      * and "cur" subdirectories.
541      *
542      * Note that this means the "folder:" prefix can't be used for
543      * distinguishing between message files in "new" or "cur". The
544      * "path:" prefix needs to be used for that.
545      *
546      * Note the deliberate difference to _filename_is_in_maildir(). We
547      * don't want to index different things depending on the existence
548      * or non-existence of all maildir sibling directories "new",
549      * "cur", and "tmp". Doing so would be surprising, and difficult
550      * for the user to fix in case all subdirectories were not in
551      * place during indexing.
552      */
553     last = strrchr (folder, '/');
554     if (last) {
555         if (is_maildir (last + 1))
556             *last = '\0';
557     } else if (is_maildir (folder)) {
558         *folder = '\0';
559     }
560
561     _notmuch_message_add_term (message, "folder", folder);
562
563     talloc_free (folder);
564
565     return NOTMUCH_STATUS_SUCCESS;
566 }
567
568 #define RECURSIVE_SUFFIX "/**"
569
570 /* Add "path:" terms for directory. */
571 static notmuch_status_t
572 _notmuch_message_add_path_terms (notmuch_message_t *message,
573                                  const char *directory)
574 {
575     /* Add exact "path:" term. */
576     _notmuch_message_add_term (message, "path", directory);
577
578     if (strlen (directory)) {
579         char *path, *p;
580
581         path = talloc_asprintf (NULL, "%s%s", directory, RECURSIVE_SUFFIX);
582         if (! path)
583             return NOTMUCH_STATUS_OUT_OF_MEMORY;
584
585         /* Add recursive "path:" terms for directory and all parents. */
586         for (p = path + strlen (path) - 1; p > path; p--) {
587             if (*p == '/') {
588                 strcpy (p, RECURSIVE_SUFFIX);
589                 _notmuch_message_add_term (message, "path", path);
590             }
591         }
592
593         talloc_free (path);
594     }
595
596     /* Recursive all-matching path:** for consistency. */
597     _notmuch_message_add_term (message, "path", "**");
598
599     return NOTMUCH_STATUS_SUCCESS;
600 }
601
602 /* Add directory based terms for all filenames of the message. */
603 static notmuch_status_t
604 _notmuch_message_add_directory_terms (void *ctx, notmuch_message_t *message)
605 {
606     const char *direntry_prefix = _find_prefix ("file-direntry");
607     int direntry_prefix_len = strlen (direntry_prefix);
608     Xapian::TermIterator i = message->doc.termlist_begin ();
609     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
610
611     for (i.skip_to (direntry_prefix); i != message->doc.termlist_end (); i++) {
612         unsigned int directory_id;
613         const char *direntry, *directory;
614         char *colon;
615
616         /* Terminate loop at first term without desired prefix. */
617         if (strncmp ((*i).c_str (), direntry_prefix, direntry_prefix_len))
618             break;
619
620         /* Indicate that there are filenames remaining. */
621         status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
622
623         direntry = (*i).c_str ();
624         direntry += direntry_prefix_len;
625
626         directory_id = strtol (direntry, &colon, 10);
627
628         if (colon == NULL || *colon != ':')
629             INTERNAL_ERROR ("malformed direntry");
630
631         directory = _notmuch_database_get_directory_path (ctx,
632                                                           message->notmuch,
633                                                           directory_id);
634
635         _notmuch_message_add_folder_terms (message, directory);
636         _notmuch_message_add_path_terms (message, directory);
637     }
638
639     return status;
640 }
641
642 /* Add an additional 'filename' for 'message'.
643  *
644  * This change will not be reflected in the database until the next
645  * call to _notmuch_message_sync. */
646 notmuch_status_t
647 _notmuch_message_add_filename (notmuch_message_t *message,
648                                const char *filename)
649 {
650     const char *relative, *directory;
651     notmuch_status_t status;
652     void *local = talloc_new (message);
653     char *direntry;
654
655     if (filename == NULL)
656         INTERNAL_ERROR ("Message filename cannot be NULL.");
657
658     relative = _notmuch_database_relative_path (message->notmuch, filename);
659
660     status = _notmuch_database_split_path (local, relative, &directory, NULL);
661     if (status)
662         return status;
663
664     status = _notmuch_database_filename_to_direntry (
665         local, message->notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
666     if (status)
667         return status;
668
669     /* New file-direntry allows navigating to this message with
670      * notmuch_directory_get_child_files() . */
671     _notmuch_message_add_term (message, "file-direntry", direntry);
672
673     _notmuch_message_add_folder_terms (message, directory);
674     _notmuch_message_add_path_terms (message, directory);
675
676     talloc_free (local);
677
678     return NOTMUCH_STATUS_SUCCESS;
679 }
680
681 /* Remove a particular 'filename' from 'message'.
682  *
683  * This change will not be reflected in the database until the next
684  * call to _notmuch_message_sync.
685  *
686  * If this message still has other filenames, returns
687  * NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID.
688  *
689  * Note: This function does not remove a document from the database,
690  * even if the specified filename is the only filename for this
691  * message. For that functionality, see
692  * _notmuch_database_remove_message. */
693 notmuch_status_t
694 _notmuch_message_remove_filename (notmuch_message_t *message,
695                                   const char *filename)
696 {
697     void *local = talloc_new (message);
698     char *direntry;
699     notmuch_private_status_t private_status;
700     notmuch_status_t status;
701
702     status = _notmuch_database_filename_to_direntry (
703         local, message->notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
704     if (status || !direntry)
705         return status;
706
707     /* Unlink this file from its parent directory. */
708     private_status = _notmuch_message_remove_term (message,
709                                                    "file-direntry", direntry);
710     status = COERCE_STATUS (private_status,
711                             "Unexpected error from _notmuch_message_remove_term");
712     if (status)
713         return status;
714
715     /* Re-synchronize "folder:" and "path:" terms for this message. */
716
717     /* Remove all "folder:" terms. */
718     _notmuch_message_remove_terms (message, _find_prefix ("folder"));
719
720     /* Remove all "path:" terms. */
721     _notmuch_message_remove_terms (message, _find_prefix ("path"));
722
723     /* Add back terms for all remaining filenames of the message. */
724     status = _notmuch_message_add_directory_terms (local, message);
725
726     talloc_free (local);
727
728     return status;
729 }
730
731 /* Upgrade the "folder:" prefix from V1 to V2. */
732 #define FOLDER_PREFIX_V1       "XFOLDER"
733 #define ZFOLDER_PREFIX_V1      "Z" FOLDER_PREFIX_V1
734 void
735 _notmuch_message_upgrade_folder (notmuch_message_t *message)
736 {
737     /* Remove all old "folder:" terms. */
738     _notmuch_message_remove_terms (message, FOLDER_PREFIX_V1);
739
740     /* Remove all old "folder:" stemmed terms. */
741     _notmuch_message_remove_terms (message, ZFOLDER_PREFIX_V1);
742
743     /* Add new boolean "folder:" and "path:" terms. */
744     _notmuch_message_add_directory_terms (message, message);
745 }
746
747 char *
748 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
749 {
750     return talloc_strdup (message, message->doc.get_data ().c_str ());
751 }
752
753 void
754 _notmuch_message_clear_data (notmuch_message_t *message)
755 {
756     message->doc.set_data ("");
757 }
758
759 static void
760 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
761 {
762     notmuch_string_node_t *node;
763
764     if (message->filename_list)
765         return;
766
767     if (!message->filename_term_list)
768         _notmuch_message_ensure_metadata (message);
769
770     message->filename_list = _notmuch_string_list_create (message);
771     node = message->filename_term_list->head;
772
773     if (!node) {
774         /* A message document created by an old version of notmuch
775          * (prior to rename support) will have the filename in the
776          * data of the document rather than as a file-direntry term.
777          *
778          * It would be nice to do the upgrade of the document directly
779          * here, but the database is likely open in read-only mode. */
780         const char *data;
781
782         data = message->doc.get_data ().c_str ();
783
784         if (data == NULL)
785             INTERNAL_ERROR ("message with no filename");
786
787         _notmuch_string_list_append (message->filename_list, data);
788
789         return;
790     }
791
792     for (; node; node = node->next) {
793         void *local = talloc_new (message);
794         const char *db_path, *directory, *basename, *filename;
795         char *colon, *direntry = NULL;
796         unsigned int directory_id;
797
798         direntry = node->string;
799
800         directory_id = strtol (direntry, &colon, 10);
801
802         if (colon == NULL || *colon != ':')
803             INTERNAL_ERROR ("malformed direntry");
804
805         basename = colon + 1;
806
807         *colon = '\0';
808
809         db_path = notmuch_database_get_path (message->notmuch);
810
811         directory = _notmuch_database_get_directory_path (local,
812                                                           message->notmuch,
813                                                           directory_id);
814
815         if (strlen (directory))
816             filename = talloc_asprintf (message, "%s/%s/%s",
817                                         db_path, directory, basename);
818         else
819             filename = talloc_asprintf (message, "%s/%s",
820                                         db_path, basename);
821
822         _notmuch_string_list_append (message->filename_list, filename);
823
824         talloc_free (local);
825     }
826
827     talloc_free (message->filename_term_list);
828     message->filename_term_list = NULL;
829 }
830
831 const char *
832 notmuch_message_get_filename (notmuch_message_t *message)
833 {
834     _notmuch_message_ensure_filename_list (message);
835
836     if (message->filename_list == NULL)
837         return NULL;
838
839     if (message->filename_list->head == NULL ||
840         message->filename_list->head->string == NULL)
841     {
842         INTERNAL_ERROR ("message with no filename");
843     }
844
845     return message->filename_list->head->string;
846 }
847
848 notmuch_filenames_t *
849 notmuch_message_get_filenames (notmuch_message_t *message)
850 {
851     _notmuch_message_ensure_filename_list (message);
852
853     return _notmuch_filenames_create (message, message->filename_list);
854 }
855
856 notmuch_bool_t
857 notmuch_message_get_flag (notmuch_message_t *message,
858                           notmuch_message_flag_t flag)
859 {
860     return message->flags & (1 << flag);
861 }
862
863 void
864 notmuch_message_set_flag (notmuch_message_t *message,
865                           notmuch_message_flag_t flag, notmuch_bool_t enable)
866 {
867     if (enable)
868         message->flags |= (1 << flag);
869     else
870         message->flags &= ~(1 << flag);
871 }
872
873 time_t
874 notmuch_message_get_date (notmuch_message_t *message)
875 {
876     std::string value;
877
878     try {
879         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
880     } catch (Xapian::Error &error) {
881         fprintf (stderr, "A Xapian exception occurred when reading date: %s\n",
882                  error.get_msg().c_str());
883         message->notmuch->exception_reported = TRUE;
884         return 0;
885     }
886
887     return Xapian::sortable_unserialise (value);
888 }
889
890 notmuch_tags_t *
891 notmuch_message_get_tags (notmuch_message_t *message)
892 {
893     notmuch_tags_t *tags;
894
895     if (!message->tag_list)
896         _notmuch_message_ensure_metadata (message);
897
898     tags = _notmuch_tags_create (message, message->tag_list);
899     /* _notmuch_tags_create steals the reference to the tag_list, but
900      * in this case it's still used by the message, so we add an
901      * *additional* talloc reference to the list.  As a result, it's
902      * possible to modify the message tags (which talloc_unlink's the
903      * current list from the message) while still iterating because
904      * the iterator will keep the current list alive. */
905     if (!talloc_reference (message, message->tag_list))
906         return NULL;
907
908     return tags;
909 }
910
911 const char *
912 _notmuch_message_get_author (notmuch_message_t *message)
913 {
914     return message->author;
915 }
916
917 void
918 _notmuch_message_set_author (notmuch_message_t *message,
919                             const char *author)
920 {
921     if (message->author)
922         talloc_free(message->author);
923     message->author = talloc_strdup(message, author);
924     return;
925 }
926
927 void
928 _notmuch_message_set_header_values (notmuch_message_t *message,
929                                     const char *date,
930                                     const char *from,
931                                     const char *subject)
932 {
933     time_t time_value;
934
935     /* GMime really doesn't want to see a NULL date, so protect its
936      * sensibilities. */
937     if (date == NULL || *date == '\0')
938         time_value = 0;
939     else
940         time_value = g_mime_utils_header_decode_date (date, NULL);
941
942     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
943                             Xapian::sortable_serialise (time_value));
944     message->doc.add_value (NOTMUCH_VALUE_FROM, from);
945     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
946 }
947
948 /* Synchronize changes made to message->doc out into the database. */
949 void
950 _notmuch_message_sync (notmuch_message_t *message)
951 {
952     Xapian::WritableDatabase *db;
953
954     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
955         return;
956
957     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
958     db->replace_document (message->doc_id, message->doc);
959 }
960
961 /* Delete a message document from the database. */
962 notmuch_status_t
963 _notmuch_message_delete (notmuch_message_t *message)
964 {
965     notmuch_status_t status;
966     Xapian::WritableDatabase *db;
967
968     status = _notmuch_database_ensure_writable (message->notmuch);
969     if (status)
970         return status;
971
972     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
973     db->delete_document (message->doc_id);
974     return NOTMUCH_STATUS_SUCCESS;
975 }
976
977 /* Ensure that 'message' is not holding any file object open. Future
978  * calls to various functions will still automatically open the
979  * message file as needed.
980  */
981 void
982 _notmuch_message_close (notmuch_message_t *message)
983 {
984     if (message->message_file) {
985         _notmuch_message_file_close (message->message_file);
986         message->message_file = NULL;
987     }
988 }
989
990 /* Add a name:value term to 'message', (the actual term will be
991  * encoded by prefixing the value with a short prefix). See
992  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
993  * names to prefix values.
994  *
995  * This change will not be reflected in the database until the next
996  * call to _notmuch_message_sync. */
997 notmuch_private_status_t
998 _notmuch_message_add_term (notmuch_message_t *message,
999                            const char *prefix_name,
1000                            const char *value)
1001 {
1002
1003     char *term;
1004
1005     if (value == NULL)
1006         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1007
1008     term = talloc_asprintf (message, "%s%s",
1009                             _find_prefix (prefix_name), value);
1010
1011     if (strlen (term) > NOTMUCH_TERM_MAX)
1012         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1013
1014     message->doc.add_term (term, 0);
1015
1016     talloc_free (term);
1017
1018     _notmuch_message_invalidate_metadata (message, prefix_name);
1019
1020     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1021 }
1022
1023 /* Parse 'text' and add a term to 'message' for each parsed word. Each
1024  * term will be added both prefixed (if prefix_name is not NULL) and
1025  * also non-prefixed). */
1026 notmuch_private_status_t
1027 _notmuch_message_gen_terms (notmuch_message_t *message,
1028                             const char *prefix_name,
1029                             const char *text)
1030 {
1031     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
1032
1033     if (text == NULL)
1034         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1035
1036     term_gen->set_document (message->doc);
1037
1038     if (prefix_name) {
1039         const char *prefix = _find_prefix (prefix_name);
1040
1041         term_gen->set_termpos (message->termpos);
1042         term_gen->index_text (text, 1, prefix);
1043         /* Create a gap between this an the next terms so they don't
1044          * appear to be a phrase. */
1045         message->termpos = term_gen->get_termpos () + 100;
1046
1047         _notmuch_message_invalidate_metadata (message, prefix_name);
1048     }
1049
1050     term_gen->set_termpos (message->termpos);
1051     term_gen->index_text (text);
1052     /* Create a term gap, as above. */
1053     message->termpos = term_gen->get_termpos () + 100;
1054
1055     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1056 }
1057
1058 /* Remove a name:value term from 'message', (the actual term will be
1059  * encoded by prefixing the value with a short prefix). See
1060  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1061  * names to prefix values.
1062  *
1063  * This change will not be reflected in the database until the next
1064  * call to _notmuch_message_sync. */
1065 notmuch_private_status_t
1066 _notmuch_message_remove_term (notmuch_message_t *message,
1067                               const char *prefix_name,
1068                               const char *value)
1069 {
1070     char *term;
1071
1072     if (value == NULL)
1073         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1074
1075     term = talloc_asprintf (message, "%s%s",
1076                             _find_prefix (prefix_name), value);
1077
1078     if (strlen (term) > NOTMUCH_TERM_MAX)
1079         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1080
1081     try {
1082         message->doc.remove_term (term);
1083     } catch (const Xapian::InvalidArgumentError) {
1084         /* We'll let the philosopher's try to wrestle with the
1085          * question of whether failing to remove that which was not
1086          * there in the first place is failure. For us, we'll silently
1087          * consider it all good. */
1088     }
1089
1090     talloc_free (term);
1091
1092     _notmuch_message_invalidate_metadata (message, prefix_name);
1093
1094     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1095 }
1096
1097 notmuch_status_t
1098 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
1099 {
1100     notmuch_private_status_t private_status;
1101     notmuch_status_t status;
1102
1103     status = _notmuch_database_ensure_writable (message->notmuch);
1104     if (status)
1105         return status;
1106
1107     if (tag == NULL)
1108         return NOTMUCH_STATUS_NULL_POINTER;
1109
1110     if (strlen (tag) > NOTMUCH_TAG_MAX)
1111         return NOTMUCH_STATUS_TAG_TOO_LONG;
1112
1113     private_status = _notmuch_message_add_term (message, "tag", tag);
1114     if (private_status) {
1115         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
1116                         private_status);
1117     }
1118
1119     if (! message->frozen)
1120         _notmuch_message_sync (message);
1121
1122     return NOTMUCH_STATUS_SUCCESS;
1123 }
1124
1125 notmuch_status_t
1126 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1127 {
1128     notmuch_private_status_t private_status;
1129     notmuch_status_t status;
1130
1131     status = _notmuch_database_ensure_writable (message->notmuch);
1132     if (status)
1133         return status;
1134
1135     if (tag == NULL)
1136         return NOTMUCH_STATUS_NULL_POINTER;
1137
1138     if (strlen (tag) > NOTMUCH_TAG_MAX)
1139         return NOTMUCH_STATUS_TAG_TOO_LONG;
1140
1141     private_status = _notmuch_message_remove_term (message, "tag", tag);
1142     if (private_status) {
1143         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1144                         private_status);
1145     }
1146
1147     if (! message->frozen)
1148         _notmuch_message_sync (message);
1149
1150     return NOTMUCH_STATUS_SUCCESS;
1151 }
1152
1153 /* Is the given filename within a maildir directory?
1154  *
1155  * Specifically, is the final directory component of 'filename' either
1156  * "cur" or "new". If so, return a pointer to that final directory
1157  * component within 'filename'. If not, return NULL.
1158  *
1159  * A non-NULL return value is guaranteed to be a valid string pointer
1160  * pointing to the characters "new/" or "cur/", (but not
1161  * NUL-terminated).
1162  */
1163 static const char *
1164 _filename_is_in_maildir (const char *filename)
1165 {
1166     const char *slash, *dir = NULL;
1167
1168     /* Find the last '/' separating directory from filename. */
1169     slash = strrchr (filename, '/');
1170     if (slash == NULL)
1171         return NULL;
1172
1173     /* Jump back 4 characters to where the previous '/' will be if the
1174      * directory is named "cur" or "new". */
1175     if (slash - filename < 4)
1176         return NULL;
1177
1178     slash -= 4;
1179
1180     if (*slash != '/')
1181         return NULL;
1182
1183     dir = slash + 1;
1184
1185     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1186         STRNCMP_LITERAL (dir, "new/") == 0)
1187     {
1188         return dir;
1189     }
1190
1191     return NULL;
1192 }
1193
1194 notmuch_status_t
1195 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1196 {
1197     const char *flags;
1198     notmuch_status_t status;
1199     notmuch_filenames_t *filenames;
1200     const char *filename, *dir;
1201     char *combined_flags = talloc_strdup (message, "");
1202     unsigned i;
1203     int seen_maildir_info = 0;
1204
1205     for (filenames = notmuch_message_get_filenames (message);
1206          notmuch_filenames_valid (filenames);
1207          notmuch_filenames_move_to_next (filenames))
1208     {
1209         filename = notmuch_filenames_get (filenames);
1210         dir = _filename_is_in_maildir (filename);
1211
1212         if (! dir)
1213             continue;
1214
1215         flags = strstr (filename, ":2,");
1216         if (flags) {
1217             seen_maildir_info = 1;
1218             flags += 3;
1219             combined_flags = talloc_strdup_append (combined_flags, flags);
1220         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1221             /* Messages are delivered to new/ with no "info" part, but
1222              * they effectively have default maildir flags.  According
1223              * to the spec, we should ignore the info part for
1224              * messages in new/, but some MUAs (mutt) can set maildir
1225              * flags on messages in new/, so we're liberal in what we
1226              * accept. */
1227             seen_maildir_info = 1;
1228         }
1229     }
1230
1231     /* If none of the filenames have any maildir info field (not even
1232      * an empty info with no flags set) then there's no information to
1233      * go on, so do nothing. */
1234     if (! seen_maildir_info)
1235         return NOTMUCH_STATUS_SUCCESS;
1236
1237     status = notmuch_message_freeze (message);
1238     if (status)
1239         return status;
1240
1241     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
1242         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
1243             ^ 
1244             flag2tag[i].inverse)
1245         {
1246             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1247         } else {
1248             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1249         }
1250         if (status)
1251             return status;
1252     }
1253     status = notmuch_message_thaw (message);
1254
1255     talloc_free (combined_flags);
1256
1257     return status;
1258 }
1259
1260 /* From the set of tags on 'message' and the flag2tag table, compute a
1261  * set of maildir-flag actions to be taken, (flags that should be
1262  * either set or cleared).
1263  *
1264  * The result is returned as two talloced strings: to_set, and to_clear
1265  */
1266 static void
1267 _get_maildir_flag_actions (notmuch_message_t *message,
1268                            char **to_set_ret,
1269                            char **to_clear_ret)
1270 {
1271     char *to_set, *to_clear;
1272     notmuch_tags_t *tags;
1273     const char *tag;
1274     unsigned i;
1275
1276     to_set = talloc_strdup (message, "");
1277     to_clear = talloc_strdup (message, "");
1278
1279     /* First, find flags for all set tags. */
1280     for (tags = notmuch_message_get_tags (message);
1281          notmuch_tags_valid (tags);
1282          notmuch_tags_move_to_next (tags))
1283     {
1284         tag = notmuch_tags_get (tags);
1285
1286         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1287             if (strcmp (tag, flag2tag[i].tag) == 0) {
1288                 if (flag2tag[i].inverse)
1289                     to_clear = talloc_asprintf_append (to_clear,
1290                                                        "%c",
1291                                                        flag2tag[i].flag);
1292                 else
1293                     to_set = talloc_asprintf_append (to_set,
1294                                                      "%c",
1295                                                      flag2tag[i].flag);
1296             }
1297         }
1298     }
1299
1300     /* Then, find the flags for all tags not present. */
1301     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1302         if (flag2tag[i].inverse) {
1303             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1304                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1305         } else {
1306             if (strchr (to_set, flag2tag[i].flag) == NULL)
1307                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1308         }
1309     }
1310
1311     *to_set_ret = to_set;
1312     *to_clear_ret = to_clear;
1313 }
1314
1315 /* Given 'filename' and a set of maildir flags to set and to clear,
1316  * compute the new maildir filename.
1317  *
1318  * If the existing filename is in the directory "new", the new
1319  * filename will be in the directory "cur", except for the case when
1320  * no flags are changed and the existing filename does not contain
1321  * maildir info (starting with ",2:").
1322  *
1323  * After a sequence of ":2," in the filename, any subsequent
1324  * single-character flags will be added or removed according to the
1325  * characters in flags_to_set and flags_to_clear. Any existing flags
1326  * not mentioned in either string will remain. The final list of flags
1327  * will be in ASCII order.
1328  *
1329  * If the original flags seem invalid, (repeated characters or
1330  * non-ASCII ordering of flags), this function will return NULL
1331  * (meaning that renaming would not be safe and should not occur).
1332  */
1333 static char*
1334 _new_maildir_filename (void *ctx,
1335                        const char *filename,
1336                        const char *flags_to_set,
1337                        const char *flags_to_clear)
1338 {
1339     const char *info, *flags;
1340     unsigned int flag, last_flag;
1341     char *filename_new, *dir;
1342     char flag_map[128];
1343     int flags_in_map = 0;
1344     notmuch_bool_t flags_changed = FALSE;
1345     unsigned int i;
1346     char *s;
1347
1348     memset (flag_map, 0, sizeof (flag_map));
1349
1350     info = strstr (filename, ":2,");
1351
1352     if (info == NULL) {
1353         info = filename + strlen(filename);
1354     } else {
1355         /* Loop through existing flags in filename. */
1356         for (flags = info + 3, last_flag = 0;
1357              *flags;
1358              last_flag = flag, flags++)
1359         {
1360             flag = *flags;
1361
1362             /* Original flags not in ASCII order. Abort. */
1363             if (flag < last_flag)
1364                 return NULL;
1365
1366             /* Non-ASCII flag. Abort. */
1367             if (flag > sizeof(flag_map) - 1)
1368                 return NULL;
1369
1370             /* Repeated flag value. Abort. */
1371             if (flag_map[flag])
1372                 return NULL;
1373
1374             flag_map[flag] = 1;
1375             flags_in_map++;
1376         }
1377     }
1378
1379     /* Then set and clear our flags from tags. */
1380     for (flags = flags_to_set; *flags; flags++) {
1381         flag = *flags;
1382         if (flag_map[flag] == 0) {
1383             flag_map[flag] = 1;
1384             flags_in_map++;
1385             flags_changed = TRUE;
1386         }
1387     }
1388
1389     for (flags = flags_to_clear; *flags; flags++) {
1390         flag = *flags;
1391         if (flag_map[flag]) {
1392             flag_map[flag] = 0;
1393             flags_in_map--;
1394             flags_changed = TRUE;
1395         }
1396     }
1397
1398     /* Messages in new/ without maildir info can be kept in new/ if no
1399      * flags have changed. */
1400     dir = (char *) _filename_is_in_maildir (filename);
1401     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && !*info && !flags_changed)
1402         return talloc_strdup (ctx, filename);
1403
1404     filename_new = (char *) talloc_size (ctx,
1405                                          info - filename +
1406                                          strlen (":2,") + flags_in_map + 1);
1407     if (unlikely (filename_new == NULL))
1408         return NULL;
1409
1410     strncpy (filename_new, filename, info - filename);
1411     filename_new[info - filename] = '\0';
1412
1413     strcat (filename_new, ":2,");
1414
1415     s = filename_new + strlen (filename_new);
1416     for (i = 0; i < sizeof (flag_map); i++)
1417     {
1418         if (flag_map[i]) {
1419             *s = i;
1420             s++;
1421         }
1422     }
1423     *s = '\0';
1424
1425     /* If message is in new/ move it under cur/. */
1426     dir = (char *) _filename_is_in_maildir (filename_new);
1427     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1428         memcpy (dir, "cur/", 4);
1429
1430     return filename_new;
1431 }
1432
1433 notmuch_status_t
1434 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1435 {
1436     notmuch_filenames_t *filenames;
1437     const char *filename;
1438     char *filename_new;
1439     char *to_set, *to_clear;
1440     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1441
1442     _get_maildir_flag_actions (message, &to_set, &to_clear);
1443
1444     for (filenames = notmuch_message_get_filenames (message);
1445          notmuch_filenames_valid (filenames);
1446          notmuch_filenames_move_to_next (filenames))
1447     {
1448         filename = notmuch_filenames_get (filenames);
1449
1450         if (! _filename_is_in_maildir (filename))
1451             continue;
1452
1453         filename_new = _new_maildir_filename (message, filename,
1454                                               to_set, to_clear);
1455         if (filename_new == NULL)
1456             continue;
1457
1458         if (strcmp (filename, filename_new)) {
1459             int err;
1460             notmuch_status_t new_status;
1461
1462             err = rename (filename, filename_new);
1463             if (err)
1464                 continue;
1465
1466             new_status = _notmuch_message_remove_filename (message,
1467                                                            filename);
1468             /* Hold on to only the first error. */
1469             if (! status && new_status
1470                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
1471                 status = new_status;
1472                 continue;
1473             }
1474
1475             new_status = _notmuch_message_add_filename (message,
1476                                                         filename_new);
1477             /* Hold on to only the first error. */
1478             if (! status && new_status) {
1479                 status = new_status;
1480                 continue;
1481             }
1482
1483             _notmuch_message_sync (message);
1484         }
1485
1486         talloc_free (filename_new);
1487     }
1488
1489     talloc_free (to_set);
1490     talloc_free (to_clear);
1491
1492     return NOTMUCH_STATUS_SUCCESS;
1493 }
1494
1495 notmuch_status_t
1496 notmuch_message_remove_all_tags (notmuch_message_t *message)
1497 {
1498     notmuch_private_status_t private_status;
1499     notmuch_status_t status;
1500     notmuch_tags_t *tags;
1501     const char *tag;
1502
1503     status = _notmuch_database_ensure_writable (message->notmuch);
1504     if (status)
1505         return status;
1506
1507     for (tags = notmuch_message_get_tags (message);
1508          notmuch_tags_valid (tags);
1509          notmuch_tags_move_to_next (tags))
1510     {
1511         tag = notmuch_tags_get (tags);
1512
1513         private_status = _notmuch_message_remove_term (message, "tag", tag);
1514         if (private_status) {
1515             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1516                             private_status);
1517         }
1518     }
1519
1520     if (! message->frozen)
1521         _notmuch_message_sync (message);
1522
1523     talloc_free (tags);
1524     return NOTMUCH_STATUS_SUCCESS;
1525 }
1526
1527 notmuch_status_t
1528 notmuch_message_freeze (notmuch_message_t *message)
1529 {
1530     notmuch_status_t status;
1531
1532     status = _notmuch_database_ensure_writable (message->notmuch);
1533     if (status)
1534         return status;
1535
1536     message->frozen++;
1537
1538     return NOTMUCH_STATUS_SUCCESS;
1539 }
1540
1541 notmuch_status_t
1542 notmuch_message_thaw (notmuch_message_t *message)
1543 {
1544     notmuch_status_t status;
1545
1546     status = _notmuch_database_ensure_writable (message->notmuch);
1547     if (status)
1548         return status;
1549
1550     if (message->frozen > 0) {
1551         message->frozen--;
1552         if (message->frozen == 0)
1553             _notmuch_message_sync (message);
1554         return NOTMUCH_STATUS_SUCCESS;
1555     } else {
1556         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1557     }
1558 }
1559
1560 void
1561 notmuch_message_destroy (notmuch_message_t *message)
1562 {
1563     talloc_free (message);
1564 }