]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
88f7c362dc6d2173d3b4b1d3709ed9e9d85e0e48
[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     char *filename;
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 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 = 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 no that all
136  * memory will be reclaimed with 'talloc_owner' is free. 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 const char *
258 notmuch_message_get_message_id (notmuch_message_t *message)
259 {
260     Xapian::TermIterator i;
261
262     if (message->message_id)
263         return message->message_id;
264
265     i = message->doc.termlist_begin ();
266     i.skip_to (_find_prefix ("id"));
267
268     if (i == message->doc.termlist_end ())
269         INTERNAL_ERROR ("Message with document ID of %d has no message ID.\n",
270                         message->doc_id);
271
272     message->message_id = talloc_strdup (message, (*i).c_str () + 1);
273
274 #if DEBUG_DATABASE_SANITY
275     i++;
276
277     if (i != message->doc.termlist_end () &&
278         strncmp ((*i).c_str (), _find_prefix ("id"),
279                  strlen (_find_prefix ("id"))) == 0)
280     {
281         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate message IDs",
282                         message->doc_id);
283     }
284 #endif
285
286     return message->message_id;
287 }
288
289 static void
290 _notmuch_message_ensure_message_file (notmuch_message_t *message)
291 {
292     const char *filename;
293
294     if (message->message_file)
295         return;
296
297     filename = notmuch_message_get_filename (message);
298     if (unlikely (filename == NULL))
299         return;
300
301     message->message_file = _notmuch_message_file_open_ctx (message, filename);
302 }
303
304 const char *
305 notmuch_message_get_header (notmuch_message_t *message, const char *header)
306 {
307     _notmuch_message_ensure_message_file (message);
308     if (message->message_file == NULL)
309         return NULL;
310
311     return notmuch_message_file_get_header (message->message_file, header);
312 }
313
314 /* Return the message ID from the In-Reply-To header of 'message'.
315  *
316  * Returns an empty string ("") if 'message' has no In-Reply-To
317  * header.
318  *
319  * Returns NULL if any error occurs.
320  */
321 const char *
322 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
323 {
324     const char *prefix = _find_prefix ("replyto");
325     int prefix_len = strlen (prefix);
326     Xapian::TermIterator i;
327     std::string in_reply_to;
328
329     if (message->in_reply_to)
330         return message->in_reply_to;
331
332     i = message->doc.termlist_begin ();
333     i.skip_to (prefix);
334
335     if (i != message->doc.termlist_end ())
336         in_reply_to = *i;
337
338     /* It's perfectly valid for a message to have no In-Reply-To
339      * header. For these cases, we return an empty string. */
340     if (i == message->doc.termlist_end () ||
341         strncmp (in_reply_to.c_str (), prefix, prefix_len))
342     {
343         message->in_reply_to = talloc_strdup (message, "");
344         return message->in_reply_to;
345     }
346
347     message->in_reply_to = talloc_strdup (message,
348                                           in_reply_to.c_str () + prefix_len);
349
350 #if DEBUG_DATABASE_SANITY
351     i++;
352
353     in_reply_to = *i;
354
355     if (i != message->doc.termlist_end () &&
356         strncmp ((*i).c_str (), prefix, prefix_len) == 0)
357     {
358        INTERNAL_ERROR ("Message %s has duplicate In-Reply-To IDs: %s and %s\n",
359                         notmuch_message_get_message_id (message),
360                         message->in_reply_to,
361                         (*i).c_str () + prefix_len);
362     }
363 #endif
364
365     return message->in_reply_to;
366 }
367
368 const char *
369 notmuch_message_get_thread_id (notmuch_message_t *message)
370 {
371     const char *prefix = _find_prefix ("thread");
372     Xapian::TermIterator i;
373     std::string id;
374
375     /* This code is written with the assumption that "thread" has a
376      * single-character prefix. */
377     assert (strlen (prefix) == 1);
378
379     if (message->thread_id)
380         return message->thread_id;
381
382     i = message->doc.termlist_begin ();
383     i.skip_to (prefix);
384
385     if (i != message->doc.termlist_end ())
386         id = *i;
387
388     if (i == message->doc.termlist_end () || id[0] != *prefix)
389         INTERNAL_ERROR ("Message with document ID of %d has no thread ID.\n",
390                         message->doc_id);
391
392     message->thread_id = talloc_strdup (message, id.c_str () + 1);
393
394 #if DEBUG_DATABASE_SANITY
395     i++;
396     id = *i;
397
398     if (i != message->doc.termlist_end () && id[0] == *prefix)
399     {
400         INTERNAL_ERROR ("Message %s has duplicate thread IDs: %s and %s\n",
401                         notmuch_message_get_message_id (message),
402                         message->thread_id,
403                         id.c_str () + 1);
404     }
405 #endif
406
407     return message->thread_id;
408 }
409
410 void
411 _notmuch_message_add_reply (notmuch_message_t *message,
412                             notmuch_message_node_t *reply)
413 {
414     _notmuch_message_list_append (message->replies, reply);
415 }
416
417 notmuch_messages_t *
418 notmuch_message_get_replies (notmuch_message_t *message)
419 {
420     return _notmuch_messages_create (message->replies);
421 }
422
423 /* Add an additional 'filename' for 'message'.
424  *
425  * This change will not be reflected in the database until the next
426  * call to _notmuch_message_sync. */
427 notmuch_status_t
428 _notmuch_message_add_filename (notmuch_message_t *message,
429                                const char *filename)
430 {
431     notmuch_status_t status;
432     void *local = talloc_new (message);
433     char *direntry;
434
435     if (message->filename) {
436         talloc_free (message->filename);
437         message->filename = NULL;
438     }
439
440     if (filename == NULL)
441         INTERNAL_ERROR ("Message filename cannot be NULL.");
442
443     status = _notmuch_database_filename_to_direntry (local,
444                                                      message->notmuch,
445                                                      filename, &direntry);
446     if (status)
447         return status;
448
449     _notmuch_message_add_term (message, "file-direntry", direntry);
450
451     talloc_free (local);
452
453     return NOTMUCH_STATUS_SUCCESS;
454 }
455
456 char *
457 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
458 {
459     return talloc_strdup (message, message->doc.get_data ().c_str ());
460 }
461
462 void
463 _notmuch_message_clear_data (notmuch_message_t *message)
464 {
465     message->doc.set_data ("");
466 }
467
468 const char *
469 notmuch_message_get_filename (notmuch_message_t *message)
470 {
471     const char *prefix = _find_prefix ("file-direntry");
472     int prefix_len = strlen (prefix);
473     Xapian::TermIterator i;
474     char *colon, *direntry = NULL;
475     const char *db_path, *directory, *basename;
476     unsigned int directory_id;
477     void *local = talloc_new (message);
478
479     if (message->filename)
480         return message->filename;
481
482     i = message->doc.termlist_begin ();
483     i.skip_to (prefix);
484
485     if (i != message->doc.termlist_end ())
486         direntry = talloc_strdup (local, (*i).c_str ());
487
488     if (i == message->doc.termlist_end () ||
489         strncmp (direntry, prefix, prefix_len))
490     {
491         /* A message document created by an old version of notmuch
492          * (prior to rename support) will have the filename in the
493          * data of the document rather than as a file-direntry term.
494          *
495          * It would be nice to do the upgrade of the document directly
496          * here, but the database is likely open in read-only mode. */
497         const char *data;
498
499         data = message->doc.get_data ().c_str ();
500
501         if (data == NULL)
502             INTERNAL_ERROR ("message with no filename");
503
504         message->filename = talloc_strdup (message, data);
505
506         return message->filename;
507     }
508
509     direntry += prefix_len;
510
511     directory_id = strtol (direntry, &colon, 10);
512
513     if (colon == NULL || *colon != ':')
514         INTERNAL_ERROR ("malformed direntry");
515
516     basename = colon + 1;
517
518     *colon = '\0';
519
520     db_path = notmuch_database_get_path (message->notmuch);
521
522     directory = _notmuch_database_get_directory_path (local,
523                                                       message->notmuch,
524                                                       directory_id);
525
526     if (strlen (directory))
527         message->filename = talloc_asprintf (message, "%s/%s/%s",
528                                              db_path, directory, basename);
529     else
530         message->filename = talloc_asprintf (message, "%s/%s",
531                                              db_path, basename);
532     talloc_free ((void *) directory);
533
534     talloc_free (local);
535
536     return message->filename;
537 }
538
539 notmuch_bool_t
540 notmuch_message_get_flag (notmuch_message_t *message,
541                           notmuch_message_flag_t flag)
542 {
543     return message->flags & (1 << flag);
544 }
545
546 void
547 notmuch_message_set_flag (notmuch_message_t *message,
548                           notmuch_message_flag_t flag, notmuch_bool_t enable)
549 {
550     if (enable)
551         message->flags |= (1 << flag);
552     else
553         message->flags &= ~(1 << flag);
554 }
555
556 time_t
557 notmuch_message_get_date (notmuch_message_t *message)
558 {
559     std::string value;
560
561     try {
562         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
563     } catch (Xapian::Error &error) {
564         INTERNAL_ERROR ("Failed to read timestamp value from document.");
565         return 0;
566     }
567
568     return Xapian::sortable_unserialise (value);
569 }
570
571 notmuch_tags_t *
572 notmuch_message_get_tags (notmuch_message_t *message)
573 {
574     Xapian::TermIterator i, end;
575     i = message->doc.termlist_begin();
576     end = message->doc.termlist_end();
577     return _notmuch_convert_tags(message, i, end);
578 }
579
580 const char *
581 notmuch_message_get_author (notmuch_message_t *message)
582 {
583     return message->author;
584 }
585
586 void
587 notmuch_message_set_author (notmuch_message_t *message,
588                             const char *author)
589 {
590     if (message->author)
591         talloc_free(message->author);
592     message->author = talloc_strdup(message, author);
593     return;
594 }
595
596 void
597 _notmuch_message_set_date (notmuch_message_t *message,
598                            const char *date)
599 {
600     time_t time_value;
601
602     /* GMime really doesn't want to see a NULL date, so protect its
603      * sensibilities. */
604     if (date == NULL || *date == '\0')
605         time_value = 0;
606     else
607         time_value = g_mime_utils_header_decode_date (date, NULL);
608
609     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
610                             Xapian::sortable_serialise (time_value));
611 }
612
613 /* Synchronize changes made to message->doc out into the database. */
614 void
615 _notmuch_message_sync (notmuch_message_t *message)
616 {
617     Xapian::WritableDatabase *db;
618
619     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
620         return;
621
622     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
623     db->replace_document (message->doc_id, message->doc);
624 }
625
626 /* Ensure that 'message' is not holding any file object open. Future
627  * calls to various functions will still automatically open the
628  * message file as needed.
629  */
630 void
631 _notmuch_message_close (notmuch_message_t *message)
632 {
633     if (message->message_file) {
634         notmuch_message_file_close (message->message_file);
635         message->message_file = NULL;
636     }
637 }
638
639 /* Add a name:value term to 'message', (the actual term will be
640  * encoded by prefixing the value with a short prefix). See
641  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
642  * names to prefix values.
643  *
644  * This change will not be reflected in the database until the next
645  * call to _notmuch_message_sync. */
646 notmuch_private_status_t
647 _notmuch_message_add_term (notmuch_message_t *message,
648                            const char *prefix_name,
649                            const char *value)
650 {
651
652     char *term;
653
654     if (value == NULL)
655         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
656
657     term = talloc_asprintf (message, "%s%s",
658                             _find_prefix (prefix_name), value);
659
660     if (strlen (term) > NOTMUCH_TERM_MAX)
661         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
662
663     message->doc.add_term (term, 0);
664
665     talloc_free (term);
666
667     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
668 }
669
670 /* Parse 'text' and add a term to 'message' for each parsed word. Each
671  * term will be added both prefixed (if prefix_name is not NULL) and
672  * also unprefixed). */
673 notmuch_private_status_t
674 _notmuch_message_gen_terms (notmuch_message_t *message,
675                             const char *prefix_name,
676                             const char *text)
677 {
678     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
679
680     if (text == NULL)
681         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
682
683     term_gen->set_document (message->doc);
684
685     if (prefix_name) {
686         const char *prefix = _find_prefix (prefix_name);
687
688         term_gen->index_text (text, 1, prefix);
689     }
690
691     term_gen->index_text (text);
692
693     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
694 }
695
696 /* Remove a name:value term from 'message', (the actual term will be
697  * encoded by prefixing the value with a short prefix). See
698  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
699  * names to prefix values.
700  *
701  * This change will not be reflected in the database until the next
702  * call to _notmuch_message_sync. */
703 notmuch_private_status_t
704 _notmuch_message_remove_term (notmuch_message_t *message,
705                               const char *prefix_name,
706                               const char *value)
707 {
708     char *term;
709
710     if (value == NULL)
711         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
712
713     term = talloc_asprintf (message, "%s%s",
714                             _find_prefix (prefix_name), value);
715
716     if (strlen (term) > NOTMUCH_TERM_MAX)
717         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
718
719     try {
720         message->doc.remove_term (term);
721     } catch (const Xapian::InvalidArgumentError) {
722         /* We'll let the philosopher's try to wrestle with the
723          * question of whether failing to remove that which was not
724          * there in the first place is failure. For us, we'll silently
725          * consider it all good. */
726     }
727
728     talloc_free (term);
729
730     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
731 }
732
733 /* Change the message filename stored in the database.
734  *
735  * This change will not be reflected in the database until the next
736  * call to _notmuch_message_sync.
737  */
738 notmuch_status_t
739 _notmuch_message_rename (notmuch_message_t *message,
740                          const char *new_filename)
741 {
742     void *local = talloc_new (message);
743     char *direntry;
744     Xapian::PostingIterator i, end;
745     Xapian::Document document;
746     notmuch_private_status_t private_status;
747     notmuch_status_t status;
748     const char *old_filename;
749
750     old_filename = notmuch_message_get_filename(message);
751     old_filename = talloc_reference(local, old_filename);
752     if (unlikely (! old_filename))
753         return NOTMUCH_STATUS_OUT_OF_MEMORY;
754
755     status = _notmuch_message_add_filename (message, new_filename);
756     if (status)
757         return status;
758
759     status = _notmuch_database_filename_to_direntry (local, message->notmuch,
760                                                      old_filename, &direntry);
761     if (status)
762         return status;
763
764     private_status = _notmuch_message_remove_term (message, "file-direntry", direntry);
765     status = COERCE_STATUS (private_status,
766                             "Unexpected error from _notmuch_message_remove_term");
767
768     talloc_free (local);
769
770     return status;
771 }
772
773 notmuch_status_t
774 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
775 {
776     notmuch_private_status_t private_status;
777     notmuch_status_t status;
778
779     status = _notmuch_database_ensure_writable (message->notmuch);
780     if (status)
781         return status;
782
783     if (tag == NULL)
784         return NOTMUCH_STATUS_NULL_POINTER;
785
786     if (strlen (tag) > NOTMUCH_TAG_MAX)
787         return NOTMUCH_STATUS_TAG_TOO_LONG;
788
789     private_status = _notmuch_message_add_term (message, "tag", tag);
790     if (private_status) {
791         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
792                         private_status);
793     }
794
795     if (! message->frozen)
796         _notmuch_message_sync (message);
797
798     return NOTMUCH_STATUS_SUCCESS;
799 }
800
801 notmuch_status_t
802 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
803 {
804     notmuch_private_status_t private_status;
805     notmuch_status_t status;
806
807     status = _notmuch_database_ensure_writable (message->notmuch);
808     if (status)
809         return status;
810
811     if (tag == NULL)
812         return NOTMUCH_STATUS_NULL_POINTER;
813
814     if (strlen (tag) > NOTMUCH_TAG_MAX)
815         return NOTMUCH_STATUS_TAG_TOO_LONG;
816
817     private_status = _notmuch_message_remove_term (message, "tag", tag);
818     if (private_status) {
819         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
820                         private_status);
821     }
822
823     if (! message->frozen)
824         _notmuch_message_sync (message);
825
826     return NOTMUCH_STATUS_SUCCESS;
827 }
828
829 /* XXX: Needs to iterate over all message filenames. */
830 notmuch_status_t
831 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
832 {
833     const char *flags, *p;
834     char f;
835     bool valid, unread;
836     unsigned i;
837     notmuch_status_t status;
838     const char *filename;
839
840     filename = notmuch_message_get_filename (message);
841
842     flags = strstr (filename, ":2,");
843     if (!flags)
844         return NOTMUCH_STATUS_FILE_NOT_EMAIL;
845     flags += 3;
846
847     /*  Check that the letters are valid Maildir flags */
848     f = 0;
849     valid = true;
850     for (p=flags; valid && *p; p++) {
851         switch (*p) {
852         case 'P':
853         case 'R':
854         case 'S':
855         case 'T':
856         case 'D':
857         case 'F':
858             if (*p > f) f=*p;
859             else valid = false;
860         break;
861         default:
862             valid = false;
863         }
864     }
865     if (!valid) {
866         fprintf (stderr, "Warning: Invalid maildir flags in filename %s\n", filename);
867         return NOTMUCH_STATUS_FILE_NOT_EMAIL;
868     }
869
870     status = notmuch_message_freeze (message);
871     if (status)
872         return status;
873     unread = true;
874     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
875         if ((strchr (flags, flag2tag[i].flag) != NULL) ^ flag2tag[i].inverse) {
876             status = notmuch_message_add_tag (message, flag2tag[i].tag);
877         } else {
878             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
879         }
880         if (status)
881             return status;
882     }
883     status = notmuch_message_thaw (message);
884
885     /* From now on, we can synchronize the tags from the database to
886      * the mailstore. */
887     notmuch_message_set_flag (message, NOTMUCH_MESSAGE_FLAG_TAGS_INVALID, FALSE);
888     return status;
889 }
890
891 static void
892 maildir_get_new_flags(notmuch_message_t *message, char *flags)
893 {
894     notmuch_tags_t *tags;
895     const char *tag;
896     unsigned i;
897     char *p;
898
899     for (i = 0; i < ARRAY_SIZE(flag2tag); i++)
900         flags[i] = flag2tag[i].inverse ? flag2tag[i].flag : '\0';
901
902     for (tags = notmuch_message_get_tags (message);
903          notmuch_tags_valid (tags);
904          notmuch_tags_move_to_next (tags))
905     {
906         tag = notmuch_tags_get (tags);
907         for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
908             if (strcmp(tag, flag2tag[i].tag) == 0)
909                 flags[i] = flag2tag[i].inverse ? '\0' : flag2tag[i].flag;
910         }
911     }
912
913     p = flags;
914     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
915         if (flags[i])
916             *p++ = flags[i];
917     }
918     *p = '\0';
919 }
920
921 static char *
922 maildir_get_subdir (char *filename)
923 {
924     char *p, *subdir = NULL;
925
926     p = filename + strlen (filename) - 1;
927     while (p > filename + 3 && *p != '/')
928         p--;
929     if (*p == '/') {
930         subdir = p - 3;
931         if (subdir > filename && *(subdir - 1) != '/')
932             subdir = NULL;
933     }
934     return subdir;
935 }
936
937 /* XXX: Needs to iterate over all filenames in the message
938  *
939  * XXX: Needs to ensure that existing, unsupported flags in the
940  *      filename are left unchanged (which also needs a test in the
941  *      test suite).
942  */
943 notmuch_status_t
944 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
945 {
946     char flags[ARRAY_SIZE(flag2tag)+1];
947     const char *filename, *p;
948     char *filename_new, *subdir = NULL;
949     int ret;
950
951     maildir_get_new_flags (message, flags);
952
953     filename = notmuch_message_get_filename (message);
954     /* TODO: Iterate over all file names. */
955     p = strstr(filename, ":2,");
956     if ((p && strcmp (p+3, flags) == 0) ||
957         (!p && flags[0] == '\0')) {
958         // Return if flags are not to be changed - this suppresses
959         // moving the message from new/ to cur/ during initial
960         // tagging.
961         return NOTMUCH_STATUS_SUCCESS;
962     }
963     if (!p)
964         p = filename + strlen(filename);
965
966     filename_new = (char*)talloc_size(message, (p-filename) + 3 + sizeof(flags));
967     if (unlikely (filename_new == NULL))
968         return NOTMUCH_STATUS_OUT_OF_MEMORY;
969
970     memcpy(filename_new, filename, p-filename);
971     filename_new[p-filename] = '\0';
972
973     /* If message is in new/ move it under cur/. */
974     subdir = maildir_get_subdir (filename_new);
975     if (subdir && memcmp (subdir, "new/", 4) == 0)
976         memcpy (subdir, "cur/", 4);
977
978     strcpy (filename_new+(p-filename), ":2,");
979     strcpy (filename_new+(p-filename)+3, flags);
980
981     if (strcmp (filename, filename_new) != 0) {
982         ret = rename (filename, filename_new);
983         if (ret == -1) {
984             perror (talloc_asprintf (message, "rename of %s to %s failed",
985                                      filename, filename_new));
986             exit (1);
987         }
988         return _notmuch_message_rename (message, filename_new);
989         /* _notmuch_message_sync is our caller. Do not call it here. */
990     }
991     return NOTMUCH_STATUS_SUCCESS;
992 }
993
994 notmuch_status_t
995 notmuch_message_remove_all_tags (notmuch_message_t *message)
996 {
997     notmuch_private_status_t private_status;
998     notmuch_status_t status;
999     notmuch_tags_t *tags;
1000     const char *tag;
1001
1002     status = _notmuch_database_ensure_writable (message->notmuch);
1003     if (status)
1004         return status;
1005
1006     for (tags = notmuch_message_get_tags (message);
1007          notmuch_tags_valid (tags);
1008          notmuch_tags_move_to_next (tags))
1009     {
1010         tag = notmuch_tags_get (tags);
1011
1012         private_status = _notmuch_message_remove_term (message, "tag", tag);
1013         if (private_status) {
1014             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1015                             private_status);
1016         }
1017     }
1018
1019     if (! message->frozen)
1020         _notmuch_message_sync (message);
1021
1022     return NOTMUCH_STATUS_SUCCESS;
1023 }
1024
1025 notmuch_status_t
1026 notmuch_message_freeze (notmuch_message_t *message)
1027 {
1028     notmuch_status_t status;
1029
1030     status = _notmuch_database_ensure_writable (message->notmuch);
1031     if (status)
1032         return status;
1033
1034     message->frozen++;
1035
1036     return NOTMUCH_STATUS_SUCCESS;
1037 }
1038
1039 notmuch_status_t
1040 notmuch_message_thaw (notmuch_message_t *message)
1041 {
1042     notmuch_status_t status;
1043
1044     status = _notmuch_database_ensure_writable (message->notmuch);
1045     if (status)
1046         return status;
1047
1048     if (message->frozen > 0) {
1049         message->frozen--;
1050         if (message->frozen == 0)
1051             _notmuch_message_sync (message);
1052         return NOTMUCH_STATUS_SUCCESS;
1053     } else {
1054         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1055     }
1056 }
1057
1058 void
1059 notmuch_message_destroy (notmuch_message_t *message)
1060 {
1061     talloc_free (message);
1062 }