]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
lib: Save and restore term position in message while indexing.
[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 http://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
24 #include <stdint.h>
25
26 #include <gmime/gmime.h>
27
28 struct _notmuch_message {
29     notmuch_database_t *notmuch;
30     Xapian::docid doc_id;
31     int frozen;
32     char *message_id;
33     char *thread_id;
34     char *in_reply_to;
35     notmuch_filename_list_t *filename_list;
36     char *author;
37     notmuch_message_file_t *message_file;
38     notmuch_message_list_t *replies;
39     unsigned long flags;
40
41     Xapian::Document doc;
42     Xapian::termcount termpos;
43 };
44
45 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
46
47 struct maildir_flag_tag {
48     char flag;
49     const char *tag;
50     bool inverse;
51 };
52
53 /* ASCII ordered table of Maildir flags and associated tags */
54 static struct maildir_flag_tag flag2tag[] = {
55     { 'D', "draft",   false},
56     { 'F', "flagged", false},
57     { 'P', "passed",  false},
58     { 'R', "replied", false},
59     { 'S', "unread",  true }
60 };
61
62 /* We end up having to call the destructor explicitly because we had
63  * to use "placement new" in order to initialize C++ objects within a
64  * block that we allocated with talloc. So C++ is making talloc
65  * slightly less simple to use, (we wouldn't need
66  * talloc_set_destructor at all otherwise).
67  */
68 static int
69 _notmuch_message_destructor (notmuch_message_t *message)
70 {
71     message->doc.~Document ();
72
73     return 0;
74 }
75
76 static notmuch_message_t *
77 _notmuch_message_create_for_document (const void *talloc_owner,
78                                       notmuch_database_t *notmuch,
79                                       unsigned int doc_id,
80                                       Xapian::Document doc,
81                                       notmuch_private_status_t *status)
82 {
83     notmuch_message_t *message;
84
85     if (status)
86         *status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
87
88     message = talloc (talloc_owner, notmuch_message_t);
89     if (unlikely (message == NULL)) {
90         if (status)
91             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
92         return NULL;
93     }
94
95     message->notmuch = notmuch;
96     message->doc_id = doc_id;
97
98     message->frozen = 0;
99     message->flags = 0;
100
101     /* Each of these will be lazily created as needed. */
102     message->message_id = NULL;
103     message->thread_id = NULL;
104     message->in_reply_to = NULL;
105     message->filename_list = NULL;
106     message->message_file = NULL;
107     message->author = NULL;
108
109     message->replies = _notmuch_message_list_create (message);
110     if (unlikely (message->replies == NULL)) {
111         if (status)
112             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
113         return NULL;
114     }
115
116     /* This is C++'s creepy "placement new", which is really just an
117      * ugly way to call a constructor for a pre-allocated object. So
118      * it's really not an error to not be checking for OUT_OF_MEMORY
119      * here, since this "new" isn't actually allocating memory. This
120      * is language-design comedy of the wrong kind. */
121
122     new (&message->doc) Xapian::Document;
123
124     talloc_set_destructor (message, _notmuch_message_destructor);
125
126     message->doc = doc;
127     message->termpos = 0;
128
129     return message;
130 }
131
132 /* Create a new notmuch_message_t object for an existing document in
133  * the database.
134  *
135  * Here, 'talloc owner' is an optional talloc context to which the new
136  * message will belong. This allows for the caller to not bother
137  * calling notmuch_message_destroy on the message, and know that all
138  * memory will be reclaimed when 'talloc_owner' is freed. The caller
139  * still can call notmuch_message_destroy when finished with the
140  * message if desired.
141  *
142  * The 'talloc_owner' argument can also be NULL, in which case the
143  * caller *is* responsible for calling notmuch_message_destroy.
144  *
145  * If no document exists in the database with document ID of 'doc_id'
146  * then this function returns NULL and optionally sets *status to
147  * NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND.
148  *
149  * This function can also fail to due lack of available memory,
150  * returning NULL and optionally setting *status to
151  * NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY.
152  *
153  * The caller can pass NULL for status if uninterested in
154  * distinguishing these two cases.
155  */
156 notmuch_message_t *
157 _notmuch_message_create (const void *talloc_owner,
158                          notmuch_database_t *notmuch,
159                          unsigned int doc_id,
160                          notmuch_private_status_t *status)
161 {
162     Xapian::Document doc;
163
164     try {
165         doc = notmuch->xapian_db->get_document (doc_id);
166     } catch (const Xapian::DocNotFoundError &error) {
167         if (status)
168             *status = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
169         return NULL;
170     }
171
172     return _notmuch_message_create_for_document (talloc_owner, notmuch,
173                                                  doc_id, doc, status);
174 }
175
176 /* Create a new notmuch_message_t object for a specific message ID,
177  * (which may or may not already exist in the database).
178  *
179  * The 'notmuch' database will be the talloc owner of the returned
180  * message.
181  *
182  * This function returns a valid notmuch_message_t whether or not
183  * there is already a document in the database with the given message
184  * ID. These two cases can be distinguished by the value of *status:
185  *
186  *
187  *   NOTMUCH_PRIVATE_STATUS_SUCCESS:
188  *
189  *     There is already a document with message ID 'message_id' in the
190  *     database. The returned message can be used to query/modify the
191  *     document.
192  *   NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND:
193  *
194  *     No document with 'message_id' exists in the database. The
195  *     returned message contains a newly created document (not yet
196  *     added to the database) and a document ID that is known not to
197  *     exist in the database. The caller can modify the message, and a
198  *     call to _notmuch_message_sync will add * the document to the
199  *     database.
200  *
201  * If an error occurs, this function will return NULL and *status
202  * will be set as appropriate. (The status pointer argument must
203  * not be NULL.)
204  */
205 notmuch_message_t *
206 _notmuch_message_create_for_message_id (notmuch_database_t *notmuch,
207                                         const char *message_id,
208                                         notmuch_private_status_t *status_ret)
209 {
210     notmuch_message_t *message;
211     Xapian::Document doc;
212     Xapian::WritableDatabase *db;
213     unsigned int doc_id;
214     char *term;
215
216     *status_ret = NOTMUCH_PRIVATE_STATUS_SUCCESS;
217
218     message = notmuch_database_find_message (notmuch, message_id);
219     if (message)
220         return talloc_steal (notmuch, message);
221
222     term = talloc_asprintf (NULL, "%s%s",
223                             _find_prefix ("id"), message_id);
224     if (term == NULL) {
225         *status_ret = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
226         return NULL;
227     }
228
229     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
230         INTERNAL_ERROR ("Failure to ensure database is writable.");
231
232     db = static_cast<Xapian::WritableDatabase *> (notmuch->xapian_db);
233     try {
234         doc.add_term (term, 0);
235         talloc_free (term);
236
237         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
238
239         doc_id = _notmuch_database_generate_doc_id (notmuch);
240     } catch (const Xapian::Error &error) {
241         fprintf (stderr, "A Xapian exception occurred creating message: %s\n",
242                  error.get_msg().c_str());
243         notmuch->exception_reported = TRUE;
244         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
245         return NULL;
246     }
247
248     message = _notmuch_message_create_for_document (notmuch, notmuch,
249                                                     doc_id, doc, status_ret);
250
251     /* We want to inform the caller that we had to create a new
252      * document. */
253     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
254         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
255
256     return message;
257 }
258
259 unsigned int
260 _notmuch_message_get_doc_id (notmuch_message_t *message)
261 {
262     return message->doc_id;
263 }
264
265 const char *
266 notmuch_message_get_message_id (notmuch_message_t *message)
267 {
268     Xapian::TermIterator i;
269
270     if (message->message_id)
271         return message->message_id;
272
273     i = message->doc.termlist_begin ();
274     i.skip_to (_find_prefix ("id"));
275
276     if (i == message->doc.termlist_end ())
277         INTERNAL_ERROR ("Message with document ID of %d has no message ID.\n",
278                         message->doc_id);
279
280     message->message_id = talloc_strdup (message, (*i).c_str () + 1);
281
282 #if DEBUG_DATABASE_SANITY
283     i++;
284
285     if (i != message->doc.termlist_end () &&
286         strncmp ((*i).c_str (), _find_prefix ("id"),
287                  strlen (_find_prefix ("id"))) == 0)
288     {
289         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate message IDs",
290                         message->doc_id);
291     }
292 #endif
293
294     return message->message_id;
295 }
296
297 static void
298 _notmuch_message_ensure_message_file (notmuch_message_t *message)
299 {
300     const char *filename;
301
302     if (message->message_file)
303         return;
304
305     filename = notmuch_message_get_filename (message);
306     if (unlikely (filename == NULL))
307         return;
308
309     message->message_file = _notmuch_message_file_open_ctx (message, filename);
310 }
311
312 const char *
313 notmuch_message_get_header (notmuch_message_t *message, const char *header)
314 {
315     _notmuch_message_ensure_message_file (message);
316     if (message->message_file == NULL)
317         return NULL;
318
319     return notmuch_message_file_get_header (message->message_file, header);
320 }
321
322 /* Return the message ID from the In-Reply-To header of 'message'.
323  *
324  * Returns an empty string ("") if 'message' has no In-Reply-To
325  * header.
326  *
327  * Returns NULL if any error occurs.
328  */
329 const char *
330 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
331 {
332     const char *prefix = _find_prefix ("replyto");
333     int prefix_len = strlen (prefix);
334     Xapian::TermIterator i;
335     std::string in_reply_to;
336
337     if (message->in_reply_to)
338         return message->in_reply_to;
339
340     i = message->doc.termlist_begin ();
341     i.skip_to (prefix);
342
343     if (i != message->doc.termlist_end ())
344         in_reply_to = *i;
345
346     /* It's perfectly valid for a message to have no In-Reply-To
347      * header. For these cases, we return an empty string. */
348     if (i == message->doc.termlist_end () ||
349         strncmp (in_reply_to.c_str (), prefix, prefix_len))
350     {
351         message->in_reply_to = talloc_strdup (message, "");
352         return message->in_reply_to;
353     }
354
355     message->in_reply_to = talloc_strdup (message,
356                                           in_reply_to.c_str () + prefix_len);
357
358 #if DEBUG_DATABASE_SANITY
359     i++;
360
361     in_reply_to = *i;
362
363     if (i != message->doc.termlist_end () &&
364         strncmp ((*i).c_str (), prefix, prefix_len) == 0)
365     {
366        INTERNAL_ERROR ("Message %s has duplicate In-Reply-To IDs: %s and %s\n",
367                         notmuch_message_get_message_id (message),
368                         message->in_reply_to,
369                         (*i).c_str () + prefix_len);
370     }
371 #endif
372
373     return message->in_reply_to;
374 }
375
376 const char *
377 notmuch_message_get_thread_id (notmuch_message_t *message)
378 {
379     const char *prefix = _find_prefix ("thread");
380     Xapian::TermIterator i;
381     std::string id;
382
383     /* This code is written with the assumption that "thread" has a
384      * single-character prefix. */
385     assert (strlen (prefix) == 1);
386
387     if (message->thread_id)
388         return message->thread_id;
389
390     i = message->doc.termlist_begin ();
391     i.skip_to (prefix);
392
393     if (i != message->doc.termlist_end ())
394         id = *i;
395
396     if (i == message->doc.termlist_end () || id[0] != *prefix)
397         INTERNAL_ERROR ("Message with document ID of %d has no thread ID.\n",
398                         message->doc_id);
399
400     message->thread_id = talloc_strdup (message, id.c_str () + 1);
401
402 #if DEBUG_DATABASE_SANITY
403     i++;
404     id = *i;
405
406     if (i != message->doc.termlist_end () && id[0] == *prefix)
407     {
408         INTERNAL_ERROR ("Message %s has duplicate thread IDs: %s and %s\n",
409                         notmuch_message_get_message_id (message),
410                         message->thread_id,
411                         id.c_str () + 1);
412     }
413 #endif
414
415     return message->thread_id;
416 }
417
418 void
419 _notmuch_message_add_reply (notmuch_message_t *message,
420                             notmuch_message_node_t *reply)
421 {
422     _notmuch_message_list_append (message->replies, reply);
423 }
424
425 notmuch_messages_t *
426 notmuch_message_get_replies (notmuch_message_t *message)
427 {
428     return _notmuch_messages_create (message->replies);
429 }
430
431 /* Add an additional 'filename' for 'message'.
432  *
433  * This change will not be reflected in the database until the next
434  * call to _notmuch_message_sync. */
435 notmuch_status_t
436 _notmuch_message_add_filename (notmuch_message_t *message,
437                                const char *filename)
438 {
439     const char *relative, *directory;
440     notmuch_status_t status;
441     void *local = talloc_new (message);
442     char *direntry;
443
444     if (filename == NULL)
445         INTERNAL_ERROR ("Message filename cannot be NULL.");
446
447     if (message->filename_list) {
448         _notmuch_filename_list_destroy (message->filename_list);
449         message->filename_list = NULL;
450     }
451
452     relative = _notmuch_database_relative_path (message->notmuch, filename);
453
454     status = _notmuch_database_split_path (local, relative, &directory, NULL);
455     if (status)
456         return status;
457
458     status = _notmuch_database_filename_to_direntry (local,
459                                                      message->notmuch,
460                                                      filename, &direntry);
461     if (status)
462         return status;
463
464     /* New file-direntry allows navigating to this message with
465      * notmuch_directory_get_child_files() . */
466     _notmuch_message_add_term (message, "file-direntry", direntry);
467
468     /* New terms allow user to search with folder: specification. */
469     _notmuch_message_gen_terms (message, "folder", directory);
470
471     talloc_free (local);
472
473     return NOTMUCH_STATUS_SUCCESS;
474 }
475
476 /* Remove a particular 'filename' from 'message'.
477  *
478  * This change will not be reflected in the database until the next
479  * call to _notmuch_message_sync.
480  *
481  * Note: This function does not remove a document from the database,
482  * even if the specified filename is the only filename for this
483  * message. For that functionality, see
484  * _notmuch_database_remove_message. */
485 notmuch_status_t
486 _notmuch_message_remove_filename (notmuch_message_t *message,
487                                   const char *filename)
488 {
489     const char *direntry_prefix = _find_prefix ("file-direntry");
490     int direntry_prefix_len = strlen (direntry_prefix);
491     const char *folder_prefix = _find_prefix ("folder");
492     int folder_prefix_len = strlen (folder_prefix);
493     void *local = talloc_new (message);
494     char *direntry;
495     notmuch_private_status_t private_status;
496     notmuch_status_t status;
497     Xapian::TermIterator i, last;
498
499     if (message->filename_list) {
500         _notmuch_filename_list_destroy (message->filename_list);
501         message->filename_list = NULL;
502     }
503
504     status = _notmuch_database_filename_to_direntry (local, message->notmuch,
505                                                      filename, &direntry);
506     if (status)
507         return status;
508
509     /* Unlink this file from its parent directory. */
510     private_status = _notmuch_message_remove_term (message,
511                                                    "file-direntry", direntry);
512     status = COERCE_STATUS (private_status,
513                             "Unexpected error from _notmuch_message_remove_term");
514
515     /* Re-synchronize "folder:" terms for this message. This requires
516      * first removing all "folder:" terms, then adding back terms for
517      * all remaining filenames of the message. */
518     while (1) {
519         i = message->doc.termlist_begin ();
520         i.skip_to (folder_prefix);
521
522         /* Terminate loop when no terms remain with desired prefix. */
523         if (i == message->doc.termlist_end () ||
524             strncmp ((*i).c_str (), folder_prefix, folder_prefix_len))
525         {
526             break;
527         }
528
529         try {
530             message->doc.remove_term ((*i));
531         } catch (const Xapian::InvalidArgumentError) {
532             /* Ignore failure to remove non-existent term. */
533         }
534     }
535
536     i = message->doc.termlist_begin ();
537     i.skip_to (direntry_prefix);
538
539     for (; i != message->doc.termlist_end (); i++) {
540         unsigned int directory_id;
541         const char *direntry, *directory;
542         char *colon;
543
544         /* Terminate loop at first term without desired prefix. */
545         if (strncmp ((*i).c_str (), direntry_prefix, direntry_prefix_len))
546             break;
547
548         direntry = (*i).c_str ();
549         direntry += direntry_prefix_len;
550
551         directory_id = strtol (direntry, &colon, 10);
552
553         if (colon == NULL || *colon != ':')
554             INTERNAL_ERROR ("malformed direntry");
555
556         directory = _notmuch_database_get_directory_path (local,
557                                                           message->notmuch,
558                                                           directory_id);
559         if (strlen (directory))
560             _notmuch_message_gen_terms (message, "folder", directory);
561     }
562
563     talloc_free (local);
564
565     return status;
566 }
567
568 char *
569 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
570 {
571     return talloc_strdup (message, message->doc.get_data ().c_str ());
572 }
573
574 void
575 _notmuch_message_clear_data (notmuch_message_t *message)
576 {
577     message->doc.set_data ("");
578 }
579
580 static void
581 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
582 {
583     const char *prefix = _find_prefix ("file-direntry");
584     int prefix_len = strlen (prefix);
585     Xapian::TermIterator i;
586
587     if (message->filename_list)
588         return;
589
590     message->filename_list = _notmuch_filename_list_create (message);
591
592     i = message->doc.termlist_begin ();
593     i.skip_to (prefix);
594
595     if (i == message->doc.termlist_end () ||
596         strncmp ((*i).c_str (), prefix, prefix_len))
597     {
598         /* A message document created by an old version of notmuch
599          * (prior to rename support) will have the filename in the
600          * data of the document rather than as a file-direntry term.
601          *
602          * It would be nice to do the upgrade of the document directly
603          * here, but the database is likely open in read-only mode. */
604         const char *data;
605
606         data = message->doc.get_data ().c_str ();
607
608         if (data == NULL)
609             INTERNAL_ERROR ("message with no filename");
610
611         _notmuch_filename_list_add_filename (message->filename_list, data);
612
613         return;
614     }
615
616     for (; i != message->doc.termlist_end (); i++) {
617         void *local = talloc_new (message);
618         const char *db_path, *directory, *basename, *filename;
619         char *colon, *direntry = NULL;
620         unsigned int directory_id;
621
622         /* Terminate loop at first term without desired prefix. */
623         if (strncmp ((*i).c_str (), prefix, prefix_len))
624             break;
625
626         direntry = talloc_strdup (local, (*i).c_str ());
627
628         direntry += prefix_len;
629
630         directory_id = strtol (direntry, &colon, 10);
631
632         if (colon == NULL || *colon != ':')
633             INTERNAL_ERROR ("malformed direntry");
634
635         basename = colon + 1;
636
637         *colon = '\0';
638
639         db_path = notmuch_database_get_path (message->notmuch);
640
641         directory = _notmuch_database_get_directory_path (local,
642                                                           message->notmuch,
643                                                           directory_id);
644
645         if (strlen (directory))
646             filename = talloc_asprintf (message, "%s/%s/%s",
647                                         db_path, directory, basename);
648         else
649             filename = talloc_asprintf (message, "%s/%s",
650                                         db_path, basename);
651
652         _notmuch_filename_list_add_filename (message->filename_list,
653                                              filename);
654
655         talloc_free (local);
656     }
657 }
658
659 const char *
660 notmuch_message_get_filename (notmuch_message_t *message)
661 {
662     _notmuch_message_ensure_filename_list (message);
663
664     if (message->filename_list == NULL)
665         return NULL;
666
667     if (message->filename_list->head == NULL ||
668         message->filename_list->head->filename == NULL)
669     {
670         INTERNAL_ERROR ("message with no filename");
671     }
672
673     return message->filename_list->head->filename;
674 }
675
676 notmuch_filenames_t *
677 notmuch_message_get_filenames (notmuch_message_t *message)
678 {
679     _notmuch_message_ensure_filename_list (message);
680
681     return _notmuch_filenames_create (message, message->filename_list);
682 }
683
684 notmuch_bool_t
685 notmuch_message_get_flag (notmuch_message_t *message,
686                           notmuch_message_flag_t flag)
687 {
688     return message->flags & (1 << flag);
689 }
690
691 void
692 notmuch_message_set_flag (notmuch_message_t *message,
693                           notmuch_message_flag_t flag, notmuch_bool_t enable)
694 {
695     if (enable)
696         message->flags |= (1 << flag);
697     else
698         message->flags &= ~(1 << flag);
699 }
700
701 time_t
702 notmuch_message_get_date (notmuch_message_t *message)
703 {
704     std::string value;
705
706     try {
707         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
708     } catch (Xapian::Error &error) {
709         INTERNAL_ERROR ("Failed to read timestamp value from document.");
710         return 0;
711     }
712
713     return Xapian::sortable_unserialise (value);
714 }
715
716 notmuch_tags_t *
717 notmuch_message_get_tags (notmuch_message_t *message)
718 {
719     Xapian::TermIterator i, end;
720     i = message->doc.termlist_begin();
721     end = message->doc.termlist_end();
722     return _notmuch_convert_tags(message, i, end);
723 }
724
725 const char *
726 notmuch_message_get_author (notmuch_message_t *message)
727 {
728     return message->author;
729 }
730
731 void
732 notmuch_message_set_author (notmuch_message_t *message,
733                             const char *author)
734 {
735     if (message->author)
736         talloc_free(message->author);
737     message->author = talloc_strdup(message, author);
738     return;
739 }
740
741 void
742 _notmuch_message_set_date (notmuch_message_t *message,
743                            const char *date)
744 {
745     time_t time_value;
746
747     /* GMime really doesn't want to see a NULL date, so protect its
748      * sensibilities. */
749     if (date == NULL || *date == '\0')
750         time_value = 0;
751     else
752         time_value = g_mime_utils_header_decode_date (date, NULL);
753
754     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
755                             Xapian::sortable_serialise (time_value));
756 }
757
758 /* Synchronize changes made to message->doc out into the database. */
759 void
760 _notmuch_message_sync (notmuch_message_t *message)
761 {
762     Xapian::WritableDatabase *db;
763
764     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
765         return;
766
767     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
768     db->replace_document (message->doc_id, message->doc);
769 }
770
771 /* Ensure that 'message' is not holding any file object open. Future
772  * calls to various functions will still automatically open the
773  * message file as needed.
774  */
775 void
776 _notmuch_message_close (notmuch_message_t *message)
777 {
778     if (message->message_file) {
779         notmuch_message_file_close (message->message_file);
780         message->message_file = NULL;
781     }
782 }
783
784 /* Add a name:value term to 'message', (the actual term will be
785  * encoded by prefixing the value with a short prefix). See
786  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
787  * names to prefix values.
788  *
789  * This change will not be reflected in the database until the next
790  * call to _notmuch_message_sync. */
791 notmuch_private_status_t
792 _notmuch_message_add_term (notmuch_message_t *message,
793                            const char *prefix_name,
794                            const char *value)
795 {
796
797     char *term;
798
799     if (value == NULL)
800         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
801
802     term = talloc_asprintf (message, "%s%s",
803                             _find_prefix (prefix_name), value);
804
805     if (strlen (term) > NOTMUCH_TERM_MAX)
806         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
807
808     message->doc.add_term (term, 0);
809
810     talloc_free (term);
811
812     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
813 }
814
815 /* Parse 'text' and add a term to 'message' for each parsed word. Each
816  * term will be added both prefixed (if prefix_name is not NULL) and
817  * also unprefixed). */
818 notmuch_private_status_t
819 _notmuch_message_gen_terms (notmuch_message_t *message,
820                             const char *prefix_name,
821                             const char *text)
822 {
823     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
824
825     if (text == NULL)
826         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
827
828     term_gen->set_document (message->doc);
829     term_gen->set_termpos (message->termpos);
830
831     if (prefix_name) {
832         const char *prefix = _find_prefix (prefix_name);
833
834         term_gen->index_text (text, 1, prefix);
835         message->termpos = term_gen->get_termpos ();
836     }
837
838     term_gen->index_text (text);
839
840     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
841 }
842
843 /* Remove a name:value term from 'message', (the actual term will be
844  * encoded by prefixing the value with a short prefix). See
845  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
846  * names to prefix values.
847  *
848  * This change will not be reflected in the database until the next
849  * call to _notmuch_message_sync. */
850 notmuch_private_status_t
851 _notmuch_message_remove_term (notmuch_message_t *message,
852                               const char *prefix_name,
853                               const char *value)
854 {
855     char *term;
856
857     if (value == NULL)
858         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
859
860     term = talloc_asprintf (message, "%s%s",
861                             _find_prefix (prefix_name), value);
862
863     if (strlen (term) > NOTMUCH_TERM_MAX)
864         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
865
866     try {
867         message->doc.remove_term (term);
868     } catch (const Xapian::InvalidArgumentError) {
869         /* We'll let the philosopher's try to wrestle with the
870          * question of whether failing to remove that which was not
871          * there in the first place is failure. For us, we'll silently
872          * consider it all good. */
873     }
874
875     talloc_free (term);
876
877     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
878 }
879
880 notmuch_status_t
881 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
882 {
883     notmuch_private_status_t private_status;
884     notmuch_status_t status;
885
886     status = _notmuch_database_ensure_writable (message->notmuch);
887     if (status)
888         return status;
889
890     if (tag == NULL)
891         return NOTMUCH_STATUS_NULL_POINTER;
892
893     if (strlen (tag) > NOTMUCH_TAG_MAX)
894         return NOTMUCH_STATUS_TAG_TOO_LONG;
895
896     private_status = _notmuch_message_add_term (message, "tag", tag);
897     if (private_status) {
898         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
899                         private_status);
900     }
901
902     if (! message->frozen)
903         _notmuch_message_sync (message);
904
905     return NOTMUCH_STATUS_SUCCESS;
906 }
907
908 notmuch_status_t
909 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
910 {
911     notmuch_private_status_t private_status;
912     notmuch_status_t status;
913
914     status = _notmuch_database_ensure_writable (message->notmuch);
915     if (status)
916         return status;
917
918     if (tag == NULL)
919         return NOTMUCH_STATUS_NULL_POINTER;
920
921     if (strlen (tag) > NOTMUCH_TAG_MAX)
922         return NOTMUCH_STATUS_TAG_TOO_LONG;
923
924     private_status = _notmuch_message_remove_term (message, "tag", tag);
925     if (private_status) {
926         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
927                         private_status);
928     }
929
930     if (! message->frozen)
931         _notmuch_message_sync (message);
932
933     return NOTMUCH_STATUS_SUCCESS;
934 }
935
936 notmuch_status_t
937 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
938 {
939     const char *flags;
940     notmuch_status_t status;
941     notmuch_filenames_t *filenames;
942     const char *filename;
943     char *combined_flags = talloc_strdup (message, "");
944     unsigned i;
945     int seen_maildir_info = 0;
946
947     for (filenames = notmuch_message_get_filenames (message);
948          notmuch_filenames_valid (filenames);
949          notmuch_filenames_move_to_next (filenames))
950     {
951         filename = notmuch_filenames_get (filenames);
952
953         flags = strstr (filename, ":2,");
954         if (! flags)
955             continue;
956
957         seen_maildir_info = 1;
958         flags += 3;
959
960         combined_flags = talloc_strdup_append (combined_flags, flags);
961     }
962
963     /* If none of the filenames have any maildir info field (not even
964      * an empty info with no flags set) then there's no information to
965      * go on, so do nothing. */
966     if (! seen_maildir_info)
967         return NOTMUCH_STATUS_SUCCESS;
968
969     status = notmuch_message_freeze (message);
970     if (status)
971         return status;
972
973     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
974         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
975             ^ 
976             flag2tag[i].inverse)
977         {
978             status = notmuch_message_add_tag (message, flag2tag[i].tag);
979         } else {
980             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
981         }
982         if (status)
983             return status;
984     }
985     status = notmuch_message_thaw (message);
986
987     talloc_free (combined_flags);
988
989     return status;
990 }
991
992 /* Is the given filename within a maildir directory?
993  *
994  * Specifically, is the final directory component of 'filename' either
995  * "cur" or "new". If so, return a pointer to that final directory
996  * component within 'filename'. If not, return NULL.
997  *
998  * A non-NULL return value is guaranteed to be a valid string pointer
999  * pointing to the characters "new/" or "cur/", (but not
1000  * NUL-terminated).
1001  */
1002 static const char *
1003 _filename_is_in_maildir (const char *filename)
1004 {
1005     const char *slash, *dir = NULL;
1006
1007     /* Find the last '/' separating directory from filename. */
1008     slash = strrchr (filename, '/');
1009     if (slash == NULL)
1010         return NULL;
1011
1012     /* Jump back 4 characters to where the previous '/' will be if the
1013      * directory is named "cur" or "new". */
1014     if (slash - filename < 4)
1015         return NULL;
1016
1017     slash -= 4;
1018
1019     if (*slash != '/')
1020         return NULL;
1021
1022     dir = slash + 1;
1023
1024     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1025         STRNCMP_LITERAL (dir, "new/") == 0)
1026     {
1027         return dir;
1028     }
1029
1030     return NULL;
1031 }
1032
1033 /* From the set of tags on 'message' and the flag2tag table, compute a
1034  * set of maildir-flag actions to be taken, (flags that should be
1035  * either set or cleared).
1036  *
1037  * The result is returned as two talloced strings: to_set, and to_clear
1038  */
1039 static void
1040 _get_maildir_flag_actions (notmuch_message_t *message,
1041                            char **to_set_ret,
1042                            char **to_clear_ret)
1043 {
1044     char *to_set, *to_clear;
1045     notmuch_tags_t *tags;
1046     const char *tag;
1047     unsigned i;
1048
1049     to_set = talloc_strdup (message, "");
1050     to_clear = talloc_strdup (message, "");
1051
1052     /* First, find flags for all set tags. */
1053     for (tags = notmuch_message_get_tags (message);
1054          notmuch_tags_valid (tags);
1055          notmuch_tags_move_to_next (tags))
1056     {
1057         tag = notmuch_tags_get (tags);
1058
1059         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1060             if (strcmp (tag, flag2tag[i].tag) == 0) {
1061                 if (flag2tag[i].inverse)
1062                     to_clear = talloc_asprintf_append (to_clear,
1063                                                        "%c",
1064                                                        flag2tag[i].flag);
1065                 else
1066                     to_set = talloc_asprintf_append (to_set,
1067                                                      "%c",
1068                                                      flag2tag[i].flag);
1069             }
1070         }
1071     }
1072
1073     /* Then, find the flags for all tags not present. */
1074     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1075         if (flag2tag[i].inverse) {
1076             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1077                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1078         } else {
1079             if (strchr (to_set, flag2tag[i].flag) == NULL)
1080                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1081         }
1082     }
1083
1084     *to_set_ret = to_set;
1085     *to_clear_ret = to_clear;
1086 }
1087
1088 /* Given 'filename' and a set of maildir flags to set and to clear,
1089  * compute the new maildir filename.
1090  *
1091  * If the existing filename is in the directory "new", the new
1092  * filename will be in the directory "cur".
1093  *
1094  * After a sequence of ":2," in the filename, any subsequent
1095  * single-character flags will be added or removed according to the
1096  * characters in flags_to_set and flags_to_clear. Any existing flags
1097  * not mentioned in either string will remain. The final list of flags
1098  * will be in ASCII order.
1099  *
1100  * If the original flags seem invalid, (repeated characters or
1101  * non-ASCII ordering of flags), this function will return NULL
1102  * (meaning that renaming would not be safe and should not occur).
1103  */
1104 static char*
1105 _new_maildir_filename (void *ctx,
1106                        const char *filename,
1107                        const char *flags_to_set,
1108                        const char *flags_to_clear)
1109 {
1110     const char *info, *flags;
1111     unsigned int flag, last_flag;
1112     char *filename_new, *dir;
1113     char flag_map[128];
1114     int flags_in_map = 0;
1115     unsigned int i;
1116     char *s;
1117
1118     memset (flag_map, 0, sizeof (flag_map));
1119
1120     info = strstr (filename, ":2,");
1121
1122     if (info == NULL) {
1123         info = filename + strlen(filename);
1124     } else {
1125         flags = info + 3;
1126
1127         /* Loop through existing flags in filename. */
1128         for (flags = info + 3, last_flag = 0;
1129              *flags;
1130              last_flag = flag, flags++)
1131         {
1132             flag = *flags;
1133
1134             /* Original flags not in ASCII order. Abort. */
1135             if (flag < last_flag)
1136                 return NULL;
1137
1138             /* Non-ASCII flag. Abort. */
1139             if (flag > sizeof(flag_map) - 1)
1140                 return NULL;
1141
1142             /* Repeated flag value. Abort. */
1143             if (flag_map[flag])
1144                 return NULL;
1145
1146             flag_map[flag] = 1;
1147             flags_in_map++;
1148         }
1149     }
1150
1151     /* Then set and clear our flags from tags. */
1152     for (flags = flags_to_set; *flags; flags++) {
1153         flag = *flags;
1154         if (flag_map[flag] == 0) {
1155             flag_map[flag] = 1;
1156             flags_in_map++;
1157         }
1158     }
1159
1160     for (flags = flags_to_clear; *flags; flags++) {
1161         flag = *flags;
1162         if (flag_map[flag]) {
1163             flag_map[flag] = 0;
1164             flags_in_map--;
1165         }
1166     }
1167
1168     filename_new = (char *) talloc_size (ctx,
1169                                          info - filename +
1170                                          strlen (":2,") + flags_in_map + 1);
1171     if (unlikely (filename_new == NULL))
1172         return NULL;
1173
1174     strncpy (filename_new, filename, info - filename);
1175     filename_new[info - filename] = '\0';
1176
1177     strcat (filename_new, ":2,");
1178
1179     s = filename_new + strlen (filename_new);
1180     for (i = 0; i < sizeof (flag_map); i++)
1181     {
1182         if (flag_map[i]) {
1183             *s = i;
1184             s++;
1185         }
1186     }
1187     *s = '\0';
1188
1189     /* If message is in new/ move it under cur/. */
1190     dir = (char *) _filename_is_in_maildir (filename_new);
1191     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1192         memcpy (dir, "cur/", 4);
1193
1194     return filename_new;
1195 }
1196
1197 notmuch_status_t
1198 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1199 {
1200     notmuch_filenames_t *filenames;
1201     const char *filename;
1202     char *filename_new;
1203     char *to_set, *to_clear;
1204     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1205
1206     _get_maildir_flag_actions (message, &to_set, &to_clear);
1207
1208     for (filenames = notmuch_message_get_filenames (message);
1209          notmuch_filenames_valid (filenames);
1210          notmuch_filenames_move_to_next (filenames))
1211     {
1212         filename = notmuch_filenames_get (filenames);
1213
1214         if (! _filename_is_in_maildir (filename))
1215             continue;
1216
1217         filename_new = _new_maildir_filename (message, filename,
1218                                               to_set, to_clear);
1219         if (filename_new == NULL)
1220             continue;
1221
1222         if (strcmp (filename, filename_new)) {
1223             int err;
1224             notmuch_status_t new_status;
1225
1226             err = rename (filename, filename_new);
1227             if (err)
1228                 continue;
1229
1230             new_status = _notmuch_message_remove_filename (message,
1231                                                            filename);
1232             /* Hold on to only the first error. */
1233             if (! status && new_status) {
1234                 status = new_status;
1235                 continue;
1236             }
1237
1238             new_status = _notmuch_message_add_filename (message,
1239                                                         filename_new);
1240             /* Hold on to only the first error. */
1241             if (! status && new_status) {
1242                 status = new_status;
1243                 continue;
1244             }
1245
1246             _notmuch_message_sync (message);
1247         }
1248
1249         talloc_free (filename_new);
1250     }
1251
1252     talloc_free (to_set);
1253     talloc_free (to_clear);
1254
1255     return NOTMUCH_STATUS_SUCCESS;
1256 }
1257
1258 notmuch_status_t
1259 notmuch_message_remove_all_tags (notmuch_message_t *message)
1260 {
1261     notmuch_private_status_t private_status;
1262     notmuch_status_t status;
1263     notmuch_tags_t *tags;
1264     const char *tag;
1265
1266     status = _notmuch_database_ensure_writable (message->notmuch);
1267     if (status)
1268         return status;
1269
1270     for (tags = notmuch_message_get_tags (message);
1271          notmuch_tags_valid (tags);
1272          notmuch_tags_move_to_next (tags))
1273     {
1274         tag = notmuch_tags_get (tags);
1275
1276         private_status = _notmuch_message_remove_term (message, "tag", tag);
1277         if (private_status) {
1278             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1279                             private_status);
1280         }
1281     }
1282
1283     if (! message->frozen)
1284         _notmuch_message_sync (message);
1285
1286     return NOTMUCH_STATUS_SUCCESS;
1287 }
1288
1289 notmuch_status_t
1290 notmuch_message_freeze (notmuch_message_t *message)
1291 {
1292     notmuch_status_t status;
1293
1294     status = _notmuch_database_ensure_writable (message->notmuch);
1295     if (status)
1296         return status;
1297
1298     message->frozen++;
1299
1300     return NOTMUCH_STATUS_SUCCESS;
1301 }
1302
1303 notmuch_status_t
1304 notmuch_message_thaw (notmuch_message_t *message)
1305 {
1306     notmuch_status_t status;
1307
1308     status = _notmuch_database_ensure_writable (message->notmuch);
1309     if (status)
1310         return status;
1311
1312     if (message->frozen > 0) {
1313         message->frozen--;
1314         if (message->frozen == 0)
1315             _notmuch_message_sync (message);
1316         return NOTMUCH_STATUS_SUCCESS;
1317     } else {
1318         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1319     }
1320 }
1321
1322 void
1323 notmuch_message_destroy (notmuch_message_t *message)
1324 {
1325     talloc_free (message);
1326 }