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