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