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