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