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