]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
Correct some minor typos in a comment
[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 _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_filename_list_t *filename_list;
36     char *author;
37     notmuch_message_file_t *message_file;
38     notmuch_message_list_t *replies;
39     unsigned long flags;
40
41     Xapian::Document doc;
42 };
43
44 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
45
46 struct maildir_flag_tag {
47     char flag;
48     const char *tag;
49     bool inverse;
50 };
51
52 /* ASCII ordered table of Maildir flags and associated tags */
53 static struct maildir_flag_tag flag2tag[] = {
54     { 'D', "draft",   false},
55     { 'F', "flagged", false},
56     { 'P', "passed",  false},
57     { 'R', "replied", false},
58     { 'S', "unread",  true }
59 };
60
61 /* We end up having to call the destructor explicitly because we had
62  * to use "placement new" in order to initialize C++ objects within a
63  * block that we allocated with talloc. So C++ is making talloc
64  * slightly less simple to use, (we wouldn't need
65  * talloc_set_destructor at all otherwise).
66  */
67 static int
68 _notmuch_message_destructor (notmuch_message_t *message)
69 {
70     message->doc.~Document ();
71
72     return 0;
73 }
74
75 static notmuch_message_t *
76 _notmuch_message_create_for_document (const void *talloc_owner,
77                                       notmuch_database_t *notmuch,
78                                       unsigned int doc_id,
79                                       Xapian::Document doc,
80                                       notmuch_private_status_t *status)
81 {
82     notmuch_message_t *message;
83
84     if (status)
85         *status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
86
87     message = talloc (talloc_owner, notmuch_message_t);
88     if (unlikely (message == NULL)) {
89         if (status)
90             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
91         return NULL;
92     }
93
94     message->notmuch = notmuch;
95     message->doc_id = doc_id;
96
97     message->frozen = 0;
98     message->flags = 0;
99
100     /* Each of these will be lazily created as needed. */
101     message->message_id = NULL;
102     message->thread_id = NULL;
103     message->in_reply_to = NULL;
104     message->filename_list = NULL;
105     message->message_file = NULL;
106     message->author = NULL;
107
108     message->replies = _notmuch_message_list_create (message);
109     if (unlikely (message->replies == NULL)) {
110         if (status)
111             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
112         return NULL;
113     }
114
115     /* This is C++'s creepy "placement new", which is really just an
116      * ugly way to call a constructor for a pre-allocated object. So
117      * it's really not an error to not be checking for OUT_OF_MEMORY
118      * here, since this "new" isn't actually allocating memory. This
119      * is language-design comedy of the wrong kind. */
120
121     new (&message->doc) Xapian::Document;
122
123     talloc_set_destructor (message, _notmuch_message_destructor);
124
125     message->doc = doc;
126
127     return message;
128 }
129
130 /* Create a new notmuch_message_t object for an existing document in
131  * the database.
132  *
133  * Here, 'talloc owner' is an optional talloc context to which the new
134  * message will belong. This allows for the caller to not bother
135  * calling notmuch_message_destroy on the message, and know that all
136  * memory will be reclaimed when 'talloc_owner' is freed. The caller
137  * still can call notmuch_message_destroy when finished with the
138  * message if desired.
139  *
140  * The 'talloc_owner' argument can also be NULL, in which case the
141  * caller *is* responsible for calling notmuch_message_destroy.
142  *
143  * If no document exists in the database with document ID of 'doc_id'
144  * then this function returns NULL and optionally sets *status to
145  * NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND.
146  *
147  * This function can also fail to due lack of available memory,
148  * returning NULL and optionally setting *status to
149  * NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY.
150  *
151  * The caller can pass NULL for status if uninterested in
152  * distinguishing these two cases.
153  */
154 notmuch_message_t *
155 _notmuch_message_create (const void *talloc_owner,
156                          notmuch_database_t *notmuch,
157                          unsigned int doc_id,
158                          notmuch_private_status_t *status)
159 {
160     Xapian::Document doc;
161
162     try {
163         doc = notmuch->xapian_db->get_document (doc_id);
164     } catch (const Xapian::DocNotFoundError &error) {
165         if (status)
166             *status = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
167         return NULL;
168     }
169
170     return _notmuch_message_create_for_document (talloc_owner, notmuch,
171                                                  doc_id, doc, status);
172 }
173
174 /* Create a new notmuch_message_t object for a specific message ID,
175  * (which may or may not already exist in the database).
176  *
177  * The 'notmuch' database will be the talloc owner of the returned
178  * message.
179  *
180  * This function returns a valid notmuch_message_t whether or not
181  * there is already a document in the database with the given message
182  * ID. These two cases can be distinguished by the value of *status:
183  *
184  *
185  *   NOTMUCH_PRIVATE_STATUS_SUCCESS:
186  *
187  *     There is already a document with message ID 'message_id' in the
188  *     database. The returned message can be used to query/modify the
189  *     document.
190  *   NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND:
191  *
192  *     No document with 'message_id' exists in the database. The
193  *     returned message contains a newly created document (not yet
194  *     added to the database) and a document ID that is known not to
195  *     exist in the database. The caller can modify the message, and a
196  *     call to _notmuch_message_sync will add * the document to the
197  *     database.
198  *
199  * If an error occurs, this function will return NULL and *status
200  * will be set as appropriate. (The status pointer argument must
201  * not be NULL.)
202  */
203 notmuch_message_t *
204 _notmuch_message_create_for_message_id (notmuch_database_t *notmuch,
205                                         const char *message_id,
206                                         notmuch_private_status_t *status_ret)
207 {
208     notmuch_message_t *message;
209     Xapian::Document doc;
210     Xapian::WritableDatabase *db;
211     unsigned int doc_id;
212     char *term;
213
214     *status_ret = NOTMUCH_PRIVATE_STATUS_SUCCESS;
215
216     message = notmuch_database_find_message (notmuch, message_id);
217     if (message)
218         return talloc_steal (notmuch, message);
219
220     term = talloc_asprintf (NULL, "%s%s",
221                             _find_prefix ("id"), message_id);
222     if (term == NULL) {
223         *status_ret = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
224         return NULL;
225     }
226
227     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
228         INTERNAL_ERROR ("Failure to ensure database is writable.");
229
230     db = static_cast<Xapian::WritableDatabase *> (notmuch->xapian_db);
231     try {
232         doc.add_term (term, 0);
233         talloc_free (term);
234
235         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
236
237         doc_id = _notmuch_database_generate_doc_id (notmuch);
238     } catch (const Xapian::Error &error) {
239         fprintf (stderr, "A Xapian exception occurred creating message: %s\n",
240                  error.get_msg().c_str());
241         notmuch->exception_reported = TRUE;
242         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
243         return NULL;
244     }
245
246     message = _notmuch_message_create_for_document (notmuch, notmuch,
247                                                     doc_id, doc, status_ret);
248
249     /* We want to inform the caller that we had to create a new
250      * document. */
251     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
252         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
253
254     return message;
255 }
256
257 unsigned int
258 _notmuch_message_get_doc_id (notmuch_message_t *message)
259 {
260     return message->doc_id;
261 }
262
263 const char *
264 notmuch_message_get_message_id (notmuch_message_t *message)
265 {
266     Xapian::TermIterator i;
267
268     if (message->message_id)
269         return message->message_id;
270
271     i = message->doc.termlist_begin ();
272     i.skip_to (_find_prefix ("id"));
273
274     if (i == message->doc.termlist_end ())
275         INTERNAL_ERROR ("Message with document ID of %d has no message ID.\n",
276                         message->doc_id);
277
278     message->message_id = talloc_strdup (message, (*i).c_str () + 1);
279
280 #if DEBUG_DATABASE_SANITY
281     i++;
282
283     if (i != message->doc.termlist_end () &&
284         strncmp ((*i).c_str (), _find_prefix ("id"),
285                  strlen (_find_prefix ("id"))) == 0)
286     {
287         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate message IDs",
288                         message->doc_id);
289     }
290 #endif
291
292     return message->message_id;
293 }
294
295 static void
296 _notmuch_message_ensure_message_file (notmuch_message_t *message)
297 {
298     const char *filename;
299
300     if (message->message_file)
301         return;
302
303     filename = notmuch_message_get_filename (message);
304     if (unlikely (filename == NULL))
305         return;
306
307     message->message_file = _notmuch_message_file_open_ctx (message, filename);
308 }
309
310 const char *
311 notmuch_message_get_header (notmuch_message_t *message, const char *header)
312 {
313     _notmuch_message_ensure_message_file (message);
314     if (message->message_file == NULL)
315         return NULL;
316
317     return notmuch_message_file_get_header (message->message_file, header);
318 }
319
320 /* Return the message ID from the In-Reply-To header of 'message'.
321  *
322  * Returns an empty string ("") if 'message' has no In-Reply-To
323  * header.
324  *
325  * Returns NULL if any error occurs.
326  */
327 const char *
328 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
329 {
330     const char *prefix = _find_prefix ("replyto");
331     int prefix_len = strlen (prefix);
332     Xapian::TermIterator i;
333     std::string in_reply_to;
334
335     if (message->in_reply_to)
336         return message->in_reply_to;
337
338     i = message->doc.termlist_begin ();
339     i.skip_to (prefix);
340
341     if (i != message->doc.termlist_end ())
342         in_reply_to = *i;
343
344     /* It's perfectly valid for a message to have no In-Reply-To
345      * header. For these cases, we return an empty string. */
346     if (i == message->doc.termlist_end () ||
347         strncmp (in_reply_to.c_str (), prefix, prefix_len))
348     {
349         message->in_reply_to = talloc_strdup (message, "");
350         return message->in_reply_to;
351     }
352
353     message->in_reply_to = talloc_strdup (message,
354                                           in_reply_to.c_str () + prefix_len);
355
356 #if DEBUG_DATABASE_SANITY
357     i++;
358
359     in_reply_to = *i;
360
361     if (i != message->doc.termlist_end () &&
362         strncmp ((*i).c_str (), prefix, prefix_len) == 0)
363     {
364        INTERNAL_ERROR ("Message %s has duplicate In-Reply-To IDs: %s and %s\n",
365                         notmuch_message_get_message_id (message),
366                         message->in_reply_to,
367                         (*i).c_str () + prefix_len);
368     }
369 #endif
370
371     return message->in_reply_to;
372 }
373
374 const char *
375 notmuch_message_get_thread_id (notmuch_message_t *message)
376 {
377     const char *prefix = _find_prefix ("thread");
378     Xapian::TermIterator i;
379     std::string id;
380
381     /* This code is written with the assumption that "thread" has a
382      * single-character prefix. */
383     assert (strlen (prefix) == 1);
384
385     if (message->thread_id)
386         return message->thread_id;
387
388     i = message->doc.termlist_begin ();
389     i.skip_to (prefix);
390
391     if (i != message->doc.termlist_end ())
392         id = *i;
393
394     if (i == message->doc.termlist_end () || id[0] != *prefix)
395         INTERNAL_ERROR ("Message with document ID of %d has no thread ID.\n",
396                         message->doc_id);
397
398     message->thread_id = talloc_strdup (message, id.c_str () + 1);
399
400 #if DEBUG_DATABASE_SANITY
401     i++;
402     id = *i;
403
404     if (i != message->doc.termlist_end () && id[0] == *prefix)
405     {
406         INTERNAL_ERROR ("Message %s has duplicate thread IDs: %s and %s\n",
407                         notmuch_message_get_message_id (message),
408                         message->thread_id,
409                         id.c_str () + 1);
410     }
411 #endif
412
413     return message->thread_id;
414 }
415
416 void
417 _notmuch_message_add_reply (notmuch_message_t *message,
418                             notmuch_message_node_t *reply)
419 {
420     _notmuch_message_list_append (message->replies, reply);
421 }
422
423 notmuch_messages_t *
424 notmuch_message_get_replies (notmuch_message_t *message)
425 {
426     return _notmuch_messages_create (message->replies);
427 }
428
429 /* Add an additional 'filename' for 'message'.
430  *
431  * This change will not be reflected in the database until the next
432  * call to _notmuch_message_sync. */
433 notmuch_status_t
434 _notmuch_message_add_filename (notmuch_message_t *message,
435                                const char *filename)
436 {
437     notmuch_status_t status;
438     void *local = talloc_new (message);
439     char *direntry;
440
441     if (message->filename_list) {
442         _notmuch_filename_list_destroy (message->filename_list);
443         message->filename_list = NULL;
444     }
445
446     if (filename == NULL)
447         INTERNAL_ERROR ("Message filename cannot be NULL.");
448
449     status = _notmuch_database_filename_to_direntry (local,
450                                                      message->notmuch,
451                                                      filename, &direntry);
452     if (status)
453         return status;
454
455     _notmuch_message_add_term (message, "file-direntry", direntry);
456
457     talloc_free (local);
458
459     return NOTMUCH_STATUS_SUCCESS;
460 }
461
462 /* Change a particular filename for 'message' from 'old_filename' to
463  * 'new_filename'
464  *
465  * This change will not be reflected in the database until the next
466  * call to _notmuch_message_sync.
467  */
468 static notmuch_status_t
469 _notmuch_message_rename (notmuch_message_t *message,
470                          const char *old_filename,
471                          const char *new_filename)
472 {
473     void *local = talloc_new (message);
474     char *direntry;
475     notmuch_private_status_t private_status;
476     notmuch_status_t status;
477
478     status = _notmuch_message_add_filename (message, new_filename);
479     if (status)
480         return status;
481
482     status = _notmuch_database_filename_to_direntry (local, message->notmuch,
483                                                      old_filename, &direntry);
484     if (status)
485         return status;
486
487     private_status = _notmuch_message_remove_term (message,
488                                                    "file-direntry", direntry);
489     status = COERCE_STATUS (private_status,
490                             "Unexpected error from _notmuch_message_remove_term");
491
492     talloc_free (local);
493
494     return status;
495 }
496
497 char *
498 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
499 {
500     return talloc_strdup (message, message->doc.get_data ().c_str ());
501 }
502
503 void
504 _notmuch_message_clear_data (notmuch_message_t *message)
505 {
506     message->doc.set_data ("");
507 }
508
509 static void
510 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
511 {
512     const char *prefix = _find_prefix ("file-direntry");
513     int prefix_len = strlen (prefix);
514     Xapian::TermIterator i;
515
516     if (message->filename_list)
517         return;
518
519     message->filename_list = _notmuch_filename_list_create (message);
520
521     i = message->doc.termlist_begin ();
522     i.skip_to (prefix);
523
524     if (i == message->doc.termlist_end () ||
525         strncmp ((*i).c_str (), prefix, prefix_len))
526     {
527         /* A message document created by an old version of notmuch
528          * (prior to rename support) will have the filename in the
529          * data of the document rather than as a file-direntry term.
530          *
531          * It would be nice to do the upgrade of the document directly
532          * here, but the database is likely open in read-only mode. */
533         const char *data;
534
535         data = message->doc.get_data ().c_str ();
536
537         if (data == NULL)
538             INTERNAL_ERROR ("message with no filename");
539
540         _notmuch_filename_list_add_filename (message->filename_list, data);
541
542         return;
543     }
544
545     for (; i != message->doc.termlist_end (); i++) {
546         void *local = talloc_new (message);
547         const char *db_path, *directory, *basename, *filename;
548         char *colon, *direntry = NULL;
549         unsigned int directory_id;
550
551         /* Terminate loop at first term without desired prefix. */
552         if (strncmp ((*i).c_str (), prefix, prefix_len))
553             break;
554
555         direntry = talloc_strdup (local, (*i).c_str ());
556
557         direntry += prefix_len;
558
559         directory_id = strtol (direntry, &colon, 10);
560
561         if (colon == NULL || *colon != ':')
562             INTERNAL_ERROR ("malformed direntry");
563
564         basename = colon + 1;
565
566         *colon = '\0';
567
568         db_path = notmuch_database_get_path (message->notmuch);
569
570         directory = _notmuch_database_get_directory_path (local,
571                                                           message->notmuch,
572                                                           directory_id);
573
574         if (strlen (directory))
575             filename = talloc_asprintf (message, "%s/%s/%s",
576                                         db_path, directory, basename);
577         else
578             filename = talloc_asprintf (message, "%s/%s",
579                                         db_path, basename);
580
581         _notmuch_filename_list_add_filename (message->filename_list,
582                                              filename);
583
584         talloc_free (local);
585     }
586 }
587
588 const char *
589 notmuch_message_get_filename (notmuch_message_t *message)
590 {
591     _notmuch_message_ensure_filename_list (message);
592
593     if (message->filename_list == NULL)
594         return NULL;
595
596     if (message->filename_list->head == NULL ||
597         message->filename_list->head->filename == NULL)
598     {
599         INTERNAL_ERROR ("message with no filename");
600     }
601
602     return message->filename_list->head->filename;
603 }
604
605 notmuch_filenames_t *
606 notmuch_message_get_filenames (notmuch_message_t *message)
607 {
608     _notmuch_message_ensure_filename_list (message);
609
610     return _notmuch_filenames_create (message, message->filename_list);
611 }
612
613 notmuch_bool_t
614 notmuch_message_get_flag (notmuch_message_t *message,
615                           notmuch_message_flag_t flag)
616 {
617     return message->flags & (1 << flag);
618 }
619
620 void
621 notmuch_message_set_flag (notmuch_message_t *message,
622                           notmuch_message_flag_t flag, notmuch_bool_t enable)
623 {
624     if (enable)
625         message->flags |= (1 << flag);
626     else
627         message->flags &= ~(1 << flag);
628 }
629
630 time_t
631 notmuch_message_get_date (notmuch_message_t *message)
632 {
633     std::string value;
634
635     try {
636         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
637     } catch (Xapian::Error &error) {
638         INTERNAL_ERROR ("Failed to read timestamp value from document.");
639         return 0;
640     }
641
642     return Xapian::sortable_unserialise (value);
643 }
644
645 notmuch_tags_t *
646 notmuch_message_get_tags (notmuch_message_t *message)
647 {
648     Xapian::TermIterator i, end;
649     i = message->doc.termlist_begin();
650     end = message->doc.termlist_end();
651     return _notmuch_convert_tags(message, i, end);
652 }
653
654 const char *
655 notmuch_message_get_author (notmuch_message_t *message)
656 {
657     return message->author;
658 }
659
660 void
661 notmuch_message_set_author (notmuch_message_t *message,
662                             const char *author)
663 {
664     if (message->author)
665         talloc_free(message->author);
666     message->author = talloc_strdup(message, author);
667     return;
668 }
669
670 void
671 _notmuch_message_set_date (notmuch_message_t *message,
672                            const char *date)
673 {
674     time_t time_value;
675
676     /* GMime really doesn't want to see a NULL date, so protect its
677      * sensibilities. */
678     if (date == NULL || *date == '\0')
679         time_value = 0;
680     else
681         time_value = g_mime_utils_header_decode_date (date, NULL);
682
683     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
684                             Xapian::sortable_serialise (time_value));
685 }
686
687 /* Synchronize changes made to message->doc out into the database. */
688 void
689 _notmuch_message_sync (notmuch_message_t *message)
690 {
691     Xapian::WritableDatabase *db;
692
693     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
694         return;
695
696     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
697     db->replace_document (message->doc_id, message->doc);
698 }
699
700 /* Ensure that 'message' is not holding any file object open. Future
701  * calls to various functions will still automatically open the
702  * message file as needed.
703  */
704 void
705 _notmuch_message_close (notmuch_message_t *message)
706 {
707     if (message->message_file) {
708         notmuch_message_file_close (message->message_file);
709         message->message_file = NULL;
710     }
711 }
712
713 /* Add a name:value term to 'message', (the actual term will be
714  * encoded by prefixing the value with a short prefix). See
715  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
716  * names to prefix values.
717  *
718  * This change will not be reflected in the database until the next
719  * call to _notmuch_message_sync. */
720 notmuch_private_status_t
721 _notmuch_message_add_term (notmuch_message_t *message,
722                            const char *prefix_name,
723                            const char *value)
724 {
725
726     char *term;
727
728     if (value == NULL)
729         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
730
731     term = talloc_asprintf (message, "%s%s",
732                             _find_prefix (prefix_name), value);
733
734     if (strlen (term) > NOTMUCH_TERM_MAX)
735         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
736
737     message->doc.add_term (term, 0);
738
739     talloc_free (term);
740
741     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
742 }
743
744 /* Parse 'text' and add a term to 'message' for each parsed word. Each
745  * term will be added both prefixed (if prefix_name is not NULL) and
746  * also unprefixed). */
747 notmuch_private_status_t
748 _notmuch_message_gen_terms (notmuch_message_t *message,
749                             const char *prefix_name,
750                             const char *text)
751 {
752     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
753
754     if (text == NULL)
755         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
756
757     term_gen->set_document (message->doc);
758
759     if (prefix_name) {
760         const char *prefix = _find_prefix (prefix_name);
761
762         term_gen->index_text (text, 1, prefix);
763     }
764
765     term_gen->index_text (text);
766
767     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
768 }
769
770 /* Remove a name:value term from 'message', (the actual term will be
771  * encoded by prefixing the value with a short prefix). See
772  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
773  * names to prefix values.
774  *
775  * This change will not be reflected in the database until the next
776  * call to _notmuch_message_sync. */
777 notmuch_private_status_t
778 _notmuch_message_remove_term (notmuch_message_t *message,
779                               const char *prefix_name,
780                               const char *value)
781 {
782     char *term;
783
784     if (value == NULL)
785         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
786
787     term = talloc_asprintf (message, "%s%s",
788                             _find_prefix (prefix_name), value);
789
790     if (strlen (term) > NOTMUCH_TERM_MAX)
791         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
792
793     try {
794         message->doc.remove_term (term);
795     } catch (const Xapian::InvalidArgumentError) {
796         /* We'll let the philosopher's try to wrestle with the
797          * question of whether failing to remove that which was not
798          * there in the first place is failure. For us, we'll silently
799          * consider it all good. */
800     }
801
802     talloc_free (term);
803
804     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
805 }
806
807 notmuch_status_t
808 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
809 {
810     notmuch_private_status_t private_status;
811     notmuch_status_t status;
812
813     status = _notmuch_database_ensure_writable (message->notmuch);
814     if (status)
815         return status;
816
817     if (tag == NULL)
818         return NOTMUCH_STATUS_NULL_POINTER;
819
820     if (strlen (tag) > NOTMUCH_TAG_MAX)
821         return NOTMUCH_STATUS_TAG_TOO_LONG;
822
823     private_status = _notmuch_message_add_term (message, "tag", tag);
824     if (private_status) {
825         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
826                         private_status);
827     }
828
829     if (! message->frozen)
830         _notmuch_message_sync (message);
831
832     return NOTMUCH_STATUS_SUCCESS;
833 }
834
835 notmuch_status_t
836 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
837 {
838     notmuch_private_status_t private_status;
839     notmuch_status_t status;
840
841     status = _notmuch_database_ensure_writable (message->notmuch);
842     if (status)
843         return status;
844
845     if (tag == NULL)
846         return NOTMUCH_STATUS_NULL_POINTER;
847
848     if (strlen (tag) > NOTMUCH_TAG_MAX)
849         return NOTMUCH_STATUS_TAG_TOO_LONG;
850
851     private_status = _notmuch_message_remove_term (message, "tag", tag);
852     if (private_status) {
853         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
854                         private_status);
855     }
856
857     if (! message->frozen)
858         _notmuch_message_sync (message);
859
860     return NOTMUCH_STATUS_SUCCESS;
861 }
862
863 notmuch_status_t
864 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
865 {
866     const char *flags;
867     notmuch_status_t status;
868     notmuch_filenames_t *filenames;
869     const char *filename;
870     char *combined_flags = talloc_strdup (message, "");
871     unsigned i;
872     int seen_maildir_info = 0;
873
874     for (filenames = notmuch_message_get_filenames (message);
875          notmuch_filenames_valid (filenames);
876          notmuch_filenames_move_to_next (filenames))
877     {
878         filename = notmuch_filenames_get (filenames);
879
880         flags = strstr (filename, ":2,");
881         if (! flags)
882             continue;
883
884         seen_maildir_info = 1;
885         flags += 3;
886
887         combined_flags = talloc_strdup_append (combined_flags, flags);
888     }
889
890     /* If none of the filenames have any maildir info field (not even
891      * an empty info with no flags set) then there's no information to
892      * go on, so do nothing. */
893     if (! seen_maildir_info)
894         return NOTMUCH_STATUS_SUCCESS;
895
896     status = notmuch_message_freeze (message);
897     if (status)
898         return status;
899
900     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
901         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
902             ^ 
903             flag2tag[i].inverse)
904         {
905             status = notmuch_message_add_tag (message, flag2tag[i].tag);
906         } else {
907             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
908         }
909         if (status)
910             return status;
911     }
912     status = notmuch_message_thaw (message);
913
914     talloc_free (combined_flags);
915
916     return status;
917 }
918
919 /* Is the given filename within a maildir directory?
920  *
921  * Specifically, is the final directory component of 'filename' either
922  * "cur" or "new". If so, return a pointer to that final directory
923  * component within 'filename'. If not, return NULL.
924  *
925  * A non-NULL return value is guaranteed to be a valid string pointer
926  * pointing to the characters "new/" or "cur/", (but not
927  * NUL-terminated).
928  */
929 static const char *
930 _filename_is_in_maildir (const char *filename)
931 {
932     const char *slash, *dir = NULL;
933
934     /* Find the last '/' separating directory from filename. */
935     slash = strrchr (filename, '/');
936     if (slash == NULL)
937         return NULL;
938
939     /* Jump back 4 characters to where the previous '/' will be if the
940      * directory is named "cur" or "new". */
941     if (slash - filename < 4)
942         return NULL;
943
944     slash -= 4;
945
946     if (*slash != '/')
947         return NULL;
948
949     dir = slash + 1;
950
951     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
952         STRNCMP_LITERAL (dir, "new/") == 0)
953     {
954         return dir;
955     }
956
957     return NULL;
958 }
959
960 /* From the set of tags on 'message' and the flag2tag table, compute a
961  * set of maildir-flag actions to be taken, (flags that should be
962  * either set or cleared).
963  *
964  * The result is returned as two talloced strings: to_set, and to_clear
965  */
966 static void
967 _get_maildir_flag_actions (notmuch_message_t *message,
968                            char **to_set_ret,
969                            char **to_clear_ret)
970 {
971     char *to_set, *to_clear;
972     notmuch_tags_t *tags;
973     const char *tag;
974     unsigned i;
975
976     to_set = talloc_strdup (message, "");
977     to_clear = talloc_strdup (message, "");
978
979     /* First, find flags for all set tags. */
980     for (tags = notmuch_message_get_tags (message);
981          notmuch_tags_valid (tags);
982          notmuch_tags_move_to_next (tags))
983     {
984         tag = notmuch_tags_get (tags);
985
986         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
987             if (strcmp (tag, flag2tag[i].tag) == 0) {
988                 if (flag2tag[i].inverse)
989                     to_clear = talloc_asprintf_append (to_clear,
990                                                        "%c",
991                                                        flag2tag[i].flag);
992                 else
993                     to_set = talloc_asprintf_append (to_set,
994                                                      "%c",
995                                                      flag2tag[i].flag);
996             }
997         }
998     }
999
1000     /* Then, find the flags for all tags not present. */
1001     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1002         if (flag2tag[i].inverse) {
1003             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1004                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1005         } else {
1006             if (strchr (to_set, flag2tag[i].flag) == NULL)
1007                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1008         }
1009     }
1010
1011     *to_set_ret = to_set;
1012     *to_clear_ret = to_clear;
1013 }
1014
1015 /* Given 'filename' and a set of maildir flags to set and to clear,
1016  * compute the new maildir filename.
1017  *
1018  * If the existing filename is in the directory "new", the new
1019  * filename will be in the directory "cur".
1020  *
1021  * After a sequence of ":2," in the filename, any subsequent
1022  * single-character flags will be added or removed according to the
1023  * characters in flags_to_set and flags_to_clear. Any existing flags
1024  * not mentioned in either string will remain. The final list of flags
1025  * will be in ASCII order.
1026  *
1027  * If the original flags seem invalid, (repeated characters or
1028  * non-ASCII ordering of flags), this function will return NULL
1029  * (meaning that renaming would not be safe and should not occur).
1030  */
1031 static char*
1032 _new_maildir_filename (void *ctx,
1033                        const char *filename,
1034                        const char *flags_to_set,
1035                        const char *flags_to_clear)
1036 {
1037     const char *info, *flags;
1038     unsigned int flag, last_flag;
1039     char *filename_new, *dir;
1040     char flag_map[128];
1041     int flags_in_map = 0;
1042     unsigned int i;
1043     char *s;
1044
1045     memset (flag_map, 0, sizeof (flag_map));
1046
1047     info = strstr (filename, ":2,");
1048
1049     if (info == NULL) {
1050         info = filename + strlen(filename);
1051     } else {
1052         flags = info + 3;
1053
1054         /* Loop through existing flags in filename. */
1055         for (flags = info + 3, last_flag = 0;
1056              *flags;
1057              last_flag = flag, flags++)
1058         {
1059             flag = *flags;
1060
1061             /* Original flags not in ASCII order. Abort. */
1062             if (flag < last_flag)
1063                 return NULL;
1064
1065             /* Non-ASCII flag. Abort. */
1066             if (flag > sizeof(flag_map) - 1)
1067                 return NULL;
1068
1069             /* Repeated flag value. Abort. */
1070             if (flag_map[flag])
1071                 return NULL;
1072
1073             flag_map[flag] = 1;
1074             flags_in_map++;
1075         }
1076     }
1077
1078     /* Then set and clear our flags from tags. */
1079     for (flags = flags_to_set; *flags; flags++) {
1080         flag = *flags;
1081         if (flag_map[flag] == 0) {
1082             flag_map[flag] = 1;
1083             flags_in_map++;
1084         }
1085     }
1086
1087     for (flags = flags_to_clear; *flags; flags++) {
1088         flag = *flags;
1089         if (flag_map[flag]) {
1090             flag_map[flag] = 0;
1091             flags_in_map--;
1092         }
1093     }
1094
1095     filename_new = (char *) talloc_size (ctx,
1096                                          info - filename +
1097                                          strlen (":2,") + flags_in_map + 1);
1098     if (unlikely (filename_new == NULL))
1099         return NULL;
1100
1101     strncpy (filename_new, filename, info - filename);
1102     filename_new[info - filename] = '\0';
1103
1104     strcat (filename_new, ":2,");
1105
1106     s = filename_new + strlen (filename_new);
1107     for (i = 0; i < sizeof (flag_map); i++)
1108     {
1109         if (flag_map[i]) {
1110             *s = i;
1111             s++;
1112         }
1113     }
1114     *s = '\0';
1115
1116     /* If message is in new/ move it under cur/. */
1117     dir = (char *) _filename_is_in_maildir (filename_new);
1118     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1119         memcpy (dir, "cur/", 4);
1120
1121     return filename_new;
1122 }
1123
1124 notmuch_status_t
1125 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1126 {
1127     notmuch_filenames_t *filenames;
1128     const char *filename;
1129     char *filename_new;
1130     char *to_set, *to_clear;
1131     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1132
1133     _get_maildir_flag_actions (message, &to_set, &to_clear);
1134
1135     for (filenames = notmuch_message_get_filenames (message);
1136          notmuch_filenames_valid (filenames);
1137          notmuch_filenames_move_to_next (filenames))
1138     {
1139         filename = notmuch_filenames_get (filenames);
1140
1141         if (! _filename_is_in_maildir (filename))
1142             continue;
1143
1144         filename_new = _new_maildir_filename (message, filename,
1145                                               to_set, to_clear);
1146         if (filename_new == NULL)
1147             continue;
1148
1149         if (strcmp (filename, filename_new)) {
1150             int err;
1151             notmuch_status_t new_status;
1152
1153             err = rename (filename, filename_new);
1154             if (err)
1155                 continue;
1156
1157             new_status = _notmuch_message_rename (message,
1158                                                   filename, filename_new);
1159             /* Hold on to only the first error. */
1160             if (! status && new_status) {
1161                 status = new_status;
1162                 continue;
1163             }
1164
1165             _notmuch_message_sync (message);
1166         }
1167
1168         talloc_free (filename_new);
1169     }
1170
1171     talloc_free (to_set);
1172     talloc_free (to_clear);
1173
1174     return NOTMUCH_STATUS_SUCCESS;
1175 }
1176
1177 notmuch_status_t
1178 notmuch_message_remove_all_tags (notmuch_message_t *message)
1179 {
1180     notmuch_private_status_t private_status;
1181     notmuch_status_t status;
1182     notmuch_tags_t *tags;
1183     const char *tag;
1184
1185     status = _notmuch_database_ensure_writable (message->notmuch);
1186     if (status)
1187         return status;
1188
1189     for (tags = notmuch_message_get_tags (message);
1190          notmuch_tags_valid (tags);
1191          notmuch_tags_move_to_next (tags))
1192     {
1193         tag = notmuch_tags_get (tags);
1194
1195         private_status = _notmuch_message_remove_term (message, "tag", tag);
1196         if (private_status) {
1197             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1198                             private_status);
1199         }
1200     }
1201
1202     if (! message->frozen)
1203         _notmuch_message_sync (message);
1204
1205     return NOTMUCH_STATUS_SUCCESS;
1206 }
1207
1208 notmuch_status_t
1209 notmuch_message_freeze (notmuch_message_t *message)
1210 {
1211     notmuch_status_t status;
1212
1213     status = _notmuch_database_ensure_writable (message->notmuch);
1214     if (status)
1215         return status;
1216
1217     message->frozen++;
1218
1219     return NOTMUCH_STATUS_SUCCESS;
1220 }
1221
1222 notmuch_status_t
1223 notmuch_message_thaw (notmuch_message_t *message)
1224 {
1225     notmuch_status_t status;
1226
1227     status = _notmuch_database_ensure_writable (message->notmuch);
1228     if (status)
1229         return status;
1230
1231     if (message->frozen > 0) {
1232         message->frozen--;
1233         if (message->frozen == 0)
1234             _notmuch_message_sync (message);
1235         return NOTMUCH_STATUS_SUCCESS;
1236     } else {
1237         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1238     }
1239 }
1240
1241 void
1242 notmuch_message_destroy (notmuch_message_t *message)
1243 {
1244     talloc_free (message);
1245 }