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