]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
4a5fae1e5901f584bdddcdd52bb9563aea585d5d
[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 #include <xapian.h>
29
30 struct _notmuch_message {
31     notmuch_database_t *notmuch;
32     Xapian::docid doc_id;
33     int frozen;
34     char *message_id;
35     char *thread_id;
36     char *in_reply_to;
37     char *filename;
38     notmuch_message_file_t *message_file;
39     notmuch_message_list_t *replies;
40
41     Xapian::Document doc;
42 };
43
44 /* "128 bits of thread-id ought to be enough for anybody" */
45 #define NOTMUCH_THREAD_ID_BITS   128
46 #define NOTMUCH_THREAD_ID_DIGITS (NOTMUCH_THREAD_ID_BITS / 4)
47 typedef struct _thread_id {
48     char str[NOTMUCH_THREAD_ID_DIGITS + 1];
49 } thread_id_t;
50
51 /* We end up having to call the destructor explicitly because we had
52  * to use "placement new" in order to initialize C++ objects within a
53  * block that we allocated with talloc. So C++ is making talloc
54  * slightly less simple to use, (we wouldn't need
55  * talloc_set_destructor at all otherwise).
56  */
57 static int
58 _notmuch_message_destructor (notmuch_message_t *message)
59 {
60     message->doc.~Document ();
61
62     return 0;
63 }
64
65 /* Create a new notmuch_message_t object for an existing document in
66  * the database.
67  *
68  * Here, 'talloc owner' is an optional talloc context to which the new
69  * message will belong. This allows for the caller to not bother
70  * calling notmuch_message_destroy on the message, and no that all
71  * memory will be reclaimed with 'talloc_owner' is free. The caller
72  * still can call notmuch_message_destroy when finished with the
73  * message if desired.
74  *
75  * The 'talloc_owner' argument can also be NULL, in which case the
76  * caller *is* responsible for calling notmuch_message_destroy.
77  *
78  * If no document exists in the database with document ID of 'doc_id'
79  * then this function returns NULL and optionally sets *status to
80  * NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND.
81  *
82  * This function can also fail to due lack of available memory,
83  * returning NULL and optionally setting *status to
84  * NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY.
85  *
86  * The caller can pass NULL for status if uninterested in
87  * distinguishing these two cases.
88  */
89 notmuch_message_t *
90 _notmuch_message_create (const void *talloc_owner,
91                          notmuch_database_t *notmuch,
92                          unsigned int doc_id,
93                          notmuch_private_status_t *status)
94 {
95     notmuch_message_t *message;
96
97     if (status)
98         *status = NOTMUCH_PRIVATE_STATUS_SUCCESS;
99
100     message = talloc (talloc_owner, notmuch_message_t);
101     if (unlikely (message == NULL)) {
102         if (status)
103             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
104         return NULL;
105     }
106
107     message->notmuch = notmuch;
108     message->doc_id = doc_id;
109
110     message->frozen = 0;
111
112     /* Each of these will be lazily created as needed. */
113     message->message_id = NULL;
114     message->thread_id = NULL;
115     message->in_reply_to = NULL;
116     message->filename = NULL;
117     message->message_file = NULL;
118
119     message->replies = _notmuch_message_list_create (message);
120     if (unlikely (message->replies == NULL)) {
121         if (status)
122             *status = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
123         return NULL;
124     }
125
126     /* This is C++'s creepy "placement new", which is really just an
127      * ugly way to call a constructor for a pre-allocated object. So
128      * it's really not an error to not be checking for OUT_OF_MEMORY
129      * here, since this "new" isn't actually allocating memory. This
130      * is language-design comedy of the wrong kind. */
131
132     new (&message->doc) Xapian::Document;
133
134     talloc_set_destructor (message, _notmuch_message_destructor);
135
136     try {
137         message->doc = notmuch->xapian_db->get_document (doc_id);
138     } catch (const Xapian::DocNotFoundError &error) {
139         talloc_free (message);
140         if (status)
141             *status = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
142         return NULL;
143     }
144
145     return message;
146 }
147
148 /* Create a new notmuch_message_t object for a specific message ID,
149  * (which may or may not already exist in the database).
150  *
151  * The 'notmuch' database will be the talloc owner of the returned
152  * message.
153  *
154  * If there is already a document with message ID 'message_id' in the
155  * database, then the returned message can be used to query/modify the
156  * document. Otherwise, a new document will be inserted into the
157  * database before this function returns, (and *status will be set
158  * to NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND).
159  *
160  * If an error occurs, this function will return NULL and *status
161  * will be set as appropriate. (The status pointer argument must
162  * not be NULL.)
163  */
164 notmuch_message_t *
165 _notmuch_message_create_for_message_id (notmuch_database_t *notmuch,
166                                         const char *message_id,
167                                         notmuch_private_status_t *status_ret)
168 {
169     notmuch_message_t *message;
170     Xapian::Document doc;
171     Xapian::WritableDatabase *db;
172     unsigned int doc_id;
173     char *term;
174
175     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
176         *status_ret = NOTMUCH_PRIVATE_STATUS_READONLY_DATABASE;
177         return NULL;
178     }
179
180     *status_ret = NOTMUCH_PRIVATE_STATUS_SUCCESS;
181
182     message = notmuch_database_find_message (notmuch, message_id);
183     if (message)
184         return talloc_steal (notmuch, message);
185
186     term = talloc_asprintf (NULL, "%s%s",
187                             _find_prefix ("id"), message_id);
188     if (term == NULL) {
189         *status_ret = NOTMUCH_PRIVATE_STATUS_OUT_OF_MEMORY;
190         return NULL;
191     }
192
193     db = static_cast<Xapian::WritableDatabase *> (notmuch->xapian_db);
194     try {
195         doc.add_term (term);
196         talloc_free (term);
197
198         doc.add_value (NOTMUCH_VALUE_MESSAGE_ID, message_id);
199
200         doc_id = db->add_document (doc);
201     } catch (const Xapian::Error &error) {
202         fprintf (stderr, "A Xapian exception occurred creating message: %s\n",
203                  error.get_msg().c_str());
204         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
205         return NULL;
206     }
207
208     message = _notmuch_message_create (notmuch, notmuch,
209                                        doc_id, status_ret);
210
211     /* We want to inform the caller that we had to create a new
212      * document. */
213     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
214         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
215
216     return message;
217 }
218
219 const char *
220 notmuch_message_get_message_id (notmuch_message_t *message)
221 {
222     Xapian::TermIterator i;
223
224     if (message->message_id)
225         return message->message_id;
226
227     i = message->doc.termlist_begin ();
228     i.skip_to (_find_prefix ("id"));
229
230     if (i == message->doc.termlist_end ())
231         INTERNAL_ERROR ("Message with document ID of %d has no message ID.\n",
232                         message->doc_id);
233
234     message->message_id = talloc_strdup (message, (*i).c_str () + 1);
235
236 #if DEBUG_DATABASE_SANITY
237     i++;
238
239     if (i != message->doc.termlist_end () &&
240         strncmp ((*i).c_str (), _find_prefix ("id"),
241                  strlen (_find_prefix ("id"))) == 0)
242     {
243         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate message IDs",
244                         message->doc_id);
245     }
246 #endif
247
248     return message->message_id;
249 }
250
251 static void
252 _notmuch_message_ensure_message_file (notmuch_message_t *message)
253 {
254     const char *filename;
255
256     if (message->message_file)
257         return;
258
259     filename = notmuch_message_get_filename (message);
260     if (unlikely (filename == NULL))
261         return;
262
263     message->message_file = _notmuch_message_file_open_ctx (message, filename);
264 }
265
266 const char *
267 notmuch_message_get_header (notmuch_message_t *message, const char *header)
268 {
269     _notmuch_message_ensure_message_file (message);
270     if (message->message_file == NULL)
271         return NULL;
272
273     return notmuch_message_file_get_header (message->message_file, header);
274 }
275
276 /* Return the message ID from the In-Reply-To header of 'message'.
277  *
278  * Returns an empty string ("") if 'message' has no In-Reply-To
279  * header.
280  *
281  * Returns NULL if any error occurs.
282  */
283 const char *
284 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
285 {
286     const char *prefix = _find_prefix ("replyto");
287     int prefix_len = strlen (prefix);
288     Xapian::TermIterator i;
289     std::string in_reply_to;
290
291     if (message->in_reply_to)
292         return message->in_reply_to;
293
294     i = message->doc.termlist_begin ();
295     i.skip_to (prefix);
296
297     if (i != message->doc.termlist_end ())
298         in_reply_to = *i;
299
300     /* It's perfectly valid for a message to have no In-Reply-To
301      * header. For these cases, we return an empty string. */
302     if (i == message->doc.termlist_end () ||
303         strncmp (in_reply_to.c_str (), prefix, prefix_len))
304     {
305         message->in_reply_to = talloc_strdup (message, "");
306         return message->in_reply_to;
307     }
308
309     message->in_reply_to = talloc_strdup (message,
310                                           in_reply_to.c_str () + prefix_len);
311
312 #if DEBUG_DATABASE_SANITY
313     i++;
314
315     in_reply_to = *i;
316
317     if (i != message->doc.termlist_end () &&
318         strncmp ((*i).c_str (), prefix, prefix_len))
319     {
320         INTERNAL_ERROR ("Message %s has duplicate In-Reply-To IDs: %s and %s\n"
321                         notmuch_message_get_message_id (message),
322                         message->in_reply_to,
323                         (*i).c_str () + prefix_len);
324     }
325 #endif
326
327     return message->in_reply_to;
328 }
329
330 const char *
331 notmuch_message_get_thread_id (notmuch_message_t *message)
332 {
333     const char *prefix = _find_prefix ("thread");
334     Xapian::TermIterator i;
335     std::string id;
336
337     /* This code is written with the assumption that "thread" has a
338      * single-character prefix. */
339     assert (strlen (prefix) == 1);
340
341     if (message->thread_id)
342         return message->thread_id;
343
344     i = message->doc.termlist_begin ();
345     i.skip_to (prefix);
346
347     if (i != message->doc.termlist_end ())
348         id = *i;
349
350     if (i == message->doc.termlist_end () || id[0] != *prefix)
351         INTERNAL_ERROR ("Message with document ID of %d has no thread ID.\n",
352                         message->doc_id);
353
354     message->thread_id = talloc_strdup (message, id.c_str () + 1);
355
356 #if DEBUG_DATABASE_SANITY
357     i++;
358     id = *i;
359
360     if (i != message->doc.termlist_end () && id[0] == *prefix)
361     {
362         INTERNAL_ERROR ("Message %s has duplicate thread IDs: %s and %s\n",
363                         notmuch_message_get_message_id (message),
364                         message->thread_id,
365                         id.c_str () + 1);
366     }
367 #endif
368
369     return message->thread_id;
370 }
371
372 void
373 _notmuch_message_add_reply (notmuch_message_t *message,
374                             notmuch_message_node_t *reply)
375 {
376     _notmuch_message_list_append (message->replies, reply);
377 }
378
379 notmuch_messages_t *
380 notmuch_message_get_replies (notmuch_message_t *message)
381 {
382     return _notmuch_messages_create (message->replies);
383 }
384
385 /* Set the filename for 'message' to 'filename'.
386  *
387  * XXX: We should still figure out if we think it's important to store
388  * multiple filenames for email messages with identical message IDs.
389  *
390  * This change will not be reflected in the database until the next
391  * call to _notmuch_message_set_sync. */
392 void
393 _notmuch_message_set_filename (notmuch_message_t *message,
394                                const char *filename)
395 {
396     const char *s;
397     const char *db_path;
398     unsigned int db_path_len;
399
400     if (message->filename) {
401         talloc_free (message->filename);
402         message->filename = NULL;
403     }
404
405     if (filename == NULL)
406         INTERNAL_ERROR ("Message filename cannot be NULL.");
407
408     s = filename;
409
410     db_path = notmuch_database_get_path (message->notmuch);
411     db_path_len = strlen (db_path);
412
413     if (*s == '/' && strncmp (s, db_path, db_path_len) == 0
414         && strlen (s) > db_path_len)
415     {
416         s += db_path_len + 1;
417     }
418
419     message->doc.set_data (s);
420 }
421
422 const char *
423 notmuch_message_get_filename (notmuch_message_t *message)
424 {
425     std::string filename_str;
426     const char *db_path;
427
428     if (message->filename)
429         return message->filename;
430
431     filename_str = message->doc.get_data ();
432     db_path = notmuch_database_get_path (message->notmuch);
433
434     if (filename_str[0] != '/')
435         message->filename = talloc_asprintf (message, "%s/%s", db_path,
436                                              filename_str.c_str ());
437     else
438         message->filename = talloc_strdup (message, filename_str.c_str ());
439
440     return message->filename;
441 }
442
443 time_t
444 notmuch_message_get_date (notmuch_message_t *message)
445 {
446     std::string value;
447
448     try {
449         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
450     } catch (Xapian::Error &error) {
451         INTERNAL_ERROR ("Failed to read timestamp value from document.");
452         return 0;
453     }
454
455     return Xapian::sortable_unserialise (value);
456 }
457
458 notmuch_tags_t *
459 notmuch_message_get_tags (notmuch_message_t *message)
460 {
461     const char *prefix = _find_prefix ("tag");
462     Xapian::TermIterator i, end;
463     notmuch_tags_t *tags;
464     std::string tag;
465
466     /* Currently this iteration is written with the assumption that
467      * "tag" has a single-character prefix. */
468     assert (strlen (prefix) == 1);
469
470     tags = _notmuch_tags_create (message);
471     if (unlikely (tags == NULL))
472         return NULL;
473
474     i = message->doc.termlist_begin ();
475     end = message->doc.termlist_end ();
476
477     i.skip_to (prefix);
478
479     while (i != end) {
480         tag = *i;
481
482         if (tag.empty () || tag[0] != *prefix)
483             break;
484
485         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
486
487         i++;
488     }
489
490     _notmuch_tags_prepare_iterator (tags);
491
492     return tags;
493 }
494
495 void
496 _notmuch_message_set_date (notmuch_message_t *message,
497                            const char *date)
498 {
499     time_t time_value;
500
501     /* GMime really doesn't want to see a NULL date, so protect its
502      * sensibilities. */
503     if (date == NULL || *date == '\0')
504         time_value = 0;
505     else
506         time_value = g_mime_utils_header_decode_date (date, NULL);
507
508     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
509                             Xapian::sortable_serialise (time_value));
510 }
511
512 static void
513 thread_id_generate (thread_id_t *thread_id)
514 {
515     static int seeded = 0;
516     FILE *dev_random;
517     uint32_t value;
518     char *s;
519     int i;
520
521     if (! seeded) {
522         dev_random = fopen ("/dev/random", "r");
523         if (dev_random == NULL) {
524             srand (time (NULL));
525         } else {
526             fread ((void *) &value, sizeof (value), 1, dev_random);
527             srand (value);
528             fclose (dev_random);
529         }
530         seeded = 1;
531     }
532
533     s = thread_id->str;
534     for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
535         value = rand ();
536         sprintf (s, "%08x", value);
537         s += 8;
538     }
539 }
540
541 void
542 _notmuch_message_ensure_thread_id (notmuch_message_t *message)
543 {
544     /* If not part of any existing thread, generate a new thread_id. */
545     thread_id_t thread_id;
546
547     thread_id_generate (&thread_id);
548     _notmuch_message_add_term (message, "thread", thread_id.str);
549 }
550
551 /* Synchronize changes made to message->doc out into the database. */
552 void
553 _notmuch_message_sync (notmuch_message_t *message)
554 {
555     Xapian::WritableDatabase *db;
556
557     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
558         return;
559
560     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
561     db->replace_document (message->doc_id, message->doc);
562 }
563
564 /* Ensure that 'message' is not holding any file object open. Future
565  * calls to various functions will still automatically open the
566  * message file as needed.
567  */
568 void
569 _notmuch_message_close (notmuch_message_t *message)
570 {
571     if (message->message_file) {
572         notmuch_message_file_close (message->message_file);
573         message->message_file = NULL;
574     }
575 }
576
577 /* Add a name:value term to 'message', (the actual term will be
578  * encoded by prefixing the value with a short prefix). See
579  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
580  * names to prefix values.
581  *
582  * This change will not be reflected in the database until the next
583  * call to _notmuch_message_set_sync. */
584 notmuch_private_status_t
585 _notmuch_message_add_term (notmuch_message_t *message,
586                            const char *prefix_name,
587                            const char *value)
588 {
589
590     char *term;
591
592     if (value == NULL)
593         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
594
595     term = talloc_asprintf (message, "%s%s",
596                             _find_prefix (prefix_name), value);
597
598     if (strlen (term) > NOTMUCH_TERM_MAX)
599         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
600
601     message->doc.add_term (term);
602
603     talloc_free (term);
604
605     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
606 }
607
608 /* Parse 'text' and add a term to 'message' for each parsed word. Each
609  * term will be added both prefixed (if prefix_name is not NULL) and
610  * also unprefixed). */
611 notmuch_private_status_t
612 _notmuch_message_gen_terms (notmuch_message_t *message,
613                             const char *prefix_name,
614                             const char *text)
615 {
616     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
617
618     if (text == NULL)
619         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
620
621     term_gen->set_document (message->doc);
622
623     if (prefix_name) {
624         const char *prefix = _find_prefix (prefix_name);
625
626         term_gen->index_text (text, 1, prefix);
627     }
628
629     term_gen->index_text (text);
630
631     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
632 }
633
634 /* Remove a name:value term from 'message', (the actual term will be
635  * encoded by prefixing the value with a short prefix). See
636  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
637  * names to prefix values.
638  *
639  * This change will not be reflected in the database until the next
640  * call to _notmuch_message_set_sync. */
641 notmuch_private_status_t
642 _notmuch_message_remove_term (notmuch_message_t *message,
643                               const char *prefix_name,
644                               const char *value)
645 {
646     char *term;
647
648     if (value == NULL)
649         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
650
651     term = talloc_asprintf (message, "%s%s",
652                             _find_prefix (prefix_name), value);
653
654     if (strlen (term) > NOTMUCH_TERM_MAX)
655         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
656
657     try {
658         message->doc.remove_term (term);
659     } catch (const Xapian::InvalidArgumentError) {
660         /* We'll let the philosopher's try to wrestle with the
661          * question of whether failing to remove that which was not
662          * there in the first place is failure. For us, we'll silently
663          * consider it all good. */
664     }
665
666     talloc_free (term);
667
668     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
669 }
670
671 notmuch_status_t
672 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
673 {
674     notmuch_private_status_t status;
675
676     if (tag == NULL)
677         return NOTMUCH_STATUS_NULL_POINTER;
678
679     if (strlen (tag) > NOTMUCH_TAG_MAX)
680         return NOTMUCH_STATUS_TAG_TOO_LONG;
681
682     status = _notmuch_message_add_term (message, "tag", tag);
683     if (status) {
684         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
685                         status);
686     }
687
688     if (! message->frozen)
689         _notmuch_message_sync (message);
690
691     return NOTMUCH_STATUS_SUCCESS;
692 }
693
694 notmuch_status_t
695 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
696 {
697     notmuch_private_status_t status;
698
699     if (tag == NULL)
700         return NOTMUCH_STATUS_NULL_POINTER;
701
702     if (strlen (tag) > NOTMUCH_TAG_MAX)
703         return NOTMUCH_STATUS_TAG_TOO_LONG;
704
705     status = _notmuch_message_remove_term (message, "tag", tag);
706     if (status) {
707         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
708                         status);
709     }
710
711     if (! message->frozen)
712         _notmuch_message_sync (message);
713
714     return NOTMUCH_STATUS_SUCCESS;
715 }
716
717 void
718 notmuch_message_remove_all_tags (notmuch_message_t *message)
719 {
720     notmuch_private_status_t status;
721     notmuch_tags_t *tags;
722     const char *tag;
723
724     for (tags = notmuch_message_get_tags (message);
725          notmuch_tags_has_more (tags);
726          notmuch_tags_advance (tags))
727     {
728         tag = notmuch_tags_get (tags);
729
730         status = _notmuch_message_remove_term (message, "tag", tag);
731         if (status) {
732             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
733                             status);
734         }
735     }
736
737     if (! message->frozen)
738         _notmuch_message_sync (message);
739 }
740
741 void
742 notmuch_message_freeze (notmuch_message_t *message)
743 {
744     message->frozen++;
745 }
746
747 notmuch_status_t
748 notmuch_message_thaw (notmuch_message_t *message)
749 {
750     if (message->frozen > 0) {
751         message->frozen--;
752         if (message->frozen == 0)
753             _notmuch_message_sync (message);
754         return NOTMUCH_STATUS_SUCCESS;
755     } else {
756         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
757     }
758 }
759
760 void
761 notmuch_message_destroy (notmuch_message_t *message)
762 {
763     talloc_free (message);
764 }