]> git.notmuchmail.org Git - notmuch/blob - lib/message.cc
017c47b200cb81a6cca408134752c1d5d079f2dd
[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         notmuch->exception_reported = TRUE;
205         *status_ret = NOTMUCH_PRIVATE_STATUS_XAPIAN_EXCEPTION;
206         return NULL;
207     }
208
209     message = _notmuch_message_create (notmuch, notmuch,
210                                        doc_id, status_ret);
211
212     /* We want to inform the caller that we had to create a new
213      * document. */
214     if (*status_ret == NOTMUCH_PRIVATE_STATUS_SUCCESS)
215         *status_ret = NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
216
217     return message;
218 }
219
220 const char *
221 notmuch_message_get_message_id (notmuch_message_t *message)
222 {
223     Xapian::TermIterator i;
224
225     if (message->message_id)
226         return message->message_id;
227
228     i = message->doc.termlist_begin ();
229     i.skip_to (_find_prefix ("id"));
230
231     if (i == message->doc.termlist_end ())
232         INTERNAL_ERROR ("Message with document ID of %d has no message ID.\n",
233                         message->doc_id);
234
235     message->message_id = talloc_strdup (message, (*i).c_str () + 1);
236
237 #if DEBUG_DATABASE_SANITY
238     i++;
239
240     if (i != message->doc.termlist_end () &&
241         strncmp ((*i).c_str (), _find_prefix ("id"),
242                  strlen (_find_prefix ("id"))) == 0)
243     {
244         INTERNAL_ERROR ("Mail (doc_id: %d) has duplicate message IDs",
245                         message->doc_id);
246     }
247 #endif
248
249     return message->message_id;
250 }
251
252 static void
253 _notmuch_message_ensure_message_file (notmuch_message_t *message)
254 {
255     const char *filename;
256
257     if (message->message_file)
258         return;
259
260     filename = notmuch_message_get_filename (message);
261     if (unlikely (filename == NULL))
262         return;
263
264     message->message_file = _notmuch_message_file_open_ctx (message, filename);
265 }
266
267 const char *
268 notmuch_message_get_header (notmuch_message_t *message, const char *header)
269 {
270     _notmuch_message_ensure_message_file (message);
271     if (message->message_file == NULL)
272         return NULL;
273
274     return notmuch_message_file_get_header (message->message_file, header);
275 }
276
277 /* Return the message ID from the In-Reply-To header of 'message'.
278  *
279  * Returns an empty string ("") if 'message' has no In-Reply-To
280  * header.
281  *
282  * Returns NULL if any error occurs.
283  */
284 const char *
285 _notmuch_message_get_in_reply_to (notmuch_message_t *message)
286 {
287     const char *prefix = _find_prefix ("replyto");
288     int prefix_len = strlen (prefix);
289     Xapian::TermIterator i;
290     std::string in_reply_to;
291
292     if (message->in_reply_to)
293         return message->in_reply_to;
294
295     i = message->doc.termlist_begin ();
296     i.skip_to (prefix);
297
298     if (i != message->doc.termlist_end ())
299         in_reply_to = *i;
300
301     /* It's perfectly valid for a message to have no In-Reply-To
302      * header. For these cases, we return an empty string. */
303     if (i == message->doc.termlist_end () ||
304         strncmp (in_reply_to.c_str (), prefix, prefix_len))
305     {
306         message->in_reply_to = talloc_strdup (message, "");
307         return message->in_reply_to;
308     }
309
310     message->in_reply_to = talloc_strdup (message,
311                                           in_reply_to.c_str () + prefix_len);
312
313 #if DEBUG_DATABASE_SANITY
314     i++;
315
316     in_reply_to = *i;
317
318     if (i != message->doc.termlist_end () &&
319         strncmp ((*i).c_str (), prefix, prefix_len))
320     {
321         INTERNAL_ERROR ("Message %s has duplicate In-Reply-To IDs: %s and %s\n"
322                         notmuch_message_get_message_id (message),
323                         message->in_reply_to,
324                         (*i).c_str () + prefix_len);
325     }
326 #endif
327
328     return message->in_reply_to;
329 }
330
331 const char *
332 notmuch_message_get_thread_id (notmuch_message_t *message)
333 {
334     const char *prefix = _find_prefix ("thread");
335     Xapian::TermIterator i;
336     std::string id;
337
338     /* This code is written with the assumption that "thread" has a
339      * single-character prefix. */
340     assert (strlen (prefix) == 1);
341
342     if (message->thread_id)
343         return message->thread_id;
344
345     i = message->doc.termlist_begin ();
346     i.skip_to (prefix);
347
348     if (i != message->doc.termlist_end ())
349         id = *i;
350
351     if (i == message->doc.termlist_end () || id[0] != *prefix)
352         INTERNAL_ERROR ("Message with document ID of %d has no thread ID.\n",
353                         message->doc_id);
354
355     message->thread_id = talloc_strdup (message, id.c_str () + 1);
356
357 #if DEBUG_DATABASE_SANITY
358     i++;
359     id = *i;
360
361     if (i != message->doc.termlist_end () && id[0] == *prefix)
362     {
363         INTERNAL_ERROR ("Message %s has duplicate thread IDs: %s and %s\n",
364                         notmuch_message_get_message_id (message),
365                         message->thread_id,
366                         id.c_str () + 1);
367     }
368 #endif
369
370     return message->thread_id;
371 }
372
373 void
374 _notmuch_message_add_reply (notmuch_message_t *message,
375                             notmuch_message_node_t *reply)
376 {
377     _notmuch_message_list_append (message->replies, reply);
378 }
379
380 notmuch_messages_t *
381 notmuch_message_get_replies (notmuch_message_t *message)
382 {
383     return _notmuch_messages_create (message->replies);
384 }
385
386 /* Set the filename for 'message' to 'filename'.
387  *
388  * XXX: We should still figure out if we think it's important to store
389  * multiple filenames for email messages with identical message IDs.
390  *
391  * This change will not be reflected in the database until the next
392  * call to _notmuch_message_set_sync. */
393 void
394 _notmuch_message_set_filename (notmuch_message_t *message,
395                                const char *filename)
396 {
397     const char *s;
398     const char *db_path;
399     unsigned int db_path_len;
400
401     if (message->filename) {
402         talloc_free (message->filename);
403         message->filename = NULL;
404     }
405
406     if (filename == NULL)
407         INTERNAL_ERROR ("Message filename cannot be NULL.");
408
409     s = filename;
410
411     db_path = notmuch_database_get_path (message->notmuch);
412     db_path_len = strlen (db_path);
413
414     if (*s == '/' && strncmp (s, db_path, db_path_len) == 0
415         && strlen (s) > db_path_len)
416     {
417         s += db_path_len + 1;
418     }
419
420     message->doc.set_data (s);
421 }
422
423 const char *
424 notmuch_message_get_filename (notmuch_message_t *message)
425 {
426     std::string filename_str;
427     const char *db_path;
428
429     if (message->filename)
430         return message->filename;
431
432     filename_str = message->doc.get_data ();
433     db_path = notmuch_database_get_path (message->notmuch);
434
435     if (filename_str[0] != '/')
436         message->filename = talloc_asprintf (message, "%s/%s", db_path,
437                                              filename_str.c_str ());
438     else
439         message->filename = talloc_strdup (message, filename_str.c_str ());
440
441     return message->filename;
442 }
443
444 time_t
445 notmuch_message_get_date (notmuch_message_t *message)
446 {
447     std::string value;
448
449     try {
450         value = message->doc.get_value (NOTMUCH_VALUE_TIMESTAMP);
451     } catch (Xapian::Error &error) {
452         INTERNAL_ERROR ("Failed to read timestamp value from document.");
453         return 0;
454     }
455
456     return Xapian::sortable_unserialise (value);
457 }
458
459 notmuch_tags_t *
460 notmuch_message_get_tags (notmuch_message_t *message)
461 {
462     const char *prefix = _find_prefix ("tag");
463     Xapian::TermIterator i, end;
464     notmuch_tags_t *tags;
465     std::string tag;
466
467     /* Currently this iteration is written with the assumption that
468      * "tag" has a single-character prefix. */
469     assert (strlen (prefix) == 1);
470
471     tags = _notmuch_tags_create (message);
472     if (unlikely (tags == NULL))
473         return NULL;
474
475     i = message->doc.termlist_begin ();
476     end = message->doc.termlist_end ();
477
478     i.skip_to (prefix);
479
480     while (i != end) {
481         tag = *i;
482
483         if (tag.empty () || tag[0] != *prefix)
484             break;
485
486         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
487
488         i++;
489     }
490
491     _notmuch_tags_prepare_iterator (tags);
492
493     return tags;
494 }
495
496 void
497 _notmuch_message_set_date (notmuch_message_t *message,
498                            const char *date)
499 {
500     time_t time_value;
501
502     /* GMime really doesn't want to see a NULL date, so protect its
503      * sensibilities. */
504     if (date == NULL || *date == '\0')
505         time_value = 0;
506     else
507         time_value = g_mime_utils_header_decode_date (date, NULL);
508
509     message->doc.add_value (NOTMUCH_VALUE_TIMESTAMP,
510                             Xapian::sortable_serialise (time_value));
511 }
512
513 static void
514 thread_id_generate (thread_id_t *thread_id)
515 {
516     static int seeded = 0;
517     FILE *dev_random;
518     uint32_t value;
519     char *s;
520     int i;
521
522     if (! seeded) {
523         dev_random = fopen ("/dev/random", "r");
524         if (dev_random == NULL) {
525             srand (time (NULL));
526         } else {
527             fread ((void *) &value, sizeof (value), 1, dev_random);
528             srand (value);
529             fclose (dev_random);
530         }
531         seeded = 1;
532     }
533
534     s = thread_id->str;
535     for (i = 0; i < NOTMUCH_THREAD_ID_DIGITS; i += 8) {
536         value = rand ();
537         sprintf (s, "%08x", value);
538         s += 8;
539     }
540 }
541
542 void
543 _notmuch_message_ensure_thread_id (notmuch_message_t *message)
544 {
545     /* If not part of any existing thread, generate a new thread_id. */
546     thread_id_t thread_id;
547
548     thread_id_generate (&thread_id);
549     _notmuch_message_add_term (message, "thread", thread_id.str);
550 }
551
552 /* Synchronize changes made to message->doc out into the database. */
553 void
554 _notmuch_message_sync (notmuch_message_t *message)
555 {
556     Xapian::WritableDatabase *db;
557
558     if (message->notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY)
559         return;
560
561     db = static_cast <Xapian::WritableDatabase *> (message->notmuch->xapian_db);
562     db->replace_document (message->doc_id, message->doc);
563 }
564
565 /* Ensure that 'message' is not holding any file object open. Future
566  * calls to various functions will still automatically open the
567  * message file as needed.
568  */
569 void
570 _notmuch_message_close (notmuch_message_t *message)
571 {
572     if (message->message_file) {
573         notmuch_message_file_close (message->message_file);
574         message->message_file = NULL;
575     }
576 }
577
578 /* Add a name:value term to 'message', (the actual term will be
579  * encoded by prefixing the value with a short prefix). See
580  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
581  * names to prefix values.
582  *
583  * This change will not be reflected in the database until the next
584  * call to _notmuch_message_set_sync. */
585 notmuch_private_status_t
586 _notmuch_message_add_term (notmuch_message_t *message,
587                            const char *prefix_name,
588                            const char *value)
589 {
590
591     char *term;
592
593     if (value == NULL)
594         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
595
596     term = talloc_asprintf (message, "%s%s",
597                             _find_prefix (prefix_name), value);
598
599     if (strlen (term) > NOTMUCH_TERM_MAX)
600         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
601
602     message->doc.add_term (term);
603
604     talloc_free (term);
605
606     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
607 }
608
609 /* Parse 'text' and add a term to 'message' for each parsed word. Each
610  * term will be added both prefixed (if prefix_name is not NULL) and
611  * also unprefixed). */
612 notmuch_private_status_t
613 _notmuch_message_gen_terms (notmuch_message_t *message,
614                             const char *prefix_name,
615                             const char *text)
616 {
617     Xapian::TermGenerator *term_gen = message->notmuch->term_gen;
618
619     if (text == NULL)
620         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
621
622     term_gen->set_document (message->doc);
623
624     if (prefix_name) {
625         const char *prefix = _find_prefix (prefix_name);
626
627         term_gen->index_text (text, 1, prefix);
628     }
629
630     term_gen->index_text (text);
631
632     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
633 }
634
635 /* Remove a name:value term from 'message', (the actual term will be
636  * encoded by prefixing the value with a short prefix). See
637  * NORMAL_PREFIX and BOOLEAN_PREFIX arrays for the mapping of term
638  * names to prefix values.
639  *
640  * This change will not be reflected in the database until the next
641  * call to _notmuch_message_set_sync. */
642 notmuch_private_status_t
643 _notmuch_message_remove_term (notmuch_message_t *message,
644                               const char *prefix_name,
645                               const char *value)
646 {
647     char *term;
648
649     if (value == NULL)
650         return NOTMUCH_PRIVATE_STATUS_NULL_POINTER;
651
652     term = talloc_asprintf (message, "%s%s",
653                             _find_prefix (prefix_name), value);
654
655     if (strlen (term) > NOTMUCH_TERM_MAX)
656         return NOTMUCH_PRIVATE_STATUS_TERM_TOO_LONG;
657
658     try {
659         message->doc.remove_term (term);
660     } catch (const Xapian::InvalidArgumentError) {
661         /* We'll let the philosopher's try to wrestle with the
662          * question of whether failing to remove that which was not
663          * there in the first place is failure. For us, we'll silently
664          * consider it all good. */
665     }
666
667     talloc_free (term);
668
669     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
670 }
671
672 notmuch_status_t
673 notmuch_message_add_tag (notmuch_message_t *message, const char *tag)
674 {
675     notmuch_private_status_t status;
676
677     if (tag == NULL)
678         return NOTMUCH_STATUS_NULL_POINTER;
679
680     if (strlen (tag) > NOTMUCH_TAG_MAX)
681         return NOTMUCH_STATUS_TAG_TOO_LONG;
682
683     status = _notmuch_message_add_term (message, "tag", tag);
684     if (status) {
685         INTERNAL_ERROR ("_notmuch_message_add_term return unexpected value: %d\n",
686                         status);
687     }
688
689     if (! message->frozen)
690         _notmuch_message_sync (message);
691
692     return NOTMUCH_STATUS_SUCCESS;
693 }
694
695 notmuch_status_t
696 notmuch_message_remove_tag (notmuch_message_t *message, const char *tag)
697 {
698     notmuch_private_status_t status;
699
700     if (tag == NULL)
701         return NOTMUCH_STATUS_NULL_POINTER;
702
703     if (strlen (tag) > NOTMUCH_TAG_MAX)
704         return NOTMUCH_STATUS_TAG_TOO_LONG;
705
706     status = _notmuch_message_remove_term (message, "tag", tag);
707     if (status) {
708         INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
709                         status);
710     }
711
712     if (! message->frozen)
713         _notmuch_message_sync (message);
714
715     return NOTMUCH_STATUS_SUCCESS;
716 }
717
718 void
719 notmuch_message_remove_all_tags (notmuch_message_t *message)
720 {
721     notmuch_private_status_t status;
722     notmuch_tags_t *tags;
723     const char *tag;
724
725     for (tags = notmuch_message_get_tags (message);
726          notmuch_tags_has_more (tags);
727          notmuch_tags_advance (tags))
728     {
729         tag = notmuch_tags_get (tags);
730
731         status = _notmuch_message_remove_term (message, "tag", tag);
732         if (status) {
733             INTERNAL_ERROR ("_notmuch_message_remove_term return unexpected value: %d\n",
734                             status);
735         }
736     }
737
738     if (! message->frozen)
739         _notmuch_message_sync (message);
740 }
741
742 void
743 notmuch_message_freeze (notmuch_message_t *message)
744 {
745     message->frozen++;
746 }
747
748 notmuch_status_t
749 notmuch_message_thaw (notmuch_message_t *message)
750 {
751     if (message->frozen > 0) {
752         message->frozen--;
753         if (message->frozen == 0)
754             _notmuch_message_sync (message);
755         return NOTMUCH_STATUS_SUCCESS;
756     } else {
757         return NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW;
758     }
759 }
760
761 void
762 notmuch_message_destroy (notmuch_message_t *message)
763 {
764     talloc_free (message);
765 }