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