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