]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
lib: Improve documentation of _notmuch_message_create_for_message_id
[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     try {
418             std::string value;
419
420             /* Fetch header from the appropriate xapian value field if
421              * available */
422             if (strcasecmp (header, "from") == 0)
423                 value = message->doc.get_value (NOTMUCH_VALUE_FROM);
424             else if (strcasecmp (header, "subject") == 0)
425                 value = message->doc.get_value (NOTMUCH_VALUE_SUBJECT);
426             else if (strcasecmp (header, "message-id") == 0)
427                 value = message->doc.get_value (NOTMUCH_VALUE_MESSAGE_ID);
428
429             if (!value.empty())
430                 return talloc_strdup (message, value.c_str ());
431
432     } catch (Xapian::Error &error) {
433         fprintf (stderr, "A Xapian exception occurred when reading header: %s\n",
434                  error.get_msg().c_str());
435         message->notmuch->exception_reported = TRUE;
436         return NULL;
437     }
438
439     /* Otherwise fall back to parsing the file */
440     _notmuch_message_ensure_message_file (message);
441     if (message->message_file == NULL)
442         return NULL;
443
444     return _notmuch_message_file_get_header (message->message_file, header);
445 }
446
447 /* Return the message ID from the In-Reply-To header of 'message'.
448  *
449  * Returns an empty string ("") if 'message' has no In-Reply-To
450  * header.
451  *
452  * Returns NULL if any error occurs.
453  */
454 const char *
455 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
456 {
457     if (!message->in_reply_to)
458         _notmuch_message_ensure_metadata (message);
459     return message->in_reply_to;
460 }
461
462 const char *
463 notmuch_message_get_thread_id (notmuch_message_t *message)
464 {
465     if (!message->thread_id)
466         _notmuch_message_ensure_metadata (message);
467     if (!message->thread_id)
468         INTERNAL_ERROR ("Message with document ID of %u has no thread ID.\n",
469                         message->doc_id);
470     return message->thread_id;
471 }
472
473 void
474 _notmuch_message_add_reply (notmuch_message_t *message,
475                             notmuch_message_t *reply)
476 {
477     _notmuch_message_list_add_message (message->replies, reply);
478 }
479
480 notmuch_messages_t *
481 notmuch_message_get_replies (notmuch_message_t *message)
482 {
483     return _notmuch_messages_create (message->replies);
484 }
485
486 static void
487 _notmuch_message_remove_terms (notmuch_message_t *message, const char *prefix)
488 {
489     Xapian::TermIterator i;
490     size_t prefix_len = strlen (prefix);
491
492     while (1) {
493         i = message->doc.termlist_begin ();
494         i.skip_to (prefix);
495
496         /* Terminate loop when no terms remain with desired prefix. */
497         if (i == message->doc.termlist_end () ||
498             strncmp ((*i).c_str (), prefix, prefix_len))
499             break;
500
501         try {
502             message->doc.remove_term ((*i));
503         } catch (const Xapian::InvalidArgumentError) {
504             /* Ignore failure to remove non-existent term. */
505         }
506     }
507 }
508
509 /* Return true if p points at "new" or "cur". */
510 static bool is_maildir (const char *p)
511 {
512     return strcmp (p, "cur") == 0 || strcmp (p, "new") == 0;
513 }
514
515 /* Add "folder:" term for directory. */
516 static notmuch_status_t
517 _notmuch_message_add_folder_terms (notmuch_message_t *message,
518                                    const char *directory)
519 {
520     char *folder, *last;
521
522     folder = talloc_strdup (NULL, directory);
523     if (! folder)
524         return NOTMUCH_STATUS_OUT_OF_MEMORY;
525
526     /*
527      * If the message file is in a leaf directory named "new" or
528      * "cur", presume maildir and index the parent directory. Thus a
529      * "folder:" prefix search matches messages in the specified
530      * maildir folder, i.e. in the specified directory and its "new"
531      * and "cur" subdirectories.
532      *
533      * Note that this means the "folder:" prefix can't be used for
534      * distinguishing between message files in "new" or "cur". The
535      * "path:" prefix needs to be used for that.
536      *
537      * Note the deliberate difference to _filename_is_in_maildir(). We
538      * don't want to index different things depending on the existence
539      * or non-existence of all maildir sibling directories "new",
540      * "cur", and "tmp". Doing so would be surprising, and difficult
541      * for the user to fix in case all subdirectories were not in
542      * place during indexing.
543      */
544     last = strrchr (folder, '/');
545     if (last) {
546         if (is_maildir (last + 1))
547             *last = '\0';
548     } else if (is_maildir (folder)) {
549         *folder = '\0';
550     }
551
552     _notmuch_message_add_term (message, "folder", folder);
553
554     talloc_free (folder);
555
556     return NOTMUCH_STATUS_SUCCESS;
557 }
558
559 #define RECURSIVE_SUFFIX "/**"
560
561 /* Add "path:" terms for directory. */
562 static notmuch_status_t
563 _notmuch_message_add_path_terms (notmuch_message_t *message,
564                                  const char *directory)
565 {
566     /* Add exact "path:" term. */
567     _notmuch_message_add_term (message, "path", directory);
568
569     if (strlen (directory)) {
570         char *path, *p;
571
572         path = talloc_asprintf (NULL, "%s%s", directory, RECURSIVE_SUFFIX);
573         if (! path)
574             return NOTMUCH_STATUS_OUT_OF_MEMORY;
575
576         /* Add recursive "path:" terms for directory and all parents. */
577         for (p = path + strlen (path) - 1; p > path; p--) {
578             if (*p == '/') {
579                 strcpy (p, RECURSIVE_SUFFIX);
580                 _notmuch_message_add_term (message, "path", path);
581             }
582         }
583
584         talloc_free (path);
585     }
586
587     /* Recursive all-matching path:** for consistency. */
588     _notmuch_message_add_term (message, "path", "**");
589
590     return NOTMUCH_STATUS_SUCCESS;
591 }
592
593 /* Add directory based terms for all filenames of the message. */
594 static notmuch_status_t
595 _notmuch_message_add_directory_terms (void *ctx, notmuch_message_t *message)
596 {
597     const char *direntry_prefix = _find_prefix ("file-direntry");
598     int direntry_prefix_len = strlen (direntry_prefix);
599     Xapian::TermIterator i = message->doc.termlist_begin ();
600     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
601
602     for (i.skip_to (direntry_prefix); i != message->doc.termlist_end (); i++) {
603         unsigned int directory_id;
604         const char *direntry, *directory;
605         char *colon;
606
607         /* Terminate loop at first term without desired prefix. */
608         if (strncmp ((*i).c_str (), direntry_prefix, direntry_prefix_len))
609             break;
610
611         /* Indicate that there are filenames remaining. */
612         status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
613
614         direntry = (*i).c_str ();
615         direntry += direntry_prefix_len;
616
617         directory_id = strtol (direntry, &colon, 10);
618
619         if (colon == NULL || *colon != ':')
620             INTERNAL_ERROR ("malformed direntry");
621
622         directory = _notmuch_database_get_directory_path (ctx,
623                                                           message->notmuch,
624                                                           directory_id);
625
626         _notmuch_message_add_folder_terms (message, directory);
627         _notmuch_message_add_path_terms (message, directory);
628     }
629
630     return status;
631 }
632
633 /* Add an additional 'filename' for 'message'.
634  *
635  * This change will not be reflected in the database until the next
636  * call to _notmuch_message_sync. */
637 notmuch_status_t
638 _notmuch_message_add_filename (notmuch_message_t *message,
639                                const char *filename)
640 {
641     const char *relative, *directory;
642     notmuch_status_t status;
643     void *local = talloc_new (message);
644     char *direntry;
645
646     if (filename == NULL)
647         INTERNAL_ERROR ("Message filename cannot be NULL.");
648
649     relative = _notmuch_database_relative_path (message->notmuch, filename);
650
651     status = _notmuch_database_split_path (local, relative, &directory, NULL);
652     if (status)
653         return status;
654
655     status = _notmuch_database_filename_to_direntry (
656         local, message->notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
657     if (status)
658         return status;
659
660     /* New file-direntry allows navigating to this message with
661      * notmuch_directory_get_child_files() . */
662     _notmuch_message_add_term (message, "file-direntry", direntry);
663
664     _notmuch_message_add_folder_terms (message, directory);
665     _notmuch_message_add_path_terms (message, directory);
666
667     talloc_free (local);
668
669     return NOTMUCH_STATUS_SUCCESS;
670 }
671
672 /* Remove a particular 'filename' from 'message'.
673  *
674  * This change will not be reflected in the database until the next
675  * call to _notmuch_message_sync.
676  *
677  * If this message still has other filenames, returns
678  * NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID.
679  *
680  * Note: This function does not remove a document from the database,
681  * even if the specified filename is the only filename for this
682  * message. For that functionality, see
683  * _notmuch_database_remove_message. */
684 notmuch_status_t
685 _notmuch_message_remove_filename (notmuch_message_t *message,
686                                   const char *filename)
687 {
688     void *local = talloc_new (message);
689     char *direntry;
690     notmuch_private_status_t private_status;
691     notmuch_status_t status;
692
693     status = _notmuch_database_filename_to_direntry (
694         local, message->notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
695     if (status || !direntry)
696         return status;
697
698     /* Unlink this file from its parent directory. */
699     private_status = _notmuch_message_remove_term (message,
700                                                    "file-direntry", direntry);
701     status = COERCE_STATUS (private_status,
702                             "Unexpected error from _notmuch_message_remove_term");
703     if (status)
704         return status;
705
706     /* Re-synchronize "folder:" and "path:" terms for this message. */
707
708     /* Remove all "folder:" terms. */
709     _notmuch_message_remove_terms (message, _find_prefix ("folder"));
710
711     /* Remove all "path:" terms. */
712     _notmuch_message_remove_terms (message, _find_prefix ("path"));
713
714     /* Add back terms for all remaining filenames of the message. */
715     status = _notmuch_message_add_directory_terms (local, message);
716
717     talloc_free (local);
718
719     return status;
720 }
721
722 /* Upgrade the "folder:" prefix from V1 to V2. */
723 #define FOLDER_PREFIX_V1       "XFOLDER"
724 #define ZFOLDER_PREFIX_V1      "Z" FOLDER_PREFIX_V1
725 void
726 _notmuch_message_upgrade_folder (notmuch_message_t *message)
727 {
728     /* Remove all old "folder:" terms. */
729     _notmuch_message_remove_terms (message, FOLDER_PREFIX_V1);
730
731     /* Remove all old "folder:" stemmed terms. */
732     _notmuch_message_remove_terms (message, ZFOLDER_PREFIX_V1);
733
734     /* Add new boolean "folder:" and "path:" terms. */
735     _notmuch_message_add_directory_terms (message, message);
736 }
737
738 char *
739 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
740 {
741     return talloc_strdup (message, message->doc.get_data ().c_str ());
742 }
743
744 void
745 _notmuch_message_clear_data (notmuch_message_t *message)
746 {
747     message->doc.set_data ("");
748 }
749
750 static void
751 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
752 {
753     notmuch_string_node_t *node;
754
755     if (message->filename_list)
756         return;
757
758     if (!message->filename_term_list)
759         _notmuch_message_ensure_metadata (message);
760
761     message->filename_list = _notmuch_string_list_create (message);
762     node = message->filename_term_list->head;
763
764     if (!node) {
765         /* A message document created by an old version of notmuch
766          * (prior to rename support) will have the filename in the
767          * data of the document rather than as a file-direntry term.
768          *
769          * It would be nice to do the upgrade of the document directly
770          * here, but the database is likely open in read-only mode. */
771         const char *data;
772
773         data = message->doc.get_data ().c_str ();
774
775         if (data == NULL)
776             INTERNAL_ERROR ("message with no filename");
777
778         _notmuch_string_list_append (message->filename_list, data);
779
780         return;
781     }
782
783     for (; node; node = node->next) {
784         void *local = talloc_new (message);
785         const char *db_path, *directory, *basename, *filename;
786         char *colon, *direntry = NULL;
787         unsigned int directory_id;
788
789         direntry = node->string;
790
791         directory_id = strtol (direntry, &colon, 10);
792
793         if (colon == NULL || *colon != ':')
794             INTERNAL_ERROR ("malformed direntry");
795
796         basename = colon + 1;
797
798         *colon = '\0';
799
800         db_path = notmuch_database_get_path (message->notmuch);
801
802         directory = _notmuch_database_get_directory_path (local,
803                                                           message->notmuch,
804                                                           directory_id);
805
806         if (strlen (directory))
807             filename = talloc_asprintf (message, "%s/%s/%s",
808                                         db_path, directory, basename);
809         else
810             filename = talloc_asprintf (message, "%s/%s",
811                                         db_path, basename);
812
813         _notmuch_string_list_append (message->filename_list, filename);
814
815         talloc_free (local);
816     }
817
818     talloc_free (message->filename_term_list);
819     message->filename_term_list = NULL;
820 }
821
822 const char *
823 notmuch_message_get_filename (notmuch_message_t *message)
824 {
825     _notmuch_message_ensure_filename_list (message);
826
827     if (message->filename_list == NULL)
828         return NULL;
829
830     if (message->filename_list->head == NULL ||
831         message->filename_list->head->string == NULL)
832     {
833         INTERNAL_ERROR ("message with no filename");
834     }
835
836     return message->filename_list->head->string;
837 }
838
839 notmuch_filenames_t *
840 notmuch_message_get_filenames (notmuch_message_t *message)
841 {
842     _notmuch_message_ensure_filename_list (message);
843
844     return _notmuch_filenames_create (message, message->filename_list);
845 }
846
847 notmuch_bool_t
848 notmuch_message_get_flag (notmuch_message_t *message,
849                           notmuch_message_flag_t flag)
850 {
851     return message->flags & (1 << flag);
852 }
853
854 void
855 notmuch_message_set_flag (notmuch_message_t *message,
856                           notmuch_message_flag_t flag, notmuch_bool_t enable)
857 {
858     if (enable)
859         message->flags |= (1 << flag);
860     else
861         message->flags &= ~(1 << flag);
862 }
863
864 time_t
865 notmuch_message_get_date (notmuch_message_t *message)
866 {
867     std::string value;
868
869     try {
870         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
871     } catch (Xapian::Error &error) {
872         fprintf (stderr, "A Xapian exception occurred when reading date: %s\n",
873                  error.get_msg().c_str());
874         message->notmuch->exception_reported = TRUE;
875         return 0;
876     }
877
878     return Xapian::sortable_unserialise (value);
879 }
880
881 notmuch_tags_t *
882 notmuch_message_get_tags (notmuch_message_t *message)
883 {
884     notmuch_tags_t *tags;
885
886     if (!message->tag_list)
887         _notmuch_message_ensure_metadata (message);
888
889     tags = _notmuch_tags_create (message, message->tag_list);
890     /* _notmuch_tags_create steals the reference to the tag_list, but
891      * in this case it's still used by the message, so we add an
892      * *additional* talloc reference to the list.  As a result, it's
893      * possible to modify the message tags (which talloc_unlink's the
894      * current list from the message) while still iterating because
895      * the iterator will keep the current list alive. */
896     if (!talloc_reference (message, message->tag_list))
897         return NULL;
898
899     return tags;
900 }
901
902 const char *
903 _notmuch_message_get_author (notmuch_message_t *message)
904 {
905     return message->author;
906 }
907
908 void
909 _notmuch_message_set_author (notmuch_message_t *message,
910                             const char *author)
911 {
912     if (message->author)
913         talloc_free(message->author);
914     message->author = talloc_strdup(message, author);
915     return;
916 }
917
918 void
919 _notmuch_message_set_header_values (notmuch_message_t *message,
920                                     const char *date,
921                                     const char *from,
922                                     const char *subject)
923 {
924     time_t time_value;
925
926     /* GMime really doesn't want to see a NULL date, so protect its
927      * sensibilities. */
928     if (date == NULL || *date == '\0')
929         time_value = 0;
930     else
931         time_value = g_mime_utils_header_decode_date (date, NULL);
932
933     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
934                             Xapian::sortable_serialise (time_value));
935     message->doc.add_value (NOTMUCH_VALUE_FROM, from);
936     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
937 }
938
939 /* Synchronize changes made to message->doc out into the database. */
940 void
941 _notmuch_message_sync (notmuch_message_t *message)
942 {
943     Xapian::WritableDatabase *db;
944
945     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
946         return;
947
948     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
949     db->replace_document (message->doc_id, message->doc);
950 }
951
952 /* Delete a message document from the database. */
953 notmuch_status_t
954 _notmuch_message_delete (notmuch_message_t *message)
955 {
956     notmuch_status_t status;
957     Xapian::WritableDatabase *db;
958
959     status = _notmuch_database_ensure_writable (message->notmuch);
960     if (status)
961         return status;
962
963     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
964     db->delete_document (message->doc_id);
965     return NOTMUCH_STATUS_SUCCESS;
966 }
967
968 /* Ensure that 'message' is not holding any file object open. Future
969  * calls to various functions will still automatically open the
970  * message file as needed.
971  */
972 void
973 _notmuch_message_close (notmuch_message_t *message)
974 {
975     if (message->message_file) {
976         _notmuch_message_file_close (message->message_file);
977         message->message_file = NULL;
978     }
979 }
980
981 /* Add a name:value term to 'message', (the actual term will be
982  * encoded by prefixing the value with a short prefix). See
983  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
984  * names to prefix values.
985  *
986  * This change will not be reflected in the database until the next
987  * call to _notmuch_message_sync. */
988 notmuch_private_status_t
989 _notmuch_message_add_term (notmuch_message_t *message,
990                            const char *prefix_name,
991                            const char *value)
992 {
993
994     char *term;
995
996     if (value == NULL)
997         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
998
999     term = talloc_asprintf (message, "%s%s",
1000                             _find_prefix (prefix_name), value);
1001
1002     if (strlen (term) > NOTMUCH_TERM_MAX)
1003         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1004
1005     message->doc.add_term (term, 0);
1006
1007     talloc_free (term);
1008
1009     _notmuch_message_invalidate_metadata (message, prefix_name);
1010
1011     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1012 }
1013
1014 /* Parse 'text' and add a term to 'message' for each parsed word. Each
1015  * term will be added both prefixed (if prefix_name is not NULL) and
1016  * also non-prefixed). */
1017 notmuch_private_status_t
1018 _notmuch_message_gen_terms (notmuch_message_t *message,
1019                             const char *prefix_name,
1020                             const char *text)
1021 {
1022     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
1023
1024     if (text == NULL)
1025         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1026
1027     term_gen->set_document (message->doc);
1028
1029     if (prefix_name) {
1030         const char *prefix = _find_prefix (prefix_name);
1031
1032         term_gen->set_termpos (message->termpos);
1033         term_gen->index_text (text, 1, prefix);
1034         /* Create a gap between this an the next terms so they don't
1035          * appear to be a phrase. */
1036         message->termpos = term_gen->get_termpos () + 100;
1037
1038         _notmuch_message_invalidate_metadata (message, prefix_name);
1039     }
1040
1041     term_gen->set_termpos (message->termpos);
1042     term_gen->index_text (text);
1043     /* Create a term gap, as above. */
1044     message->termpos = term_gen->get_termpos () + 100;
1045
1046     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1047 }
1048
1049 /* Remove a name:value term from 'message', (the actual term will be
1050  * encoded by prefixing the value with a short prefix). See
1051  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1052  * names to prefix values.
1053  *
1054  * This change will not be reflected in the database until the next
1055  * call to _notmuch_message_sync. */
1056 notmuch_private_status_t
1057 _notmuch_message_remove_term (notmuch_message_t *message,
1058                               const char *prefix_name,
1059                               const char *value)
1060 {
1061     char *term;
1062
1063     if (value == NULL)
1064         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1065
1066     term = talloc_asprintf (message, "%s%s",
1067                             _find_prefix (prefix_name), value);
1068
1069     if (strlen (term) > NOTMUCH_TERM_MAX)
1070         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1071
1072     try {
1073         message->doc.remove_term (term);
1074     } catch (const Xapian::InvalidArgumentError) {
1075         /* We'll let the philosopher's try to wrestle with the
1076          * question of whether failing to remove that which was not
1077          * there in the first place is failure. For us, we'll silently
1078          * consider it all good. */
1079     }
1080
1081     talloc_free (term);
1082
1083     _notmuch_message_invalidate_metadata (message, prefix_name);
1084
1085     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1086 }
1087
1088 notmuch_status_t
1089 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
1090 {
1091     notmuch_private_status_t private_status;
1092     notmuch_status_t status;
1093
1094     status = _notmuch_database_ensure_writable (message->notmuch);
1095     if (status)
1096         return status;
1097
1098     if (tag == NULL)
1099         return NOTMUCH_STATUS_NULL_POINTER;
1100
1101     if (strlen (tag) > NOTMUCH_TAG_MAX)
1102         return NOTMUCH_STATUS_TAG_TOO_LONG;
1103
1104     private_status = _notmuch_message_add_term (message, "tag", tag);
1105     if (private_status) {
1106         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
1107                         private_status);
1108     }
1109
1110     if (! message->frozen)
1111         _notmuch_message_sync (message);
1112
1113     return NOTMUCH_STATUS_SUCCESS;
1114 }
1115
1116 notmuch_status_t
1117 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1118 {
1119     notmuch_private_status_t private_status;
1120     notmuch_status_t status;
1121
1122     status = _notmuch_database_ensure_writable (message->notmuch);
1123     if (status)
1124         return status;
1125
1126     if (tag == NULL)
1127         return NOTMUCH_STATUS_NULL_POINTER;
1128
1129     if (strlen (tag) > NOTMUCH_TAG_MAX)
1130         return NOTMUCH_STATUS_TAG_TOO_LONG;
1131
1132     private_status = _notmuch_message_remove_term (message, "tag", tag);
1133     if (private_status) {
1134         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1135                         private_status);
1136     }
1137
1138     if (! message->frozen)
1139         _notmuch_message_sync (message);
1140
1141     return NOTMUCH_STATUS_SUCCESS;
1142 }
1143
1144 /* Is the given filename within a maildir directory?
1145  *
1146  * Specifically, is the final directory component of 'filename' either
1147  * "cur" or "new". If so, return a pointer to that final directory
1148  * component within 'filename'. If not, return NULL.
1149  *
1150  * A non-NULL return value is guaranteed to be a valid string pointer
1151  * pointing to the characters "new/" or "cur/", (but not
1152  * NUL-terminated).
1153  */
1154 static const char *
1155 _filename_is_in_maildir (const char *filename)
1156 {
1157     const char *slash, *dir = NULL;
1158
1159     /* Find the last '/' separating directory from filename. */
1160     slash = strrchr (filename, '/');
1161     if (slash == NULL)
1162         return NULL;
1163
1164     /* Jump back 4 characters to where the previous '/' will be if the
1165      * directory is named "cur" or "new". */
1166     if (slash - filename < 4)
1167         return NULL;
1168
1169     slash -= 4;
1170
1171     if (*slash != '/')
1172         return NULL;
1173
1174     dir = slash + 1;
1175
1176     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1177         STRNCMP_LITERAL (dir, "new/") == 0)
1178     {
1179         return dir;
1180     }
1181
1182     return NULL;
1183 }
1184
1185 notmuch_status_t
1186 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1187 {
1188     const char *flags;
1189     notmuch_status_t status;
1190     notmuch_filenames_t *filenames;
1191     const char *filename, *dir;
1192     char *combined_flags = talloc_strdup (message, "");
1193     unsigned i;
1194     int seen_maildir_info = 0;
1195
1196     for (filenames = notmuch_message_get_filenames (message);
1197          notmuch_filenames_valid (filenames);
1198          notmuch_filenames_move_to_next (filenames))
1199     {
1200         filename = notmuch_filenames_get (filenames);
1201         dir = _filename_is_in_maildir (filename);
1202
1203         if (! dir)
1204             continue;
1205
1206         flags = strstr (filename, ":2,");
1207         if (flags) {
1208             seen_maildir_info = 1;
1209             flags += 3;
1210             combined_flags = talloc_strdup_append (combined_flags, flags);
1211         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1212             /* Messages are delivered to new/ with no "info" part, but
1213              * they effectively have default maildir flags.  According
1214              * to the spec, we should ignore the info part for
1215              * messages in new/, but some MUAs (mutt) can set maildir
1216              * flags on messages in new/, so we're liberal in what we
1217              * accept. */
1218             seen_maildir_info = 1;
1219         }
1220     }
1221
1222     /* If none of the filenames have any maildir info field (not even
1223      * an empty info with no flags set) then there's no information to
1224      * go on, so do nothing. */
1225     if (! seen_maildir_info)
1226         return NOTMUCH_STATUS_SUCCESS;
1227
1228     status = notmuch_message_freeze (message);
1229     if (status)
1230         return status;
1231
1232     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
1233         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
1234             ^ 
1235             flag2tag[i].inverse)
1236         {
1237             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1238         } else {
1239             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1240         }
1241         if (status)
1242             return status;
1243     }
1244     status = notmuch_message_thaw (message);
1245
1246     talloc_free (combined_flags);
1247
1248     return status;
1249 }
1250
1251 /* From the set of tags on 'message' and the flag2tag table, compute a
1252  * set of maildir-flag actions to be taken, (flags that should be
1253  * either set or cleared).
1254  *
1255  * The result is returned as two talloced strings: to_set, and to_clear
1256  */
1257 static void
1258 _get_maildir_flag_actions (notmuch_message_t *message,
1259                            char **to_set_ret,
1260                            char **to_clear_ret)
1261 {
1262     char *to_set, *to_clear;
1263     notmuch_tags_t *tags;
1264     const char *tag;
1265     unsigned i;
1266
1267     to_set = talloc_strdup (message, "");
1268     to_clear = talloc_strdup (message, "");
1269
1270     /* First, find flags for all set tags. */
1271     for (tags = notmuch_message_get_tags (message);
1272          notmuch_tags_valid (tags);
1273          notmuch_tags_move_to_next (tags))
1274     {
1275         tag = notmuch_tags_get (tags);
1276
1277         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1278             if (strcmp (tag, flag2tag[i].tag) == 0) {
1279                 if (flag2tag[i].inverse)
1280                     to_clear = talloc_asprintf_append (to_clear,
1281                                                        "%c",
1282                                                        flag2tag[i].flag);
1283                 else
1284                     to_set = talloc_asprintf_append (to_set,
1285                                                      "%c",
1286                                                      flag2tag[i].flag);
1287             }
1288         }
1289     }
1290
1291     /* Then, find the flags for all tags not present. */
1292     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1293         if (flag2tag[i].inverse) {
1294             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1295                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1296         } else {
1297             if (strchr (to_set, flag2tag[i].flag) == NULL)
1298                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1299         }
1300     }
1301
1302     *to_set_ret = to_set;
1303     *to_clear_ret = to_clear;
1304 }
1305
1306 /* Given 'filename' and a set of maildir flags to set and to clear,
1307  * compute the new maildir filename.
1308  *
1309  * If the existing filename is in the directory "new", the new
1310  * filename will be in the directory "cur", except for the case when
1311  * no flags are changed and the existing filename does not contain
1312  * maildir info (starting with ",2:").
1313  *
1314  * After a sequence of ":2," in the filename, any subsequent
1315  * single-character flags will be added or removed according to the
1316  * characters in flags_to_set and flags_to_clear. Any existing flags
1317  * not mentioned in either string will remain. The final list of flags
1318  * will be in ASCII order.
1319  *
1320  * If the original flags seem invalid, (repeated characters or
1321  * non-ASCII ordering of flags), this function will return NULL
1322  * (meaning that renaming would not be safe and should not occur).
1323  */
1324 static char*
1325 _new_maildir_filename (void *ctx,
1326                        const char *filename,
1327                        const char *flags_to_set,
1328                        const char *flags_to_clear)
1329 {
1330     const char *info, *flags;
1331     unsigned int flag, last_flag;
1332     char *filename_new, *dir;
1333     char flag_map[128];
1334     int flags_in_map = 0;
1335     notmuch_bool_t flags_changed = FALSE;
1336     unsigned int i;
1337     char *s;
1338
1339     memset (flag_map, 0, sizeof (flag_map));
1340
1341     info = strstr (filename, ":2,");
1342
1343     if (info == NULL) {
1344         info = filename + strlen(filename);
1345     } else {
1346         /* Loop through existing flags in filename. */
1347         for (flags = info + 3, last_flag = 0;
1348              *flags;
1349              last_flag = flag, flags++)
1350         {
1351             flag = *flags;
1352
1353             /* Original flags not in ASCII order. Abort. */
1354             if (flag < last_flag)
1355                 return NULL;
1356
1357             /* Non-ASCII flag. Abort. */
1358             if (flag > sizeof(flag_map) - 1)
1359                 return NULL;
1360
1361             /* Repeated flag value. Abort. */
1362             if (flag_map[flag])
1363                 return NULL;
1364
1365             flag_map[flag] = 1;
1366             flags_in_map++;
1367         }
1368     }
1369
1370     /* Then set and clear our flags from tags. */
1371     for (flags = flags_to_set; *flags; flags++) {
1372         flag = *flags;
1373         if (flag_map[flag] == 0) {
1374             flag_map[flag] = 1;
1375             flags_in_map++;
1376             flags_changed = TRUE;
1377         }
1378     }
1379
1380     for (flags = flags_to_clear; *flags; flags++) {
1381         flag = *flags;
1382         if (flag_map[flag]) {
1383             flag_map[flag] = 0;
1384             flags_in_map--;
1385             flags_changed = TRUE;
1386         }
1387     }
1388
1389     /* Messages in new/ without maildir info can be kept in new/ if no
1390      * flags have changed. */
1391     dir = (char *) _filename_is_in_maildir (filename);
1392     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && !*info && !flags_changed)
1393         return talloc_strdup (ctx, filename);
1394
1395     filename_new = (char *) talloc_size (ctx,
1396                                          info - filename +
1397                                          strlen (":2,") + flags_in_map + 1);
1398     if (unlikely (filename_new == NULL))
1399         return NULL;
1400
1401     strncpy (filename_new, filename, info - filename);
1402     filename_new[info - filename] = '\0';
1403
1404     strcat (filename_new, ":2,");
1405
1406     s = filename_new + strlen (filename_new);
1407     for (i = 0; i < sizeof (flag_map); i++)
1408     {
1409         if (flag_map[i]) {
1410             *s = i;
1411             s++;
1412         }
1413     }
1414     *s = '\0';
1415
1416     /* If message is in new/ move it under cur/. */
1417     dir = (char *) _filename_is_in_maildir (filename_new);
1418     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1419         memcpy (dir, "cur/", 4);
1420
1421     return filename_new;
1422 }
1423
1424 notmuch_status_t
1425 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1426 {
1427     notmuch_filenames_t *filenames;
1428     const char *filename;
1429     char *filename_new;
1430     char *to_set, *to_clear;
1431     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1432
1433     _get_maildir_flag_actions (message, &to_set, &to_clear);
1434
1435     for (filenames = notmuch_message_get_filenames (message);
1436          notmuch_filenames_valid (filenames);
1437          notmuch_filenames_move_to_next (filenames))
1438     {
1439         filename = notmuch_filenames_get (filenames);
1440
1441         if (! _filename_is_in_maildir (filename))
1442             continue;
1443
1444         filename_new = _new_maildir_filename (message, filename,
1445                                               to_set, to_clear);
1446         if (filename_new == NULL)
1447             continue;
1448
1449         if (strcmp (filename, filename_new)) {
1450             int err;
1451             notmuch_status_t new_status;
1452
1453             err = rename (filename, filename_new);
1454             if (err)
1455                 continue;
1456
1457             new_status = _notmuch_message_remove_filename (message,
1458                                                            filename);
1459             /* Hold on to only the first error. */
1460             if (! status && new_status
1461                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
1462                 status = new_status;
1463                 continue;
1464             }
1465
1466             new_status = _notmuch_message_add_filename (message,
1467                                                         filename_new);
1468             /* Hold on to only the first error. */
1469             if (! status && new_status) {
1470                 status = new_status;
1471                 continue;
1472             }
1473
1474             _notmuch_message_sync (message);
1475         }
1476
1477         talloc_free (filename_new);
1478     }
1479
1480     talloc_free (to_set);
1481     talloc_free (to_clear);
1482
1483     return NOTMUCH_STATUS_SUCCESS;
1484 }
1485
1486 notmuch_status_t
1487 notmuch_message_remove_all_tags (notmuch_message_t *message)
1488 {
1489     notmuch_private_status_t private_status;
1490     notmuch_status_t status;
1491     notmuch_tags_t *tags;
1492     const char *tag;
1493
1494     status = _notmuch_database_ensure_writable (message->notmuch);
1495     if (status)
1496         return status;
1497
1498     for (tags = notmuch_message_get_tags (message);
1499          notmuch_tags_valid (tags);
1500          notmuch_tags_move_to_next (tags))
1501     {
1502         tag = notmuch_tags_get (tags);
1503
1504         private_status = _notmuch_message_remove_term (message, "tag", tag);
1505         if (private_status) {
1506             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1507                             private_status);
1508         }
1509     }
1510
1511     if (! message->frozen)
1512         _notmuch_message_sync (message);
1513
1514     talloc_free (tags);
1515     return NOTMUCH_STATUS_SUCCESS;
1516 }
1517
1518 notmuch_status_t
1519 notmuch_message_freeze (notmuch_message_t *message)
1520 {
1521     notmuch_status_t status;
1522
1523     status = _notmuch_database_ensure_writable (message->notmuch);
1524     if (status)
1525         return status;
1526
1527     message->frozen++;
1528
1529     return NOTMUCH_STATUS_SUCCESS;
1530 }
1531
1532 notmuch_status_t
1533 notmuch_message_thaw (notmuch_message_t *message)
1534 {
1535     notmuch_status_t status;
1536
1537     status = _notmuch_database_ensure_writable (message->notmuch);
1538     if (status)
1539         return status;
1540
1541     if (message->frozen > 0) {
1542         message->frozen--;
1543         if (message->frozen == 0)
1544             _notmuch_message_sync (message);
1545         return NOTMUCH_STATUS_SUCCESS;
1546     } else {
1547         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1548     }
1549 }
1550
1551 void
1552 notmuch_message_destroy (notmuch_message_t *message)
1553 {
1554     talloc_free (message);
1555 }