]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
Merge branch 'release'
[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 = 0;
583
584     prefix_len = strlen (prefix);
585
586     while (1) {
587         i = message->doc.termlist_begin ();
588         i.skip_to (prefix);
589
590         /* Terminate loop when no terms remain with desired prefix. */
591         if (i == message->doc.termlist_end () ||
592             strncmp ((*i).c_str (), prefix, prefix_len))
593             break;
594
595         try {
596             message->doc.remove_term ((*i));
597             message->modified = TRUE;
598         } catch (const Xapian::InvalidArgumentError) {
599             /* Ignore failure to remove non-existent term. */
600         }
601     }
602 }
603
604
605 /* Remove all terms generated by indexing, i.e. not tags or
606  * properties, along with any automatic tags*/
607 notmuch_private_status_t
608 _notmuch_message_remove_indexed_terms (notmuch_message_t *message)
609 {
610     Xapian::TermIterator i;
611
612     const std::string
613         id_prefix = _find_prefix ("id"),
614         property_prefix = _find_prefix ("property"),
615         tag_prefix = _find_prefix ("tag"),
616         type_prefix = _find_prefix ("type");
617
618     for (i = message->doc.termlist_begin ();
619          i != message->doc.termlist_end (); i++) {
620
621         const std::string term = *i;
622
623         if (term.compare (0, type_prefix.size (), type_prefix) == 0)
624             continue;
625
626         if (term.compare (0, id_prefix.size (), id_prefix) == 0)
627             continue;
628
629         if (term.compare (0, property_prefix.size (), property_prefix) == 0)
630             continue;
631
632         if (term.compare (0, tag_prefix.size (), tag_prefix) == 0 &&
633             term.compare (1, strlen("encrypted"), "encrypted") != 0 &&
634             term.compare (1, strlen("signed"), "signed") != 0 &&
635             term.compare (1, strlen("attachment"), "attachment") != 0)
636             continue;
637
638         try {
639             message->doc.remove_term ((*i));
640             message->modified = TRUE;
641         } catch (const Xapian::InvalidArgumentError) {
642             /* Ignore failure to remove non-existent term. */
643         } catch (const Xapian::Error &error) {
644             notmuch_database_t *notmuch = message->notmuch;
645
646             if (!notmuch->exception_reported) {
647                 _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred creating message: %s\n",
648                                       error.get_msg().c_str());
649                 notmuch->exception_reported = TRUE;
650             }
651             return NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
652         }
653     }
654     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
655 }
656
657 /* Return true if p points at "new" or "cur". */
658 static bool is_maildir (const char *p)
659 {
660     return strcmp (p, "cur") == 0 || strcmp (p, "new") == 0;
661 }
662
663 /* Add "folder:" term for directory. */
664 static notmuch_status_t
665 _notmuch_message_add_folder_terms (notmuch_message_t *message,
666                                    const char *directory)
667 {
668     char *folder, *last;
669
670     folder = talloc_strdup (NULL, directory);
671     if (! folder)
672         return NOTMUCH_STATUS_OUT_OF_MEMORY;
673
674     /*
675      * If the message file is in a leaf directory named "new" or
676      * "cur", presume maildir and index the parent directory. Thus a
677      * "folder:" prefix search matches messages in the specified
678      * maildir folder, i.e. in the specified directory and its "new"
679      * and "cur" subdirectories.
680      *
681      * Note that this means the "folder:" prefix can't be used for
682      * distinguishing between message files in "new" or "cur". The
683      * "path:" prefix needs to be used for that.
684      *
685      * Note the deliberate difference to _filename_is_in_maildir(). We
686      * don't want to index different things depending on the existence
687      * or non-existence of all maildir sibling directories "new",
688      * "cur", and "tmp". Doing so would be surprising, and difficult
689      * for the user to fix in case all subdirectories were not in
690      * place during indexing.
691      */
692     last = strrchr (folder, '/');
693     if (last) {
694         if (is_maildir (last + 1))
695             *last = '\0';
696     } else if (is_maildir (folder)) {
697         *folder = '\0';
698     }
699
700     _notmuch_message_add_term (message, "folder", folder);
701
702     talloc_free (folder);
703
704     message->modified = TRUE;
705     return NOTMUCH_STATUS_SUCCESS;
706 }
707
708 #define RECURSIVE_SUFFIX "/**"
709
710 /* Add "path:" terms for directory. */
711 static notmuch_status_t
712 _notmuch_message_add_path_terms (notmuch_message_t *message,
713                                  const char *directory)
714 {
715     /* Add exact "path:" term. */
716     _notmuch_message_add_term (message, "path", directory);
717
718     if (strlen (directory)) {
719         char *path, *p;
720
721         path = talloc_asprintf (NULL, "%s%s", directory, RECURSIVE_SUFFIX);
722         if (! path)
723             return NOTMUCH_STATUS_OUT_OF_MEMORY;
724
725         /* Add recursive "path:" terms for directory and all parents. */
726         for (p = path + strlen (path) - 1; p > path; p--) {
727             if (*p == '/') {
728                 strcpy (p, RECURSIVE_SUFFIX);
729                 _notmuch_message_add_term (message, "path", path);
730             }
731         }
732
733         talloc_free (path);
734     }
735
736     /* Recursive all-matching path:** for consistency. */
737     _notmuch_message_add_term (message, "path", "**");
738
739     return NOTMUCH_STATUS_SUCCESS;
740 }
741
742 /* Add directory based terms for all filenames of the message. */
743 static notmuch_status_t
744 _notmuch_message_add_directory_terms (void *ctx, notmuch_message_t *message)
745 {
746     const char *direntry_prefix = _find_prefix ("file-direntry");
747     int direntry_prefix_len = strlen (direntry_prefix);
748     Xapian::TermIterator i = message->doc.termlist_begin ();
749     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
750
751     for (i.skip_to (direntry_prefix); i != message->doc.termlist_end (); i++) {
752         unsigned int directory_id;
753         const char *direntry, *directory;
754         char *colon;
755         const std::string &term = *i;
756
757         /* Terminate loop at first term without desired prefix. */
758         if (strncmp (term.c_str (), direntry_prefix, direntry_prefix_len))
759             break;
760
761         /* Indicate that there are filenames remaining. */
762         status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
763
764         direntry = term.c_str ();
765         direntry += direntry_prefix_len;
766
767         directory_id = strtol (direntry, &colon, 10);
768
769         if (colon == NULL || *colon != ':')
770             INTERNAL_ERROR ("malformed direntry");
771
772         directory = _notmuch_database_get_directory_path (ctx,
773                                                           message->notmuch,
774                                                           directory_id);
775
776         _notmuch_message_add_folder_terms (message, directory);
777         _notmuch_message_add_path_terms (message, directory);
778     }
779
780     return status;
781 }
782
783 /* Add an additional 'filename' for 'message'.
784  *
785  * This change will not be reflected in the database until the next
786  * call to _notmuch_message_sync. */
787 notmuch_status_t
788 _notmuch_message_add_filename (notmuch_message_t *message,
789                                const char *filename)
790 {
791     const char *relative, *directory;
792     notmuch_status_t status;
793     void *local = talloc_new (message);
794     char *direntry;
795
796     if (filename == NULL)
797         INTERNAL_ERROR ("Message filename cannot be NULL.");
798
799     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
800         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
801         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
802
803     relative = _notmuch_database_relative_path (message->notmuch, filename);
804
805     status = _notmuch_database_split_path (local, relative, &directory, NULL);
806     if (status)
807         return status;
808
809     status = _notmuch_database_filename_to_direntry (
810         local, message->notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
811     if (status)
812         return status;
813
814     /* New file-direntry allows navigating to this message with
815      * notmuch_directory_get_child_files() . */
816     _notmuch_message_add_term (message, "file-direntry", direntry);
817
818     _notmuch_message_add_folder_terms (message, directory);
819     _notmuch_message_add_path_terms (message, directory);
820
821     talloc_free (local);
822
823     return NOTMUCH_STATUS_SUCCESS;
824 }
825
826 /* Remove a particular 'filename' from 'message'.
827  *
828  * This change will not be reflected in the database until the next
829  * call to _notmuch_message_sync.
830  *
831  * If this message still has other filenames, returns
832  * NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID.
833  *
834  * Note: This function does not remove a document from the database,
835  * even if the specified filename is the only filename for this
836  * message. For that functionality, see
837  * notmuch_database_remove_message. */
838 notmuch_status_t
839 _notmuch_message_remove_filename (notmuch_message_t *message,
840                                   const char *filename)
841 {
842     void *local = talloc_new (message);
843     char *direntry;
844     notmuch_private_status_t private_status;
845     notmuch_status_t status;
846
847     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
848         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
849         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
850
851     status = _notmuch_database_filename_to_direntry (
852         local, message->notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
853     if (status || !direntry)
854         return status;
855
856     /* Unlink this file from its parent directory. */
857     private_status = _notmuch_message_remove_term (message,
858                                                    "file-direntry", direntry);
859     status = COERCE_STATUS (private_status,
860                             "Unexpected error from _notmuch_message_remove_term");
861     if (status)
862         return status;
863
864     /* Re-synchronize "folder:" and "path:" terms for this message. */
865
866     /* Remove all "folder:" terms. */
867     _notmuch_message_remove_terms (message, _find_prefix ("folder"));
868
869     /* Remove all "path:" terms. */
870     _notmuch_message_remove_terms (message, _find_prefix ("path"));
871
872     /* Add back terms for all remaining filenames of the message. */
873     status = _notmuch_message_add_directory_terms (local, message);
874
875     talloc_free (local);
876
877     return status;
878 }
879
880 /* Upgrade the "folder:" prefix from V1 to V2. */
881 #define FOLDER_PREFIX_V1       "XFOLDER"
882 #define ZFOLDER_PREFIX_V1      "Z" FOLDER_PREFIX_V1
883 void
884 _notmuch_message_upgrade_folder (notmuch_message_t *message)
885 {
886     /* Remove all old "folder:" terms. */
887     _notmuch_message_remove_terms (message, FOLDER_PREFIX_V1);
888
889     /* Remove all old "folder:" stemmed terms. */
890     _notmuch_message_remove_terms (message, ZFOLDER_PREFIX_V1);
891
892     /* Add new boolean "folder:" and "path:" terms. */
893     _notmuch_message_add_directory_terms (message, message);
894 }
895
896 char *
897 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
898 {
899     return talloc_strdup (message, message->doc.get_data ().c_str ());
900 }
901
902 void
903 _notmuch_message_clear_data (notmuch_message_t *message)
904 {
905     message->doc.set_data ("");
906     message->modified = TRUE;
907 }
908
909 static void
910 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
911 {
912     notmuch_string_node_t *node;
913
914     if (message->filename_list)
915         return;
916
917     _notmuch_message_ensure_metadata (message, message->filename_term_list);
918
919     message->filename_list = _notmuch_string_list_create (message);
920     node = message->filename_term_list->head;
921
922     if (!node) {
923         /* A message document created by an old version of notmuch
924          * (prior to rename support) will have the filename in the
925          * data of the document rather than as a file-direntry term.
926          *
927          * It would be nice to do the upgrade of the document directly
928          * here, but the database is likely open in read-only mode. */
929
930         std::string datastr = message->doc.get_data ();
931         const char *data = datastr.c_str ();
932
933         if (data == NULL)
934             INTERNAL_ERROR ("message with no filename");
935
936         _notmuch_string_list_append (message->filename_list, data);
937
938         return;
939     }
940
941     for (; node; node = node->next) {
942         void *local = talloc_new (message);
943         const char *db_path, *directory, *basename, *filename;
944         char *colon, *direntry = NULL;
945         unsigned int directory_id;
946
947         direntry = node->string;
948
949         directory_id = strtol (direntry, &colon, 10);
950
951         if (colon == NULL || *colon != ':')
952             INTERNAL_ERROR ("malformed direntry");
953
954         basename = colon + 1;
955
956         *colon = '\0';
957
958         db_path = notmuch_database_get_path (message->notmuch);
959
960         directory = _notmuch_database_get_directory_path (local,
961                                                           message->notmuch,
962                                                           directory_id);
963
964         if (strlen (directory))
965             filename = talloc_asprintf (message, "%s/%s/%s",
966                                         db_path, directory, basename);
967         else
968             filename = talloc_asprintf (message, "%s/%s",
969                                         db_path, basename);
970
971         _notmuch_string_list_append (message->filename_list, filename);
972
973         talloc_free (local);
974     }
975
976     talloc_free (message->filename_term_list);
977     message->filename_term_list = NULL;
978 }
979
980 const char *
981 notmuch_message_get_filename (notmuch_message_t *message)
982 {
983     _notmuch_message_ensure_filename_list (message);
984
985     if (message->filename_list == NULL)
986         return NULL;
987
988     if (message->filename_list->head == NULL ||
989         message->filename_list->head->string == NULL)
990     {
991         INTERNAL_ERROR ("message with no filename");
992     }
993
994     return message->filename_list->head->string;
995 }
996
997 notmuch_filenames_t *
998 notmuch_message_get_filenames (notmuch_message_t *message)
999 {
1000     _notmuch_message_ensure_filename_list (message);
1001
1002     return _notmuch_filenames_create (message, message->filename_list);
1003 }
1004
1005 int
1006 notmuch_message_count_files (notmuch_message_t *message)
1007 {
1008     _notmuch_message_ensure_filename_list (message);
1009
1010     return _notmuch_string_list_length (message->filename_list);
1011 }
1012
1013 notmuch_bool_t
1014 notmuch_message_get_flag (notmuch_message_t *message,
1015                           notmuch_message_flag_t flag)
1016 {
1017     if (flag == NOTMUCH_MESSAGE_FLAG_GHOST &&
1018         ! NOTMUCH_TEST_BIT (message->lazy_flags, flag))
1019         _notmuch_message_ensure_metadata (message, NULL);
1020
1021     return NOTMUCH_TEST_BIT (message->flags, flag);
1022 }
1023
1024 void
1025 notmuch_message_set_flag (notmuch_message_t *message,
1026                           notmuch_message_flag_t flag, notmuch_bool_t enable)
1027 {
1028     if (enable)
1029         NOTMUCH_SET_BIT (&message->flags, flag);
1030     else
1031         NOTMUCH_CLEAR_BIT (&message->flags, flag);
1032     NOTMUCH_SET_BIT (&message->lazy_flags, flag);
1033 }
1034
1035 time_t
1036 notmuch_message_get_date (notmuch_message_t *message)
1037 {
1038     std::string value;
1039
1040     try {
1041         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
1042     } catch (Xapian::Error &error) {
1043         _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred when reading date: %s\n",
1044                  error.get_msg().c_str());
1045         message->notmuch->exception_reported = TRUE;
1046         return 0;
1047     }
1048
1049     if (value.empty ())
1050         /* sortable_unserialise is undefined on empty string */
1051         return 0;
1052     return Xapian::sortable_unserialise (value);
1053 }
1054
1055 notmuch_tags_t *
1056 notmuch_message_get_tags (notmuch_message_t *message)
1057 {
1058     notmuch_tags_t *tags;
1059
1060     _notmuch_message_ensure_metadata (message, message->tag_list);
1061
1062     tags = _notmuch_tags_create (message, message->tag_list);
1063     /* _notmuch_tags_create steals the reference to the tag_list, but
1064      * in this case it's still used by the message, so we add an
1065      * *additional* talloc reference to the list.  As a result, it's
1066      * possible to modify the message tags (which talloc_unlink's the
1067      * current list from the message) while still iterating because
1068      * the iterator will keep the current list alive. */
1069     if (!talloc_reference (message, message->tag_list))
1070         return NULL;
1071
1072     return tags;
1073 }
1074
1075 const char *
1076 _notmuch_message_get_author (notmuch_message_t *message)
1077 {
1078     return message->author;
1079 }
1080
1081 void
1082 _notmuch_message_set_author (notmuch_message_t *message,
1083                             const char *author)
1084 {
1085     if (message->author)
1086         talloc_free(message->author);
1087     message->author = talloc_strdup(message, author);
1088     return;
1089 }
1090
1091 void
1092 _notmuch_message_set_header_values (notmuch_message_t *message,
1093                                     const char *date,
1094                                     const char *from,
1095                                     const char *subject)
1096 {
1097     time_t time_value;
1098
1099     /* GMime really doesn't want to see a NULL date, so protect its
1100      * sensibilities. */
1101     if (date == NULL || *date == '\0') {
1102         time_value = 0;
1103     } else {
1104         time_value = g_mime_utils_header_decode_date_unix (date);
1105         /*
1106          * Workaround for https://bugzilla.gnome.org/show_bug.cgi?id=779923
1107          */
1108         if (time_value < 0)
1109             time_value = 0;
1110     }
1111
1112     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
1113                             Xapian::sortable_serialise (time_value));
1114     message->doc.add_value (NOTMUCH_VALUE_FROM, from);
1115     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
1116     message->modified = TRUE;
1117 }
1118
1119 /* Upgrade a message to support NOTMUCH_FEATURE_LAST_MOD.  The caller
1120  * must call _notmuch_message_sync. */
1121 void
1122 _notmuch_message_upgrade_last_mod (notmuch_message_t *message)
1123 {
1124     /* _notmuch_message_sync will update the last modification
1125      * revision; we just have to ask it to. */
1126     message->modified = TRUE;
1127 }
1128
1129 /* Synchronize changes made to message->doc out into the database. */
1130 void
1131 _notmuch_message_sync (notmuch_message_t *message)
1132 {
1133     Xapian::WritableDatabase *db;
1134
1135     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
1136         return;
1137
1138     if (! message->modified)
1139         return;
1140
1141     /* Update the last modification of this message. */
1142     if (message->notmuch->features & NOTMUCH_FEATURE_LAST_MOD)
1143         /* sortable_serialise gives a reasonably compact encoding,
1144          * which directly translates to reduced IO when scanning the
1145          * value stream.  Since it's built for doubles, we only get 53
1146          * effective bits, but that's still enough for the database to
1147          * last a few centuries at 1 million revisions per second. */
1148         message->doc.add_value (NOTMUCH_VALUE_LAST_MOD,
1149                                 Xapian::sortable_serialise (
1150                                     _notmuch_database_new_revision (
1151                                         message->notmuch)));
1152
1153     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
1154     db->replace_document (message->doc_id, message->doc);
1155     message->modified = FALSE;
1156 }
1157
1158 /* Delete a message document from the database, leaving a ghost
1159  * message in its place */
1160 notmuch_status_t
1161 _notmuch_message_delete (notmuch_message_t *message)
1162 {
1163     notmuch_status_t status;
1164     Xapian::WritableDatabase *db;
1165     const char *mid, *tid, *query_string;
1166     notmuch_message_t *ghost;
1167     notmuch_private_status_t private_status;
1168     notmuch_database_t *notmuch;
1169     notmuch_query_t *query;
1170     unsigned int count = 0;
1171     notmuch_bool_t is_ghost;
1172
1173     mid = notmuch_message_get_message_id (message);
1174     tid = notmuch_message_get_thread_id (message);
1175     notmuch = message->notmuch;
1176
1177     status = _notmuch_database_ensure_writable (message->notmuch);
1178     if (status)
1179         return status;
1180
1181     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1182     db->delete_document (message->doc_id);
1183
1184     /* if this was a ghost to begin with, we are done */
1185     private_status = _notmuch_message_has_term (message, "type", "ghost", &is_ghost);
1186     if (private_status)
1187         return COERCE_STATUS (private_status,
1188                               "Error trying to determine whether message was a ghost");
1189     if (is_ghost)
1190         return NOTMUCH_STATUS_SUCCESS;
1191
1192     query_string = talloc_asprintf (message, "thread:%s", tid);
1193     query = notmuch_query_create (notmuch, query_string);
1194     if (query == NULL)
1195         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1196     status = notmuch_query_count_messages (query, &count);
1197     if (status) {
1198         notmuch_query_destroy (query);
1199         return status;
1200     }
1201
1202     if (count > 0) {
1203         /* reintroduce a ghost in its place because there are still
1204          * other active messages in this thread: */
1205         ghost = _notmuch_message_create_for_message_id (notmuch, mid, &private_status);
1206         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1207             private_status = _notmuch_message_initialize_ghost (ghost, tid);
1208             if (! private_status)
1209                 _notmuch_message_sync (ghost);
1210         } else if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1211             /* this is deeply weird, and we should not have gotten
1212                into this state.  is there a better error message to
1213                return here? */
1214             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1215         }
1216
1217         notmuch_message_destroy (ghost);
1218         status = COERCE_STATUS (private_status, "Error converting to ghost message");
1219     } else {
1220         /* the thread is empty; drop all ghost messages from it */
1221         notmuch_messages_t *messages;
1222         status = _notmuch_query_search_documents (query,
1223                                                   "ghost",
1224                                                   &messages);
1225         if (status == NOTMUCH_STATUS_SUCCESS) {
1226             notmuch_status_t last_error = NOTMUCH_STATUS_SUCCESS;
1227             while (notmuch_messages_valid (messages)) {
1228                 message = notmuch_messages_get (messages);
1229                 status = _notmuch_message_delete (message);
1230                 if (status) /* we'll report the last failure we see;
1231                              * if there is more than one failure, we
1232                              * forget about previous ones */
1233                     last_error = status;
1234                 notmuch_message_destroy (message);
1235                 notmuch_messages_move_to_next (messages);
1236             }
1237             status = last_error;
1238         }
1239     }
1240     notmuch_query_destroy (query);
1241     return status;
1242 }
1243
1244 /* Transform a blank message into a ghost message.  The caller must
1245  * _notmuch_message_sync the message. */
1246 notmuch_private_status_t
1247 _notmuch_message_initialize_ghost (notmuch_message_t *message,
1248                                    const char *thread_id)
1249 {
1250     notmuch_private_status_t status;
1251
1252     status = _notmuch_message_add_term (message, "type", "ghost");
1253     if (status)
1254         return status;
1255     status = _notmuch_message_add_term (message, "thread", thread_id);
1256     if (status)
1257         return status;
1258
1259     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1260 }
1261
1262 /* Ensure that 'message' is not holding any file object open. Future
1263  * calls to various functions will still automatically open the
1264  * message file as needed.
1265  */
1266 void
1267 _notmuch_message_close (notmuch_message_t *message)
1268 {
1269     if (message->message_file) {
1270         _notmuch_message_file_close (message->message_file);
1271         message->message_file = NULL;
1272     }
1273 }
1274
1275 /* Add a name:value term to 'message', (the actual term will be
1276  * encoded by prefixing the value with a short prefix). See
1277  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1278  * names to prefix values.
1279  *
1280  * This change will not be reflected in the database until the next
1281  * call to _notmuch_message_sync. */
1282 notmuch_private_status_t
1283 _notmuch_message_add_term (notmuch_message_t *message,
1284                            const char *prefix_name,
1285                            const char *value)
1286 {
1287
1288     char *term;
1289
1290     if (value == NULL)
1291         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1292
1293     term = talloc_asprintf (message, "%s%s",
1294                             _find_prefix (prefix_name), value);
1295
1296     if (strlen (term) > NOTMUCH_TERM_MAX)
1297         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1298
1299     message->doc.add_term (term, 0);
1300     message->modified = TRUE;
1301
1302     talloc_free (term);
1303
1304     _notmuch_message_invalidate_metadata (message, prefix_name);
1305
1306     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1307 }
1308
1309 /* Parse 'text' and add a term to 'message' for each parsed word. Each
1310  * term will be added both prefixed (if prefix_name is not NULL) and
1311  * also non-prefixed). */
1312 notmuch_private_status_t
1313 _notmuch_message_gen_terms (notmuch_message_t *message,
1314                             const char *prefix_name,
1315                             const char *text)
1316 {
1317     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
1318
1319     if (text == NULL)
1320         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1321
1322     term_gen->set_document (message->doc);
1323
1324     if (prefix_name) {
1325         const char *prefix = _find_prefix (prefix_name);
1326
1327         term_gen->set_termpos (message->termpos);
1328         term_gen->index_text (text, 1, prefix);
1329         /* Create a gap between this an the next terms so they don't
1330          * appear to be a phrase. */
1331         message->termpos = term_gen->get_termpos () + 100;
1332
1333         _notmuch_message_invalidate_metadata (message, prefix_name);
1334     }
1335
1336     term_gen->set_termpos (message->termpos);
1337     term_gen->index_text (text);
1338     /* Create a term gap, as above. */
1339     message->termpos = term_gen->get_termpos () + 100;
1340
1341     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1342 }
1343
1344 /* Remove a name:value term from 'message', (the actual term will be
1345  * encoded by prefixing the value with a short prefix). See
1346  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1347  * names to prefix values.
1348  *
1349  * This change will not be reflected in the database until the next
1350  * call to _notmuch_message_sync. */
1351 notmuch_private_status_t
1352 _notmuch_message_remove_term (notmuch_message_t *message,
1353                               const char *prefix_name,
1354                               const char *value)
1355 {
1356     char *term;
1357
1358     if (value == NULL)
1359         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1360
1361     term = talloc_asprintf (message, "%s%s",
1362                             _find_prefix (prefix_name), value);
1363
1364     if (strlen (term) > NOTMUCH_TERM_MAX)
1365         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1366
1367     try {
1368         message->doc.remove_term (term);
1369         message->modified = TRUE;
1370     } catch (const Xapian::InvalidArgumentError) {
1371         /* We'll let the philosophers try to wrestle with the
1372          * question of whether failing to remove that which was not
1373          * there in the first place is failure. For us, we'll silently
1374          * consider it all good. */
1375     }
1376
1377     talloc_free (term);
1378
1379     _notmuch_message_invalidate_metadata (message, prefix_name);
1380
1381     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1382 }
1383
1384 notmuch_private_status_t
1385 _notmuch_message_has_term (notmuch_message_t *message,
1386                            const char *prefix_name,
1387                            const char *value,
1388                            notmuch_bool_t *result)
1389 {
1390     char *term;
1391     notmuch_bool_t out = FALSE;
1392     notmuch_private_status_t status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
1393
1394     if (value == NULL)
1395         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1396
1397     term = talloc_asprintf (message, "%s%s",
1398                             _find_prefix (prefix_name), value);
1399
1400     if (strlen (term) > NOTMUCH_TERM_MAX)
1401         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1402
1403     try {
1404         /* Look for the exact term */
1405         Xapian::TermIterator i = message->doc.termlist_begin ();
1406         i.skip_to (term);
1407         if (i != message->doc.termlist_end () &&
1408             !strcmp ((*i).c_str (), term))
1409             out = TRUE;
1410     } catch (Xapian::Error &error) {
1411         status = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
1412     }
1413     talloc_free (term);
1414
1415     *result = out;
1416     return status;
1417 }
1418
1419 notmuch_status_t
1420 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
1421 {
1422     notmuch_private_status_t private_status;
1423     notmuch_status_t status;
1424
1425     status = _notmuch_database_ensure_writable (message->notmuch);
1426     if (status)
1427         return status;
1428
1429     if (tag == NULL)
1430         return NOTMUCH_STATUS_NULL_POINTER;
1431
1432     if (strlen (tag) > NOTMUCH_TAG_MAX)
1433         return NOTMUCH_STATUS_TAG_TOO_LONG;
1434
1435     private_status = _notmuch_message_add_term (message, "tag", tag);
1436     if (private_status) {
1437         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
1438                         private_status);
1439     }
1440
1441     if (! message->frozen)
1442         _notmuch_message_sync (message);
1443
1444     return NOTMUCH_STATUS_SUCCESS;
1445 }
1446
1447 notmuch_status_t
1448 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1449 {
1450     notmuch_private_status_t private_status;
1451     notmuch_status_t status;
1452
1453     status = _notmuch_database_ensure_writable (message->notmuch);
1454     if (status)
1455         return status;
1456
1457     if (tag == NULL)
1458         return NOTMUCH_STATUS_NULL_POINTER;
1459
1460     if (strlen (tag) > NOTMUCH_TAG_MAX)
1461         return NOTMUCH_STATUS_TAG_TOO_LONG;
1462
1463     private_status = _notmuch_message_remove_term (message, "tag", tag);
1464     if (private_status) {
1465         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1466                         private_status);
1467     }
1468
1469     if (! message->frozen)
1470         _notmuch_message_sync (message);
1471
1472     return NOTMUCH_STATUS_SUCCESS;
1473 }
1474
1475 /* Is the given filename within a maildir directory?
1476  *
1477  * Specifically, is the final directory component of 'filename' either
1478  * "cur" or "new". If so, return a pointer to that final directory
1479  * component within 'filename'. If not, return NULL.
1480  *
1481  * A non-NULL return value is guaranteed to be a valid string pointer
1482  * pointing to the characters "new/" or "cur/", (but not
1483  * NUL-terminated).
1484  */
1485 static const char *
1486 _filename_is_in_maildir (const char *filename)
1487 {
1488     const char *slash, *dir = NULL;
1489
1490     /* Find the last '/' separating directory from filename. */
1491     slash = strrchr (filename, '/');
1492     if (slash == NULL)
1493         return NULL;
1494
1495     /* Jump back 4 characters to where the previous '/' will be if the
1496      * directory is named "cur" or "new". */
1497     if (slash - filename < 4)
1498         return NULL;
1499
1500     slash -= 4;
1501
1502     if (*slash != '/')
1503         return NULL;
1504
1505     dir = slash + 1;
1506
1507     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1508         STRNCMP_LITERAL (dir, "new/") == 0)
1509     {
1510         return dir;
1511     }
1512
1513     return NULL;
1514 }
1515
1516 notmuch_status_t
1517 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1518 {
1519     const char *flags;
1520     notmuch_status_t status;
1521     notmuch_filenames_t *filenames;
1522     const char *filename, *dir;
1523     char *combined_flags = talloc_strdup (message, "");
1524     unsigned i;
1525     int seen_maildir_info = 0;
1526
1527     for (filenames = notmuch_message_get_filenames (message);
1528          notmuch_filenames_valid (filenames);
1529          notmuch_filenames_move_to_next (filenames))
1530     {
1531         filename = notmuch_filenames_get (filenames);
1532         dir = _filename_is_in_maildir (filename);
1533
1534         if (! dir)
1535             continue;
1536
1537         flags = strstr (filename, ":2,");
1538         if (flags) {
1539             seen_maildir_info = 1;
1540             flags += 3;
1541             combined_flags = talloc_strdup_append (combined_flags, flags);
1542         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1543             /* Messages are delivered to new/ with no "info" part, but
1544              * they effectively have default maildir flags.  According
1545              * to the spec, we should ignore the info part for
1546              * messages in new/, but some MUAs (mutt) can set maildir
1547              * flags on messages in new/, so we're liberal in what we
1548              * accept. */
1549             seen_maildir_info = 1;
1550         }
1551     }
1552
1553     /* If none of the filenames have any maildir info field (not even
1554      * an empty info with no flags set) then there's no information to
1555      * go on, so do nothing. */
1556     if (! seen_maildir_info)
1557         return NOTMUCH_STATUS_SUCCESS;
1558
1559     status = notmuch_message_freeze (message);
1560     if (status)
1561         return status;
1562
1563     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
1564         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
1565             ^
1566             flag2tag[i].inverse)
1567         {
1568             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1569         } else {
1570             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1571         }
1572         if (status)
1573             return status;
1574     }
1575     status = notmuch_message_thaw (message);
1576
1577     talloc_free (combined_flags);
1578
1579     return status;
1580 }
1581
1582 /* From the set of tags on 'message' and the flag2tag table, compute a
1583  * set of maildir-flag actions to be taken, (flags that should be
1584  * either set or cleared).
1585  *
1586  * The result is returned as two talloced strings: to_set, and to_clear
1587  */
1588 static void
1589 _get_maildir_flag_actions (notmuch_message_t *message,
1590                            char **to_set_ret,
1591                            char **to_clear_ret)
1592 {
1593     char *to_set, *to_clear;
1594     notmuch_tags_t *tags;
1595     const char *tag;
1596     unsigned i;
1597
1598     to_set = talloc_strdup (message, "");
1599     to_clear = talloc_strdup (message, "");
1600
1601     /* First, find flags for all set tags. */
1602     for (tags = notmuch_message_get_tags (message);
1603          notmuch_tags_valid (tags);
1604          notmuch_tags_move_to_next (tags))
1605     {
1606         tag = notmuch_tags_get (tags);
1607
1608         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1609             if (strcmp (tag, flag2tag[i].tag) == 0) {
1610                 if (flag2tag[i].inverse)
1611                     to_clear = talloc_asprintf_append (to_clear,
1612                                                        "%c",
1613                                                        flag2tag[i].flag);
1614                 else
1615                     to_set = talloc_asprintf_append (to_set,
1616                                                      "%c",
1617                                                      flag2tag[i].flag);
1618             }
1619         }
1620     }
1621
1622     /* Then, find the flags for all tags not present. */
1623     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1624         if (flag2tag[i].inverse) {
1625             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1626                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1627         } else {
1628             if (strchr (to_set, flag2tag[i].flag) == NULL)
1629                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1630         }
1631     }
1632
1633     *to_set_ret = to_set;
1634     *to_clear_ret = to_clear;
1635 }
1636
1637 /* Given 'filename' and a set of maildir flags to set and to clear,
1638  * compute the new maildir filename.
1639  *
1640  * If the existing filename is in the directory "new", the new
1641  * filename will be in the directory "cur", except for the case when
1642  * no flags are changed and the existing filename does not contain
1643  * maildir info (starting with ",2:").
1644  *
1645  * After a sequence of ":2," in the filename, any subsequent
1646  * single-character flags will be added or removed according to the
1647  * characters in flags_to_set and flags_to_clear. Any existing flags
1648  * not mentioned in either string will remain. The final list of flags
1649  * will be in ASCII order.
1650  *
1651  * If the original flags seem invalid, (repeated characters or
1652  * non-ASCII ordering of flags), this function will return NULL
1653  * (meaning that renaming would not be safe and should not occur).
1654  */
1655 static char*
1656 _new_maildir_filename (void *ctx,
1657                        const char *filename,
1658                        const char *flags_to_set,
1659                        const char *flags_to_clear)
1660 {
1661     const char *info, *flags;
1662     unsigned int flag, last_flag;
1663     char *filename_new, *dir;
1664     char flag_map[128];
1665     int flags_in_map = 0;
1666     notmuch_bool_t flags_changed = FALSE;
1667     unsigned int i;
1668     char *s;
1669
1670     memset (flag_map, 0, sizeof (flag_map));
1671
1672     info = strstr (filename, ":2,");
1673
1674     if (info == NULL) {
1675         info = filename + strlen(filename);
1676     } else {
1677         /* Loop through existing flags in filename. */
1678         for (flags = info + 3, last_flag = 0;
1679              *flags;
1680              last_flag = flag, flags++)
1681         {
1682             flag = *flags;
1683
1684             /* Original flags not in ASCII order. Abort. */
1685             if (flag < last_flag)
1686                 return NULL;
1687
1688             /* Non-ASCII flag. Abort. */
1689             if (flag > sizeof(flag_map) - 1)
1690                 return NULL;
1691
1692             /* Repeated flag value. Abort. */
1693             if (flag_map[flag])
1694                 return NULL;
1695
1696             flag_map[flag] = 1;
1697             flags_in_map++;
1698         }
1699     }
1700
1701     /* Then set and clear our flags from tags. */
1702     for (flags = flags_to_set; *flags; flags++) {
1703         flag = *flags;
1704         if (flag_map[flag] == 0) {
1705             flag_map[flag] = 1;
1706             flags_in_map++;
1707             flags_changed = TRUE;
1708         }
1709     }
1710
1711     for (flags = flags_to_clear; *flags; flags++) {
1712         flag = *flags;
1713         if (flag_map[flag]) {
1714             flag_map[flag] = 0;
1715             flags_in_map--;
1716             flags_changed = TRUE;
1717         }
1718     }
1719
1720     /* Messages in new/ without maildir info can be kept in new/ if no
1721      * flags have changed. */
1722     dir = (char *) _filename_is_in_maildir (filename);
1723     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && !*info && !flags_changed)
1724         return talloc_strdup (ctx, filename);
1725
1726     filename_new = (char *) talloc_size (ctx,
1727                                          info - filename +
1728                                          strlen (":2,") + flags_in_map + 1);
1729     if (unlikely (filename_new == NULL))
1730         return NULL;
1731
1732     strncpy (filename_new, filename, info - filename);
1733     filename_new[info - filename] = '\0';
1734
1735     strcat (filename_new, ":2,");
1736
1737     s = filename_new + strlen (filename_new);
1738     for (i = 0; i < sizeof (flag_map); i++)
1739     {
1740         if (flag_map[i]) {
1741             *s = i;
1742             s++;
1743         }
1744     }
1745     *s = '\0';
1746
1747     /* If message is in new/ move it under cur/. */
1748     dir = (char *) _filename_is_in_maildir (filename_new);
1749     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1750         memcpy (dir, "cur/", 4);
1751
1752     return filename_new;
1753 }
1754
1755 notmuch_status_t
1756 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1757 {
1758     notmuch_filenames_t *filenames;
1759     const char *filename;
1760     char *filename_new;
1761     char *to_set, *to_clear;
1762     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1763
1764     _get_maildir_flag_actions (message, &to_set, &to_clear);
1765
1766     for (filenames = notmuch_message_get_filenames (message);
1767          notmuch_filenames_valid (filenames);
1768          notmuch_filenames_move_to_next (filenames))
1769     {
1770         filename = notmuch_filenames_get (filenames);
1771
1772         if (! _filename_is_in_maildir (filename))
1773             continue;
1774
1775         filename_new = _new_maildir_filename (message, filename,
1776                                               to_set, to_clear);
1777         if (filename_new == NULL)
1778             continue;
1779
1780         if (strcmp (filename, filename_new)) {
1781             int err;
1782             notmuch_status_t new_status;
1783
1784             err = rename (filename, filename_new);
1785             if (err)
1786                 continue;
1787
1788             new_status = _notmuch_message_remove_filename (message,
1789                                                            filename);
1790             /* Hold on to only the first error. */
1791             if (! status && new_status
1792                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
1793                 status = new_status;
1794                 continue;
1795             }
1796
1797             new_status = _notmuch_message_add_filename (message,
1798                                                         filename_new);
1799             /* Hold on to only the first error. */
1800             if (! status && new_status) {
1801                 status = new_status;
1802                 continue;
1803             }
1804
1805             _notmuch_message_sync (message);
1806         }
1807
1808         talloc_free (filename_new);
1809     }
1810
1811     talloc_free (to_set);
1812     talloc_free (to_clear);
1813
1814     return status;
1815 }
1816
1817 notmuch_status_t
1818 notmuch_message_remove_all_tags (notmuch_message_t *message)
1819 {
1820     notmuch_private_status_t private_status;
1821     notmuch_status_t status;
1822     notmuch_tags_t *tags;
1823     const char *tag;
1824
1825     status = _notmuch_database_ensure_writable (message->notmuch);
1826     if (status)
1827         return status;
1828
1829     for (tags = notmuch_message_get_tags (message);
1830          notmuch_tags_valid (tags);
1831          notmuch_tags_move_to_next (tags))
1832     {
1833         tag = notmuch_tags_get (tags);
1834
1835         private_status = _notmuch_message_remove_term (message, "tag", tag);
1836         if (private_status) {
1837             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1838                             private_status);
1839         }
1840     }
1841
1842     if (! message->frozen)
1843         _notmuch_message_sync (message);
1844
1845     talloc_free (tags);
1846     return NOTMUCH_STATUS_SUCCESS;
1847 }
1848
1849 notmuch_status_t
1850 notmuch_message_freeze (notmuch_message_t *message)
1851 {
1852     notmuch_status_t status;
1853
1854     status = _notmuch_database_ensure_writable (message->notmuch);
1855     if (status)
1856         return status;
1857
1858     message->frozen++;
1859
1860     return NOTMUCH_STATUS_SUCCESS;
1861 }
1862
1863 notmuch_status_t
1864 notmuch_message_thaw (notmuch_message_t *message)
1865 {
1866     notmuch_status_t status;
1867
1868     status = _notmuch_database_ensure_writable (message->notmuch);
1869     if (status)
1870         return status;
1871
1872     if (message->frozen > 0) {
1873         message->frozen--;
1874         if (message->frozen == 0)
1875             _notmuch_message_sync (message);
1876         return NOTMUCH_STATUS_SUCCESS;
1877     } else {
1878         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1879     }
1880 }
1881
1882 void
1883 notmuch_message_destroy (notmuch_message_t *message)
1884 {
1885     talloc_free (message);
1886 }
1887
1888 notmuch_database_t *
1889 _notmuch_message_database (notmuch_message_t *message)
1890 {
1891     return message->notmuch;
1892 }
1893
1894 static void
1895 _notmuch_message_ensure_property_map (notmuch_message_t *message)
1896 {
1897     notmuch_string_node_t *node;
1898
1899     if (message->property_map)
1900         return;
1901
1902     _notmuch_message_ensure_metadata (message, message->property_term_list);
1903
1904     message->property_map = _notmuch_string_map_create (message);
1905
1906     for (node = message->property_term_list->head; node; node = node->next) {
1907         const char *key;
1908         char *value;
1909
1910         value = strchr(node->string, '=');
1911         if (!value)
1912             INTERNAL_ERROR ("malformed property term");
1913
1914         *value = '\0';
1915         value++;
1916         key = node->string;
1917
1918         _notmuch_string_map_append (message->property_map, key, value);
1919
1920     }
1921
1922     talloc_free (message->property_term_list);
1923     message->property_term_list = NULL;
1924 }
1925
1926 notmuch_string_map_t *
1927 _notmuch_message_property_map (notmuch_message_t *message)
1928 {
1929     _notmuch_message_ensure_property_map (message);
1930
1931     return message->property_map;
1932 }
1933
1934 notmuch_bool_t
1935 _notmuch_message_frozen (notmuch_message_t *message)
1936 {
1937     return message->frozen;
1938 }
1939
1940 notmuch_status_t
1941 notmuch_message_reindex (notmuch_message_t *message,
1942                          notmuch_param_t unused (*indexopts))
1943 {
1944     notmuch_database_t *notmuch = NULL;
1945     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1946     notmuch_private_status_t private_status;
1947     notmuch_filenames_t *orig_filenames = NULL;
1948     const char *orig_thread_id = NULL;
1949     notmuch_message_file_t *message_file = NULL;
1950
1951     int found = 0;
1952
1953     if (message == NULL)
1954         return NOTMUCH_STATUS_NULL_POINTER;
1955
1956     /* Save in case we need to delete message */
1957     orig_thread_id = notmuch_message_get_thread_id (message);
1958     if (!orig_thread_id) {
1959         /* XXX TODO: make up new error return? */
1960         INTERNAL_ERROR ("message without thread-id");
1961     }
1962
1963     /* strdup it because the metadata may be invalidated */
1964     orig_thread_id = talloc_strdup (message, orig_thread_id);
1965
1966     notmuch = _notmuch_message_database (message);
1967
1968     ret = _notmuch_database_ensure_writable (notmuch);
1969     if (ret)
1970         return ret;
1971
1972     orig_filenames = notmuch_message_get_filenames (message);
1973
1974     private_status = _notmuch_message_remove_indexed_terms (message);
1975     if (private_status) {
1976         ret = COERCE_STATUS(private_status, "error removing terms");
1977         goto DONE;
1978     }
1979
1980     /* re-add the filenames with the associated indexopts */
1981     for (; notmuch_filenames_valid (orig_filenames);
1982          notmuch_filenames_move_to_next (orig_filenames)) {
1983
1984         const char *date;
1985         const char *from, *to, *subject;
1986         char *message_id = NULL;
1987         const char *thread_id = NULL;
1988
1989         const char *filename = notmuch_filenames_get (orig_filenames);
1990
1991         message_file = _notmuch_message_file_open (notmuch, filename);
1992         if (message_file == NULL)
1993             continue;
1994
1995         ret = _notmuch_message_file_get_headers (message_file,
1996                                                  &from, &subject, &to, &date,
1997                                                  &message_id);
1998         if (ret)
1999             goto DONE;
2000
2001         /* XXX TODO: deal with changing message id? */
2002
2003         _notmuch_message_add_filename (message, filename);
2004
2005         ret = _notmuch_database_link_message_to_parents (notmuch, message,
2006                                                          message_file,
2007                                                          &thread_id);
2008         if (ret)
2009             goto DONE;
2010
2011         if (thread_id == NULL)
2012             thread_id = orig_thread_id;
2013
2014         _notmuch_message_add_term (message, "thread", thread_id);
2015         _notmuch_message_set_header_values (message, date, from, subject);
2016
2017         ret = _notmuch_message_index_file (message, message_file);
2018
2019         if (ret == NOTMUCH_STATUS_FILE_ERROR)
2020             continue;
2021         if (ret)
2022             goto DONE;
2023
2024         found++;
2025         _notmuch_message_file_close (message_file);
2026         message_file = NULL;
2027     }
2028     if (found == 0) {
2029         /* put back thread id to help cleanup */
2030         _notmuch_message_add_term (message, "thread", orig_thread_id);
2031         ret = _notmuch_message_delete (message);
2032     } else {
2033         _notmuch_message_sync (message);
2034     }
2035
2036  DONE:
2037     if (message_file)
2038         _notmuch_message_file_close (message_file);
2039
2040     /* XXX TODO destroy orig_filenames? */
2041     return ret;
2042 }