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