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