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