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