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