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