]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
a1c3cd7812023a0acf8675f82aef121e49f2871b
[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 https://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 #include "message-private.h"
24
25 #include <stdint.h>
26
27 #include <gmime/gmime.h>
28
29 struct _notmuch_message {
30     notmuch_database_t *notmuch;
31     Xapian::docid doc_id;
32     int frozen;
33     char *message_id;
34     char *thread_id;
35     char *in_reply_to;
36     notmuch_string_list_t *tag_list;
37     notmuch_string_list_t *filename_term_list;
38     notmuch_string_list_t *filename_list;
39     char *author;
40     notmuch_message_file_t *message_file;
41     notmuch_string_list_t *property_term_list;
42     notmuch_string_map_t *property_map;
43     notmuch_message_list_t *replies;
44     unsigned long flags;
45     /* For flags that are initialized on-demand, lazy_flags indicates
46      * if each flag has been initialized. */
47     unsigned long lazy_flags;
48
49     /* Message document modified since last sync */
50     notmuch_bool_t modified;
51
52     /* last view of database the struct is synced with */
53     unsigned long last_view;
54
55     Xapian::Document doc;
56     Xapian::termcount termpos;
57 };
58
59 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
60
61 struct maildir_flag_tag {
62     char flag;
63     const char *tag;
64     notmuch_bool_t inverse;
65 };
66
67 /* ASCII ordered table of Maildir flags and associated tags */
68 static struct maildir_flag_tag flag2tag[] = {
69     { 'D', "draft",   FALSE},
70     { 'F', "flagged", FALSE},
71     { 'P', "passed",  FALSE},
72     { 'R', "replied", FALSE},
73     { 'S', "unread",  TRUE }
74 };
75
76 /* We end up having to call the destructor explicitly because we had
77  * to use "placement new" in order to initialize C++ objects within a
78  * block that we allocated with talloc. So C++ is making talloc
79  * slightly less simple to use, (we wouldn't need
80  * talloc_set_destructor at all otherwise).
81  */
82 static int
83 _notmuch_message_destructor (notmuch_message_t *message)
84 {
85     message->doc.~Document ();
86
87     return 0;
88 }
89
90 static notmuch_message_t *
91 _notmuch_message_create_for_document (const void *talloc_owner,
92                                       notmuch_database_t *notmuch,
93                                       unsigned int doc_id,
94                                       Xapian::Document doc,
95                                       notmuch_private_status_t *status)
96 {
97     notmuch_message_t *message;
98
99     if (status)
100         *status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
101
102     message = talloc (talloc_owner, notmuch_message_t);
103     if (unlikely (message == NULL)) {
104         if (status)
105             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
106         return NULL;
107     }
108
109     message->notmuch = notmuch;
110     message->doc_id = doc_id;
111
112     message->frozen = 0;
113     message->flags = 0;
114     message->lazy_flags = 0;
115
116     /* the message is initially not synchronized with Xapian */
117     message->last_view = 0;
118
119     /* Each of these will be lazily created as needed. */
120     message->message_id = NULL;
121     message->thread_id = NULL;
122     message->in_reply_to = NULL;
123     message->tag_list = NULL;
124     message->filename_term_list = NULL;
125     message->filename_list = NULL;
126     message->message_file = NULL;
127     message->author = NULL;
128     message->property_term_list = NULL;
129     message->property_map = NULL;
130
131     message->replies = _notmuch_message_list_create (message);
132     if (unlikely (message->replies == NULL)) {
133         if (status)
134             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
135         return NULL;
136     }
137
138     /* This is C++'s creepy "placement new", which is really just an
139      * ugly way to call a constructor for a pre-allocated object. So
140      * it's really not an error to not be checking for OUT_OF_MEMORY
141      * here, since this "new" isn't actually allocating memory. This
142      * is language-design comedy of the wrong kind. */
143
144     new (&message->doc) Xapian::Document;
145
146     talloc_set_destructor (message, _notmuch_message_destructor);
147
148     message->doc = doc;
149     message->termpos = 0;
150
151     return message;
152 }
153
154 /* Create a new notmuch_message_t object for an existing document in
155  * the database.
156  *
157  * Here, 'talloc owner' is an optional talloc context to which the new
158  * message will belong. This allows for the caller to not bother
159  * calling notmuch_message_destroy on the message, and know that all
160  * memory will be reclaimed when 'talloc_owner' is freed. The caller
161  * still can call notmuch_message_destroy when finished with the
162  * message if desired.
163  *
164  * The 'talloc_owner' argument can also be NULL, in which case the
165  * caller *is* responsible for calling notmuch_message_destroy.
166  *
167  * If no document exists in the database with document ID of 'doc_id'
168  * then this function returns NULL and optionally sets *status to
169  * NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND.
170  *
171  * This function can also fail to due lack of available memory,
172  * returning NULL and optionally setting *status to
173  * NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY.
174  *
175  * The caller can pass NULL for status if uninterested in
176  * distinguishing these two cases.
177  */
178 notmuch_message_t *
179 _notmuch_message_create (const void *talloc_owner,
180                          notmuch_database_t *notmuch,
181                          unsigned int doc_id,
182                          notmuch_private_status_t *status)
183 {
184     Xapian::Document doc;
185
186     try {
187         doc = notmuch->xapian_db->get_document (doc_id);
188     } catch (const Xapian::DocNotFoundError &error) {
189         if (status)
190             *status = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
191         return NULL;
192     }
193
194     return _notmuch_message_create_for_document (talloc_owner, notmuch,
195                                                  doc_id, doc, status);
196 }
197
198 /* Create a new notmuch_message_t object for a specific message ID,
199  * (which may or may not already exist in the database).
200  *
201  * The 'notmuch' database will be the talloc owner of the returned
202  * message.
203  *
204  * This function returns a valid notmuch_message_t whether or not
205  * there is already a document in the database with the given message
206  * ID. These two cases can be distinguished by the value of *status:
207  *
208  *
209  *   NOTMUCH_PRIVATE_STATUS_SUCCESS:
210  *
211  *     There is already a document with message ID 'message_id' in the
212  *     database. The returned message can be used to query/modify the
213  *     document. The message may be a ghost message.
214  *
215  *   NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND:
216  *
217  *     No document with 'message_id' exists in the database. The
218  *     returned message contains a newly created document (not yet
219  *     added to the database) and a document ID that is known not to
220  *     exist in the database.  This message is "blank"; that is, it
221  *     contains only a message ID and no other metadata. The caller
222  *     can modify the message, and a call to _notmuch_message_sync
223  *     will add the document to the database.
224  *
225  * If an error occurs, this function will return NULL and *status
226  * will be set as appropriate. (The status pointer argument must
227  * not be NULL.)
228  */
229 notmuch_message_t *
230 _notmuch_message_create_for_message_id (notmuch_database_t *notmuch,
231                                         const char *message_id,
232                                         notmuch_private_status_t *status_ret)
233 {
234     notmuch_message_t *message;
235     Xapian::Document doc;
236     unsigned int doc_id;
237     char *term;
238
239     *status_ret = (notmuch_private_status_t) notmuch_database_find_message (notmuch,
240                                                                             message_id,
241                                                                             &message);
242     if (message)
243         return talloc_steal (notmuch, message);
244     else if (*status_ret)
245         return NULL;
246
247     /* If the message ID is too long, substitute its sha1 instead. */
248     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
249         message_id = _notmuch_message_id_compressed (message, message_id);
250
251     term = talloc_asprintf (NULL, "%s%s",
252                             _find_prefix ("id"), message_id);
253     if (term == NULL) {
254         *status_ret = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
255         return NULL;
256     }
257
258     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
259         INTERNAL_ERROR ("Failure to ensure database is writable.");
260
261     try {
262         doc.add_term (term, 0);
263         talloc_free (term);
264
265         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
266
267         doc_id = _notmuch_database_generate_doc_id (notmuch);
268     } catch (const Xapian::Error &error) {
269         _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred creating message: %s\n",
270                  error.get_msg().c_str());
271         notmuch->exception_reported = TRUE;
272         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
273         return NULL;
274     }
275
276     message = _notmuch_message_create_for_document (notmuch, notmuch,
277                                                     doc_id, doc, status_ret);
278
279     /* We want to inform the caller that we had to create a new
280      * document. */
281     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
282         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
283
284     return message;
285 }
286
287 static char *
288 _notmuch_message_get_term (notmuch_message_t *message,
289                            Xapian::TermIterator &i, Xapian::TermIterator &end,
290                            const char *prefix)
291 {
292     int prefix_len = strlen (prefix);
293     char *value;
294
295     i.skip_to (prefix);
296
297     if (i == end)
298         return NULL;
299
300     const std::string &term = *i;
301     if (strncmp (term.c_str(), prefix, prefix_len))
302         return NULL;
303
304     value = talloc_strdup (message, term.c_str() + prefix_len);
305
306 #if DEBUG_DATABASE_SANITY
307     i++;
308
309     if (i != end && strncmp ((*i).c_str (), prefix, prefix_len) == 0) {
310         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate %s terms: %s and %s\n",
311                         message->doc_id, prefix, value,
312                         (*i).c_str () + prefix_len);
313     }
314 #endif
315
316     return value;
317 }
318
319 static void
320 _notmuch_message_ensure_metadata (notmuch_message_t *message, void *field)
321 {
322     Xapian::TermIterator i, end;
323
324     if (field && (message->last_view >= message->notmuch->view))
325         return;
326
327     const char *thread_prefix = _find_prefix ("thread"),
328         *tag_prefix = _find_prefix ("tag"),
329         *id_prefix = _find_prefix ("id"),
330         *type_prefix = _find_prefix ("type"),
331         *filename_prefix = _find_prefix ("file-direntry"),
332         *property_prefix = _find_prefix ("property"),
333         *replyto_prefix = _find_prefix ("replyto");
334
335     /* We do this all in a single pass because Xapian decompresses the
336      * term list every time you iterate over it.  Thus, while this is
337      * slightly more costly than looking up individual fields if only
338      * one field of the message object is actually used, it's a huge
339      * win as more fields are used. */
340     for (int count=0; count < 3; count++) {
341         try {
342             i = message->doc.termlist_begin ();
343             end = message->doc.termlist_end ();
344
345             /* Get thread */
346             if (!message->thread_id)
347                 message->thread_id =
348                     _notmuch_message_get_term (message, i, end, thread_prefix);
349
350             /* Get tags */
351             assert (strcmp (thread_prefix, tag_prefix) < 0);
352             if (!message->tag_list) {
353                 message->tag_list =
354                     _notmuch_database_get_terms_with_prefix (message, i, end,
355                                                              tag_prefix);
356                 _notmuch_string_list_sort (message->tag_list);
357             }
358
359             /* Get id */
360             assert (strcmp (tag_prefix, id_prefix) < 0);
361             if (!message->message_id)
362                 message->message_id =
363                     _notmuch_message_get_term (message, i, end, id_prefix);
364
365             /* Get document type */
366             assert (strcmp (id_prefix, type_prefix) < 0);
367             if (! NOTMUCH_TEST_BIT (message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST)) {
368                 i.skip_to (type_prefix);
369                 /* "T" is the prefix "type" fields.  See
370                  * BOOLEAN_PREFIX_INTERNAL. */
371                 if (*i == "Tmail")
372                     NOTMUCH_CLEAR_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
373                 else if (*i == "Tghost")
374                     NOTMUCH_SET_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
375                 else
376                     INTERNAL_ERROR ("Message without type term");
377                 NOTMUCH_SET_BIT (&message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST);
378             }
379
380             /* Get filename list.  Here we get only the terms.  We lazily
381              * expand them to full file names when needed in
382              * _notmuch_message_ensure_filename_list. */
383             assert (strcmp (type_prefix, filename_prefix) < 0);
384             if (!message->filename_term_list && !message->filename_list)
385                 message->filename_term_list =
386                     _notmuch_database_get_terms_with_prefix (message, i, end,
387                                                              filename_prefix);
388
389
390             /* Get property terms. Mimic the setup with filenames above */
391             assert (strcmp (filename_prefix, property_prefix) < 0);
392             if (!message->property_map && !message->property_term_list)
393                 message->property_term_list =
394                     _notmuch_database_get_terms_with_prefix (message, i, end,
395                                                          property_prefix);
396
397             /* Get reply to */
398             assert (strcmp (property_prefix, replyto_prefix) < 0);
399             if (!message->in_reply_to)
400                 message->in_reply_to =
401                     _notmuch_message_get_term (message, i, end, replyto_prefix);
402
403
404             /* It's perfectly valid for a message to have no In-Reply-To
405              * header. For these cases, we return an empty string. */
406             if (!message->in_reply_to)
407                 message->in_reply_to = talloc_strdup (message, "");
408
409             /* all the way without an exception */
410             break;
411         } catch (const Xapian::DatabaseModifiedError &error) {
412             notmuch_status_t status = _notmuch_database_reopen (message->notmuch);
413             if (status != NOTMUCH_STATUS_SUCCESS)
414                 INTERNAL_ERROR ("unhandled error from notmuch_database_reopen: %s\n",
415                                 notmuch_status_to_string (status));
416         } catch (const Xapian::Error &error) {
417             INTERNAL_ERROR ("A Xapian exception occurred fetching message metadata: %s\n",
418                             error.get_msg().c_str());
419         }
420     }
421     message->last_view = message->notmuch->view;
422 }
423
424 void
425 _notmuch_message_invalidate_metadata (notmuch_message_t *message,
426                                       const char *prefix_name)
427 {
428     if (strcmp ("thread", prefix_name) == 0) {
429         talloc_free (message->thread_id);
430         message->thread_id = NULL;
431     }
432
433     if (strcmp ("tag", prefix_name) == 0) {
434         talloc_unlink (message, message->tag_list);
435         message->tag_list = NULL;
436     }
437
438     if (strcmp ("type", prefix_name) == 0) {
439         NOTMUCH_CLEAR_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
440         NOTMUCH_CLEAR_BIT (&message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST);
441     }
442
443     if (strcmp ("file-direntry", prefix_name) == 0) {
444         talloc_free (message->filename_term_list);
445         talloc_free (message->filename_list);
446         message->filename_term_list = message->filename_list = NULL;
447     }
448
449     if (strcmp ("property", prefix_name) == 0) {
450
451         if (message->property_term_list)
452             talloc_free (message->property_term_list);
453         message->property_term_list = NULL;
454
455         if (message->property_map)
456             talloc_unlink (message, message->property_map);
457
458         message->property_map = NULL;
459     }
460
461     if (strcmp ("replyto", prefix_name) == 0) {
462         talloc_free (message->in_reply_to);
463         message->in_reply_to = NULL;
464     }
465 }
466
467 unsigned int
468 _notmuch_message_get_doc_id (notmuch_message_t *message)
469 {
470     return message->doc_id;
471 }
472
473 const char *
474 notmuch_message_get_message_id (notmuch_message_t *message)
475 {
476     _notmuch_message_ensure_metadata (message, message->message_id);
477     if (!message->message_id)
478         INTERNAL_ERROR ("Message with document ID of %u has no message ID.\n",
479                         message->doc_id);
480     return message->message_id;
481 }
482
483 static void
484 _notmuch_message_ensure_message_file (notmuch_message_t *message)
485 {
486     const char *filename;
487
488     if (message->message_file)
489         return;
490
491     filename = notmuch_message_get_filename (message);
492     if (unlikely (filename == NULL))
493         return;
494
495     message->message_file = _notmuch_message_file_open_ctx (
496         _notmuch_message_database (message), message, filename);
497 }
498
499 const char *
500 notmuch_message_get_header (notmuch_message_t *message, const char *header)
501 {
502     Xapian::valueno slot = Xapian::BAD_VALUENO;
503
504     /* Fetch header from the appropriate xapian value field if
505      * available */
506     if (strcasecmp (header, "from") == 0)
507         slot = NOTMUCH_VALUE_FROM;
508     else if (strcasecmp (header, "subject") == 0)
509         slot = NOTMUCH_VALUE_SUBJECT;
510     else if (strcasecmp (header, "message-id") == 0)
511         slot = NOTMUCH_VALUE_MESSAGE_ID;
512
513     if (slot != Xapian::BAD_VALUENO) {
514         try {
515             std::string value = message->doc.get_value (slot);
516
517             /* If we have NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES, then
518              * empty values indicate empty headers.  If we don't, then
519              * it could just mean we didn't record the header. */
520             if ((message->notmuch->features &
521                  NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES) ||
522                 ! value.empty())
523                 return talloc_strdup (message, value.c_str ());
524
525         } catch (Xapian::Error &error) {
526             _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred when reading header: %s\n",
527                      error.get_msg().c_str());
528             message->notmuch->exception_reported = TRUE;
529             return NULL;
530         }
531     }
532
533     /* Otherwise fall back to parsing the file */
534     _notmuch_message_ensure_message_file (message);
535     if (message->message_file == NULL)
536         return NULL;
537
538     return _notmuch_message_file_get_header (message->message_file, header);
539 }
540
541 /* Return the message ID from the In-Reply-To header of 'message'.
542  *
543  * Returns an empty string ("") if 'message' has no In-Reply-To
544  * header.
545  *
546  * Returns NULL if any error occurs.
547  */
548 const char *
549 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
550 {
551     _notmuch_message_ensure_metadata (message, message->in_reply_to);
552     return message->in_reply_to;
553 }
554
555 const char *
556 notmuch_message_get_thread_id (notmuch_message_t *message)
557 {
558     _notmuch_message_ensure_metadata (message, message->thread_id);
559     if (!message->thread_id)
560         INTERNAL_ERROR ("Message with document ID of %u has no thread ID.\n",
561                         message->doc_id);
562     return message->thread_id;
563 }
564
565 void
566 _notmuch_message_add_reply (notmuch_message_t *message,
567                             notmuch_message_t *reply)
568 {
569     _notmuch_message_list_add_message (message->replies, reply);
570 }
571
572 notmuch_messages_t *
573 notmuch_message_get_replies (notmuch_message_t *message)
574 {
575     return _notmuch_messages_create (message->replies);
576 }
577
578 void
579 _notmuch_message_remove_terms (notmuch_message_t *message, const char *prefix)
580 {
581     Xapian::TermIterator i;
582     size_t prefix_len = strlen (prefix);
583
584     while (1) {
585         i = message->doc.termlist_begin ();
586         i.skip_to (prefix);
587
588         /* Terminate loop when no terms remain with desired prefix. */
589         if (i == message->doc.termlist_end () ||
590             strncmp ((*i).c_str (), prefix, prefix_len))
591             break;
592
593         try {
594             message->doc.remove_term ((*i));
595             message->modified = TRUE;
596         } catch (const Xapian::InvalidArgumentError) {
597             /* Ignore failure to remove non-existent term. */
598         }
599     }
600 }
601
602
603 /* Remove all terms generated by indexing, i.e. not tags or
604  * properties, along with any automatic tags*/
605 notmuch_private_status_t
606 _notmuch_message_remove_indexed_terms (notmuch_message_t *message)
607 {
608     Xapian::TermIterator i;
609
610     const std::string
611         id_prefix = _find_prefix ("id"),
612         property_prefix = _find_prefix ("property"),
613         tag_prefix = _find_prefix ("tag"),
614         type_prefix = _find_prefix ("type");
615
616     for (i = message->doc.termlist_begin ();
617          i != message->doc.termlist_end (); i++) {
618
619         const std::string term = *i;
620
621         if (term.compare (0, type_prefix.size (), type_prefix) == 0)
622             continue;
623
624         if (term.compare (0, id_prefix.size (), id_prefix) == 0)
625             continue;
626
627         if (term.compare (0, property_prefix.size (), property_prefix) == 0)
628             continue;
629
630         if (term.compare (0, tag_prefix.size (), tag_prefix) == 0 &&
631             term.compare (1, strlen("encrypted"), "encrypted") != 0 &&
632             term.compare (1, strlen("signed"), "signed") != 0 &&
633             term.compare (1, strlen("attachment"), "attachment") != 0)
634             continue;
635
636         try {
637             message->doc.remove_term ((*i));
638             message->modified = TRUE;
639         } catch (const Xapian::InvalidArgumentError) {
640             /* Ignore failure to remove non-existent term. */
641         } catch (const Xapian::Error &error) {
642             notmuch_database_t *notmuch = message->notmuch;
643
644             if (!notmuch->exception_reported) {
645                 _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred creating message: %s\n",
646                                       error.get_msg().c_str());
647                 notmuch->exception_reported = TRUE;
648             }
649             return NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
650         }
651     }
652     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
653 }
654
655 /* Return true if p points at "new" or "cur". */
656 static bool is_maildir (const char *p)
657 {
658     return strcmp (p, "cur") == 0 || strcmp (p, "new") == 0;
659 }
660
661 /* Add "folder:" term for directory. */
662 static notmuch_status_t
663 _notmuch_message_add_folder_terms (notmuch_message_t *message,
664                                    const char *directory)
665 {
666     char *folder, *last;
667
668     folder = talloc_strdup (NULL, directory);
669     if (! folder)
670         return NOTMUCH_STATUS_OUT_OF_MEMORY;
671
672     /*
673      * If the message file is in a leaf directory named "new" or
674      * "cur", presume maildir and index the parent directory. Thus a
675      * "folder:" prefix search matches messages in the specified
676      * maildir folder, i.e. in the specified directory and its "new"
677      * and "cur" subdirectories.
678      *
679      * Note that this means the "folder:" prefix can't be used for
680      * distinguishing between message files in "new" or "cur". The
681      * "path:" prefix needs to be used for that.
682      *
683      * Note the deliberate difference to _filename_is_in_maildir(). We
684      * don't want to index different things depending on the existence
685      * or non-existence of all maildir sibling directories "new",
686      * "cur", and "tmp". Doing so would be surprising, and difficult
687      * for the user to fix in case all subdirectories were not in
688      * place during indexing.
689      */
690     last = strrchr (folder, '/');
691     if (last) {
692         if (is_maildir (last + 1))
693             *last = '\0';
694     } else if (is_maildir (folder)) {
695         *folder = '\0';
696     }
697
698     _notmuch_message_add_term (message, "folder", folder);
699
700     talloc_free (folder);
701
702     message->modified = TRUE;
703     return NOTMUCH_STATUS_SUCCESS;
704 }
705
706 #define RECURSIVE_SUFFIX "/**"
707
708 /* Add "path:" terms for directory. */
709 static notmuch_status_t
710 _notmuch_message_add_path_terms (notmuch_message_t *message,
711                                  const char *directory)
712 {
713     /* Add exact "path:" term. */
714     _notmuch_message_add_term (message, "path", directory);
715
716     if (strlen (directory)) {
717         char *path, *p;
718
719         path = talloc_asprintf (NULL, "%s%s", directory, RECURSIVE_SUFFIX);
720         if (! path)
721             return NOTMUCH_STATUS_OUT_OF_MEMORY;
722
723         /* Add recursive "path:" terms for directory and all parents. */
724         for (p = path + strlen (path) - 1; p > path; p--) {
725             if (*p == '/') {
726                 strcpy (p, RECURSIVE_SUFFIX);
727                 _notmuch_message_add_term (message, "path", path);
728             }
729         }
730
731         talloc_free (path);
732     }
733
734     /* Recursive all-matching path:** for consistency. */
735     _notmuch_message_add_term (message, "path", "**");
736
737     return NOTMUCH_STATUS_SUCCESS;
738 }
739
740 /* Add directory based terms for all filenames of the message. */
741 static notmuch_status_t
742 _notmuch_message_add_directory_terms (void *ctx, notmuch_message_t *message)
743 {
744     const char *direntry_prefix = _find_prefix ("file-direntry");
745     int direntry_prefix_len = strlen (direntry_prefix);
746     Xapian::TermIterator i = message->doc.termlist_begin ();
747     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
748
749     for (i.skip_to (direntry_prefix); i != message->doc.termlist_end (); i++) {
750         unsigned int directory_id;
751         const char *direntry, *directory;
752         char *colon;
753         const std::string &term = *i;
754
755         /* Terminate loop at first term without desired prefix. */
756         if (strncmp (term.c_str (), direntry_prefix, direntry_prefix_len))
757             break;
758
759         /* Indicate that there are filenames remaining. */
760         status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
761
762         direntry = term.c_str ();
763         direntry += direntry_prefix_len;
764
765         directory_id = strtol (direntry, &colon, 10);
766
767         if (colon == NULL || *colon != ':')
768             INTERNAL_ERROR ("malformed direntry");
769
770         directory = _notmuch_database_get_directory_path (ctx,
771                                                           message->notmuch,
772                                                           directory_id);
773
774         _notmuch_message_add_folder_terms (message, directory);
775         _notmuch_message_add_path_terms (message, directory);
776     }
777
778     return status;
779 }
780
781 /* Add an additional 'filename' for 'message'.
782  *
783  * This change will not be reflected in the database until the next
784  * call to _notmuch_message_sync. */
785 notmuch_status_t
786 _notmuch_message_add_filename (notmuch_message_t *message,
787                                const char *filename)
788 {
789     const char *relative, *directory;
790     notmuch_status_t status;
791     void *local = talloc_new (message);
792     char *direntry;
793
794     if (filename == NULL)
795         INTERNAL_ERROR ("Message filename cannot be NULL.");
796
797     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
798         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
799         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
800
801     relative = _notmuch_database_relative_path (message->notmuch, filename);
802
803     status = _notmuch_database_split_path (local, relative, &directory, NULL);
804     if (status)
805         return status;
806
807     status = _notmuch_database_filename_to_direntry (
808         local, message->notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
809     if (status)
810         return status;
811
812     /* New file-direntry allows navigating to this message with
813      * notmuch_directory_get_child_files() . */
814     _notmuch_message_add_term (message, "file-direntry", direntry);
815
816     _notmuch_message_add_folder_terms (message, directory);
817     _notmuch_message_add_path_terms (message, directory);
818
819     talloc_free (local);
820
821     return NOTMUCH_STATUS_SUCCESS;
822 }
823
824 /* Remove a particular 'filename' from 'message'.
825  *
826  * This change will not be reflected in the database until the next
827  * call to _notmuch_message_sync.
828  *
829  * If this message still has other filenames, returns
830  * NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID.
831  *
832  * Note: This function does not remove a document from the database,
833  * even if the specified filename is the only filename for this
834  * message. For that functionality, see
835  * notmuch_database_remove_message. */
836 notmuch_status_t
837 _notmuch_message_remove_filename (notmuch_message_t *message,
838                                   const char *filename)
839 {
840     void *local = talloc_new (message);
841     char *direntry;
842     notmuch_private_status_t private_status;
843     notmuch_status_t status;
844
845     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
846         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
847         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
848
849     status = _notmuch_database_filename_to_direntry (
850         local, message->notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
851     if (status || !direntry)
852         return status;
853
854     /* Unlink this file from its parent directory. */
855     private_status = _notmuch_message_remove_term (message,
856                                                    "file-direntry", direntry);
857     status = COERCE_STATUS (private_status,
858                             "Unexpected error from _notmuch_message_remove_term");
859     if (status)
860         return status;
861
862     /* Re-synchronize "folder:" and "path:" terms for this message. */
863
864     /* Remove all "folder:" terms. */
865     _notmuch_message_remove_terms (message, _find_prefix ("folder"));
866
867     /* Remove all "path:" terms. */
868     _notmuch_message_remove_terms (message, _find_prefix ("path"));
869
870     /* Add back terms for all remaining filenames of the message. */
871     status = _notmuch_message_add_directory_terms (local, message);
872
873     talloc_free (local);
874
875     return status;
876 }
877
878 /* Upgrade the "folder:" prefix from V1 to V2. */
879 #define FOLDER_PREFIX_V1       "XFOLDER"
880 #define ZFOLDER_PREFIX_V1      "Z" FOLDER_PREFIX_V1
881 void
882 _notmuch_message_upgrade_folder (notmuch_message_t *message)
883 {
884     /* Remove all old "folder:" terms. */
885     _notmuch_message_remove_terms (message, FOLDER_PREFIX_V1);
886
887     /* Remove all old "folder:" stemmed terms. */
888     _notmuch_message_remove_terms (message, ZFOLDER_PREFIX_V1);
889
890     /* Add new boolean "folder:" and "path:" terms. */
891     _notmuch_message_add_directory_terms (message, message);
892 }
893
894 char *
895 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
896 {
897     return talloc_strdup (message, message->doc.get_data ().c_str ());
898 }
899
900 void
901 _notmuch_message_clear_data (notmuch_message_t *message)
902 {
903     message->doc.set_data ("");
904     message->modified = TRUE;
905 }
906
907 static void
908 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
909 {
910     notmuch_string_node_t *node;
911
912     if (message->filename_list)
913         return;
914
915     _notmuch_message_ensure_metadata (message, message->filename_term_list);
916
917     message->filename_list = _notmuch_string_list_create (message);
918     node = message->filename_term_list->head;
919
920     if (!node) {
921         /* A message document created by an old version of notmuch
922          * (prior to rename support) will have the filename in the
923          * data of the document rather than as a file-direntry term.
924          *
925          * It would be nice to do the upgrade of the document directly
926          * here, but the database is likely open in read-only mode. */
927
928         std::string datastr = message->doc.get_data ();
929         const char *data = datastr.c_str ();
930
931         if (data == NULL)
932             INTERNAL_ERROR ("message with no filename");
933
934         _notmuch_string_list_append (message->filename_list, data);
935
936         return;
937     }
938
939     for (; node; node = node->next) {
940         void *local = talloc_new (message);
941         const char *db_path, *directory, *basename, *filename;
942         char *colon, *direntry = NULL;
943         unsigned int directory_id;
944
945         direntry = node->string;
946
947         directory_id = strtol (direntry, &colon, 10);
948
949         if (colon == NULL || *colon != ':')
950             INTERNAL_ERROR ("malformed direntry");
951
952         basename = colon + 1;
953
954         *colon = '\0';
955
956         db_path = notmuch_database_get_path (message->notmuch);
957
958         directory = _notmuch_database_get_directory_path (local,
959                                                           message->notmuch,
960                                                           directory_id);
961
962         if (strlen (directory))
963             filename = talloc_asprintf (message, "%s/%s/%s",
964                                         db_path, directory, basename);
965         else
966             filename = talloc_asprintf (message, "%s/%s",
967                                         db_path, basename);
968
969         _notmuch_string_list_append (message->filename_list, filename);
970
971         talloc_free (local);
972     }
973
974     talloc_free (message->filename_term_list);
975     message->filename_term_list = NULL;
976 }
977
978 const char *
979 notmuch_message_get_filename (notmuch_message_t *message)
980 {
981     _notmuch_message_ensure_filename_list (message);
982
983     if (message->filename_list == NULL)
984         return NULL;
985
986     if (message->filename_list->head == NULL ||
987         message->filename_list->head->string == NULL)
988     {
989         INTERNAL_ERROR ("message with no filename");
990     }
991
992     return message->filename_list->head->string;
993 }
994
995 notmuch_filenames_t *
996 notmuch_message_get_filenames (notmuch_message_t *message)
997 {
998     _notmuch_message_ensure_filename_list (message);
999
1000     return _notmuch_filenames_create (message, message->filename_list);
1001 }
1002
1003 int
1004 notmuch_message_count_files (notmuch_message_t *message)
1005 {
1006     _notmuch_message_ensure_filename_list (message);
1007
1008     return _notmuch_string_list_length (message->filename_list);
1009 }
1010
1011 notmuch_bool_t
1012 notmuch_message_get_flag (notmuch_message_t *message,
1013                           notmuch_message_flag_t flag)
1014 {
1015     if (flag == NOTMUCH_MESSAGE_FLAG_GHOST &&
1016         ! NOTMUCH_TEST_BIT (message->lazy_flags, flag))
1017         _notmuch_message_ensure_metadata (message, NULL);
1018
1019     return NOTMUCH_TEST_BIT (message->flags, flag);
1020 }
1021
1022 void
1023 notmuch_message_set_flag (notmuch_message_t *message,
1024                           notmuch_message_flag_t flag, notmuch_bool_t enable)
1025 {
1026     if (enable)
1027         NOTMUCH_SET_BIT (&message->flags, flag);
1028     else
1029         NOTMUCH_CLEAR_BIT (&message->flags, flag);
1030     NOTMUCH_SET_BIT (&message->lazy_flags, flag);
1031 }
1032
1033 time_t
1034 notmuch_message_get_date (notmuch_message_t *message)
1035 {
1036     std::string value;
1037
1038     try {
1039         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
1040     } catch (Xapian::Error &error) {
1041         _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred when reading date: %s\n",
1042                  error.get_msg().c_str());
1043         message->notmuch->exception_reported = TRUE;
1044         return 0;
1045     }
1046
1047     if (value.empty ())
1048         /* sortable_unserialise is undefined on empty string */
1049         return 0;
1050     return Xapian::sortable_unserialise (value);
1051 }
1052
1053 notmuch_tags_t *
1054 notmuch_message_get_tags (notmuch_message_t *message)
1055 {
1056     notmuch_tags_t *tags;
1057
1058     _notmuch_message_ensure_metadata (message, message->tag_list);
1059
1060     tags = _notmuch_tags_create (message, message->tag_list);
1061     /* _notmuch_tags_create steals the reference to the tag_list, but
1062      * in this case it's still used by the message, so we add an
1063      * *additional* talloc reference to the list.  As a result, it's
1064      * possible to modify the message tags (which talloc_unlink's the
1065      * current list from the message) while still iterating because
1066      * the iterator will keep the current list alive. */
1067     if (!talloc_reference (message, message->tag_list))
1068         return NULL;
1069
1070     return tags;
1071 }
1072
1073 const char *
1074 _notmuch_message_get_author (notmuch_message_t *message)
1075 {
1076     return message->author;
1077 }
1078
1079 void
1080 _notmuch_message_set_author (notmuch_message_t *message,
1081                             const char *author)
1082 {
1083     if (message->author)
1084         talloc_free(message->author);
1085     message->author = talloc_strdup(message, author);
1086     return;
1087 }
1088
1089 void
1090 _notmuch_message_set_header_values (notmuch_message_t *message,
1091                                     const char *date,
1092                                     const char *from,
1093                                     const char *subject)
1094 {
1095     time_t time_value;
1096
1097     /* GMime really doesn't want to see a NULL date, so protect its
1098      * sensibilities. */
1099     if (date == NULL || *date == '\0') {
1100         time_value = 0;
1101     } else {
1102         time_value = g_mime_utils_header_decode_date_unix (date);
1103         /*
1104          * Workaround for https://bugzilla.gnome.org/show_bug.cgi?id=779923
1105          */
1106         if (time_value < 0)
1107             time_value = 0;
1108     }
1109
1110     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
1111                             Xapian::sortable_serialise (time_value));
1112     message->doc.add_value (NOTMUCH_VALUE_FROM, from);
1113     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
1114     message->modified = TRUE;
1115 }
1116
1117 /* Upgrade a message to support NOTMUCH_FEATURE_LAST_MOD.  The caller
1118  * must call _notmuch_message_sync. */
1119 void
1120 _notmuch_message_upgrade_last_mod (notmuch_message_t *message)
1121 {
1122     /* _notmuch_message_sync will update the last modification
1123      * revision; we just have to ask it to. */
1124     message->modified = TRUE;
1125 }
1126
1127 /* Synchronize changes made to message->doc out into the database. */
1128 void
1129 _notmuch_message_sync (notmuch_message_t *message)
1130 {
1131     Xapian::WritableDatabase *db;
1132
1133     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
1134         return;
1135
1136     if (! message->modified)
1137         return;
1138
1139     /* Update the last modification of this message. */
1140     if (message->notmuch->features & NOTMUCH_FEATURE_LAST_MOD)
1141         /* sortable_serialise gives a reasonably compact encoding,
1142          * which directly translates to reduced IO when scanning the
1143          * value stream.  Since it's built for doubles, we only get 53
1144          * effective bits, but that's still enough for the database to
1145          * last a few centuries at 1 million revisions per second. */
1146         message->doc.add_value (NOTMUCH_VALUE_LAST_MOD,
1147                                 Xapian::sortable_serialise (
1148                                     _notmuch_database_new_revision (
1149                                         message->notmuch)));
1150
1151     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
1152     db->replace_document (message->doc_id, message->doc);
1153     message->modified = FALSE;
1154 }
1155
1156 /* Delete a message document from the database, leaving a ghost
1157  * message in its place */
1158 notmuch_status_t
1159 _notmuch_message_delete (notmuch_message_t *message)
1160 {
1161     notmuch_status_t status;
1162     Xapian::WritableDatabase *db;
1163     const char *mid, *tid, *query_string;
1164     notmuch_message_t *ghost;
1165     notmuch_private_status_t private_status;
1166     notmuch_database_t *notmuch;
1167     notmuch_query_t *query;
1168     unsigned int count = 0;
1169     notmuch_bool_t is_ghost;
1170
1171     mid = notmuch_message_get_message_id (message);
1172     tid = notmuch_message_get_thread_id (message);
1173     notmuch = message->notmuch;
1174
1175     status = _notmuch_database_ensure_writable (message->notmuch);
1176     if (status)
1177         return status;
1178
1179     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1180     db->delete_document (message->doc_id);
1181
1182     /* if this was a ghost to begin with, we are done */
1183     private_status = _notmuch_message_has_term (message, "type", "ghost", &is_ghost);
1184     if (private_status)
1185         return COERCE_STATUS (private_status,
1186                               "Error trying to determine whether message was a ghost");
1187     if (is_ghost)
1188         return NOTMUCH_STATUS_SUCCESS;
1189
1190     query_string = talloc_asprintf (message, "thread:%s", tid);
1191     query = notmuch_query_create (notmuch, query_string);
1192     if (query == NULL)
1193         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1194     status = notmuch_query_count_messages (query, &count);
1195     if (status) {
1196         notmuch_query_destroy (query);
1197         return status;
1198     }
1199
1200     if (count > 0) {
1201         /* reintroduce a ghost in its place because there are still
1202          * other active messages in this thread: */
1203         ghost = _notmuch_message_create_for_message_id (notmuch, mid, &private_status);
1204         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1205             private_status = _notmuch_message_initialize_ghost (ghost, tid);
1206             if (! private_status)
1207                 _notmuch_message_sync (ghost);
1208         } else if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1209             /* this is deeply weird, and we should not have gotten
1210                into this state.  is there a better error message to
1211                return here? */
1212             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1213         }
1214
1215         notmuch_message_destroy (ghost);
1216         status = COERCE_STATUS (private_status, "Error converting to ghost message");
1217     } else {
1218         /* the thread is empty; drop all ghost messages from it */
1219         notmuch_messages_t *messages;
1220         status = _notmuch_query_search_documents (query,
1221                                                   "ghost",
1222                                                   &messages);
1223         if (status == NOTMUCH_STATUS_SUCCESS) {
1224             notmuch_status_t last_error = NOTMUCH_STATUS_SUCCESS;
1225             while (notmuch_messages_valid (messages)) {
1226                 message = notmuch_messages_get (messages);
1227                 status = _notmuch_message_delete (message);
1228                 if (status) /* we'll report the last failure we see;
1229                              * if there is more than one failure, we
1230                              * forget about previous ones */
1231                     last_error = status;
1232                 notmuch_message_destroy (message);
1233                 notmuch_messages_move_to_next (messages);
1234             }
1235             status = last_error;
1236         }
1237     }
1238     notmuch_query_destroy (query);
1239     return status;
1240 }
1241
1242 /* Transform a blank message into a ghost message.  The caller must
1243  * _notmuch_message_sync the message. */
1244 notmuch_private_status_t
1245 _notmuch_message_initialize_ghost (notmuch_message_t *message,
1246                                    const char *thread_id)
1247 {
1248     notmuch_private_status_t status;
1249
1250     status = _notmuch_message_add_term (message, "type", "ghost");
1251     if (status)
1252         return status;
1253     status = _notmuch_message_add_term (message, "thread", thread_id);
1254     if (status)
1255         return status;
1256
1257     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1258 }
1259
1260 /* Ensure that 'message' is not holding any file object open. Future
1261  * calls to various functions will still automatically open the
1262  * message file as needed.
1263  */
1264 void
1265 _notmuch_message_close (notmuch_message_t *message)
1266 {
1267     if (message->message_file) {
1268         _notmuch_message_file_close (message->message_file);
1269         message->message_file = NULL;
1270     }
1271 }
1272
1273 /* Add a name:value term to 'message', (the actual term will be
1274  * encoded by prefixing the value with a short prefix). See
1275  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1276  * names to prefix values.
1277  *
1278  * This change will not be reflected in the database until the next
1279  * call to _notmuch_message_sync. */
1280 notmuch_private_status_t
1281 _notmuch_message_add_term (notmuch_message_t *message,
1282                            const char *prefix_name,
1283                            const char *value)
1284 {
1285
1286     char *term;
1287
1288     if (value == NULL)
1289         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1290
1291     term = talloc_asprintf (message, "%s%s",
1292                             _find_prefix (prefix_name), value);
1293
1294     if (strlen (term) > NOTMUCH_TERM_MAX)
1295         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1296
1297     message->doc.add_term (term, 0);
1298     message->modified = TRUE;
1299
1300     talloc_free (term);
1301
1302     _notmuch_message_invalidate_metadata (message, prefix_name);
1303
1304     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1305 }
1306
1307 /* Parse 'text' and add a term to 'message' for each parsed word. Each
1308  * term will be added both prefixed (if prefix_name is not NULL) and
1309  * also non-prefixed). */
1310 notmuch_private_status_t
1311 _notmuch_message_gen_terms (notmuch_message_t *message,
1312                             const char *prefix_name,
1313                             const char *text)
1314 {
1315     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
1316
1317     if (text == NULL)
1318         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1319
1320     term_gen->set_document (message->doc);
1321
1322     if (prefix_name) {
1323         const char *prefix = _find_prefix (prefix_name);
1324
1325         term_gen->set_termpos (message->termpos);
1326         term_gen->index_text (text, 1, prefix);
1327         /* Create a gap between this an the next terms so they don't
1328          * appear to be a phrase. */
1329         message->termpos = term_gen->get_termpos () + 100;
1330
1331         _notmuch_message_invalidate_metadata (message, prefix_name);
1332     }
1333
1334     term_gen->set_termpos (message->termpos);
1335     term_gen->index_text (text);
1336     /* Create a term gap, as above. */
1337     message->termpos = term_gen->get_termpos () + 100;
1338
1339     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1340 }
1341
1342 /* Remove a name:value term from 'message', (the actual term will be
1343  * encoded by prefixing the value with a short prefix). See
1344  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1345  * names to prefix values.
1346  *
1347  * This change will not be reflected in the database until the next
1348  * call to _notmuch_message_sync. */
1349 notmuch_private_status_t
1350 _notmuch_message_remove_term (notmuch_message_t *message,
1351                               const char *prefix_name,
1352                               const char *value)
1353 {
1354     char *term;
1355
1356     if (value == NULL)
1357         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1358
1359     term = talloc_asprintf (message, "%s%s",
1360                             _find_prefix (prefix_name), value);
1361
1362     if (strlen (term) > NOTMUCH_TERM_MAX)
1363         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1364
1365     try {
1366         message->doc.remove_term (term);
1367         message->modified = TRUE;
1368     } catch (const Xapian::InvalidArgumentError) {
1369         /* We'll let the philosophers try to wrestle with the
1370          * question of whether failing to remove that which was not
1371          * there in the first place is failure. For us, we'll silently
1372          * consider it all good. */
1373     }
1374
1375     talloc_free (term);
1376
1377     _notmuch_message_invalidate_metadata (message, prefix_name);
1378
1379     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1380 }
1381
1382 notmuch_private_status_t
1383 _notmuch_message_has_term (notmuch_message_t *message,
1384                            const char *prefix_name,
1385                            const char *value,
1386                            notmuch_bool_t *result)
1387 {
1388     char *term;
1389     notmuch_bool_t out = FALSE;
1390     notmuch_private_status_t status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
1391
1392     if (value == NULL)
1393         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1394
1395     term = talloc_asprintf (message, "%s%s",
1396                             _find_prefix (prefix_name), value);
1397
1398     if (strlen (term) > NOTMUCH_TERM_MAX)
1399         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1400
1401     try {
1402         /* Look for the exact term */
1403         Xapian::TermIterator i = message->doc.termlist_begin ();
1404         i.skip_to (term);
1405         if (i != message->doc.termlist_end () &&
1406             !strcmp ((*i).c_str (), term))
1407             out = TRUE;
1408     } catch (Xapian::Error &error) {
1409         status = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
1410     }
1411     talloc_free (term);
1412
1413     *result = out;
1414     return status;
1415 }
1416
1417 notmuch_status_t
1418 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
1419 {
1420     notmuch_private_status_t private_status;
1421     notmuch_status_t status;
1422
1423     status = _notmuch_database_ensure_writable (message->notmuch);
1424     if (status)
1425         return status;
1426
1427     if (tag == NULL)
1428         return NOTMUCH_STATUS_NULL_POINTER;
1429
1430     if (strlen (tag) > NOTMUCH_TAG_MAX)
1431         return NOTMUCH_STATUS_TAG_TOO_LONG;
1432
1433     private_status = _notmuch_message_add_term (message, "tag", tag);
1434     if (private_status) {
1435         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
1436                         private_status);
1437     }
1438
1439     if (! message->frozen)
1440         _notmuch_message_sync (message);
1441
1442     return NOTMUCH_STATUS_SUCCESS;
1443 }
1444
1445 notmuch_status_t
1446 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1447 {
1448     notmuch_private_status_t private_status;
1449     notmuch_status_t status;
1450
1451     status = _notmuch_database_ensure_writable (message->notmuch);
1452     if (status)
1453         return status;
1454
1455     if (tag == NULL)
1456         return NOTMUCH_STATUS_NULL_POINTER;
1457
1458     if (strlen (tag) > NOTMUCH_TAG_MAX)
1459         return NOTMUCH_STATUS_TAG_TOO_LONG;
1460
1461     private_status = _notmuch_message_remove_term (message, "tag", tag);
1462     if (private_status) {
1463         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1464                         private_status);
1465     }
1466
1467     if (! message->frozen)
1468         _notmuch_message_sync (message);
1469
1470     return NOTMUCH_STATUS_SUCCESS;
1471 }
1472
1473 /* Is the given filename within a maildir directory?
1474  *
1475  * Specifically, is the final directory component of 'filename' either
1476  * "cur" or "new". If so, return a pointer to that final directory
1477  * component within 'filename'. If not, return NULL.
1478  *
1479  * A non-NULL return value is guaranteed to be a valid string pointer
1480  * pointing to the characters "new/" or "cur/", (but not
1481  * NUL-terminated).
1482  */
1483 static const char *
1484 _filename_is_in_maildir (const char *filename)
1485 {
1486     const char *slash, *dir = NULL;
1487
1488     /* Find the last '/' separating directory from filename. */
1489     slash = strrchr (filename, '/');
1490     if (slash == NULL)
1491         return NULL;
1492
1493     /* Jump back 4 characters to where the previous '/' will be if the
1494      * directory is named "cur" or "new". */
1495     if (slash - filename < 4)
1496         return NULL;
1497
1498     slash -= 4;
1499
1500     if (*slash != '/')
1501         return NULL;
1502
1503     dir = slash + 1;
1504
1505     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1506         STRNCMP_LITERAL (dir, "new/") == 0)
1507     {
1508         return dir;
1509     }
1510
1511     return NULL;
1512 }
1513
1514 notmuch_status_t
1515 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1516 {
1517     const char *flags;
1518     notmuch_status_t status;
1519     notmuch_filenames_t *filenames;
1520     const char *filename, *dir;
1521     char *combined_flags = talloc_strdup (message, "");
1522     unsigned i;
1523     int seen_maildir_info = 0;
1524
1525     for (filenames = notmuch_message_get_filenames (message);
1526          notmuch_filenames_valid (filenames);
1527          notmuch_filenames_move_to_next (filenames))
1528     {
1529         filename = notmuch_filenames_get (filenames);
1530         dir = _filename_is_in_maildir (filename);
1531
1532         if (! dir)
1533             continue;
1534
1535         flags = strstr (filename, ":2,");
1536         if (flags) {
1537             seen_maildir_info = 1;
1538             flags += 3;
1539             combined_flags = talloc_strdup_append (combined_flags, flags);
1540         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1541             /* Messages are delivered to new/ with no "info" part, but
1542              * they effectively have default maildir flags.  According
1543              * to the spec, we should ignore the info part for
1544              * messages in new/, but some MUAs (mutt) can set maildir
1545              * flags on messages in new/, so we're liberal in what we
1546              * accept. */
1547             seen_maildir_info = 1;
1548         }
1549     }
1550
1551     /* If none of the filenames have any maildir info field (not even
1552      * an empty info with no flags set) then there's no information to
1553      * go on, so do nothing. */
1554     if (! seen_maildir_info)
1555         return NOTMUCH_STATUS_SUCCESS;
1556
1557     status = notmuch_message_freeze (message);
1558     if (status)
1559         return status;
1560
1561     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
1562         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
1563             ^
1564             flag2tag[i].inverse)
1565         {
1566             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1567         } else {
1568             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1569         }
1570         if (status)
1571             return status;
1572     }
1573     status = notmuch_message_thaw (message);
1574
1575     talloc_free (combined_flags);
1576
1577     return status;
1578 }
1579
1580 /* From the set of tags on 'message' and the flag2tag table, compute a
1581  * set of maildir-flag actions to be taken, (flags that should be
1582  * either set or cleared).
1583  *
1584  * The result is returned as two talloced strings: to_set, and to_clear
1585  */
1586 static void
1587 _get_maildir_flag_actions (notmuch_message_t *message,
1588                            char **to_set_ret,
1589                            char **to_clear_ret)
1590 {
1591     char *to_set, *to_clear;
1592     notmuch_tags_t *tags;
1593     const char *tag;
1594     unsigned i;
1595
1596     to_set = talloc_strdup (message, "");
1597     to_clear = talloc_strdup (message, "");
1598
1599     /* First, find flags for all set tags. */
1600     for (tags = notmuch_message_get_tags (message);
1601          notmuch_tags_valid (tags);
1602          notmuch_tags_move_to_next (tags))
1603     {
1604         tag = notmuch_tags_get (tags);
1605
1606         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1607             if (strcmp (tag, flag2tag[i].tag) == 0) {
1608                 if (flag2tag[i].inverse)
1609                     to_clear = talloc_asprintf_append (to_clear,
1610                                                        "%c",
1611                                                        flag2tag[i].flag);
1612                 else
1613                     to_set = talloc_asprintf_append (to_set,
1614                                                      "%c",
1615                                                      flag2tag[i].flag);
1616             }
1617         }
1618     }
1619
1620     /* Then, find the flags for all tags not present. */
1621     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1622         if (flag2tag[i].inverse) {
1623             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1624                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1625         } else {
1626             if (strchr (to_set, flag2tag[i].flag) == NULL)
1627                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1628         }
1629     }
1630
1631     *to_set_ret = to_set;
1632     *to_clear_ret = to_clear;
1633 }
1634
1635 /* Given 'filename' and a set of maildir flags to set and to clear,
1636  * compute the new maildir filename.
1637  *
1638  * If the existing filename is in the directory "new", the new
1639  * filename will be in the directory "cur", except for the case when
1640  * no flags are changed and the existing filename does not contain
1641  * maildir info (starting with ",2:").
1642  *
1643  * After a sequence of ":2," in the filename, any subsequent
1644  * single-character flags will be added or removed according to the
1645  * characters in flags_to_set and flags_to_clear. Any existing flags
1646  * not mentioned in either string will remain. The final list of flags
1647  * will be in ASCII order.
1648  *
1649  * If the original flags seem invalid, (repeated characters or
1650  * non-ASCII ordering of flags), this function will return NULL
1651  * (meaning that renaming would not be safe and should not occur).
1652  */
1653 static char*
1654 _new_maildir_filename (void *ctx,
1655                        const char *filename,
1656                        const char *flags_to_set,
1657                        const char *flags_to_clear)
1658 {
1659     const char *info, *flags;
1660     unsigned int flag, last_flag;
1661     char *filename_new, *dir;
1662     char flag_map[128];
1663     int flags_in_map = 0;
1664     notmuch_bool_t flags_changed = FALSE;
1665     unsigned int i;
1666     char *s;
1667
1668     memset (flag_map, 0, sizeof (flag_map));
1669
1670     info = strstr (filename, ":2,");
1671
1672     if (info == NULL) {
1673         info = filename + strlen(filename);
1674     } else {
1675         /* Loop through existing flags in filename. */
1676         for (flags = info + 3, last_flag = 0;
1677              *flags;
1678              last_flag = flag, flags++)
1679         {
1680             flag = *flags;
1681
1682             /* Original flags not in ASCII order. Abort. */
1683             if (flag < last_flag)
1684                 return NULL;
1685
1686             /* Non-ASCII flag. Abort. */
1687             if (flag > sizeof(flag_map) - 1)
1688                 return NULL;
1689
1690             /* Repeated flag value. Abort. */
1691             if (flag_map[flag])
1692                 return NULL;
1693
1694             flag_map[flag] = 1;
1695             flags_in_map++;
1696         }
1697     }
1698
1699     /* Then set and clear our flags from tags. */
1700     for (flags = flags_to_set; *flags; flags++) {
1701         flag = *flags;
1702         if (flag_map[flag] == 0) {
1703             flag_map[flag] = 1;
1704             flags_in_map++;
1705             flags_changed = TRUE;
1706         }
1707     }
1708
1709     for (flags = flags_to_clear; *flags; flags++) {
1710         flag = *flags;
1711         if (flag_map[flag]) {
1712             flag_map[flag] = 0;
1713             flags_in_map--;
1714             flags_changed = TRUE;
1715         }
1716     }
1717
1718     /* Messages in new/ without maildir info can be kept in new/ if no
1719      * flags have changed. */
1720     dir = (char *) _filename_is_in_maildir (filename);
1721     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && !*info && !flags_changed)
1722         return talloc_strdup (ctx, filename);
1723
1724     filename_new = (char *) talloc_size (ctx,
1725                                          info - filename +
1726                                          strlen (":2,") + flags_in_map + 1);
1727     if (unlikely (filename_new == NULL))
1728         return NULL;
1729
1730     strncpy (filename_new, filename, info - filename);
1731     filename_new[info - filename] = '\0';
1732
1733     strcat (filename_new, ":2,");
1734
1735     s = filename_new + strlen (filename_new);
1736     for (i = 0; i < sizeof (flag_map); i++)
1737     {
1738         if (flag_map[i]) {
1739             *s = i;
1740             s++;
1741         }
1742     }
1743     *s = '\0';
1744
1745     /* If message is in new/ move it under cur/. */
1746     dir = (char *) _filename_is_in_maildir (filename_new);
1747     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1748         memcpy (dir, "cur/", 4);
1749
1750     return filename_new;
1751 }
1752
1753 notmuch_status_t
1754 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1755 {
1756     notmuch_filenames_t *filenames;
1757     const char *filename;
1758     char *filename_new;
1759     char *to_set, *to_clear;
1760     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1761
1762     _get_maildir_flag_actions (message, &to_set, &to_clear);
1763
1764     for (filenames = notmuch_message_get_filenames (message);
1765          notmuch_filenames_valid (filenames);
1766          notmuch_filenames_move_to_next (filenames))
1767     {
1768         filename = notmuch_filenames_get (filenames);
1769
1770         if (! _filename_is_in_maildir (filename))
1771             continue;
1772
1773         filename_new = _new_maildir_filename (message, filename,
1774                                               to_set, to_clear);
1775         if (filename_new == NULL)
1776             continue;
1777
1778         if (strcmp (filename, filename_new)) {
1779             int err;
1780             notmuch_status_t new_status;
1781
1782             err = rename (filename, filename_new);
1783             if (err)
1784                 continue;
1785
1786             new_status = _notmuch_message_remove_filename (message,
1787                                                            filename);
1788             /* Hold on to only the first error. */
1789             if (! status && new_status
1790                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
1791                 status = new_status;
1792                 continue;
1793             }
1794
1795             new_status = _notmuch_message_add_filename (message,
1796                                                         filename_new);
1797             /* Hold on to only the first error. */
1798             if (! status && new_status) {
1799                 status = new_status;
1800                 continue;
1801             }
1802
1803             _notmuch_message_sync (message);
1804         }
1805
1806         talloc_free (filename_new);
1807     }
1808
1809     talloc_free (to_set);
1810     talloc_free (to_clear);
1811
1812     return status;
1813 }
1814
1815 notmuch_status_t
1816 notmuch_message_remove_all_tags (notmuch_message_t *message)
1817 {
1818     notmuch_private_status_t private_status;
1819     notmuch_status_t status;
1820     notmuch_tags_t *tags;
1821     const char *tag;
1822
1823     status = _notmuch_database_ensure_writable (message->notmuch);
1824     if (status)
1825         return status;
1826
1827     for (tags = notmuch_message_get_tags (message);
1828          notmuch_tags_valid (tags);
1829          notmuch_tags_move_to_next (tags))
1830     {
1831         tag = notmuch_tags_get (tags);
1832
1833         private_status = _notmuch_message_remove_term (message, "tag", tag);
1834         if (private_status) {
1835             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1836                             private_status);
1837         }
1838     }
1839
1840     if (! message->frozen)
1841         _notmuch_message_sync (message);
1842
1843     talloc_free (tags);
1844     return NOTMUCH_STATUS_SUCCESS;
1845 }
1846
1847 notmuch_status_t
1848 notmuch_message_freeze (notmuch_message_t *message)
1849 {
1850     notmuch_status_t status;
1851
1852     status = _notmuch_database_ensure_writable (message->notmuch);
1853     if (status)
1854         return status;
1855
1856     message->frozen++;
1857
1858     return NOTMUCH_STATUS_SUCCESS;
1859 }
1860
1861 notmuch_status_t
1862 notmuch_message_thaw (notmuch_message_t *message)
1863 {
1864     notmuch_status_t status;
1865
1866     status = _notmuch_database_ensure_writable (message->notmuch);
1867     if (status)
1868         return status;
1869
1870     if (message->frozen > 0) {
1871         message->frozen--;
1872         if (message->frozen == 0)
1873             _notmuch_message_sync (message);
1874         return NOTMUCH_STATUS_SUCCESS;
1875     } else {
1876         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1877     }
1878 }
1879
1880 void
1881 notmuch_message_destroy (notmuch_message_t *message)
1882 {
1883     talloc_free (message);
1884 }
1885
1886 notmuch_database_t *
1887 _notmuch_message_database (notmuch_message_t *message)
1888 {
1889     return message->notmuch;
1890 }
1891
1892 static void
1893 _notmuch_message_ensure_property_map (notmuch_message_t *message)
1894 {
1895     notmuch_string_node_t *node;
1896
1897     if (message->property_map)
1898         return;
1899
1900     _notmuch_message_ensure_metadata (message, message->property_term_list);
1901
1902     message->property_map = _notmuch_string_map_create (message);
1903
1904     for (node = message->property_term_list->head; node; node = node->next) {
1905         const char *key;
1906         char *value;
1907
1908         value = strchr(node->string, '=');
1909         if (!value)
1910             INTERNAL_ERROR ("malformed property term");
1911
1912         *value = '\0';
1913         value++;
1914         key = node->string;
1915
1916         _notmuch_string_map_append (message->property_map, key, value);
1917
1918     }
1919
1920     talloc_free (message->property_term_list);
1921     message->property_term_list = NULL;
1922 }
1923
1924 notmuch_string_map_t *
1925 _notmuch_message_property_map (notmuch_message_t *message)
1926 {
1927     _notmuch_message_ensure_property_map (message);
1928
1929     return message->property_map;
1930 }
1931
1932 notmuch_bool_t
1933 _notmuch_message_frozen (notmuch_message_t *message)
1934 {
1935     return message->frozen;
1936 }