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