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