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