]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
da4a102c3fc1c10f171d837bffa7707b416f81b4
[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_string_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 static char *
260 _notmuch_message_get_term (notmuch_message_t *message,
261                            Xapian::TermIterator &i, Xapian::TermIterator &end,
262                            const char *prefix)
263 {
264     int prefix_len = strlen (prefix);
265     const char *term = NULL;
266     char *value;
267
268     i.skip_to (prefix);
269
270     if (i != end)
271         term = (*i).c_str ();
272
273     if (!term || strncmp (term, prefix, prefix_len))
274         return NULL;
275
276     value = talloc_strdup (message, term + prefix_len);
277
278 #if DEBUG_DATABASE_SANITY
279     i++;
280
281     if (i != end && strncmp ((*i).c_str (), prefix, prefix_len) == 0) {
282         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate %s terms: %s and %s\n",
283                         message->doc_id, prefix, value,
284                         (*i).c_str () + prefix_len);
285     }
286 #endif
287
288     return value;
289 }
290
291 void
292 _notmuch_message_ensure_metadata (notmuch_message_t *message)
293 {
294     Xapian::TermIterator i, end;
295     const char *thread_prefix = _find_prefix ("thread"),
296         *id_prefix = _find_prefix ("id"),
297         *replyto_prefix = _find_prefix ("replyto");
298
299     /* We do this all in a single pass because Xapian decompresses the
300      * term list every time you iterate over it.  Thus, while this is
301      * slightly more costly than looking up individual fields if only
302      * one field of the message object is actually used, it's a huge
303      * win as more fields are used. */
304
305     i = message->doc.termlist_begin ();
306     end = message->doc.termlist_end ();
307
308     /* Get thread */
309     if (!message->thread_id)
310         message->thread_id =
311             _notmuch_message_get_term (message, i, end, thread_prefix);
312
313     /* Get id */
314     assert (strcmp (thread_prefix, id_prefix) < 0);
315     if (!message->message_id)
316         message->message_id =
317             _notmuch_message_get_term (message, i, end, id_prefix);
318
319     /* Get reply to */
320     assert (strcmp (id_prefix, replyto_prefix) < 0);
321     if (!message->in_reply_to)
322         message->in_reply_to =
323             _notmuch_message_get_term (message, i, end, replyto_prefix);
324     /* It's perfectly valid for a message to have no In-Reply-To
325      * header. For these cases, we return an empty string. */
326     if (!message->in_reply_to)
327         message->in_reply_to = talloc_strdup (message, "");
328 }
329
330 static void
331 _notmuch_message_invalidate_metadata (notmuch_message_t *message,
332                                       const char *prefix_name)
333 {
334     if (strcmp ("thread", prefix_name) == 0) {
335         talloc_free (message->thread_id);
336         message->thread_id = NULL;
337     }
338
339     if (strcmp ("replyto", prefix_name) == 0) {
340         talloc_free (message->in_reply_to);
341         message->in_reply_to = NULL;
342     }
343 }
344
345 unsigned int
346 _notmuch_message_get_doc_id (notmuch_message_t *message)
347 {
348     return message->doc_id;
349 }
350
351 const char *
352 notmuch_message_get_message_id (notmuch_message_t *message)
353 {
354     if (!message->message_id)
355         _notmuch_message_ensure_metadata (message);
356     if (!message->message_id)
357         INTERNAL_ERROR ("Message with document ID of %u has no message ID.\n",
358                         message->doc_id);
359     return message->message_id;
360 }
361
362 static void
363 _notmuch_message_ensure_message_file (notmuch_message_t *message)
364 {
365     const char *filename;
366
367     if (message->message_file)
368         return;
369
370     filename = notmuch_message_get_filename (message);
371     if (unlikely (filename == NULL))
372         return;
373
374     message->message_file = _notmuch_message_file_open_ctx (message, filename);
375 }
376
377 const char *
378 notmuch_message_get_header (notmuch_message_t *message, const char *header)
379 {
380     _notmuch_message_ensure_message_file (message);
381     if (message->message_file == NULL)
382         return NULL;
383
384     return notmuch_message_file_get_header (message->message_file, header);
385 }
386
387 /* Return the message ID from the In-Reply-To header of 'message'.
388  *
389  * Returns an empty string ("") if 'message' has no In-Reply-To
390  * header.
391  *
392  * Returns NULL if any error occurs.
393  */
394 const char *
395 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
396 {
397     if (!message->in_reply_to)
398         _notmuch_message_ensure_metadata (message);
399     return message->in_reply_to;
400 }
401
402 const char *
403 notmuch_message_get_thread_id (notmuch_message_t *message)
404 {
405     if (!message->thread_id)
406         _notmuch_message_ensure_metadata (message);
407     if (!message->thread_id)
408         INTERNAL_ERROR ("Message with document ID of %u has no thread ID.\n",
409                         message->doc_id);
410     return message->thread_id;
411 }
412
413 void
414 _notmuch_message_add_reply (notmuch_message_t *message,
415                             notmuch_message_node_t *reply)
416 {
417     _notmuch_message_list_append (message->replies, reply);
418 }
419
420 notmuch_messages_t *
421 notmuch_message_get_replies (notmuch_message_t *message)
422 {
423     return _notmuch_messages_create (message->replies);
424 }
425
426 /* Add an additional 'filename' for 'message'.
427  *
428  * This change will not be reflected in the database until the next
429  * call to _notmuch_message_sync. */
430 notmuch_status_t
431 _notmuch_message_add_filename (notmuch_message_t *message,
432                                const char *filename)
433 {
434     const char *relative, *directory;
435     notmuch_status_t status;
436     void *local = talloc_new (message);
437     char *direntry;
438
439     if (filename == NULL)
440         INTERNAL_ERROR ("Message filename cannot be NULL.");
441
442     if (message->filename_list) {
443         talloc_free (message->filename_list);
444         message->filename_list = NULL;
445     }
446
447     relative = _notmuch_database_relative_path (message->notmuch, filename);
448
449     status = _notmuch_database_split_path (local, relative, &directory, NULL);
450     if (status)
451         return status;
452
453     status = _notmuch_database_filename_to_direntry (local,
454                                                      message->notmuch,
455                                                      filename, &direntry);
456     if (status)
457         return status;
458
459     /* New file-direntry allows navigating to this message with
460      * notmuch_directory_get_child_files() . */
461     _notmuch_message_add_term (message, "file-direntry", direntry);
462
463     /* New terms allow user to search with folder: specification. */
464     _notmuch_message_gen_terms (message, "folder", directory);
465
466     talloc_free (local);
467
468     return NOTMUCH_STATUS_SUCCESS;
469 }
470
471 /* Remove a particular 'filename' from 'message'.
472  *
473  * This change will not be reflected in the database until the next
474  * call to _notmuch_message_sync.
475  *
476  * Note: This function does not remove a document from the database,
477  * even if the specified filename is the only filename for this
478  * message. For that functionality, see
479  * _notmuch_database_remove_message. */
480 notmuch_status_t
481 _notmuch_message_remove_filename (notmuch_message_t *message,
482                                   const char *filename)
483 {
484     const char *direntry_prefix = _find_prefix ("file-direntry");
485     int direntry_prefix_len = strlen (direntry_prefix);
486     const char *folder_prefix = _find_prefix ("folder");
487     int folder_prefix_len = strlen (folder_prefix);
488     void *local = talloc_new (message);
489     char *direntry;
490     notmuch_private_status_t private_status;
491     notmuch_status_t status;
492     Xapian::TermIterator i, last;
493
494     if (message->filename_list) {
495         talloc_free (message->filename_list);
496         message->filename_list = NULL;
497     }
498
499     status = _notmuch_database_filename_to_direntry (local, message->notmuch,
500                                                      filename, &direntry);
501     if (status)
502         return status;
503
504     /* Unlink this file from its parent directory. */
505     private_status = _notmuch_message_remove_term (message,
506                                                    "file-direntry", direntry);
507     status = COERCE_STATUS (private_status,
508                             "Unexpected error from _notmuch_message_remove_term");
509
510     /* Re-synchronize "folder:" terms for this message. This requires
511      * first removing all "folder:" terms, then adding back terms for
512      * all remaining filenames of the message. */
513     while (1) {
514         i = message->doc.termlist_begin ();
515         i.skip_to (folder_prefix);
516
517         /* Terminate loop when no terms remain with desired prefix. */
518         if (i == message->doc.termlist_end () ||
519             strncmp ((*i).c_str (), folder_prefix, folder_prefix_len))
520         {
521             break;
522         }
523
524         try {
525             message->doc.remove_term ((*i));
526         } catch (const Xapian::InvalidArgumentError) {
527             /* Ignore failure to remove non-existent term. */
528         }
529     }
530
531     i = message->doc.termlist_begin ();
532     i.skip_to (direntry_prefix);
533
534     for (; i != message->doc.termlist_end (); i++) {
535         unsigned int directory_id;
536         const char *direntry, *directory;
537         char *colon;
538
539         /* Terminate loop at first term without desired prefix. */
540         if (strncmp ((*i).c_str (), direntry_prefix, direntry_prefix_len))
541             break;
542
543         direntry = (*i).c_str ();
544         direntry += direntry_prefix_len;
545
546         directory_id = strtol (direntry, &colon, 10);
547
548         if (colon == NULL || *colon != ':')
549             INTERNAL_ERROR ("malformed direntry");
550
551         directory = _notmuch_database_get_directory_path (local,
552                                                           message->notmuch,
553                                                           directory_id);
554         if (strlen (directory))
555             _notmuch_message_gen_terms (message, "folder", directory);
556     }
557
558     talloc_free (local);
559
560     return status;
561 }
562
563 char *
564 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
565 {
566     return talloc_strdup (message, message->doc.get_data ().c_str ());
567 }
568
569 void
570 _notmuch_message_clear_data (notmuch_message_t *message)
571 {
572     message->doc.set_data ("");
573 }
574
575 static void
576 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
577 {
578     const char *prefix = _find_prefix ("file-direntry");
579     int prefix_len = strlen (prefix);
580     Xapian::TermIterator i;
581
582     if (message->filename_list)
583         return;
584
585     message->filename_list = _notmuch_string_list_create (message);
586
587     i = message->doc.termlist_begin ();
588     i.skip_to (prefix);
589
590     if (i == message->doc.termlist_end () ||
591         strncmp ((*i).c_str (), prefix, prefix_len))
592     {
593         /* A message document created by an old version of notmuch
594          * (prior to rename support) will have the filename in the
595          * data of the document rather than as a file-direntry term.
596          *
597          * It would be nice to do the upgrade of the document directly
598          * here, but the database is likely open in read-only mode. */
599         const char *data;
600
601         data = message->doc.get_data ().c_str ();
602
603         if (data == NULL)
604             INTERNAL_ERROR ("message with no filename");
605
606         _notmuch_string_list_append (message->filename_list, data);
607
608         return;
609     }
610
611     for (; i != message->doc.termlist_end (); i++) {
612         void *local = talloc_new (message);
613         const char *db_path, *directory, *basename, *filename;
614         char *colon, *direntry = NULL;
615         unsigned int directory_id;
616
617         /* Terminate loop at first term without desired prefix. */
618         if (strncmp ((*i).c_str (), prefix, prefix_len))
619             break;
620
621         direntry = talloc_strdup (local, (*i).c_str ());
622
623         direntry += prefix_len;
624
625         directory_id = strtol (direntry, &colon, 10);
626
627         if (colon == NULL || *colon != ':')
628             INTERNAL_ERROR ("malformed direntry");
629
630         basename = colon + 1;
631
632         *colon = '\0';
633
634         db_path = notmuch_database_get_path (message->notmuch);
635
636         directory = _notmuch_database_get_directory_path (local,
637                                                           message->notmuch,
638                                                           directory_id);
639
640         if (strlen (directory))
641             filename = talloc_asprintf (message, "%s/%s/%s",
642                                         db_path, directory, basename);
643         else
644             filename = talloc_asprintf (message, "%s/%s",
645                                         db_path, basename);
646
647         _notmuch_string_list_append (message->filename_list, filename);
648
649         talloc_free (local);
650     }
651 }
652
653 const char *
654 notmuch_message_get_filename (notmuch_message_t *message)
655 {
656     _notmuch_message_ensure_filename_list (message);
657
658     if (message->filename_list == NULL)
659         return NULL;
660
661     if (message->filename_list->head == NULL ||
662         message->filename_list->head->string == NULL)
663     {
664         INTERNAL_ERROR ("message with no filename");
665     }
666
667     return message->filename_list->head->string;
668 }
669
670 notmuch_filenames_t *
671 notmuch_message_get_filenames (notmuch_message_t *message)
672 {
673     _notmuch_message_ensure_filename_list (message);
674
675     return _notmuch_filenames_create (message, message->filename_list);
676 }
677
678 notmuch_bool_t
679 notmuch_message_get_flag (notmuch_message_t *message,
680                           notmuch_message_flag_t flag)
681 {
682     return message->flags & (1 << flag);
683 }
684
685 void
686 notmuch_message_set_flag (notmuch_message_t *message,
687                           notmuch_message_flag_t flag, notmuch_bool_t enable)
688 {
689     if (enable)
690         message->flags |= (1 << flag);
691     else
692         message->flags &= ~(1 << flag);
693 }
694
695 time_t
696 notmuch_message_get_date (notmuch_message_t *message)
697 {
698     std::string value;
699
700     try {
701         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
702     } catch (Xapian::Error &error) {
703         INTERNAL_ERROR ("Failed to read timestamp value from document.");
704         return 0;
705     }
706
707     return Xapian::sortable_unserialise (value);
708 }
709
710 notmuch_tags_t *
711 notmuch_message_get_tags (notmuch_message_t *message)
712 {
713     Xapian::TermIterator i, end;
714     notmuch_string_list_t *tags;
715     i = message->doc.termlist_begin();
716     end = message->doc.termlist_end();
717     tags = _notmuch_database_get_terms_with_prefix (message, i, end,
718                                                     _find_prefix ("tag"));
719     _notmuch_string_list_sort (tags);
720     return _notmuch_tags_create (message, tags);
721 }
722
723 const char *
724 notmuch_message_get_author (notmuch_message_t *message)
725 {
726     return message->author;
727 }
728
729 void
730 notmuch_message_set_author (notmuch_message_t *message,
731                             const char *author)
732 {
733     if (message->author)
734         talloc_free(message->author);
735     message->author = talloc_strdup(message, author);
736     return;
737 }
738
739 void
740 _notmuch_message_set_date (notmuch_message_t *message,
741                            const char *date)
742 {
743     time_t time_value;
744
745     /* GMime really doesn't want to see a NULL date, so protect its
746      * sensibilities. */
747     if (date == NULL || *date == '\0')
748         time_value = 0;
749     else
750         time_value = g_mime_utils_header_decode_date (date, NULL);
751
752     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
753                             Xapian::sortable_serialise (time_value));
754 }
755
756 /* Synchronize changes made to message->doc out into the database. */
757 void
758 _notmuch_message_sync (notmuch_message_t *message)
759 {
760     Xapian::WritableDatabase *db;
761
762     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
763         return;
764
765     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
766     db->replace_document (message->doc_id, message->doc);
767 }
768
769 /* Ensure that 'message' is not holding any file object open. Future
770  * calls to various functions will still automatically open the
771  * message file as needed.
772  */
773 void
774 _notmuch_message_close (notmuch_message_t *message)
775 {
776     if (message->message_file) {
777         notmuch_message_file_close (message->message_file);
778         message->message_file = NULL;
779     }
780 }
781
782 /* Add a name:value term to 'message', (the actual term will be
783  * encoded by prefixing the value with a short prefix). See
784  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
785  * names to prefix values.
786  *
787  * This change will not be reflected in the database until the next
788  * call to _notmuch_message_sync. */
789 notmuch_private_status_t
790 _notmuch_message_add_term (notmuch_message_t *message,
791                            const char *prefix_name,
792                            const char *value)
793 {
794
795     char *term;
796
797     if (value == NULL)
798         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
799
800     term = talloc_asprintf (message, "%s%s",
801                             _find_prefix (prefix_name), value);
802
803     if (strlen (term) > NOTMUCH_TERM_MAX)
804         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
805
806     message->doc.add_term (term, 0);
807
808     talloc_free (term);
809
810     _notmuch_message_invalidate_metadata (message, prefix_name);
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     _notmuch_message_invalidate_metadata (message, prefix_name);
878
879     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
880 }
881
882 notmuch_status_t
883 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
884 {
885     notmuch_private_status_t private_status;
886     notmuch_status_t status;
887
888     status = _notmuch_database_ensure_writable (message->notmuch);
889     if (status)
890         return status;
891
892     if (tag == NULL)
893         return NOTMUCH_STATUS_NULL_POINTER;
894
895     if (strlen (tag) > NOTMUCH_TAG_MAX)
896         return NOTMUCH_STATUS_TAG_TOO_LONG;
897
898     private_status = _notmuch_message_add_term (message, "tag", tag);
899     if (private_status) {
900         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
901                         private_status);
902     }
903
904     if (! message->frozen)
905         _notmuch_message_sync (message);
906
907     return NOTMUCH_STATUS_SUCCESS;
908 }
909
910 notmuch_status_t
911 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
912 {
913     notmuch_private_status_t private_status;
914     notmuch_status_t status;
915
916     status = _notmuch_database_ensure_writable (message->notmuch);
917     if (status)
918         return status;
919
920     if (tag == NULL)
921         return NOTMUCH_STATUS_NULL_POINTER;
922
923     if (strlen (tag) > NOTMUCH_TAG_MAX)
924         return NOTMUCH_STATUS_TAG_TOO_LONG;
925
926     private_status = _notmuch_message_remove_term (message, "tag", tag);
927     if (private_status) {
928         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
929                         private_status);
930     }
931
932     if (! message->frozen)
933         _notmuch_message_sync (message);
934
935     return NOTMUCH_STATUS_SUCCESS;
936 }
937
938 notmuch_status_t
939 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
940 {
941     const char *flags;
942     notmuch_status_t status;
943     notmuch_filenames_t *filenames;
944     const char *filename;
945     char *combined_flags = talloc_strdup (message, "");
946     unsigned i;
947     int seen_maildir_info = 0;
948
949     for (filenames = notmuch_message_get_filenames (message);
950          notmuch_filenames_valid (filenames);
951          notmuch_filenames_move_to_next (filenames))
952     {
953         filename = notmuch_filenames_get (filenames);
954
955         flags = strstr (filename, ":2,");
956         if (! flags)
957             continue;
958
959         seen_maildir_info = 1;
960         flags += 3;
961
962         combined_flags = talloc_strdup_append (combined_flags, flags);
963     }
964
965     /* If none of the filenames have any maildir info field (not even
966      * an empty info with no flags set) then there's no information to
967      * go on, so do nothing. */
968     if (! seen_maildir_info)
969         return NOTMUCH_STATUS_SUCCESS;
970
971     status = notmuch_message_freeze (message);
972     if (status)
973         return status;
974
975     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
976         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
977             ^ 
978             flag2tag[i].inverse)
979         {
980             status = notmuch_message_add_tag (message, flag2tag[i].tag);
981         } else {
982             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
983         }
984         if (status)
985             return status;
986     }
987     status = notmuch_message_thaw (message);
988
989     talloc_free (combined_flags);
990
991     return status;
992 }
993
994 /* Is the given filename within a maildir directory?
995  *
996  * Specifically, is the final directory component of 'filename' either
997  * "cur" or "new". If so, return a pointer to that final directory
998  * component within 'filename'. If not, return NULL.
999  *
1000  * A non-NULL return value is guaranteed to be a valid string pointer
1001  * pointing to the characters "new/" or "cur/", (but not
1002  * NUL-terminated).
1003  */
1004 static const char *
1005 _filename_is_in_maildir (const char *filename)
1006 {
1007     const char *slash, *dir = NULL;
1008
1009     /* Find the last '/' separating directory from filename. */
1010     slash = strrchr (filename, '/');
1011     if (slash == NULL)
1012         return NULL;
1013
1014     /* Jump back 4 characters to where the previous '/' will be if the
1015      * directory is named "cur" or "new". */
1016     if (slash - filename < 4)
1017         return NULL;
1018
1019     slash -= 4;
1020
1021     if (*slash != '/')
1022         return NULL;
1023
1024     dir = slash + 1;
1025
1026     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1027         STRNCMP_LITERAL (dir, "new/") == 0)
1028     {
1029         return dir;
1030     }
1031
1032     return NULL;
1033 }
1034
1035 /* From the set of tags on 'message' and the flag2tag table, compute a
1036  * set of maildir-flag actions to be taken, (flags that should be
1037  * either set or cleared).
1038  *
1039  * The result is returned as two talloced strings: to_set, and to_clear
1040  */
1041 static void
1042 _get_maildir_flag_actions (notmuch_message_t *message,
1043                            char **to_set_ret,
1044                            char **to_clear_ret)
1045 {
1046     char *to_set, *to_clear;
1047     notmuch_tags_t *tags;
1048     const char *tag;
1049     unsigned i;
1050
1051     to_set = talloc_strdup (message, "");
1052     to_clear = talloc_strdup (message, "");
1053
1054     /* First, find flags for all set tags. */
1055     for (tags = notmuch_message_get_tags (message);
1056          notmuch_tags_valid (tags);
1057          notmuch_tags_move_to_next (tags))
1058     {
1059         tag = notmuch_tags_get (tags);
1060
1061         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1062             if (strcmp (tag, flag2tag[i].tag) == 0) {
1063                 if (flag2tag[i].inverse)
1064                     to_clear = talloc_asprintf_append (to_clear,
1065                                                        "%c",
1066                                                        flag2tag[i].flag);
1067                 else
1068                     to_set = talloc_asprintf_append (to_set,
1069                                                      "%c",
1070                                                      flag2tag[i].flag);
1071             }
1072         }
1073     }
1074
1075     /* Then, find the flags for all tags not present. */
1076     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1077         if (flag2tag[i].inverse) {
1078             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1079                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1080         } else {
1081             if (strchr (to_set, flag2tag[i].flag) == NULL)
1082                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1083         }
1084     }
1085
1086     *to_set_ret = to_set;
1087     *to_clear_ret = to_clear;
1088 }
1089
1090 /* Given 'filename' and a set of maildir flags to set and to clear,
1091  * compute the new maildir filename.
1092  *
1093  * If the existing filename is in the directory "new", the new
1094  * filename will be in the directory "cur".
1095  *
1096  * After a sequence of ":2," in the filename, any subsequent
1097  * single-character flags will be added or removed according to the
1098  * characters in flags_to_set and flags_to_clear. Any existing flags
1099  * not mentioned in either string will remain. The final list of flags
1100  * will be in ASCII order.
1101  *
1102  * If the original flags seem invalid, (repeated characters or
1103  * non-ASCII ordering of flags), this function will return NULL
1104  * (meaning that renaming would not be safe and should not occur).
1105  */
1106 static char*
1107 _new_maildir_filename (void *ctx,
1108                        const char *filename,
1109                        const char *flags_to_set,
1110                        const char *flags_to_clear)
1111 {
1112     const char *info, *flags;
1113     unsigned int flag, last_flag;
1114     char *filename_new, *dir;
1115     char flag_map[128];
1116     int flags_in_map = 0;
1117     unsigned int i;
1118     char *s;
1119
1120     memset (flag_map, 0, sizeof (flag_map));
1121
1122     info = strstr (filename, ":2,");
1123
1124     if (info == NULL) {
1125         info = filename + strlen(filename);
1126     } else {
1127         flags = info + 3;
1128
1129         /* Loop through existing flags in filename. */
1130         for (flags = info + 3, last_flag = 0;
1131              *flags;
1132              last_flag = flag, flags++)
1133         {
1134             flag = *flags;
1135
1136             /* Original flags not in ASCII order. Abort. */
1137             if (flag < last_flag)
1138                 return NULL;
1139
1140             /* Non-ASCII flag. Abort. */
1141             if (flag > sizeof(flag_map) - 1)
1142                 return NULL;
1143
1144             /* Repeated flag value. Abort. */
1145             if (flag_map[flag])
1146                 return NULL;
1147
1148             flag_map[flag] = 1;
1149             flags_in_map++;
1150         }
1151     }
1152
1153     /* Then set and clear our flags from tags. */
1154     for (flags = flags_to_set; *flags; flags++) {
1155         flag = *flags;
1156         if (flag_map[flag] == 0) {
1157             flag_map[flag] = 1;
1158             flags_in_map++;
1159         }
1160     }
1161
1162     for (flags = flags_to_clear; *flags; flags++) {
1163         flag = *flags;
1164         if (flag_map[flag]) {
1165             flag_map[flag] = 0;
1166             flags_in_map--;
1167         }
1168     }
1169
1170     filename_new = (char *) talloc_size (ctx,
1171                                          info - filename +
1172                                          strlen (":2,") + flags_in_map + 1);
1173     if (unlikely (filename_new == NULL))
1174         return NULL;
1175
1176     strncpy (filename_new, filename, info - filename);
1177     filename_new[info - filename] = '\0';
1178
1179     strcat (filename_new, ":2,");
1180
1181     s = filename_new + strlen (filename_new);
1182     for (i = 0; i < sizeof (flag_map); i++)
1183     {
1184         if (flag_map[i]) {
1185             *s = i;
1186             s++;
1187         }
1188     }
1189     *s = '\0';
1190
1191     /* If message is in new/ move it under cur/. */
1192     dir = (char *) _filename_is_in_maildir (filename_new);
1193     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1194         memcpy (dir, "cur/", 4);
1195
1196     return filename_new;
1197 }
1198
1199 notmuch_status_t
1200 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1201 {
1202     notmuch_filenames_t *filenames;
1203     const char *filename;
1204     char *filename_new;
1205     char *to_set, *to_clear;
1206     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1207
1208     _get_maildir_flag_actions (message, &to_set, &to_clear);
1209
1210     for (filenames = notmuch_message_get_filenames (message);
1211          notmuch_filenames_valid (filenames);
1212          notmuch_filenames_move_to_next (filenames))
1213     {
1214         filename = notmuch_filenames_get (filenames);
1215
1216         if (! _filename_is_in_maildir (filename))
1217             continue;
1218
1219         filename_new = _new_maildir_filename (message, filename,
1220                                               to_set, to_clear);
1221         if (filename_new == NULL)
1222             continue;
1223
1224         if (strcmp (filename, filename_new)) {
1225             int err;
1226             notmuch_status_t new_status;
1227
1228             err = rename (filename, filename_new);
1229             if (err)
1230                 continue;
1231
1232             new_status = _notmuch_message_remove_filename (message,
1233                                                            filename);
1234             /* Hold on to only the first error. */
1235             if (! status && new_status) {
1236                 status = new_status;
1237                 continue;
1238             }
1239
1240             new_status = _notmuch_message_add_filename (message,
1241                                                         filename_new);
1242             /* Hold on to only the first error. */
1243             if (! status && new_status) {
1244                 status = new_status;
1245                 continue;
1246             }
1247
1248             _notmuch_message_sync (message);
1249         }
1250
1251         talloc_free (filename_new);
1252     }
1253
1254     talloc_free (to_set);
1255     talloc_free (to_clear);
1256
1257     return NOTMUCH_STATUS_SUCCESS;
1258 }
1259
1260 notmuch_status_t
1261 notmuch_message_remove_all_tags (notmuch_message_t *message)
1262 {
1263     notmuch_private_status_t private_status;
1264     notmuch_status_t status;
1265     notmuch_tags_t *tags;
1266     const char *tag;
1267
1268     status = _notmuch_database_ensure_writable (message->notmuch);
1269     if (status)
1270         return status;
1271
1272     for (tags = notmuch_message_get_tags (message);
1273          notmuch_tags_valid (tags);
1274          notmuch_tags_move_to_next (tags))
1275     {
1276         tag = notmuch_tags_get (tags);
1277
1278         private_status = _notmuch_message_remove_term (message, "tag", tag);
1279         if (private_status) {
1280             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1281                             private_status);
1282         }
1283     }
1284
1285     if (! message->frozen)
1286         _notmuch_message_sync (message);
1287
1288     return NOTMUCH_STATUS_SUCCESS;
1289 }
1290
1291 notmuch_status_t
1292 notmuch_message_freeze (notmuch_message_t *message)
1293 {
1294     notmuch_status_t status;
1295
1296     status = _notmuch_database_ensure_writable (message->notmuch);
1297     if (status)
1298         return status;
1299
1300     message->frozen++;
1301
1302     return NOTMUCH_STATUS_SUCCESS;
1303 }
1304
1305 notmuch_status_t
1306 notmuch_message_thaw (notmuch_message_t *message)
1307 {
1308     notmuch_status_t status;
1309
1310     status = _notmuch_database_ensure_writable (message->notmuch);
1311     if (status)
1312         return status;
1313
1314     if (message->frozen > 0) {
1315         message->frozen--;
1316         if (message->frozen == 0)
1317             _notmuch_message_sync (message);
1318         return NOTMUCH_STATUS_SUCCESS;
1319     } else {
1320         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1321     }
1322 }
1323
1324 void
1325 notmuch_message_destroy (notmuch_message_t *message)
1326 {
1327     talloc_free (message);
1328 }