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