]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
7aff4ae5111a800a4204c0255e2b070c86164fce
[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     char *value;
270
271     i.skip_to (prefix);
272
273     if (i == end)
274         return NULL;
275
276     std::string term = *i;
277     if (strncmp (term.c_str(), prefix, prefix_len))
278         return NULL;
279
280     value = talloc_strdup (message, term.c_str() + 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     try {
416             std::string value;
417
418             /* Fetch header from the appropriate xapian value field if
419              * available */
420             if (strcasecmp (header, "from") == 0)
421                 value = message->doc.get_value (NOTMUCH_VALUE_FROM);
422             else if (strcasecmp (header, "subject") == 0)
423                 value = message->doc.get_value (NOTMUCH_VALUE_SUBJECT);
424             else if (strcasecmp (header, "message-id") == 0)
425                 value = message->doc.get_value (NOTMUCH_VALUE_MESSAGE_ID);
426
427             if (!value.empty())
428                 return talloc_strdup (message, value.c_str ());
429
430     } catch (Xapian::Error &error) {
431         fprintf (stderr, "A Xapian exception occurred when reading header: %s\n",
432                  error.get_msg().c_str());
433         message->notmuch->exception_reported = TRUE;
434         return NULL;
435     }
436
437     /* Otherwise fall back to parsing the file */
438     _notmuch_message_ensure_message_file (message);
439     if (message->message_file == NULL)
440         return NULL;
441
442     return notmuch_message_file_get_header (message->message_file, header);
443 }
444
445 /* Return the message ID from the In-Reply-To header of 'message'.
446  *
447  * Returns an empty string ("") if 'message' has no In-Reply-To
448  * header.
449  *
450  * Returns NULL if any error occurs.
451  */
452 const char *
453 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
454 {
455     if (!message->in_reply_to)
456         _notmuch_message_ensure_metadata (message);
457     return message->in_reply_to;
458 }
459
460 const char *
461 notmuch_message_get_thread_id (notmuch_message_t *message)
462 {
463     if (!message->thread_id)
464         _notmuch_message_ensure_metadata (message);
465     if (!message->thread_id)
466         INTERNAL_ERROR ("Message with document ID of %u has no thread ID.\n",
467                         message->doc_id);
468     return message->thread_id;
469 }
470
471 void
472 _notmuch_message_add_reply (notmuch_message_t *message,
473                             notmuch_message_t *reply)
474 {
475     _notmuch_message_list_add_message (message->replies, reply);
476 }
477
478 notmuch_messages_t *
479 notmuch_message_get_replies (notmuch_message_t *message)
480 {
481     return _notmuch_messages_create (message->replies);
482 }
483
484 static void
485 _notmuch_message_remove_terms (notmuch_message_t *message, const char *prefix)
486 {
487     Xapian::TermIterator i;
488     size_t prefix_len = strlen (prefix);
489
490     while (1) {
491         i = message->doc.termlist_begin ();
492         i.skip_to (prefix);
493
494         /* Terminate loop when no terms remain with desired prefix. */
495         if (i == message->doc.termlist_end () ||
496             strncmp ((*i).c_str (), prefix, prefix_len))
497             break;
498
499         try {
500             message->doc.remove_term ((*i));
501         } catch (const Xapian::InvalidArgumentError) {
502             /* Ignore failure to remove non-existent term. */
503         }
504     }
505 }
506
507 /* Add directory based terms for all filenames of the message. */
508 static notmuch_status_t
509 _notmuch_message_add_directory_terms (void *ctx, notmuch_message_t *message)
510 {
511     const char *direntry_prefix = _find_prefix ("file-direntry");
512     int direntry_prefix_len = strlen (direntry_prefix);
513     Xapian::TermIterator i = message->doc.termlist_begin ();
514     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
515
516     for (i.skip_to (direntry_prefix); i != message->doc.termlist_end (); i++) {
517         unsigned int directory_id;
518         const char *direntry, *directory;
519         char *colon;
520
521         /* Terminate loop at first term without desired prefix. */
522         if (strncmp ((*i).c_str (), direntry_prefix, direntry_prefix_len))
523             break;
524
525         /* Indicate that there are filenames remaining. */
526         status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
527
528         direntry = (*i).c_str ();
529         direntry += direntry_prefix_len;
530
531         directory_id = strtol (direntry, &colon, 10);
532
533         if (colon == NULL || *colon != ':')
534             INTERNAL_ERROR ("malformed direntry");
535
536         directory = _notmuch_database_get_directory_path (ctx,
537                                                           message->notmuch,
538                                                           directory_id);
539         if (strlen (directory))
540             _notmuch_message_gen_terms (message, "folder", directory);
541     }
542
543     return status;
544 }
545
546 /* Add an additional 'filename' for 'message'.
547  *
548  * This change will not be reflected in the database until the next
549  * call to _notmuch_message_sync. */
550 notmuch_status_t
551 _notmuch_message_add_filename (notmuch_message_t *message,
552                                const char *filename)
553 {
554     const char *relative, *directory;
555     notmuch_status_t status;
556     void *local = talloc_new (message);
557     char *direntry;
558
559     if (filename == NULL)
560         INTERNAL_ERROR ("Message filename cannot be NULL.");
561
562     relative = _notmuch_database_relative_path (message->notmuch, filename);
563
564     status = _notmuch_database_split_path (local, relative, &directory, NULL);
565     if (status)
566         return status;
567
568     status = _notmuch_database_filename_to_direntry (
569         local, message->notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
570     if (status)
571         return status;
572
573     /* New file-direntry allows navigating to this message with
574      * notmuch_directory_get_child_files() . */
575     _notmuch_message_add_term (message, "file-direntry", direntry);
576
577     /* New terms allow user to search with folder: specification. */
578     _notmuch_message_gen_terms (message, "folder", directory);
579
580     talloc_free (local);
581
582     return NOTMUCH_STATUS_SUCCESS;
583 }
584
585 /* Remove a particular 'filename' from 'message'.
586  *
587  * This change will not be reflected in the database until the next
588  * call to _notmuch_message_sync.
589  *
590  * If this message still has other filenames, returns
591  * NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID.
592  *
593  * Note: This function does not remove a document from the database,
594  * even if the specified filename is the only filename for this
595  * message. For that functionality, see
596  * _notmuch_database_remove_message. */
597 notmuch_status_t
598 _notmuch_message_remove_filename (notmuch_message_t *message,
599                                   const char *filename)
600 {
601     void *local = talloc_new (message);
602     const char *folder_prefix = _find_prefix ("folder");
603     char *zfolder_prefix = talloc_asprintf(local, "Z%s", folder_prefix);
604     char *direntry;
605     notmuch_private_status_t private_status;
606     notmuch_status_t status;
607
608     status = _notmuch_database_filename_to_direntry (
609         local, message->notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
610     if (status || !direntry)
611         return status;
612
613     /* Unlink this file from its parent directory. */
614     private_status = _notmuch_message_remove_term (message,
615                                                    "file-direntry", direntry);
616     status = COERCE_STATUS (private_status,
617                             "Unexpected error from _notmuch_message_remove_term");
618     if (status)
619         return status;
620
621     /* Re-synchronize "folder:" terms for this message. This requires:
622      *  1. removing all "folder:" terms
623      *  2. removing all "folder:" stemmed terms
624      *  3. adding back terms for all remaining filenames of the message. */
625
626     /* 1. removing all "folder:" terms */
627     _notmuch_message_remove_terms (message, folder_prefix);
628
629     /* 2. removing all "folder:" stemmed terms */
630     _notmuch_message_remove_terms (message, zfolder_prefix);
631
632     /* 3. adding back terms for all remaining filenames of the message. */
633     status = _notmuch_message_add_directory_terms (local, message);
634
635     talloc_free (local);
636
637     return status;
638 }
639
640 char *
641 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
642 {
643     return talloc_strdup (message, message->doc.get_data ().c_str ());
644 }
645
646 void
647 _notmuch_message_clear_data (notmuch_message_t *message)
648 {
649     message->doc.set_data ("");
650 }
651
652 static void
653 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
654 {
655     notmuch_string_node_t *node;
656
657     if (message->filename_list)
658         return;
659
660     if (!message->filename_term_list)
661         _notmuch_message_ensure_metadata (message);
662
663     message->filename_list = _notmuch_string_list_create (message);
664     node = message->filename_term_list->head;
665
666     if (!node) {
667         /* A message document created by an old version of notmuch
668          * (prior to rename support) will have the filename in the
669          * data of the document rather than as a file-direntry term.
670          *
671          * It would be nice to do the upgrade of the document directly
672          * here, but the database is likely open in read-only mode. */
673         const char *data;
674
675         data = message->doc.get_data ().c_str ();
676
677         if (data == NULL)
678             INTERNAL_ERROR ("message with no filename");
679
680         _notmuch_string_list_append (message->filename_list, data);
681
682         return;
683     }
684
685     for (; node; node = node->next) {
686         void *local = talloc_new (message);
687         const char *db_path, *directory, *basename, *filename;
688         char *colon, *direntry = NULL;
689         unsigned int directory_id;
690
691         direntry = node->string;
692
693         directory_id = strtol (direntry, &colon, 10);
694
695         if (colon == NULL || *colon != ':')
696             INTERNAL_ERROR ("malformed direntry");
697
698         basename = colon + 1;
699
700         *colon = '\0';
701
702         db_path = notmuch_database_get_path (message->notmuch);
703
704         directory = _notmuch_database_get_directory_path (local,
705                                                           message->notmuch,
706                                                           directory_id);
707
708         if (strlen (directory))
709             filename = talloc_asprintf (message, "%s/%s/%s",
710                                         db_path, directory, basename);
711         else
712             filename = talloc_asprintf (message, "%s/%s",
713                                         db_path, basename);
714
715         _notmuch_string_list_append (message->filename_list, filename);
716
717         talloc_free (local);
718     }
719
720     talloc_free (message->filename_term_list);
721     message->filename_term_list = NULL;
722 }
723
724 const char *
725 notmuch_message_get_filename (notmuch_message_t *message)
726 {
727     _notmuch_message_ensure_filename_list (message);
728
729     if (message->filename_list == NULL)
730         return NULL;
731
732     if (message->filename_list->head == NULL ||
733         message->filename_list->head->string == NULL)
734     {
735         INTERNAL_ERROR ("message with no filename");
736     }
737
738     return message->filename_list->head->string;
739 }
740
741 notmuch_filenames_t *
742 notmuch_message_get_filenames (notmuch_message_t *message)
743 {
744     _notmuch_message_ensure_filename_list (message);
745
746     return _notmuch_filenames_create (message, message->filename_list);
747 }
748
749 notmuch_bool_t
750 notmuch_message_get_flag (notmuch_message_t *message,
751                           notmuch_message_flag_t flag)
752 {
753     return message->flags & (1 << flag);
754 }
755
756 void
757 notmuch_message_set_flag (notmuch_message_t *message,
758                           notmuch_message_flag_t flag, notmuch_bool_t enable)
759 {
760     if (enable)
761         message->flags |= (1 << flag);
762     else
763         message->flags &= ~(1 << flag);
764 }
765
766 time_t
767 notmuch_message_get_date (notmuch_message_t *message)
768 {
769     std::string value;
770
771     try {
772         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
773     } catch (Xapian::Error &error) {
774         fprintf (stderr, "A Xapian exception occurred when reading date: %s\n",
775                  error.get_msg().c_str());
776         message->notmuch->exception_reported = TRUE;
777         return 0;
778     }
779
780     return Xapian::sortable_unserialise (value);
781 }
782
783 notmuch_tags_t *
784 notmuch_message_get_tags (notmuch_message_t *message)
785 {
786     notmuch_tags_t *tags;
787
788     if (!message->tag_list)
789         _notmuch_message_ensure_metadata (message);
790
791     tags = _notmuch_tags_create (message, message->tag_list);
792     /* _notmuch_tags_create steals the reference to the tag_list, but
793      * in this case it's still used by the message, so we add an
794      * *additional* talloc reference to the list.  As a result, it's
795      * possible to modify the message tags (which talloc_unlink's the
796      * current list from the message) while still iterating because
797      * the iterator will keep the current list alive. */
798     if (!talloc_reference (message, message->tag_list))
799         return NULL;
800
801     return tags;
802 }
803
804 const char *
805 notmuch_message_get_author (notmuch_message_t *message)
806 {
807     return message->author;
808 }
809
810 void
811 notmuch_message_set_author (notmuch_message_t *message,
812                             const char *author)
813 {
814     if (message->author)
815         talloc_free(message->author);
816     message->author = talloc_strdup(message, author);
817     return;
818 }
819
820 void
821 _notmuch_message_set_header_values (notmuch_message_t *message,
822                                     const char *date,
823                                     const char *from,
824                                     const char *subject)
825 {
826     time_t time_value;
827
828     /* GMime really doesn't want to see a NULL date, so protect its
829      * sensibilities. */
830     if (date == NULL || *date == '\0')
831         time_value = 0;
832     else
833         time_value = g_mime_utils_header_decode_date (date, NULL);
834
835     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
836                             Xapian::sortable_serialise (time_value));
837     message->doc.add_value (NOTMUCH_VALUE_FROM, from);
838     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
839 }
840
841 /* Synchronize changes made to message->doc out into the database. */
842 void
843 _notmuch_message_sync (notmuch_message_t *message)
844 {
845     Xapian::WritableDatabase *db;
846
847     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
848         return;
849
850     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
851     db->replace_document (message->doc_id, message->doc);
852 }
853
854 /* Delete a message document from the database. */
855 notmuch_status_t
856 _notmuch_message_delete (notmuch_message_t *message)
857 {
858     notmuch_status_t status;
859     Xapian::WritableDatabase *db;
860
861     status = _notmuch_database_ensure_writable (message->notmuch);
862     if (status)
863         return status;
864
865     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
866     db->delete_document (message->doc_id);
867     return NOTMUCH_STATUS_SUCCESS;
868 }
869
870 /* Ensure that 'message' is not holding any file object open. Future
871  * calls to various functions will still automatically open the
872  * message file as needed.
873  */
874 void
875 _notmuch_message_close (notmuch_message_t *message)
876 {
877     if (message->message_file) {
878         notmuch_message_file_close (message->message_file);
879         message->message_file = NULL;
880     }
881 }
882
883 /* Add a name:value term to 'message', (the actual term will be
884  * encoded by prefixing the value with a short prefix). See
885  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
886  * names to prefix values.
887  *
888  * This change will not be reflected in the database until the next
889  * call to _notmuch_message_sync. */
890 notmuch_private_status_t
891 _notmuch_message_add_term (notmuch_message_t *message,
892                            const char *prefix_name,
893                            const char *value)
894 {
895
896     char *term;
897
898     if (value == NULL)
899         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
900
901     term = talloc_asprintf (message, "%s%s",
902                             _find_prefix (prefix_name), value);
903
904     if (strlen (term) > NOTMUCH_TERM_MAX)
905         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
906
907     message->doc.add_term (term, 0);
908
909     talloc_free (term);
910
911     _notmuch_message_invalidate_metadata (message, prefix_name);
912
913     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
914 }
915
916 /* Parse 'text' and add a term to 'message' for each parsed word. Each
917  * term will be added both prefixed (if prefix_name is not NULL) and
918  * also non-prefixed). */
919 notmuch_private_status_t
920 _notmuch_message_gen_terms (notmuch_message_t *message,
921                             const char *prefix_name,
922                             const char *text)
923 {
924     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
925
926     if (text == NULL)
927         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
928
929     term_gen->set_document (message->doc);
930     term_gen->set_termpos (message->termpos);
931
932     if (prefix_name) {
933         const char *prefix = _find_prefix (prefix_name);
934
935         term_gen->index_text (text, 1, prefix);
936         message->termpos = term_gen->get_termpos ();
937     }
938
939     term_gen->index_text (text);
940
941     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
942 }
943
944 /* Remove a name:value term from 'message', (the actual term will be
945  * encoded by prefixing the value with a short prefix). See
946  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
947  * names to prefix values.
948  *
949  * This change will not be reflected in the database until the next
950  * call to _notmuch_message_sync. */
951 notmuch_private_status_t
952 _notmuch_message_remove_term (notmuch_message_t *message,
953                               const char *prefix_name,
954                               const char *value)
955 {
956     char *term;
957
958     if (value == NULL)
959         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
960
961     term = talloc_asprintf (message, "%s%s",
962                             _find_prefix (prefix_name), value);
963
964     if (strlen (term) > NOTMUCH_TERM_MAX)
965         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
966
967     try {
968         message->doc.remove_term (term);
969     } catch (const Xapian::InvalidArgumentError) {
970         /* We'll let the philosopher's try to wrestle with the
971          * question of whether failing to remove that which was not
972          * there in the first place is failure. For us, we'll silently
973          * consider it all good. */
974     }
975
976     talloc_free (term);
977
978     _notmuch_message_invalidate_metadata (message, prefix_name);
979
980     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
981 }
982
983 notmuch_status_t
984 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
985 {
986     notmuch_private_status_t private_status;
987     notmuch_status_t status;
988
989     status = _notmuch_database_ensure_writable (message->notmuch);
990     if (status)
991         return status;
992
993     if (tag == NULL)
994         return NOTMUCH_STATUS_NULL_POINTER;
995
996     if (strlen (tag) > NOTMUCH_TAG_MAX)
997         return NOTMUCH_STATUS_TAG_TOO_LONG;
998
999     private_status = _notmuch_message_add_term (message, "tag", tag);
1000     if (private_status) {
1001         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
1002                         private_status);
1003     }
1004
1005     if (! message->frozen)
1006         _notmuch_message_sync (message);
1007
1008     return NOTMUCH_STATUS_SUCCESS;
1009 }
1010
1011 notmuch_status_t
1012 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1013 {
1014     notmuch_private_status_t private_status;
1015     notmuch_status_t status;
1016
1017     status = _notmuch_database_ensure_writable (message->notmuch);
1018     if (status)
1019         return status;
1020
1021     if (tag == NULL)
1022         return NOTMUCH_STATUS_NULL_POINTER;
1023
1024     if (strlen (tag) > NOTMUCH_TAG_MAX)
1025         return NOTMUCH_STATUS_TAG_TOO_LONG;
1026
1027     private_status = _notmuch_message_remove_term (message, "tag", tag);
1028     if (private_status) {
1029         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1030                         private_status);
1031     }
1032
1033     if (! message->frozen)
1034         _notmuch_message_sync (message);
1035
1036     return NOTMUCH_STATUS_SUCCESS;
1037 }
1038
1039 /* Is the given filename within a maildir directory?
1040  *
1041  * Specifically, is the final directory component of 'filename' either
1042  * "cur" or "new". If so, return a pointer to that final directory
1043  * component within 'filename'. If not, return NULL.
1044  *
1045  * A non-NULL return value is guaranteed to be a valid string pointer
1046  * pointing to the characters "new/" or "cur/", (but not
1047  * NUL-terminated).
1048  */
1049 static const char *
1050 _filename_is_in_maildir (const char *filename)
1051 {
1052     const char *slash, *dir = NULL;
1053
1054     /* Find the last '/' separating directory from filename. */
1055     slash = strrchr (filename, '/');
1056     if (slash == NULL)
1057         return NULL;
1058
1059     /* Jump back 4 characters to where the previous '/' will be if the
1060      * directory is named "cur" or "new". */
1061     if (slash - filename < 4)
1062         return NULL;
1063
1064     slash -= 4;
1065
1066     if (*slash != '/')
1067         return NULL;
1068
1069     dir = slash + 1;
1070
1071     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1072         STRNCMP_LITERAL (dir, "new/") == 0)
1073     {
1074         return dir;
1075     }
1076
1077     return NULL;
1078 }
1079
1080 notmuch_status_t
1081 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1082 {
1083     const char *flags;
1084     notmuch_status_t status;
1085     notmuch_filenames_t *filenames;
1086     const char *filename, *dir;
1087     char *combined_flags = talloc_strdup (message, "");
1088     unsigned i;
1089     int seen_maildir_info = 0;
1090
1091     for (filenames = notmuch_message_get_filenames (message);
1092          notmuch_filenames_valid (filenames);
1093          notmuch_filenames_move_to_next (filenames))
1094     {
1095         filename = notmuch_filenames_get (filenames);
1096         dir = _filename_is_in_maildir (filename);
1097
1098         if (! dir)
1099             continue;
1100
1101         flags = strstr (filename, ":2,");
1102         if (flags) {
1103             seen_maildir_info = 1;
1104             flags += 3;
1105             combined_flags = talloc_strdup_append (combined_flags, flags);
1106         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1107             /* Messages are delivered to new/ with no "info" part, but
1108              * they effectively have default maildir flags.  According
1109              * to the spec, we should ignore the info part for
1110              * messages in new/, but some MUAs (mutt) can set maildir
1111              * flags on messages in new/, so we're liberal in what we
1112              * accept. */
1113             seen_maildir_info = 1;
1114         }
1115     }
1116
1117     /* If none of the filenames have any maildir info field (not even
1118      * an empty info with no flags set) then there's no information to
1119      * go on, so do nothing. */
1120     if (! seen_maildir_info)
1121         return NOTMUCH_STATUS_SUCCESS;
1122
1123     status = notmuch_message_freeze (message);
1124     if (status)
1125         return status;
1126
1127     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
1128         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
1129             ^ 
1130             flag2tag[i].inverse)
1131         {
1132             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1133         } else {
1134             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1135         }
1136         if (status)
1137             return status;
1138     }
1139     status = notmuch_message_thaw (message);
1140
1141     talloc_free (combined_flags);
1142
1143     return status;
1144 }
1145
1146 /* From the set of tags on 'message' and the flag2tag table, compute a
1147  * set of maildir-flag actions to be taken, (flags that should be
1148  * either set or cleared).
1149  *
1150  * The result is returned as two talloced strings: to_set, and to_clear
1151  */
1152 static void
1153 _get_maildir_flag_actions (notmuch_message_t *message,
1154                            char **to_set_ret,
1155                            char **to_clear_ret)
1156 {
1157     char *to_set, *to_clear;
1158     notmuch_tags_t *tags;
1159     const char *tag;
1160     unsigned i;
1161
1162     to_set = talloc_strdup (message, "");
1163     to_clear = talloc_strdup (message, "");
1164
1165     /* First, find flags for all set tags. */
1166     for (tags = notmuch_message_get_tags (message);
1167          notmuch_tags_valid (tags);
1168          notmuch_tags_move_to_next (tags))
1169     {
1170         tag = notmuch_tags_get (tags);
1171
1172         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1173             if (strcmp (tag, flag2tag[i].tag) == 0) {
1174                 if (flag2tag[i].inverse)
1175                     to_clear = talloc_asprintf_append (to_clear,
1176                                                        "%c",
1177                                                        flag2tag[i].flag);
1178                 else
1179                     to_set = talloc_asprintf_append (to_set,
1180                                                      "%c",
1181                                                      flag2tag[i].flag);
1182             }
1183         }
1184     }
1185
1186     /* Then, find the flags for all tags not present. */
1187     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1188         if (flag2tag[i].inverse) {
1189             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1190                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1191         } else {
1192             if (strchr (to_set, flag2tag[i].flag) == NULL)
1193                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1194         }
1195     }
1196
1197     *to_set_ret = to_set;
1198     *to_clear_ret = to_clear;
1199 }
1200
1201 /* Given 'filename' and a set of maildir flags to set and to clear,
1202  * compute the new maildir filename.
1203  *
1204  * If the existing filename is in the directory "new", the new
1205  * filename will be in the directory "cur", except for the case when
1206  * no flags are changed and the existing filename does not contain
1207  * maildir info (starting with ",2:").
1208  *
1209  * After a sequence of ":2," in the filename, any subsequent
1210  * single-character flags will be added or removed according to the
1211  * characters in flags_to_set and flags_to_clear. Any existing flags
1212  * not mentioned in either string will remain. The final list of flags
1213  * will be in ASCII order.
1214  *
1215  * If the original flags seem invalid, (repeated characters or
1216  * non-ASCII ordering of flags), this function will return NULL
1217  * (meaning that renaming would not be safe and should not occur).
1218  */
1219 static char*
1220 _new_maildir_filename (void *ctx,
1221                        const char *filename,
1222                        const char *flags_to_set,
1223                        const char *flags_to_clear)
1224 {
1225     const char *info, *flags;
1226     unsigned int flag, last_flag;
1227     char *filename_new, *dir;
1228     char flag_map[128];
1229     int flags_in_map = 0;
1230     notmuch_bool_t flags_changed = FALSE;
1231     unsigned int i;
1232     char *s;
1233
1234     memset (flag_map, 0, sizeof (flag_map));
1235
1236     info = strstr (filename, ":2,");
1237
1238     if (info == NULL) {
1239         info = filename + strlen(filename);
1240     } else {
1241         /* Loop through existing flags in filename. */
1242         for (flags = info + 3, last_flag = 0;
1243              *flags;
1244              last_flag = flag, flags++)
1245         {
1246             flag = *flags;
1247
1248             /* Original flags not in ASCII order. Abort. */
1249             if (flag < last_flag)
1250                 return NULL;
1251
1252             /* Non-ASCII flag. Abort. */
1253             if (flag > sizeof(flag_map) - 1)
1254                 return NULL;
1255
1256             /* Repeated flag value. Abort. */
1257             if (flag_map[flag])
1258                 return NULL;
1259
1260             flag_map[flag] = 1;
1261             flags_in_map++;
1262         }
1263     }
1264
1265     /* Then set and clear our flags from tags. */
1266     for (flags = flags_to_set; *flags; flags++) {
1267         flag = *flags;
1268         if (flag_map[flag] == 0) {
1269             flag_map[flag] = 1;
1270             flags_in_map++;
1271             flags_changed = TRUE;
1272         }
1273     }
1274
1275     for (flags = flags_to_clear; *flags; flags++) {
1276         flag = *flags;
1277         if (flag_map[flag]) {
1278             flag_map[flag] = 0;
1279             flags_in_map--;
1280             flags_changed = TRUE;
1281         }
1282     }
1283
1284     /* Messages in new/ without maildir info can be kept in new/ if no
1285      * flags have changed. */
1286     dir = (char *) _filename_is_in_maildir (filename);
1287     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && !*info && !flags_changed)
1288         return talloc_strdup (ctx, filename);
1289
1290     filename_new = (char *) talloc_size (ctx,
1291                                          info - filename +
1292                                          strlen (":2,") + flags_in_map + 1);
1293     if (unlikely (filename_new == NULL))
1294         return NULL;
1295
1296     strncpy (filename_new, filename, info - filename);
1297     filename_new[info - filename] = '\0';
1298
1299     strcat (filename_new, ":2,");
1300
1301     s = filename_new + strlen (filename_new);
1302     for (i = 0; i < sizeof (flag_map); i++)
1303     {
1304         if (flag_map[i]) {
1305             *s = i;
1306             s++;
1307         }
1308     }
1309     *s = '\0';
1310
1311     /* If message is in new/ move it under cur/. */
1312     dir = (char *) _filename_is_in_maildir (filename_new);
1313     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1314         memcpy (dir, "cur/", 4);
1315
1316     return filename_new;
1317 }
1318
1319 notmuch_status_t
1320 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1321 {
1322     notmuch_filenames_t *filenames;
1323     const char *filename;
1324     char *filename_new;
1325     char *to_set, *to_clear;
1326     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1327
1328     _get_maildir_flag_actions (message, &to_set, &to_clear);
1329
1330     for (filenames = notmuch_message_get_filenames (message);
1331          notmuch_filenames_valid (filenames);
1332          notmuch_filenames_move_to_next (filenames))
1333     {
1334         filename = notmuch_filenames_get (filenames);
1335
1336         if (! _filename_is_in_maildir (filename))
1337             continue;
1338
1339         filename_new = _new_maildir_filename (message, filename,
1340                                               to_set, to_clear);
1341         if (filename_new == NULL)
1342             continue;
1343
1344         if (strcmp (filename, filename_new)) {
1345             int err;
1346             notmuch_status_t new_status;
1347
1348             err = rename (filename, filename_new);
1349             if (err)
1350                 continue;
1351
1352             new_status = _notmuch_message_remove_filename (message,
1353                                                            filename);
1354             /* Hold on to only the first error. */
1355             if (! status && new_status
1356                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
1357                 status = new_status;
1358                 continue;
1359             }
1360
1361             new_status = _notmuch_message_add_filename (message,
1362                                                         filename_new);
1363             /* Hold on to only the first error. */
1364             if (! status && new_status) {
1365                 status = new_status;
1366                 continue;
1367             }
1368
1369             _notmuch_message_sync (message);
1370         }
1371
1372         talloc_free (filename_new);
1373     }
1374
1375     talloc_free (to_set);
1376     talloc_free (to_clear);
1377
1378     return NOTMUCH_STATUS_SUCCESS;
1379 }
1380
1381 notmuch_status_t
1382 notmuch_message_remove_all_tags (notmuch_message_t *message)
1383 {
1384     notmuch_private_status_t private_status;
1385     notmuch_status_t status;
1386     notmuch_tags_t *tags;
1387     const char *tag;
1388
1389     status = _notmuch_database_ensure_writable (message->notmuch);
1390     if (status)
1391         return status;
1392
1393     for (tags = notmuch_message_get_tags (message);
1394          notmuch_tags_valid (tags);
1395          notmuch_tags_move_to_next (tags))
1396     {
1397         tag = notmuch_tags_get (tags);
1398
1399         private_status = _notmuch_message_remove_term (message, "tag", tag);
1400         if (private_status) {
1401             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1402                             private_status);
1403         }
1404     }
1405
1406     if (! message->frozen)
1407         _notmuch_message_sync (message);
1408
1409     talloc_free (tags);
1410     return NOTMUCH_STATUS_SUCCESS;
1411 }
1412
1413 notmuch_status_t
1414 notmuch_message_freeze (notmuch_message_t *message)
1415 {
1416     notmuch_status_t status;
1417
1418     status = _notmuch_database_ensure_writable (message->notmuch);
1419     if (status)
1420         return status;
1421
1422     message->frozen++;
1423
1424     return NOTMUCH_STATUS_SUCCESS;
1425 }
1426
1427 notmuch_status_t
1428 notmuch_message_thaw (notmuch_message_t *message)
1429 {
1430     notmuch_status_t status;
1431
1432     status = _notmuch_database_ensure_writable (message->notmuch);
1433     if (status)
1434         return status;
1435
1436     if (message->frozen > 0) {
1437         message->frozen--;
1438         if (message->frozen == 0)
1439             _notmuch_message_sync (message);
1440         return NOTMUCH_STATUS_SUCCESS;
1441     } else {
1442         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1443     }
1444 }
1445
1446 void
1447 notmuch_message_destroy (notmuch_message_t *message)
1448 {
1449     talloc_free (message);
1450 }