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