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