]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
0d9542e653a4566e1554816646d591172c15a345
[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     const char *relative, *directory;
438     notmuch_status_t status;
439     void *local = talloc_new (message);
440     char *direntry;
441
442     if (filename == NULL)
443         INTERNAL_ERROR ("Message filename cannot be NULL.");
444
445     if (message->filename_list) {
446         _notmuch_filename_list_destroy (message->filename_list);
447         message->filename_list = NULL;
448     }
449
450     relative = _notmuch_database_relative_path (message->notmuch, filename);
451
452     status = _notmuch_database_split_path (local, relative, &directory, NULL);
453     if (status)
454         return status;
455
456     status = _notmuch_database_filename_to_direntry (local,
457                                                      message->notmuch,
458                                                      filename, &direntry);
459     if (status)
460         return status;
461
462     /* New file-direntry allows navigating to this message with
463      * notmuch_directory_get_child_files() . */
464     _notmuch_message_add_term (message, "file-direntry", direntry);
465
466     /* New terms allow user to search with folder: specification. */
467     _notmuch_message_gen_terms (message, "folder", directory);
468
469     talloc_free (local);
470
471     return NOTMUCH_STATUS_SUCCESS;
472 }
473
474 /* Remove a particular 'filename' from 'message'.
475  *
476  * This change will not be reflected in the database until the next
477  * call to _notmuch_message_sync.
478  *
479  * Note: This function does not remove a document from the database,
480  * even if the specified filename is the only filename for this
481  * message. For that functionality, see
482  * _notmuch_database_remove_message. */
483 notmuch_status_t
484 _notmuch_message_remove_filename (notmuch_message_t *message,
485                                   const char *filename)
486 {
487     const char *direntry_prefix = _find_prefix ("file-direntry");
488     int direntry_prefix_len = strlen (direntry_prefix);
489     const char *folder_prefix = _find_prefix ("folder");
490     int folder_prefix_len = strlen (folder_prefix);
491     void *local = talloc_new (message);
492     char *direntry;
493     notmuch_private_status_t private_status;
494     notmuch_status_t status;
495     Xapian::TermIterator i, last;
496
497     if (message->filename_list) {
498         _notmuch_filename_list_destroy (message->filename_list);
499         message->filename_list = NULL;
500     }
501
502     status = _notmuch_database_filename_to_direntry (local, message->notmuch,
503                                                      filename, &direntry);
504     if (status)
505         return status;
506
507     /* Unlink this file from its parent directory. */
508     private_status = _notmuch_message_remove_term (message,
509                                                    "file-direntry", direntry);
510     status = COERCE_STATUS (private_status,
511                             "Unexpected error from _notmuch_message_remove_term");
512
513     /* Re-synchronize "folder:" terms for this message. This requires
514      * first removing all "folder:" terms, then adding back terms for
515      * all remaining filenames of the message. */
516     while (1) {
517         i = message->doc.termlist_begin ();
518         i.skip_to (folder_prefix);
519
520         /* Terminate loop when no terms remain with desired prefix. */
521         if (i == message->doc.termlist_end () ||
522             strncmp ((*i).c_str (), folder_prefix, folder_prefix_len))
523         {
524             break;
525         }
526
527         try {
528             message->doc.remove_term ((*i));
529         } catch (const Xapian::InvalidArgumentError) {
530             /* Ignore failure to remove non-existent term. */
531         }
532     }
533
534     i = message->doc.termlist_begin ();
535     i.skip_to (direntry_prefix);
536
537     for (; i != message->doc.termlist_end (); i++) {
538         unsigned int directory_id;
539         const char *direntry, *directory;
540         char *colon;
541
542         /* Terminate loop at first term without desired prefix. */
543         if (strncmp ((*i).c_str (), direntry_prefix, direntry_prefix_len))
544             break;
545
546         direntry = (*i).c_str ();
547         direntry += direntry_prefix_len;
548
549         directory_id = strtol (direntry, &colon, 10);
550
551         if (colon == NULL || *colon != ':')
552             INTERNAL_ERROR ("malformed direntry");
553
554         directory = _notmuch_database_get_directory_path (local,
555                                                           message->notmuch,
556                                                           directory_id);
557         if (strlen (directory))
558             _notmuch_message_gen_terms (message, "folder", directory);
559     }
560
561     talloc_free (local);
562
563     return status;
564 }
565
566 char *
567 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
568 {
569     return talloc_strdup (message, message->doc.get_data ().c_str ());
570 }
571
572 void
573 _notmuch_message_clear_data (notmuch_message_t *message)
574 {
575     message->doc.set_data ("");
576 }
577
578 static void
579 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
580 {
581     const char *prefix = _find_prefix ("file-direntry");
582     int prefix_len = strlen (prefix);
583     Xapian::TermIterator i;
584
585     if (message->filename_list)
586         return;
587
588     message->filename_list = _notmuch_filename_list_create (message);
589
590     i = message->doc.termlist_begin ();
591     i.skip_to (prefix);
592
593     if (i == message->doc.termlist_end () ||
594         strncmp ((*i).c_str (), prefix, prefix_len))
595     {
596         /* A message document created by an old version of notmuch
597          * (prior to rename support) will have the filename in the
598          * data of the document rather than as a file-direntry term.
599          *
600          * It would be nice to do the upgrade of the document directly
601          * here, but the database is likely open in read-only mode. */
602         const char *data;
603
604         data = message->doc.get_data ().c_str ();
605
606         if (data == NULL)
607             INTERNAL_ERROR ("message with no filename");
608
609         _notmuch_filename_list_add_filename (message->filename_list, data);
610
611         return;
612     }
613
614     for (; i != message->doc.termlist_end (); i++) {
615         void *local = talloc_new (message);
616         const char *db_path, *directory, *basename, *filename;
617         char *colon, *direntry = NULL;
618         unsigned int directory_id;
619
620         /* Terminate loop at first term without desired prefix. */
621         if (strncmp ((*i).c_str (), prefix, prefix_len))
622             break;
623
624         direntry = talloc_strdup (local, (*i).c_str ());
625
626         direntry += prefix_len;
627
628         directory_id = strtol (direntry, &colon, 10);
629
630         if (colon == NULL || *colon != ':')
631             INTERNAL_ERROR ("malformed direntry");
632
633         basename = colon + 1;
634
635         *colon = '\0';
636
637         db_path = notmuch_database_get_path (message->notmuch);
638
639         directory = _notmuch_database_get_directory_path (local,
640                                                           message->notmuch,
641                                                           directory_id);
642
643         if (strlen (directory))
644             filename = talloc_asprintf (message, "%s/%s/%s",
645                                         db_path, directory, basename);
646         else
647             filename = talloc_asprintf (message, "%s/%s",
648                                         db_path, basename);
649
650         _notmuch_filename_list_add_filename (message->filename_list,
651                                              filename);
652
653         talloc_free (local);
654     }
655 }
656
657 const char *
658 notmuch_message_get_filename (notmuch_message_t *message)
659 {
660     _notmuch_message_ensure_filename_list (message);
661
662     if (message->filename_list == NULL)
663         return NULL;
664
665     if (message->filename_list->head == NULL ||
666         message->filename_list->head->filename == NULL)
667     {
668         INTERNAL_ERROR ("message with no filename");
669     }
670
671     return message->filename_list->head->filename;
672 }
673
674 notmuch_filenames_t *
675 notmuch_message_get_filenames (notmuch_message_t *message)
676 {
677     _notmuch_message_ensure_filename_list (message);
678
679     return _notmuch_filenames_create (message, message->filename_list);
680 }
681
682 notmuch_bool_t
683 notmuch_message_get_flag (notmuch_message_t *message,
684                           notmuch_message_flag_t flag)
685 {
686     return message->flags & (1 << flag);
687 }
688
689 void
690 notmuch_message_set_flag (notmuch_message_t *message,
691                           notmuch_message_flag_t flag, notmuch_bool_t enable)
692 {
693     if (enable)
694         message->flags |= (1 << flag);
695     else
696         message->flags &= ~(1 << flag);
697 }
698
699 time_t
700 notmuch_message_get_date (notmuch_message_t *message)
701 {
702     std::string value;
703
704     try {
705         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
706     } catch (Xapian::Error &error) {
707         INTERNAL_ERROR ("Failed to read timestamp value from document.");
708         return 0;
709     }
710
711     return Xapian::sortable_unserialise (value);
712 }
713
714 notmuch_tags_t *
715 notmuch_message_get_tags (notmuch_message_t *message)
716 {
717     Xapian::TermIterator i, end;
718     i = message->doc.termlist_begin();
719     end = message->doc.termlist_end();
720     return _notmuch_convert_tags(message, i, end);
721 }
722
723 const char *
724 notmuch_message_get_author (notmuch_message_t *message)
725 {
726     return message->author;
727 }
728
729 void
730 notmuch_message_set_author (notmuch_message_t *message,
731                             const char *author)
732 {
733     if (message->author)
734         talloc_free(message->author);
735     message->author = talloc_strdup(message, author);
736     return;
737 }
738
739 void
740 _notmuch_message_set_date (notmuch_message_t *message,
741                            const char *date)
742 {
743     time_t time_value;
744
745     /* GMime really doesn't want to see a NULL date, so protect its
746      * sensibilities. */
747     if (date == NULL || *date == '\0')
748         time_value = 0;
749     else
750         time_value = g_mime_utils_header_decode_date (date, NULL);
751
752     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
753                             Xapian::sortable_serialise (time_value));
754 }
755
756 /* Synchronize changes made to message->doc out into the database. */
757 void
758 _notmuch_message_sync (notmuch_message_t *message)
759 {
760     Xapian::WritableDatabase *db;
761
762     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
763         return;
764
765     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
766     db->replace_document (message->doc_id, message->doc);
767 }
768
769 /* Ensure that 'message' is not holding any file object open. Future
770  * calls to various functions will still automatically open the
771  * message file as needed.
772  */
773 void
774 _notmuch_message_close (notmuch_message_t *message)
775 {
776     if (message->message_file) {
777         notmuch_message_file_close (message->message_file);
778         message->message_file = NULL;
779     }
780 }
781
782 /* Add a name:value term to 'message', (the actual term will be
783  * encoded by prefixing the value with a short prefix). See
784  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
785  * names to prefix values.
786  *
787  * This change will not be reflected in the database until the next
788  * call to _notmuch_message_sync. */
789 notmuch_private_status_t
790 _notmuch_message_add_term (notmuch_message_t *message,
791                            const char *prefix_name,
792                            const char *value)
793 {
794
795     char *term;
796
797     if (value == NULL)
798         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
799
800     term = talloc_asprintf (message, "%s%s",
801                             _find_prefix (prefix_name), value);
802
803     if (strlen (term) > NOTMUCH_TERM_MAX)
804         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
805
806     message->doc.add_term (term, 0);
807
808     talloc_free (term);
809
810     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
811 }
812
813 /* Parse 'text' and add a term to 'message' for each parsed word. Each
814  * term will be added both prefixed (if prefix_name is not NULL) and
815  * also unprefixed). */
816 notmuch_private_status_t
817 _notmuch_message_gen_terms (notmuch_message_t *message,
818                             const char *prefix_name,
819                             const char *text)
820 {
821     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
822
823     if (text == NULL)
824         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
825
826     term_gen->set_document (message->doc);
827
828     if (prefix_name) {
829         const char *prefix = _find_prefix (prefix_name);
830
831         term_gen->index_text (text, 1, prefix);
832     }
833
834     term_gen->index_text (text);
835
836     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
837 }
838
839 /* Remove a name:value term from 'message', (the actual term will be
840  * encoded by prefixing the value with a short prefix). See
841  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
842  * names to prefix values.
843  *
844  * This change will not be reflected in the database until the next
845  * call to _notmuch_message_sync. */
846 notmuch_private_status_t
847 _notmuch_message_remove_term (notmuch_message_t *message,
848                               const char *prefix_name,
849                               const char *value)
850 {
851     char *term;
852
853     if (value == NULL)
854         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
855
856     term = talloc_asprintf (message, "%s%s",
857                             _find_prefix (prefix_name), value);
858
859     if (strlen (term) > NOTMUCH_TERM_MAX)
860         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
861
862     try {
863         message->doc.remove_term (term);
864     } catch (const Xapian::InvalidArgumentError) {
865         /* We'll let the philosopher's try to wrestle with the
866          * question of whether failing to remove that which was not
867          * there in the first place is failure. For us, we'll silently
868          * consider it all good. */
869     }
870
871     talloc_free (term);
872
873     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
874 }
875
876 notmuch_status_t
877 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
878 {
879     notmuch_private_status_t private_status;
880     notmuch_status_t status;
881
882     status = _notmuch_database_ensure_writable (message->notmuch);
883     if (status)
884         return status;
885
886     if (tag == NULL)
887         return NOTMUCH_STATUS_NULL_POINTER;
888
889     if (strlen (tag) > NOTMUCH_TAG_MAX)
890         return NOTMUCH_STATUS_TAG_TOO_LONG;
891
892     private_status = _notmuch_message_add_term (message, "tag", tag);
893     if (private_status) {
894         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
895                         private_status);
896     }
897
898     if (! message->frozen)
899         _notmuch_message_sync (message);
900
901     return NOTMUCH_STATUS_SUCCESS;
902 }
903
904 notmuch_status_t
905 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
906 {
907     notmuch_private_status_t private_status;
908     notmuch_status_t status;
909
910     status = _notmuch_database_ensure_writable (message->notmuch);
911     if (status)
912         return status;
913
914     if (tag == NULL)
915         return NOTMUCH_STATUS_NULL_POINTER;
916
917     if (strlen (tag) > NOTMUCH_TAG_MAX)
918         return NOTMUCH_STATUS_TAG_TOO_LONG;
919
920     private_status = _notmuch_message_remove_term (message, "tag", tag);
921     if (private_status) {
922         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
923                         private_status);
924     }
925
926     if (! message->frozen)
927         _notmuch_message_sync (message);
928
929     return NOTMUCH_STATUS_SUCCESS;
930 }
931
932 notmuch_status_t
933 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
934 {
935     const char *flags;
936     notmuch_status_t status;
937     notmuch_filenames_t *filenames;
938     const char *filename;
939     char *combined_flags = talloc_strdup (message, "");
940     unsigned i;
941     int seen_maildir_info = 0;
942
943     for (filenames = notmuch_message_get_filenames (message);
944          notmuch_filenames_valid (filenames);
945          notmuch_filenames_move_to_next (filenames))
946     {
947         filename = notmuch_filenames_get (filenames);
948
949         flags = strstr (filename, ":2,");
950         if (! flags)
951             continue;
952
953         seen_maildir_info = 1;
954         flags += 3;
955
956         combined_flags = talloc_strdup_append (combined_flags, flags);
957     }
958
959     /* If none of the filenames have any maildir info field (not even
960      * an empty info with no flags set) then there's no information to
961      * go on, so do nothing. */
962     if (! seen_maildir_info)
963         return NOTMUCH_STATUS_SUCCESS;
964
965     status = notmuch_message_freeze (message);
966     if (status)
967         return status;
968
969     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
970         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
971             ^ 
972             flag2tag[i].inverse)
973         {
974             status = notmuch_message_add_tag (message, flag2tag[i].tag);
975         } else {
976             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
977         }
978         if (status)
979             return status;
980     }
981     status = notmuch_message_thaw (message);
982
983     talloc_free (combined_flags);
984
985     return status;
986 }
987
988 /* Is the given filename within a maildir directory?
989  *
990  * Specifically, is the final directory component of 'filename' either
991  * "cur" or "new". If so, return a pointer to that final directory
992  * component within 'filename'. If not, return NULL.
993  *
994  * A non-NULL return value is guaranteed to be a valid string pointer
995  * pointing to the characters "new/" or "cur/", (but not
996  * NUL-terminated).
997  */
998 static const char *
999 _filename_is_in_maildir (const char *filename)
1000 {
1001     const char *slash, *dir = NULL;
1002
1003     /* Find the last '/' separating directory from filename. */
1004     slash = strrchr (filename, '/');
1005     if (slash == NULL)
1006         return NULL;
1007
1008     /* Jump back 4 characters to where the previous '/' will be if the
1009      * directory is named "cur" or "new". */
1010     if (slash - filename < 4)
1011         return NULL;
1012
1013     slash -= 4;
1014
1015     if (*slash != '/')
1016         return NULL;
1017
1018     dir = slash + 1;
1019
1020     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1021         STRNCMP_LITERAL (dir, "new/") == 0)
1022     {
1023         return dir;
1024     }
1025
1026     return NULL;
1027 }
1028
1029 /* From the set of tags on 'message' and the flag2tag table, compute a
1030  * set of maildir-flag actions to be taken, (flags that should be
1031  * either set or cleared).
1032  *
1033  * The result is returned as two talloced strings: to_set, and to_clear
1034  */
1035 static void
1036 _get_maildir_flag_actions (notmuch_message_t *message,
1037                            char **to_set_ret,
1038                            char **to_clear_ret)
1039 {
1040     char *to_set, *to_clear;
1041     notmuch_tags_t *tags;
1042     const char *tag;
1043     unsigned i;
1044
1045     to_set = talloc_strdup (message, "");
1046     to_clear = talloc_strdup (message, "");
1047
1048     /* First, find flags for all set tags. */
1049     for (tags = notmuch_message_get_tags (message);
1050          notmuch_tags_valid (tags);
1051          notmuch_tags_move_to_next (tags))
1052     {
1053         tag = notmuch_tags_get (tags);
1054
1055         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1056             if (strcmp (tag, flag2tag[i].tag) == 0) {
1057                 if (flag2tag[i].inverse)
1058                     to_clear = talloc_asprintf_append (to_clear,
1059                                                        "%c",
1060                                                        flag2tag[i].flag);
1061                 else
1062                     to_set = talloc_asprintf_append (to_set,
1063                                                      "%c",
1064                                                      flag2tag[i].flag);
1065             }
1066         }
1067     }
1068
1069     /* Then, find the flags for all tags not present. */
1070     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1071         if (flag2tag[i].inverse) {
1072             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1073                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1074         } else {
1075             if (strchr (to_set, flag2tag[i].flag) == NULL)
1076                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1077         }
1078     }
1079
1080     *to_set_ret = to_set;
1081     *to_clear_ret = to_clear;
1082 }
1083
1084 /* Given 'filename' and a set of maildir flags to set and to clear,
1085  * compute the new maildir filename.
1086  *
1087  * If the existing filename is in the directory "new", the new
1088  * filename will be in the directory "cur".
1089  *
1090  * After a sequence of ":2," in the filename, any subsequent
1091  * single-character flags will be added or removed according to the
1092  * characters in flags_to_set and flags_to_clear. Any existing flags
1093  * not mentioned in either string will remain. The final list of flags
1094  * will be in ASCII order.
1095  *
1096  * If the original flags seem invalid, (repeated characters or
1097  * non-ASCII ordering of flags), this function will return NULL
1098  * (meaning that renaming would not be safe and should not occur).
1099  */
1100 static char*
1101 _new_maildir_filename (void *ctx,
1102                        const char *filename,
1103                        const char *flags_to_set,
1104                        const char *flags_to_clear)
1105 {
1106     const char *info, *flags;
1107     unsigned int flag, last_flag;
1108     char *filename_new, *dir;
1109     char flag_map[128];
1110     int flags_in_map = 0;
1111     unsigned int i;
1112     char *s;
1113
1114     memset (flag_map, 0, sizeof (flag_map));
1115
1116     info = strstr (filename, ":2,");
1117
1118     if (info == NULL) {
1119         info = filename + strlen(filename);
1120     } else {
1121         flags = info + 3;
1122
1123         /* Loop through existing flags in filename. */
1124         for (flags = info + 3, last_flag = 0;
1125              *flags;
1126              last_flag = flag, flags++)
1127         {
1128             flag = *flags;
1129
1130             /* Original flags not in ASCII order. Abort. */
1131             if (flag < last_flag)
1132                 return NULL;
1133
1134             /* Non-ASCII flag. Abort. */
1135             if (flag > sizeof(flag_map) - 1)
1136                 return NULL;
1137
1138             /* Repeated flag value. Abort. */
1139             if (flag_map[flag])
1140                 return NULL;
1141
1142             flag_map[flag] = 1;
1143             flags_in_map++;
1144         }
1145     }
1146
1147     /* Then set and clear our flags from tags. */
1148     for (flags = flags_to_set; *flags; flags++) {
1149         flag = *flags;
1150         if (flag_map[flag] == 0) {
1151             flag_map[flag] = 1;
1152             flags_in_map++;
1153         }
1154     }
1155
1156     for (flags = flags_to_clear; *flags; flags++) {
1157         flag = *flags;
1158         if (flag_map[flag]) {
1159             flag_map[flag] = 0;
1160             flags_in_map--;
1161         }
1162     }
1163
1164     filename_new = (char *) talloc_size (ctx,
1165                                          info - filename +
1166                                          strlen (":2,") + flags_in_map + 1);
1167     if (unlikely (filename_new == NULL))
1168         return NULL;
1169
1170     strncpy (filename_new, filename, info - filename);
1171     filename_new[info - filename] = '\0';
1172
1173     strcat (filename_new, ":2,");
1174
1175     s = filename_new + strlen (filename_new);
1176     for (i = 0; i < sizeof (flag_map); i++)
1177     {
1178         if (flag_map[i]) {
1179             *s = i;
1180             s++;
1181         }
1182     }
1183     *s = '\0';
1184
1185     /* If message is in new/ move it under cur/. */
1186     dir = (char *) _filename_is_in_maildir (filename_new);
1187     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1188         memcpy (dir, "cur/", 4);
1189
1190     return filename_new;
1191 }
1192
1193 notmuch_status_t
1194 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1195 {
1196     notmuch_filenames_t *filenames;
1197     const char *filename;
1198     char *filename_new;
1199     char *to_set, *to_clear;
1200     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1201
1202     _get_maildir_flag_actions (message, &to_set, &to_clear);
1203
1204     for (filenames = notmuch_message_get_filenames (message);
1205          notmuch_filenames_valid (filenames);
1206          notmuch_filenames_move_to_next (filenames))
1207     {
1208         filename = notmuch_filenames_get (filenames);
1209
1210         if (! _filename_is_in_maildir (filename))
1211             continue;
1212
1213         filename_new = _new_maildir_filename (message, filename,
1214                                               to_set, to_clear);
1215         if (filename_new == NULL)
1216             continue;
1217
1218         if (strcmp (filename, filename_new)) {
1219             int err;
1220             notmuch_status_t new_status;
1221
1222             err = rename (filename, filename_new);
1223             if (err)
1224                 continue;
1225
1226             new_status = _notmuch_message_remove_filename (message,
1227                                                            filename);
1228             /* Hold on to only the first error. */
1229             if (! status && new_status) {
1230                 status = new_status;
1231                 continue;
1232             }
1233
1234             new_status = _notmuch_message_add_filename (message,
1235                                                         filename_new);
1236             /* Hold on to only the first error. */
1237             if (! status && new_status) {
1238                 status = new_status;
1239                 continue;
1240             }
1241
1242             _notmuch_message_sync (message);
1243         }
1244
1245         talloc_free (filename_new);
1246     }
1247
1248     talloc_free (to_set);
1249     talloc_free (to_clear);
1250
1251     return NOTMUCH_STATUS_SUCCESS;
1252 }
1253
1254 notmuch_status_t
1255 notmuch_message_remove_all_tags (notmuch_message_t *message)
1256 {
1257     notmuch_private_status_t private_status;
1258     notmuch_status_t status;
1259     notmuch_tags_t *tags;
1260     const char *tag;
1261
1262     status = _notmuch_database_ensure_writable (message->notmuch);
1263     if (status)
1264         return status;
1265
1266     for (tags = notmuch_message_get_tags (message);
1267          notmuch_tags_valid (tags);
1268          notmuch_tags_move_to_next (tags))
1269     {
1270         tag = notmuch_tags_get (tags);
1271
1272         private_status = _notmuch_message_remove_term (message, "tag", tag);
1273         if (private_status) {
1274             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1275                             private_status);
1276         }
1277     }
1278
1279     if (! message->frozen)
1280         _notmuch_message_sync (message);
1281
1282     return NOTMUCH_STATUS_SUCCESS;
1283 }
1284
1285 notmuch_status_t
1286 notmuch_message_freeze (notmuch_message_t *message)
1287 {
1288     notmuch_status_t status;
1289
1290     status = _notmuch_database_ensure_writable (message->notmuch);
1291     if (status)
1292         return status;
1293
1294     message->frozen++;
1295
1296     return NOTMUCH_STATUS_SUCCESS;
1297 }
1298
1299 notmuch_status_t
1300 notmuch_message_thaw (notmuch_message_t *message)
1301 {
1302     notmuch_status_t status;
1303
1304     status = _notmuch_database_ensure_writable (message->notmuch);
1305     if (status)
1306         return status;
1307
1308     if (message->frozen > 0) {
1309         message->frozen--;
1310         if (message->frozen == 0)
1311             _notmuch_message_sync (message);
1312         return NOTMUCH_STATUS_SUCCESS;
1313     } else {
1314         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1315     }
1316 }
1317
1318 void
1319 notmuch_message_destroy (notmuch_message_t *message)
1320 {
1321     talloc_free (message);
1322 }