]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
9bafff0bb3c83fa67df50176901cfe66070568ca
[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 https://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 #include "message-private.h"
24
25 #include <stdint.h>
26
27 #include <gmime/gmime.h>
28
29 struct visible _notmuch_message {
30     notmuch_database_t *notmuch;
31     Xapian::docid doc_id;
32     int frozen;
33     char *message_id;
34     char *thread_id;
35     char *in_reply_to;
36     notmuch_string_list_t *tag_list;
37     notmuch_string_list_t *filename_term_list;
38     notmuch_string_list_t *filename_list;
39     char *author;
40     notmuch_message_file_t *message_file;
41     notmuch_string_list_t *property_term_list;
42     notmuch_string_map_t *property_map;
43     notmuch_message_list_t *replies;
44     unsigned long flags;
45     /* For flags that are initialized on-demand, lazy_flags indicates
46      * if each flag has been initialized. */
47     unsigned long lazy_flags;
48
49     /* Message document modified since last sync */
50     notmuch_bool_t modified;
51
52     /* last view of database the struct is synced with */
53     unsigned long last_view;
54
55     Xapian::Document doc;
56     Xapian::termcount termpos;
57 };
58
59 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
60
61 struct maildir_flag_tag {
62     char flag;
63     const char *tag;
64     notmuch_bool_t inverse;
65 };
66
67 /* ASCII ordered table of Maildir flags and associated tags */
68 static struct maildir_flag_tag flag2tag[] = {
69     { 'D', "draft",   FALSE},
70     { 'F', "flagged", FALSE},
71     { 'P', "passed",  FALSE},
72     { 'R', "replied", FALSE},
73     { 'S', "unread",  TRUE }
74 };
75
76 /* We end up having to call the destructor explicitly because we had
77  * to use "placement new" in order to initialize C++ objects within a
78  * block that we allocated with talloc. So C++ is making talloc
79  * slightly less simple to use, (we wouldn't need
80  * talloc_set_destructor at all otherwise).
81  */
82 static int
83 _notmuch_message_destructor (notmuch_message_t *message)
84 {
85     message->doc.~Document ();
86
87     return 0;
88 }
89
90 static notmuch_message_t *
91 _notmuch_message_create_for_document (const void *talloc_owner,
92                                       notmuch_database_t *notmuch,
93                                       unsigned int doc_id,
94                                       Xapian::Document doc,
95                                       notmuch_private_status_t *status)
96 {
97     notmuch_message_t *message;
98
99     if (status)
100         *status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
101
102     message = talloc (talloc_owner, notmuch_message_t);
103     if (unlikely (message == NULL)) {
104         if (status)
105             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
106         return NULL;
107     }
108
109     message->notmuch = notmuch;
110     message->doc_id = doc_id;
111
112     message->frozen = 0;
113     message->flags = 0;
114     message->lazy_flags = 0;
115
116     /* the message is initially not synchronized with Xapian */
117     message->last_view = 0;
118
119     /* Each of these will be lazily created as needed. */
120     message->message_id = NULL;
121     message->thread_id = NULL;
122     message->in_reply_to = NULL;
123     message->tag_list = NULL;
124     message->filename_term_list = NULL;
125     message->filename_list = NULL;
126     message->message_file = NULL;
127     message->author = NULL;
128     message->property_term_list = NULL;
129     message->property_map = NULL;
130
131     message->replies = _notmuch_message_list_create (message);
132     if (unlikely (message->replies == NULL)) {
133         if (status)
134             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
135         return NULL;
136     }
137
138     /* This is C++'s creepy "placement new", which is really just an
139      * ugly way to call a constructor for a pre-allocated object. So
140      * it's really not an error to not be checking for OUT_OF_MEMORY
141      * here, since this "new" isn't actually allocating memory. This
142      * is language-design comedy of the wrong kind. */
143
144     new (&message->doc) Xapian::Document;
145
146     talloc_set_destructor (message, _notmuch_message_destructor);
147
148     message->doc = doc;
149     message->termpos = 0;
150
151     return message;
152 }
153
154 /* Create a new notmuch_message_t object for an existing document in
155  * the database.
156  *
157  * Here, 'talloc owner' is an optional talloc context to which the new
158  * message will belong. This allows for the caller to not bother
159  * calling notmuch_message_destroy on the message, and know that all
160  * memory will be reclaimed when 'talloc_owner' is freed. The caller
161  * still can call notmuch_message_destroy when finished with the
162  * message if desired.
163  *
164  * The 'talloc_owner' argument can also be NULL, in which case the
165  * caller *is* responsible for calling notmuch_message_destroy.
166  *
167  * If no document exists in the database with document ID of 'doc_id'
168  * then this function returns NULL and optionally sets *status to
169  * NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND.
170  *
171  * This function can also fail to due lack of available memory,
172  * returning NULL and optionally setting *status to
173  * NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY.
174  *
175  * The caller can pass NULL for status if uninterested in
176  * distinguishing these two cases.
177  */
178 notmuch_message_t *
179 _notmuch_message_create (const void *talloc_owner,
180                          notmuch_database_t *notmuch,
181                          unsigned int doc_id,
182                          notmuch_private_status_t *status)
183 {
184     Xapian::Document doc;
185
186     try {
187         doc = notmuch->xapian_db->get_document (doc_id);
188     } catch (const Xapian::DocNotFoundError &error) {
189         if (status)
190             *status = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
191         return NULL;
192     }
193
194     return _notmuch_message_create_for_document (talloc_owner, notmuch,
195                                                  doc_id, doc, status);
196 }
197
198 /* Create a new notmuch_message_t object for a specific message ID,
199  * (which may or may not already exist in the database).
200  *
201  * The 'notmuch' database will be the talloc owner of the returned
202  * message.
203  *
204  * This function returns a valid notmuch_message_t whether or not
205  * there is already a document in the database with the given message
206  * ID. These two cases can be distinguished by the value of *status:
207  *
208  *
209  *   NOTMUCH_PRIVATE_STATUS_SUCCESS:
210  *
211  *     There is already a document with message ID 'message_id' in the
212  *     database. The returned message can be used to query/modify the
213  *     document. The message may be a ghost message.
214  *
215  *   NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND:
216  *
217  *     No document with 'message_id' exists in the database. The
218  *     returned message contains a newly created document (not yet
219  *     added to the database) and a document ID that is known not to
220  *     exist in the database.  This message is "blank"; that is, it
221  *     contains only a message ID and no other metadata. The caller
222  *     can modify the message, and a call to _notmuch_message_sync
223  *     will add the document to the database.
224  *
225  * If an error occurs, this function will return NULL and *status
226  * will be set as appropriate. (The status pointer argument must
227  * not be NULL.)
228  */
229 notmuch_message_t *
230 _notmuch_message_create_for_message_id (notmuch_database_t *notmuch,
231                                         const char *message_id,
232                                         notmuch_private_status_t *status_ret)
233 {
234     notmuch_message_t *message;
235     Xapian::Document doc;
236     unsigned int doc_id;
237     char *term;
238
239     *status_ret = (notmuch_private_status_t) notmuch_database_find_message (notmuch,
240                                                                             message_id,
241                                                                             &message);
242     if (message)
243         return talloc_steal (notmuch, message);
244     else if (*status_ret)
245         return NULL;
246
247     /* If the message ID is too long, substitute its sha1 instead. */
248     if (strlen (message_id) > NOTMUCH_MESSAGE_ID_MAX)
249         message_id = _notmuch_message_id_compressed (message, message_id);
250
251     term = talloc_asprintf (NULL, "%s%s",
252                             _find_prefix ("id"), message_id);
253     if (term == NULL) {
254         *status_ret = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
255         return NULL;
256     }
257
258     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
259         INTERNAL_ERROR ("Failure to ensure database is writable.");
260
261     try {
262         doc.add_term (term, 0);
263         talloc_free (term);
264
265         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
266
267         doc_id = _notmuch_database_generate_doc_id (notmuch);
268     } catch (const Xapian::Error &error) {
269         _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred creating message: %s\n",
270                  error.get_msg().c_str());
271         notmuch->exception_reported = TRUE;
272         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
273         return NULL;
274     }
275
276     message = _notmuch_message_create_for_document (notmuch, notmuch,
277                                                     doc_id, doc, status_ret);
278
279     /* We want to inform the caller that we had to create a new
280      * document. */
281     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
282         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
283
284     return message;
285 }
286
287 static char *
288 _notmuch_message_get_term (notmuch_message_t *message,
289                            Xapian::TermIterator &i, Xapian::TermIterator &end,
290                            const char *prefix)
291 {
292     int prefix_len = strlen (prefix);
293     char *value;
294
295     i.skip_to (prefix);
296
297     if (i == end)
298         return NULL;
299
300     const std::string &term = *i;
301     if (strncmp (term.c_str(), prefix, prefix_len))
302         return NULL;
303
304     value = talloc_strdup (message, term.c_str() + prefix_len);
305
306 #if DEBUG_DATABASE_SANITY
307     i++;
308
309     if (i != end && strncmp ((*i).c_str (), prefix, prefix_len) == 0) {
310         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate %s terms: %s and %s\n",
311                         message->doc_id, prefix, value,
312                         (*i).c_str () + prefix_len);
313     }
314 #endif
315
316     return value;
317 }
318
319 static void
320 _notmuch_message_ensure_metadata (notmuch_message_t *message)
321 {
322     Xapian::TermIterator i, end;
323
324     const char *thread_prefix = _find_prefix ("thread"),
325         *tag_prefix = _find_prefix ("tag"),
326         *id_prefix = _find_prefix ("id"),
327         *type_prefix = _find_prefix ("type"),
328         *filename_prefix = _find_prefix ("file-direntry"),
329         *property_prefix = _find_prefix ("property"),
330         *replyto_prefix = _find_prefix ("replyto");
331
332     /* We do this all in a single pass because Xapian decompresses the
333      * term list every time you iterate over it.  Thus, while this is
334      * slightly more costly than looking up individual fields if only
335      * one field of the message object is actually used, it's a huge
336      * win as more fields are used. */
337     for (int count=0; count < 3; count++) {
338         try {
339             i = message->doc.termlist_begin ();
340             end = message->doc.termlist_end ();
341
342             /* Get thread */
343             if (!message->thread_id)
344                 message->thread_id =
345                     _notmuch_message_get_term (message, i, end, thread_prefix);
346
347             /* Get tags */
348             assert (strcmp (thread_prefix, tag_prefix) < 0);
349             if (!message->tag_list) {
350                 message->tag_list =
351                     _notmuch_database_get_terms_with_prefix (message, i, end,
352                                                              tag_prefix);
353                 _notmuch_string_list_sort (message->tag_list);
354             }
355
356             /* Get id */
357             assert (strcmp (tag_prefix, id_prefix) < 0);
358             if (!message->message_id)
359                 message->message_id =
360                     _notmuch_message_get_term (message, i, end, id_prefix);
361
362             /* Get document type */
363             assert (strcmp (id_prefix, type_prefix) < 0);
364             if (! NOTMUCH_TEST_BIT (message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST)) {
365                 i.skip_to (type_prefix);
366                 /* "T" is the prefix "type" fields.  See
367                  * BOOLEAN_PREFIX_INTERNAL. */
368                 if (*i == "Tmail")
369                     NOTMUCH_CLEAR_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
370                 else if (*i == "Tghost")
371                     NOTMUCH_SET_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
372                 else
373                     INTERNAL_ERROR ("Message without type term");
374                 NOTMUCH_SET_BIT (&message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST);
375             }
376
377             /* Get filename list.  Here we get only the terms.  We lazily
378              * expand them to full file names when needed in
379              * _notmuch_message_ensure_filename_list. */
380             assert (strcmp (type_prefix, filename_prefix) < 0);
381             if (!message->filename_term_list && !message->filename_list)
382                 message->filename_term_list =
383                     _notmuch_database_get_terms_with_prefix (message, i, end,
384                                                              filename_prefix);
385
386
387             /* Get property terms. Mimic the setup with filenames above */
388             assert (strcmp (filename_prefix, property_prefix) < 0);
389             if (!message->property_map && !message->property_term_list)
390                 message->property_term_list =
391                     _notmuch_database_get_terms_with_prefix (message, i, end,
392                                                          property_prefix);
393
394             /* Get reply to */
395             assert (strcmp (property_prefix, replyto_prefix) < 0);
396             if (!message->in_reply_to)
397                 message->in_reply_to =
398                     _notmuch_message_get_term (message, i, end, replyto_prefix);
399
400
401             /* It's perfectly valid for a message to have no In-Reply-To
402              * header. For these cases, we return an empty string. */
403             if (!message->in_reply_to)
404                 message->in_reply_to = talloc_strdup (message, "");
405
406             /* all the way without an exception */
407             break;
408         } catch (const Xapian::DatabaseModifiedError &error) {
409             notmuch_status_t status = _notmuch_database_reopen (message->notmuch);
410             if (status != NOTMUCH_STATUS_SUCCESS)
411                 INTERNAL_ERROR ("unhandled error from notmuch_database_reopen: %s\n",
412                                 notmuch_status_to_string (status));
413         } catch (const Xapian::Error &error) {
414             INTERNAL_ERROR ("A Xapian exception occurred fetching message metadata: %s\n",
415                             error.get_msg().c_str());
416         }
417     }
418     message->last_view = message->notmuch->view;
419 }
420
421 void
422 _notmuch_message_invalidate_metadata (notmuch_message_t *message,
423                                       const char *prefix_name)
424 {
425     if (strcmp ("thread", prefix_name) == 0) {
426         talloc_free (message->thread_id);
427         message->thread_id = NULL;
428     }
429
430     if (strcmp ("tag", prefix_name) == 0) {
431         talloc_unlink (message, message->tag_list);
432         message->tag_list = NULL;
433     }
434
435     if (strcmp ("type", prefix_name) == 0) {
436         NOTMUCH_CLEAR_BIT (&message->flags, NOTMUCH_MESSAGE_FLAG_GHOST);
437         NOTMUCH_CLEAR_BIT (&message->lazy_flags, NOTMUCH_MESSAGE_FLAG_GHOST);
438     }
439
440     if (strcmp ("file-direntry", prefix_name) == 0) {
441         talloc_free (message->filename_term_list);
442         talloc_free (message->filename_list);
443         message->filename_term_list = message->filename_list = NULL;
444     }
445
446     if (strcmp ("property", prefix_name) == 0) {
447
448         if (message->property_term_list)
449             talloc_free (message->property_term_list);
450         message->property_term_list = NULL;
451
452         if (message->property_map)
453             talloc_unlink (message, message->property_map);
454
455         message->property_map = NULL;
456     }
457
458     if (strcmp ("replyto", prefix_name) == 0) {
459         talloc_free (message->in_reply_to);
460         message->in_reply_to = NULL;
461     }
462 }
463
464 unsigned int
465 _notmuch_message_get_doc_id (notmuch_message_t *message)
466 {
467     return message->doc_id;
468 }
469
470 const char *
471 notmuch_message_get_message_id (notmuch_message_t *message)
472 {
473     if (!message->message_id)
474         _notmuch_message_ensure_metadata (message);
475     if (!message->message_id)
476         INTERNAL_ERROR ("Message with document ID of %u has no message ID.\n",
477                         message->doc_id);
478     return message->message_id;
479 }
480
481 static void
482 _notmuch_message_ensure_message_file (notmuch_message_t *message)
483 {
484     const char *filename;
485
486     if (message->message_file)
487         return;
488
489     filename = notmuch_message_get_filename (message);
490     if (unlikely (filename == NULL))
491         return;
492
493     message->message_file = _notmuch_message_file_open_ctx (
494         _notmuch_message_database (message), message, filename);
495 }
496
497 const char *
498 notmuch_message_get_header (notmuch_message_t *message, const char *header)
499 {
500     Xapian::valueno slot = Xapian::BAD_VALUENO;
501
502     /* Fetch header from the appropriate xapian value field if
503      * available */
504     if (strcasecmp (header, "from") == 0)
505         slot = NOTMUCH_VALUE_FROM;
506     else if (strcasecmp (header, "subject") == 0)
507         slot = NOTMUCH_VALUE_SUBJECT;
508     else if (strcasecmp (header, "message-id") == 0)
509         slot = NOTMUCH_VALUE_MESSAGE_ID;
510
511     if (slot != Xapian::BAD_VALUENO) {
512         try {
513             std::string value = message->doc.get_value (slot);
514
515             /* If we have NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES, then
516              * empty values indicate empty headers.  If we don't, then
517              * it could just mean we didn't record the header. */
518             if ((message->notmuch->features &
519                  NOTMUCH_FEATURE_FROM_SUBJECT_ID_VALUES) ||
520                 ! value.empty())
521                 return talloc_strdup (message, value.c_str ());
522
523         } catch (Xapian::Error &error) {
524             _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred when reading header: %s\n",
525                      error.get_msg().c_str());
526             message->notmuch->exception_reported = TRUE;
527             return NULL;
528         }
529     }
530
531     /* Otherwise fall back to parsing the file */
532     _notmuch_message_ensure_message_file (message);
533     if (message->message_file == NULL)
534         return NULL;
535
536     return _notmuch_message_file_get_header (message->message_file, header);
537 }
538
539 /* Return the message ID from the In-Reply-To header of 'message'.
540  *
541  * Returns an empty string ("") if 'message' has no In-Reply-To
542  * header.
543  *
544  * Returns NULL if any error occurs.
545  */
546 const char *
547 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
548 {
549     if (!message->in_reply_to)
550         _notmuch_message_ensure_metadata (message);
551     return message->in_reply_to;
552 }
553
554 const char *
555 notmuch_message_get_thread_id (notmuch_message_t *message)
556 {
557     if (!message->thread_id)
558         _notmuch_message_ensure_metadata (message);
559     if (!message->thread_id)
560         INTERNAL_ERROR ("Message with document ID of %u has no thread ID.\n",
561                         message->doc_id);
562     return message->thread_id;
563 }
564
565 void
566 _notmuch_message_add_reply (notmuch_message_t *message,
567                             notmuch_message_t *reply)
568 {
569     _notmuch_message_list_add_message (message->replies, reply);
570 }
571
572 notmuch_messages_t *
573 notmuch_message_get_replies (notmuch_message_t *message)
574 {
575     return _notmuch_messages_create (message->replies);
576 }
577
578 void
579 _notmuch_message_remove_terms (notmuch_message_t *message, const char *prefix)
580 {
581     Xapian::TermIterator i;
582     size_t prefix_len = strlen (prefix);
583
584     while (1) {
585         i = message->doc.termlist_begin ();
586         i.skip_to (prefix);
587
588         /* Terminate loop when no terms remain with desired prefix. */
589         if (i == message->doc.termlist_end () ||
590             strncmp ((*i).c_str (), prefix, prefix_len))
591             break;
592
593         try {
594             message->doc.remove_term ((*i));
595             message->modified = TRUE;
596         } catch (const Xapian::InvalidArgumentError) {
597             /* Ignore failure to remove non-existent term. */
598         }
599     }
600 }
601
602 /* Return true if p points at "new" or "cur". */
603 static bool is_maildir (const char *p)
604 {
605     return strcmp (p, "cur") == 0 || strcmp (p, "new") == 0;
606 }
607
608 /* Add "folder:" term for directory. */
609 static notmuch_status_t
610 _notmuch_message_add_folder_terms (notmuch_message_t *message,
611                                    const char *directory)
612 {
613     char *folder, *last;
614
615     folder = talloc_strdup (NULL, directory);
616     if (! folder)
617         return NOTMUCH_STATUS_OUT_OF_MEMORY;
618
619     /*
620      * If the message file is in a leaf directory named "new" or
621      * "cur", presume maildir and index the parent directory. Thus a
622      * "folder:" prefix search matches messages in the specified
623      * maildir folder, i.e. in the specified directory and its "new"
624      * and "cur" subdirectories.
625      *
626      * Note that this means the "folder:" prefix can't be used for
627      * distinguishing between message files in "new" or "cur". The
628      * "path:" prefix needs to be used for that.
629      *
630      * Note the deliberate difference to _filename_is_in_maildir(). We
631      * don't want to index different things depending on the existence
632      * or non-existence of all maildir sibling directories "new",
633      * "cur", and "tmp". Doing so would be surprising, and difficult
634      * for the user to fix in case all subdirectories were not in
635      * place during indexing.
636      */
637     last = strrchr (folder, '/');
638     if (last) {
639         if (is_maildir (last + 1))
640             *last = '\0';
641     } else if (is_maildir (folder)) {
642         *folder = '\0';
643     }
644
645     _notmuch_message_add_term (message, "folder", folder);
646
647     talloc_free (folder);
648
649     return NOTMUCH_STATUS_SUCCESS;
650 }
651
652 #define RECURSIVE_SUFFIX "/**"
653
654 /* Add "path:" terms for directory. */
655 static notmuch_status_t
656 _notmuch_message_add_path_terms (notmuch_message_t *message,
657                                  const char *directory)
658 {
659     /* Add exact "path:" term. */
660     _notmuch_message_add_term (message, "path", directory);
661
662     if (strlen (directory)) {
663         char *path, *p;
664
665         path = talloc_asprintf (NULL, "%s%s", directory, RECURSIVE_SUFFIX);
666         if (! path)
667             return NOTMUCH_STATUS_OUT_OF_MEMORY;
668
669         /* Add recursive "path:" terms for directory and all parents. */
670         for (p = path + strlen (path) - 1; p > path; p--) {
671             if (*p == '/') {
672                 strcpy (p, RECURSIVE_SUFFIX);
673                 _notmuch_message_add_term (message, "path", path);
674             }
675         }
676
677         talloc_free (path);
678     }
679
680     /* Recursive all-matching path:** for consistency. */
681     _notmuch_message_add_term (message, "path", "**");
682
683     return NOTMUCH_STATUS_SUCCESS;
684 }
685
686 /* Add directory based terms for all filenames of the message. */
687 static notmuch_status_t
688 _notmuch_message_add_directory_terms (void *ctx, notmuch_message_t *message)
689 {
690     const char *direntry_prefix = _find_prefix ("file-direntry");
691     int direntry_prefix_len = strlen (direntry_prefix);
692     Xapian::TermIterator i = message->doc.termlist_begin ();
693     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
694
695     for (i.skip_to (direntry_prefix); i != message->doc.termlist_end (); i++) {
696         unsigned int directory_id;
697         const char *direntry, *directory;
698         char *colon;
699         const std::string &term = *i;
700
701         /* Terminate loop at first term without desired prefix. */
702         if (strncmp (term.c_str (), direntry_prefix, direntry_prefix_len))
703             break;
704
705         /* Indicate that there are filenames remaining. */
706         status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
707
708         direntry = term.c_str ();
709         direntry += direntry_prefix_len;
710
711         directory_id = strtol (direntry, &colon, 10);
712
713         if (colon == NULL || *colon != ':')
714             INTERNAL_ERROR ("malformed direntry");
715
716         directory = _notmuch_database_get_directory_path (ctx,
717                                                           message->notmuch,
718                                                           directory_id);
719
720         _notmuch_message_add_folder_terms (message, directory);
721         _notmuch_message_add_path_terms (message, directory);
722     }
723
724     return status;
725 }
726
727 /* Add an additional 'filename' for 'message'.
728  *
729  * This change will not be reflected in the database until the next
730  * call to _notmuch_message_sync. */
731 notmuch_status_t
732 _notmuch_message_add_filename (notmuch_message_t *message,
733                                const char *filename)
734 {
735     const char *relative, *directory;
736     notmuch_status_t status;
737     void *local = talloc_new (message);
738     char *direntry;
739
740     if (filename == NULL)
741         INTERNAL_ERROR ("Message filename cannot be NULL.");
742
743     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
744         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
745         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
746
747     relative = _notmuch_database_relative_path (message->notmuch, filename);
748
749     status = _notmuch_database_split_path (local, relative, &directory, NULL);
750     if (status)
751         return status;
752
753     status = _notmuch_database_filename_to_direntry (
754         local, message->notmuch, filename, NOTMUCH_FIND_CREATE, &direntry);
755     if (status)
756         return status;
757
758     /* New file-direntry allows navigating to this message with
759      * notmuch_directory_get_child_files() . */
760     _notmuch_message_add_term (message, "file-direntry", direntry);
761
762     _notmuch_message_add_folder_terms (message, directory);
763     _notmuch_message_add_path_terms (message, directory);
764
765     talloc_free (local);
766
767     return NOTMUCH_STATUS_SUCCESS;
768 }
769
770 /* Remove a particular 'filename' from 'message'.
771  *
772  * This change will not be reflected in the database until the next
773  * call to _notmuch_message_sync.
774  *
775  * If this message still has other filenames, returns
776  * NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID.
777  *
778  * Note: This function does not remove a document from the database,
779  * even if the specified filename is the only filename for this
780  * message. For that functionality, see
781  * notmuch_database_remove_message. */
782 notmuch_status_t
783 _notmuch_message_remove_filename (notmuch_message_t *message,
784                                   const char *filename)
785 {
786     void *local = talloc_new (message);
787     char *direntry;
788     notmuch_private_status_t private_status;
789     notmuch_status_t status;
790
791     if (! (message->notmuch->features & NOTMUCH_FEATURE_FILE_TERMS) ||
792         ! (message->notmuch->features & NOTMUCH_FEATURE_BOOL_FOLDER))
793         return NOTMUCH_STATUS_UPGRADE_REQUIRED;
794
795     status = _notmuch_database_filename_to_direntry (
796         local, message->notmuch, filename, NOTMUCH_FIND_LOOKUP, &direntry);
797     if (status || !direntry)
798         return status;
799
800     /* Unlink this file from its parent directory. */
801     private_status = _notmuch_message_remove_term (message,
802                                                    "file-direntry", direntry);
803     status = COERCE_STATUS (private_status,
804                             "Unexpected error from _notmuch_message_remove_term");
805     if (status)
806         return status;
807
808     /* Re-synchronize "folder:" and "path:" terms for this message. */
809
810     /* Remove all "folder:" terms. */
811     _notmuch_message_remove_terms (message, _find_prefix ("folder"));
812
813     /* Remove all "path:" terms. */
814     _notmuch_message_remove_terms (message, _find_prefix ("path"));
815
816     /* Add back terms for all remaining filenames of the message. */
817     status = _notmuch_message_add_directory_terms (local, message);
818
819     talloc_free (local);
820
821     return status;
822 }
823
824 /* Upgrade the "folder:" prefix from V1 to V2. */
825 #define FOLDER_PREFIX_V1       "XFOLDER"
826 #define ZFOLDER_PREFIX_V1      "Z" FOLDER_PREFIX_V1
827 void
828 _notmuch_message_upgrade_folder (notmuch_message_t *message)
829 {
830     /* Remove all old "folder:" terms. */
831     _notmuch_message_remove_terms (message, FOLDER_PREFIX_V1);
832
833     /* Remove all old "folder:" stemmed terms. */
834     _notmuch_message_remove_terms (message, ZFOLDER_PREFIX_V1);
835
836     /* Add new boolean "folder:" and "path:" terms. */
837     _notmuch_message_add_directory_terms (message, message);
838 }
839
840 char *
841 _notmuch_message_talloc_copy_data (notmuch_message_t *message)
842 {
843     return talloc_strdup (message, message->doc.get_data ().c_str ());
844 }
845
846 void
847 _notmuch_message_clear_data (notmuch_message_t *message)
848 {
849     message->doc.set_data ("");
850     message->modified = TRUE;
851 }
852
853 static void
854 _notmuch_message_ensure_filename_list (notmuch_message_t *message)
855 {
856     notmuch_string_node_t *node;
857
858     if (message->filename_list)
859         return;
860
861     if (!message->filename_term_list)
862         _notmuch_message_ensure_metadata (message);
863
864     message->filename_list = _notmuch_string_list_create (message);
865     node = message->filename_term_list->head;
866
867     if (!node) {
868         /* A message document created by an old version of notmuch
869          * (prior to rename support) will have the filename in the
870          * data of the document rather than as a file-direntry term.
871          *
872          * It would be nice to do the upgrade of the document directly
873          * here, but the database is likely open in read-only mode. */
874         const char *data;
875
876         data = message->doc.get_data ().c_str ();
877
878         if (data == NULL)
879             INTERNAL_ERROR ("message with no filename");
880
881         _notmuch_string_list_append (message->filename_list, data);
882
883         return;
884     }
885
886     for (; node; node = node->next) {
887         void *local = talloc_new (message);
888         const char *db_path, *directory, *basename, *filename;
889         char *colon, *direntry = NULL;
890         unsigned int directory_id;
891
892         direntry = node->string;
893
894         directory_id = strtol (direntry, &colon, 10);
895
896         if (colon == NULL || *colon != ':')
897             INTERNAL_ERROR ("malformed direntry");
898
899         basename = colon + 1;
900
901         *colon = '\0';
902
903         db_path = notmuch_database_get_path (message->notmuch);
904
905         directory = _notmuch_database_get_directory_path (local,
906                                                           message->notmuch,
907                                                           directory_id);
908
909         if (strlen (directory))
910             filename = talloc_asprintf (message, "%s/%s/%s",
911                                         db_path, directory, basename);
912         else
913             filename = talloc_asprintf (message, "%s/%s",
914                                         db_path, basename);
915
916         _notmuch_string_list_append (message->filename_list, filename);
917
918         talloc_free (local);
919     }
920
921     talloc_free (message->filename_term_list);
922     message->filename_term_list = NULL;
923 }
924
925 const char *
926 notmuch_message_get_filename (notmuch_message_t *message)
927 {
928     _notmuch_message_ensure_filename_list (message);
929
930     if (message->filename_list == NULL)
931         return NULL;
932
933     if (message->filename_list->head == NULL ||
934         message->filename_list->head->string == NULL)
935     {
936         INTERNAL_ERROR ("message with no filename");
937     }
938
939     return message->filename_list->head->string;
940 }
941
942 notmuch_filenames_t *
943 notmuch_message_get_filenames (notmuch_message_t *message)
944 {
945     _notmuch_message_ensure_filename_list (message);
946
947     return _notmuch_filenames_create (message, message->filename_list);
948 }
949
950 notmuch_bool_t
951 notmuch_message_get_flag (notmuch_message_t *message,
952                           notmuch_message_flag_t flag)
953 {
954     if (flag == NOTMUCH_MESSAGE_FLAG_GHOST &&
955         ! NOTMUCH_TEST_BIT (message->lazy_flags, flag))
956         _notmuch_message_ensure_metadata (message);
957
958     return NOTMUCH_TEST_BIT (message->flags, flag);
959 }
960
961 void
962 notmuch_message_set_flag (notmuch_message_t *message,
963                           notmuch_message_flag_t flag, notmuch_bool_t enable)
964 {
965     if (enable)
966         NOTMUCH_SET_BIT (&message->flags, flag);
967     else
968         NOTMUCH_CLEAR_BIT (&message->flags, flag);
969     NOTMUCH_SET_BIT (&message->lazy_flags, flag);
970 }
971
972 time_t
973 notmuch_message_get_date (notmuch_message_t *message)
974 {
975     std::string value;
976
977     try {
978         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
979     } catch (Xapian::Error &error) {
980         _notmuch_database_log(_notmuch_message_database (message), "A Xapian exception occurred when reading date: %s\n",
981                  error.get_msg().c_str());
982         message->notmuch->exception_reported = TRUE;
983         return 0;
984     }
985
986     if (value.empty ())
987         /* sortable_unserialise is undefined on empty string */
988         return 0;
989     return Xapian::sortable_unserialise (value);
990 }
991
992 notmuch_tags_t *
993 notmuch_message_get_tags (notmuch_message_t *message)
994 {
995     notmuch_tags_t *tags;
996
997     if (!message->tag_list)
998         _notmuch_message_ensure_metadata (message);
999
1000     tags = _notmuch_tags_create (message, message->tag_list);
1001     /* _notmuch_tags_create steals the reference to the tag_list, but
1002      * in this case it's still used by the message, so we add an
1003      * *additional* talloc reference to the list.  As a result, it's
1004      * possible to modify the message tags (which talloc_unlink's the
1005      * current list from the message) while still iterating because
1006      * the iterator will keep the current list alive. */
1007     if (!talloc_reference (message, message->tag_list))
1008         return NULL;
1009
1010     return tags;
1011 }
1012
1013 const char *
1014 _notmuch_message_get_author (notmuch_message_t *message)
1015 {
1016     return message->author;
1017 }
1018
1019 void
1020 _notmuch_message_set_author (notmuch_message_t *message,
1021                             const char *author)
1022 {
1023     if (message->author)
1024         talloc_free(message->author);
1025     message->author = talloc_strdup(message, author);
1026     return;
1027 }
1028
1029 void
1030 _notmuch_message_set_header_values (notmuch_message_t *message,
1031                                     const char *date,
1032                                     const char *from,
1033                                     const char *subject)
1034 {
1035     time_t time_value;
1036
1037     /* GMime really doesn't want to see a NULL date, so protect its
1038      * sensibilities. */
1039     if (date == NULL || *date == '\0')
1040         time_value = 0;
1041     else
1042         time_value = g_mime_utils_header_decode_date (date, NULL);
1043
1044     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
1045                             Xapian::sortable_serialise (time_value));
1046     message->doc.add_value (NOTMUCH_VALUE_FROM, from);
1047     message->doc.add_value (NOTMUCH_VALUE_SUBJECT, subject);
1048     message->modified = TRUE;
1049 }
1050
1051 /* Upgrade a message to support NOTMUCH_FEATURE_LAST_MOD.  The caller
1052  * must call _notmuch_message_sync. */
1053 void
1054 _notmuch_message_upgrade_last_mod (notmuch_message_t *message)
1055 {
1056     /* _notmuch_message_sync will update the last modification
1057      * revision; we just have to ask it to. */
1058     message->modified = TRUE;
1059 }
1060
1061 /* Synchronize changes made to message->doc out into the database. */
1062 void
1063 _notmuch_message_sync (notmuch_message_t *message)
1064 {
1065     Xapian::WritableDatabase *db;
1066
1067     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
1068         return;
1069
1070     if (! message->modified)
1071         return;
1072
1073     /* Update the last modification of this message. */
1074     if (message->notmuch->features & NOTMUCH_FEATURE_LAST_MOD)
1075         /* sortable_serialise gives a reasonably compact encoding,
1076          * which directly translates to reduced IO when scanning the
1077          * value stream.  Since it's built for doubles, we only get 53
1078          * effective bits, but that's still enough for the database to
1079          * last a few centuries at 1 million revisions per second. */
1080         message->doc.add_value (NOTMUCH_VALUE_LAST_MOD,
1081                                 Xapian::sortable_serialise (
1082                                     _notmuch_database_new_revision (
1083                                         message->notmuch)));
1084
1085     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
1086     db->replace_document (message->doc_id, message->doc);
1087     message->modified = FALSE;
1088 }
1089
1090 /* Delete a message document from the database, leaving a ghost
1091  * message in its place */
1092 notmuch_status_t
1093 _notmuch_message_delete (notmuch_message_t *message)
1094 {
1095     notmuch_status_t status;
1096     Xapian::WritableDatabase *db;
1097     const char *mid, *tid, *query_string;
1098     notmuch_message_t *ghost;
1099     notmuch_private_status_t private_status;
1100     notmuch_database_t *notmuch;
1101     notmuch_query_t *query;
1102     unsigned int count = 0;
1103     notmuch_bool_t is_ghost;
1104
1105     mid = notmuch_message_get_message_id (message);
1106     tid = notmuch_message_get_thread_id (message);
1107     notmuch = message->notmuch;
1108
1109     status = _notmuch_database_ensure_writable (message->notmuch);
1110     if (status)
1111         return status;
1112
1113     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1114     db->delete_document (message->doc_id);
1115
1116     /* if this was a ghost to begin with, we are done */
1117     private_status = _notmuch_message_has_term (message, "type", "ghost", &is_ghost);
1118     if (private_status)
1119         return COERCE_STATUS (private_status,
1120                               "Error trying to determine whether message was a ghost");
1121     if (is_ghost)
1122         return NOTMUCH_STATUS_SUCCESS;
1123
1124     query_string = talloc_asprintf (message, "thread:%s", tid);
1125     query = notmuch_query_create (notmuch, query_string);
1126     if (query == NULL)
1127         return NOTMUCH_STATUS_OUT_OF_MEMORY;
1128     status = notmuch_query_count_messages_st (query, &count);
1129     if (status) {
1130         notmuch_query_destroy (query);
1131         return status;
1132     }
1133
1134     if (count > 0) {
1135         /* reintroduce a ghost in its place because there are still
1136          * other active messages in this thread: */
1137         ghost = _notmuch_message_create_for_message_id (notmuch, mid, &private_status);
1138         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1139             private_status = _notmuch_message_initialize_ghost (ghost, tid);
1140             if (! private_status)
1141                 _notmuch_message_sync (ghost);
1142         } else if (private_status == NOTMUCH_PRIVATE_STATUS_SUCCESS) {
1143             /* this is deeply weird, and we should not have gotten
1144                into this state.  is there a better error message to
1145                return here? */
1146             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1147         }
1148
1149         notmuch_message_destroy (ghost);
1150         status = COERCE_STATUS (private_status, "Error converting to ghost message");
1151     } else {
1152         /* the thread is empty; drop all ghost messages from it */
1153         notmuch_messages_t *messages;
1154         status = _notmuch_query_search_documents (query,
1155                                                   "ghost",
1156                                                   &messages);
1157         if (status == NOTMUCH_STATUS_SUCCESS) {
1158             notmuch_status_t last_error = NOTMUCH_STATUS_SUCCESS;
1159             while (notmuch_messages_valid (messages)) {
1160                 message = notmuch_messages_get (messages);
1161                 status = _notmuch_message_delete (message);
1162                 if (status) /* we'll report the last failure we see;
1163                              * if there is more than one failure, we
1164                              * forget about previous ones */
1165                     last_error = status;
1166                 notmuch_message_destroy (message);
1167                 notmuch_messages_move_to_next (messages);
1168             }
1169             status = last_error;
1170         }
1171     }
1172     notmuch_query_destroy (query);
1173     return status;
1174 }
1175
1176 /* Transform a blank message into a ghost message.  The caller must
1177  * _notmuch_message_sync the message. */
1178 notmuch_private_status_t
1179 _notmuch_message_initialize_ghost (notmuch_message_t *message,
1180                                    const char *thread_id)
1181 {
1182     notmuch_private_status_t status;
1183
1184     status = _notmuch_message_add_term (message, "type", "ghost");
1185     if (status)
1186         return status;
1187     status = _notmuch_message_add_term (message, "thread", thread_id);
1188     if (status)
1189         return status;
1190
1191     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1192 }
1193
1194 /* Ensure that 'message' is not holding any file object open. Future
1195  * calls to various functions will still automatically open the
1196  * message file as needed.
1197  */
1198 void
1199 _notmuch_message_close (notmuch_message_t *message)
1200 {
1201     if (message->message_file) {
1202         _notmuch_message_file_close (message->message_file);
1203         message->message_file = NULL;
1204     }
1205 }
1206
1207 /* Add a name:value term to 'message', (the actual term will be
1208  * encoded by prefixing the value with a short prefix). See
1209  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1210  * names to prefix values.
1211  *
1212  * This change will not be reflected in the database until the next
1213  * call to _notmuch_message_sync. */
1214 notmuch_private_status_t
1215 _notmuch_message_add_term (notmuch_message_t *message,
1216                            const char *prefix_name,
1217                            const char *value)
1218 {
1219
1220     char *term;
1221
1222     if (value == NULL)
1223         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1224
1225     term = talloc_asprintf (message, "%s%s",
1226                             _find_prefix (prefix_name), value);
1227
1228     if (strlen (term) > NOTMUCH_TERM_MAX)
1229         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1230
1231     message->doc.add_term (term, 0);
1232     message->modified = TRUE;
1233
1234     talloc_free (term);
1235
1236     _notmuch_message_invalidate_metadata (message, prefix_name);
1237
1238     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1239 }
1240
1241 /* Parse 'text' and add a term to 'message' for each parsed word. Each
1242  * term will be added both prefixed (if prefix_name is not NULL) and
1243  * also non-prefixed). */
1244 notmuch_private_status_t
1245 _notmuch_message_gen_terms (notmuch_message_t *message,
1246                             const char *prefix_name,
1247                             const char *text)
1248 {
1249     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
1250
1251     if (text == NULL)
1252         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1253
1254     term_gen->set_document (message->doc);
1255
1256     if (prefix_name) {
1257         const char *prefix = _find_prefix (prefix_name);
1258
1259         term_gen->set_termpos (message->termpos);
1260         term_gen->index_text (text, 1, prefix);
1261         /* Create a gap between this an the next terms so they don't
1262          * appear to be a phrase. */
1263         message->termpos = term_gen->get_termpos () + 100;
1264
1265         _notmuch_message_invalidate_metadata (message, prefix_name);
1266     }
1267
1268     term_gen->set_termpos (message->termpos);
1269     term_gen->index_text (text);
1270     /* Create a term gap, as above. */
1271     message->termpos = term_gen->get_termpos () + 100;
1272
1273     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1274 }
1275
1276 /* Remove a name:value term from 'message', (the actual term will be
1277  * encoded by prefixing the value with a short prefix). See
1278  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
1279  * names to prefix values.
1280  *
1281  * This change will not be reflected in the database until the next
1282  * call to _notmuch_message_sync. */
1283 notmuch_private_status_t
1284 _notmuch_message_remove_term (notmuch_message_t *message,
1285                               const char *prefix_name,
1286                               const char *value)
1287 {
1288     char *term;
1289
1290     if (value == NULL)
1291         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1292
1293     term = talloc_asprintf (message, "%s%s",
1294                             _find_prefix (prefix_name), value);
1295
1296     if (strlen (term) > NOTMUCH_TERM_MAX)
1297         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1298
1299     try {
1300         message->doc.remove_term (term);
1301         message->modified = TRUE;
1302     } catch (const Xapian::InvalidArgumentError) {
1303         /* We'll let the philosophers try to wrestle with the
1304          * question of whether failing to remove that which was not
1305          * there in the first place is failure. For us, we'll silently
1306          * consider it all good. */
1307     }
1308
1309     talloc_free (term);
1310
1311     _notmuch_message_invalidate_metadata (message, prefix_name);
1312
1313     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
1314 }
1315
1316 notmuch_private_status_t
1317 _notmuch_message_has_term (notmuch_message_t *message,
1318                            const char *prefix_name,
1319                            const char *value,
1320                            notmuch_bool_t *result)
1321 {
1322     char *term;
1323     notmuch_bool_t out = FALSE;
1324     notmuch_private_status_t status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
1325
1326     if (value == NULL)
1327         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
1328
1329     term = talloc_asprintf (message, "%s%s",
1330                             _find_prefix (prefix_name), value);
1331
1332     if (strlen (term) > NOTMUCH_TERM_MAX)
1333         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
1334
1335     try {
1336         /* Look for the exact term */
1337         Xapian::TermIterator i = message->doc.termlist_begin ();
1338         i.skip_to (term);
1339         if (i != message->doc.termlist_end () &&
1340             !strcmp ((*i).c_str (), term))
1341             out = TRUE;
1342     } catch (Xapian::Error &error) {
1343         status = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
1344     }
1345     talloc_free (term);
1346
1347     *result = out;
1348     return status;
1349 }
1350
1351 notmuch_status_t
1352 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
1353 {
1354     notmuch_private_status_t private_status;
1355     notmuch_status_t status;
1356
1357     status = _notmuch_database_ensure_writable (message->notmuch);
1358     if (status)
1359         return status;
1360
1361     if (tag == NULL)
1362         return NOTMUCH_STATUS_NULL_POINTER;
1363
1364     if (strlen (tag) > NOTMUCH_TAG_MAX)
1365         return NOTMUCH_STATUS_TAG_TOO_LONG;
1366
1367     private_status = _notmuch_message_add_term (message, "tag", tag);
1368     if (private_status) {
1369         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
1370                         private_status);
1371     }
1372
1373     if (! message->frozen)
1374         _notmuch_message_sync (message);
1375
1376     return NOTMUCH_STATUS_SUCCESS;
1377 }
1378
1379 notmuch_status_t
1380 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
1381 {
1382     notmuch_private_status_t private_status;
1383     notmuch_status_t status;
1384
1385     status = _notmuch_database_ensure_writable (message->notmuch);
1386     if (status)
1387         return status;
1388
1389     if (tag == NULL)
1390         return NOTMUCH_STATUS_NULL_POINTER;
1391
1392     if (strlen (tag) > NOTMUCH_TAG_MAX)
1393         return NOTMUCH_STATUS_TAG_TOO_LONG;
1394
1395     private_status = _notmuch_message_remove_term (message, "tag", tag);
1396     if (private_status) {
1397         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1398                         private_status);
1399     }
1400
1401     if (! message->frozen)
1402         _notmuch_message_sync (message);
1403
1404     return NOTMUCH_STATUS_SUCCESS;
1405 }
1406
1407 /* Is the given filename within a maildir directory?
1408  *
1409  * Specifically, is the final directory component of 'filename' either
1410  * "cur" or "new". If so, return a pointer to that final directory
1411  * component within 'filename'. If not, return NULL.
1412  *
1413  * A non-NULL return value is guaranteed to be a valid string pointer
1414  * pointing to the characters "new/" or "cur/", (but not
1415  * NUL-terminated).
1416  */
1417 static const char *
1418 _filename_is_in_maildir (const char *filename)
1419 {
1420     const char *slash, *dir = NULL;
1421
1422     /* Find the last '/' separating directory from filename. */
1423     slash = strrchr (filename, '/');
1424     if (slash == NULL)
1425         return NULL;
1426
1427     /* Jump back 4 characters to where the previous '/' will be if the
1428      * directory is named "cur" or "new". */
1429     if (slash - filename < 4)
1430         return NULL;
1431
1432     slash -= 4;
1433
1434     if (*slash != '/')
1435         return NULL;
1436
1437     dir = slash + 1;
1438
1439     if (STRNCMP_LITERAL (dir, "cur/") == 0 ||
1440         STRNCMP_LITERAL (dir, "new/") == 0)
1441     {
1442         return dir;
1443     }
1444
1445     return NULL;
1446 }
1447
1448 notmuch_status_t
1449 notmuch_message_maildir_flags_to_tags (notmuch_message_t *message)
1450 {
1451     const char *flags;
1452     notmuch_status_t status;
1453     notmuch_filenames_t *filenames;
1454     const char *filename, *dir;
1455     char *combined_flags = talloc_strdup (message, "");
1456     unsigned i;
1457     int seen_maildir_info = 0;
1458
1459     for (filenames = notmuch_message_get_filenames (message);
1460          notmuch_filenames_valid (filenames);
1461          notmuch_filenames_move_to_next (filenames))
1462     {
1463         filename = notmuch_filenames_get (filenames);
1464         dir = _filename_is_in_maildir (filename);
1465
1466         if (! dir)
1467             continue;
1468
1469         flags = strstr (filename, ":2,");
1470         if (flags) {
1471             seen_maildir_info = 1;
1472             flags += 3;
1473             combined_flags = talloc_strdup_append (combined_flags, flags);
1474         } else if (STRNCMP_LITERAL (dir, "new/") == 0) {
1475             /* Messages are delivered to new/ with no "info" part, but
1476              * they effectively have default maildir flags.  According
1477              * to the spec, we should ignore the info part for
1478              * messages in new/, but some MUAs (mutt) can set maildir
1479              * flags on messages in new/, so we're liberal in what we
1480              * accept. */
1481             seen_maildir_info = 1;
1482         }
1483     }
1484
1485     /* If none of the filenames have any maildir info field (not even
1486      * an empty info with no flags set) then there's no information to
1487      * go on, so do nothing. */
1488     if (! seen_maildir_info)
1489         return NOTMUCH_STATUS_SUCCESS;
1490
1491     status = notmuch_message_freeze (message);
1492     if (status)
1493         return status;
1494
1495     for (i = 0; i < ARRAY_SIZE(flag2tag); i++) {
1496         if ((strchr (combined_flags, flag2tag[i].flag) != NULL)
1497             ^
1498             flag2tag[i].inverse)
1499         {
1500             status = notmuch_message_add_tag (message, flag2tag[i].tag);
1501         } else {
1502             status = notmuch_message_remove_tag (message, flag2tag[i].tag);
1503         }
1504         if (status)
1505             return status;
1506     }
1507     status = notmuch_message_thaw (message);
1508
1509     talloc_free (combined_flags);
1510
1511     return status;
1512 }
1513
1514 /* From the set of tags on 'message' and the flag2tag table, compute a
1515  * set of maildir-flag actions to be taken, (flags that should be
1516  * either set or cleared).
1517  *
1518  * The result is returned as two talloced strings: to_set, and to_clear
1519  */
1520 static void
1521 _get_maildir_flag_actions (notmuch_message_t *message,
1522                            char **to_set_ret,
1523                            char **to_clear_ret)
1524 {
1525     char *to_set, *to_clear;
1526     notmuch_tags_t *tags;
1527     const char *tag;
1528     unsigned i;
1529
1530     to_set = talloc_strdup (message, "");
1531     to_clear = talloc_strdup (message, "");
1532
1533     /* First, find flags for all set tags. */
1534     for (tags = notmuch_message_get_tags (message);
1535          notmuch_tags_valid (tags);
1536          notmuch_tags_move_to_next (tags))
1537     {
1538         tag = notmuch_tags_get (tags);
1539
1540         for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1541             if (strcmp (tag, flag2tag[i].tag) == 0) {
1542                 if (flag2tag[i].inverse)
1543                     to_clear = talloc_asprintf_append (to_clear,
1544                                                        "%c",
1545                                                        flag2tag[i].flag);
1546                 else
1547                     to_set = talloc_asprintf_append (to_set,
1548                                                      "%c",
1549                                                      flag2tag[i].flag);
1550             }
1551         }
1552     }
1553
1554     /* Then, find the flags for all tags not present. */
1555     for (i = 0; i < ARRAY_SIZE (flag2tag); i++) {
1556         if (flag2tag[i].inverse) {
1557             if (strchr (to_clear, flag2tag[i].flag) == NULL)
1558                 to_set = talloc_asprintf_append (to_set, "%c", flag2tag[i].flag);
1559         } else {
1560             if (strchr (to_set, flag2tag[i].flag) == NULL)
1561                 to_clear = talloc_asprintf_append (to_clear, "%c", flag2tag[i].flag);
1562         }
1563     }
1564
1565     *to_set_ret = to_set;
1566     *to_clear_ret = to_clear;
1567 }
1568
1569 /* Given 'filename' and a set of maildir flags to set and to clear,
1570  * compute the new maildir filename.
1571  *
1572  * If the existing filename is in the directory "new", the new
1573  * filename will be in the directory "cur", except for the case when
1574  * no flags are changed and the existing filename does not contain
1575  * maildir info (starting with ",2:").
1576  *
1577  * After a sequence of ":2," in the filename, any subsequent
1578  * single-character flags will be added or removed according to the
1579  * characters in flags_to_set and flags_to_clear. Any existing flags
1580  * not mentioned in either string will remain. The final list of flags
1581  * will be in ASCII order.
1582  *
1583  * If the original flags seem invalid, (repeated characters or
1584  * non-ASCII ordering of flags), this function will return NULL
1585  * (meaning that renaming would not be safe and should not occur).
1586  */
1587 static char*
1588 _new_maildir_filename (void *ctx,
1589                        const char *filename,
1590                        const char *flags_to_set,
1591                        const char *flags_to_clear)
1592 {
1593     const char *info, *flags;
1594     unsigned int flag, last_flag;
1595     char *filename_new, *dir;
1596     char flag_map[128];
1597     int flags_in_map = 0;
1598     notmuch_bool_t flags_changed = FALSE;
1599     unsigned int i;
1600     char *s;
1601
1602     memset (flag_map, 0, sizeof (flag_map));
1603
1604     info = strstr (filename, ":2,");
1605
1606     if (info == NULL) {
1607         info = filename + strlen(filename);
1608     } else {
1609         /* Loop through existing flags in filename. */
1610         for (flags = info + 3, last_flag = 0;
1611              *flags;
1612              last_flag = flag, flags++)
1613         {
1614             flag = *flags;
1615
1616             /* Original flags not in ASCII order. Abort. */
1617             if (flag < last_flag)
1618                 return NULL;
1619
1620             /* Non-ASCII flag. Abort. */
1621             if (flag > sizeof(flag_map) - 1)
1622                 return NULL;
1623
1624             /* Repeated flag value. Abort. */
1625             if (flag_map[flag])
1626                 return NULL;
1627
1628             flag_map[flag] = 1;
1629             flags_in_map++;
1630         }
1631     }
1632
1633     /* Then set and clear our flags from tags. */
1634     for (flags = flags_to_set; *flags; flags++) {
1635         flag = *flags;
1636         if (flag_map[flag] == 0) {
1637             flag_map[flag] = 1;
1638             flags_in_map++;
1639             flags_changed = TRUE;
1640         }
1641     }
1642
1643     for (flags = flags_to_clear; *flags; flags++) {
1644         flag = *flags;
1645         if (flag_map[flag]) {
1646             flag_map[flag] = 0;
1647             flags_in_map--;
1648             flags_changed = TRUE;
1649         }
1650     }
1651
1652     /* Messages in new/ without maildir info can be kept in new/ if no
1653      * flags have changed. */
1654     dir = (char *) _filename_is_in_maildir (filename);
1655     if (dir && STRNCMP_LITERAL (dir, "new/") == 0 && !*info && !flags_changed)
1656         return talloc_strdup (ctx, filename);
1657
1658     filename_new = (char *) talloc_size (ctx,
1659                                          info - filename +
1660                                          strlen (":2,") + flags_in_map + 1);
1661     if (unlikely (filename_new == NULL))
1662         return NULL;
1663
1664     strncpy (filename_new, filename, info - filename);
1665     filename_new[info - filename] = '\0';
1666
1667     strcat (filename_new, ":2,");
1668
1669     s = filename_new + strlen (filename_new);
1670     for (i = 0; i < sizeof (flag_map); i++)
1671     {
1672         if (flag_map[i]) {
1673             *s = i;
1674             s++;
1675         }
1676     }
1677     *s = '\0';
1678
1679     /* If message is in new/ move it under cur/. */
1680     dir = (char *) _filename_is_in_maildir (filename_new);
1681     if (dir && STRNCMP_LITERAL (dir, "new/") == 0)
1682         memcpy (dir, "cur/", 4);
1683
1684     return filename_new;
1685 }
1686
1687 notmuch_status_t
1688 notmuch_message_tags_to_maildir_flags (notmuch_message_t *message)
1689 {
1690     notmuch_filenames_t *filenames;
1691     const char *filename;
1692     char *filename_new;
1693     char *to_set, *to_clear;
1694     notmuch_status_t status = NOTMUCH_STATUS_SUCCESS;
1695
1696     _get_maildir_flag_actions (message, &to_set, &to_clear);
1697
1698     for (filenames = notmuch_message_get_filenames (message);
1699          notmuch_filenames_valid (filenames);
1700          notmuch_filenames_move_to_next (filenames))
1701     {
1702         filename = notmuch_filenames_get (filenames);
1703
1704         if (! _filename_is_in_maildir (filename))
1705             continue;
1706
1707         filename_new = _new_maildir_filename (message, filename,
1708                                               to_set, to_clear);
1709         if (filename_new == NULL)
1710             continue;
1711
1712         if (strcmp (filename, filename_new)) {
1713             int err;
1714             notmuch_status_t new_status;
1715
1716             err = rename (filename, filename_new);
1717             if (err)
1718                 continue;
1719
1720             new_status = _notmuch_message_remove_filename (message,
1721                                                            filename);
1722             /* Hold on to only the first error. */
1723             if (! status && new_status
1724                 && new_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
1725                 status = new_status;
1726                 continue;
1727             }
1728
1729             new_status = _notmuch_message_add_filename (message,
1730                                                         filename_new);
1731             /* Hold on to only the first error. */
1732             if (! status && new_status) {
1733                 status = new_status;
1734                 continue;
1735             }
1736
1737             _notmuch_message_sync (message);
1738         }
1739
1740         talloc_free (filename_new);
1741     }
1742
1743     talloc_free (to_set);
1744     talloc_free (to_clear);
1745
1746     return status;
1747 }
1748
1749 notmuch_status_t
1750 notmuch_message_remove_all_tags (notmuch_message_t *message)
1751 {
1752     notmuch_private_status_t private_status;
1753     notmuch_status_t status;
1754     notmuch_tags_t *tags;
1755     const char *tag;
1756
1757     status = _notmuch_database_ensure_writable (message->notmuch);
1758     if (status)
1759         return status;
1760
1761     for (tags = notmuch_message_get_tags (message);
1762          notmuch_tags_valid (tags);
1763          notmuch_tags_move_to_next (tags))
1764     {
1765         tag = notmuch_tags_get (tags);
1766
1767         private_status = _notmuch_message_remove_term (message, "tag", tag);
1768         if (private_status) {
1769             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
1770                             private_status);
1771         }
1772     }
1773
1774     if (! message->frozen)
1775         _notmuch_message_sync (message);
1776
1777     talloc_free (tags);
1778     return NOTMUCH_STATUS_SUCCESS;
1779 }
1780
1781 notmuch_status_t
1782 notmuch_message_freeze (notmuch_message_t *message)
1783 {
1784     notmuch_status_t status;
1785
1786     status = _notmuch_database_ensure_writable (message->notmuch);
1787     if (status)
1788         return status;
1789
1790     message->frozen++;
1791
1792     return NOTMUCH_STATUS_SUCCESS;
1793 }
1794
1795 notmuch_status_t
1796 notmuch_message_thaw (notmuch_message_t *message)
1797 {
1798     notmuch_status_t status;
1799
1800     status = _notmuch_database_ensure_writable (message->notmuch);
1801     if (status)
1802         return status;
1803
1804     if (message->frozen > 0) {
1805         message->frozen--;
1806         if (message->frozen == 0)
1807             _notmuch_message_sync (message);
1808         return NOTMUCH_STATUS_SUCCESS;
1809     } else {
1810         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
1811     }
1812 }
1813
1814 void
1815 notmuch_message_destroy (notmuch_message_t *message)
1816 {
1817     talloc_free (message);
1818 }
1819
1820 notmuch_database_t *
1821 _notmuch_message_database (notmuch_message_t *message)
1822 {
1823     return message->notmuch;
1824 }
1825
1826 static void
1827 _notmuch_message_ensure_property_map (notmuch_message_t *message)
1828 {
1829     notmuch_string_node_t *node;
1830
1831     if (message->property_map)
1832         return;
1833
1834     if (!message->property_term_list)
1835         _notmuch_message_ensure_metadata (message);
1836
1837     message->property_map = _notmuch_string_map_create (message);
1838
1839     for (node = message->property_term_list->head; node; node = node->next) {
1840         const char *key;
1841         char *value;
1842
1843         value = index(node->string, '=');
1844         if (!value)
1845             INTERNAL_ERROR ("malformed property term");
1846
1847         *value = '\0';
1848         value++;
1849         key = node->string;
1850
1851         _notmuch_string_map_append (message->property_map, key, value);
1852
1853     }
1854
1855     talloc_free (message->property_term_list);
1856     message->property_term_list = NULL;
1857 }
1858
1859 notmuch_string_map_t *
1860 _notmuch_message_property_map (notmuch_message_t *message)
1861 {
1862     _notmuch_message_ensure_property_map (message);
1863
1864     return message->property_map;
1865 }
1866
1867 notmuch_bool_t
1868 _notmuch_message_frozen (notmuch_message_t *message)
1869 {
1870     return message->frozen;
1871 }