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