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