]> git.notmuchmail.org Git - notmuch/blob - lib/index.cc
crypto: record whether an actual decryption attempt happened
[notmuch] / lib / index.cc
1 /*
2  * Copyright © 2009 Carl Worth
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see https://www.gnu.org/licenses/ .
16  *
17  * Author: Carl Worth <cworth@cworth.org>
18  */
19
20 #include "notmuch-private.h"
21
22 #include <gmime/gmime.h>
23 #include <gmime/gmime-filter.h>
24
25 #include <xapian.h>
26
27
28 typedef struct {
29     int state;
30     int a;
31     int b;
32     int next_if_match;
33     int next_if_not_match;
34 } scanner_state_t;
35
36 /* Simple, linear state-transition diagram for the uuencode filter.
37  *
38  * If the character being processed is within the range of [a, b]
39  * for the current state then we transition next_if_match
40  * state. If not, we transition to the next_if_not_match state.
41  *
42  * The final two states are special in that they are the states in
43  * which we discard data. */
44 static const int first_uuencode_skipping_state = 11;
45 static const scanner_state_t uuencode_states[] = {
46     {0,  'b',  'b',  1,  0},
47     {1,  'e',  'e',  2,  0},
48     {2,  'g',  'g',  3,  0},
49     {3,  'i',  'i',  4,  0},
50     {4,  'n',  'n',  5,  0},
51     {5,  ' ',  ' ',  6,  0},
52     {6,  '0',  '7',  7,  0},
53     {7,  '0',  '7',  8,  0},
54     {8,  '0',  '7',  9,  0},
55     {9,  ' ',  ' ',  10, 0},
56     {10, '\n', '\n', 11, 10},
57     {11, 'M',  'M',  12, 0},
58     {12, ' ',  '`',  12, 11}
59 };
60
61 /* The following table is intended to implement this DFA (in 'dot'
62    format). Note that 2 and 3 are "hidden" states used to step through
63    the possible out edges of state 1.
64
65 digraph html_filter {
66        0 -> 1  [label="<"];
67        0 -> 0;
68        1 -> 4 [label="'"];
69        1 -> 5 [label="\""];
70        1 -> 0 [label=">"];
71        1 -> 1;
72        4 -> 1 [label="'"];
73        4 -> 4;
74        5 -> 1 [label="\""];
75        5 -> 5;
76 }
77 */
78 static const int first_html_skipping_state = 1;
79 static const scanner_state_t html_states[] = {
80     {0,  '<',  '<',  1,  0},
81     {1,  '\'', '\'', 4,  2},  /* scanning for quote or > */
82     {1,  '"',  '"',  5,  3},
83     {1,  '>',  '>',  0,  1},
84     {4,  '\'', '\'', 1,  4},  /* inside single quotes */
85     {5,  '"', '"',   1,  5},  /* inside double quotes */
86 };
87
88 /* Oh, how I wish that gobject didn't require so much noisy boilerplate!
89  * (Though I have at least eliminated some of the stock set...) */
90 typedef struct _NotmuchFilterDiscardNonTerm NotmuchFilterDiscardNonTerm;
91 typedef struct _NotmuchFilterDiscardNonTermClass NotmuchFilterDiscardNonTermClass;
92
93 /**
94  * NotmuchFilterDiscardNonTerm:
95  *
96  * @parent_object: parent #GMimeFilter
97  * @encode: encoding vs decoding
98  * @state: State of the parser
99  *
100  * A filter to discard uuencoded portions of an email.
101  *
102  * A uuencoded portion is identified as beginning with a line
103  * matching:
104  *
105  *      begin [0-7][0-7][0-7] .*
106  *
107  * After that detection, and beginning with the following line,
108  * characters will be discarded as long as the first character of each
109  * line begins with M and subsequent characters on the line are within
110  * the range of ASCII characters from ' ' to '`'.
111  *
112  * This is not a perfect UUencode filter. It's possible to have a
113  * message that will legitimately match that pattern, (so that some
114  * legitimate content is discarded). And for most UUencoded files, the
115  * final line of encoded data (the line not starting with M) will be
116  * indexed.
117  **/
118 struct _NotmuchFilterDiscardNonTerm {
119     GMimeFilter parent_object;
120     GMimeContentType *content_type;
121     int state;
122     int first_skipping_state;
123     const scanner_state_t *states;
124 };
125
126 struct _NotmuchFilterDiscardNonTermClass {
127     GMimeFilterClass parent_class;
128 };
129
130 static GMimeFilter *notmuch_filter_discard_non_term_new (GMimeContentType *content);
131
132 static void notmuch_filter_discard_non_term_finalize (GObject *object);
133
134 static GMimeFilter *filter_copy (GMimeFilter *filter);
135 static void filter_filter (GMimeFilter *filter, char *in, size_t len, size_t prespace,
136                            char **out, size_t *outlen, size_t *outprespace);
137 static void filter_complete (GMimeFilter *filter, char *in, size_t len, size_t prespace,
138                              char **out, size_t *outlen, size_t *outprespace);
139 static void filter_reset (GMimeFilter *filter);
140
141
142 static GMimeFilterClass *parent_class = NULL;
143
144 static void
145 notmuch_filter_discard_non_term_class_init (NotmuchFilterDiscardNonTermClass *klass)
146 {
147     GObjectClass *object_class = G_OBJECT_CLASS (klass);
148     GMimeFilterClass *filter_class = GMIME_FILTER_CLASS (klass);
149
150     parent_class = (GMimeFilterClass *) g_type_class_ref (GMIME_TYPE_FILTER);
151
152     object_class->finalize = notmuch_filter_discard_non_term_finalize;
153
154     filter_class->copy = filter_copy;
155     filter_class->filter = filter_filter;
156     filter_class->complete = filter_complete;
157     filter_class->reset = filter_reset;
158 }
159
160 static void
161 notmuch_filter_discard_non_term_finalize (GObject *object)
162 {
163     G_OBJECT_CLASS (parent_class)->finalize (object);
164 }
165
166 static GMimeFilter *
167 filter_copy (GMimeFilter *gmime_filter)
168 {
169     NotmuchFilterDiscardNonTerm *filter = (NotmuchFilterDiscardNonTerm *) gmime_filter;
170     return notmuch_filter_discard_non_term_new (filter->content_type);
171 }
172
173 static void
174 filter_filter (GMimeFilter *gmime_filter, char *inbuf, size_t inlen, size_t prespace,
175                char **outbuf, size_t *outlen, size_t *outprespace)
176 {
177     NotmuchFilterDiscardNonTerm *filter = (NotmuchFilterDiscardNonTerm *) gmime_filter;
178     const scanner_state_t *states = filter->states;
179     register const char *inptr = inbuf;
180     const char *inend = inbuf + inlen;
181     char *outptr;
182
183     (void) prespace;
184
185     int next;
186
187     g_mime_filter_set_size (gmime_filter, inlen, false);
188     outptr = gmime_filter->outbuf;
189
190     next = filter->state;
191     while (inptr < inend) {
192          /* Each state is defined by a contiguous set of rows of the
193          * state table marked by a common value for '.state'. The
194          * state numbers must be equal to the index of the first row
195          * in a given state; thus the loop condition here looks for a
196          * jump to a first row of a state, which is a real transition
197          * in the underlying DFA.
198          */
199         do {
200             if (*inptr >= states[next].a && *inptr <= states[next].b)  {
201                 next = states[next].next_if_match;
202             } else  {
203                 next = states[next].next_if_not_match;
204             }
205
206         } while (next != states[next].state);
207
208         if (filter->state < filter->first_skipping_state)
209             *outptr++ = *inptr;
210
211         filter->state = next;
212         inptr++;
213     }
214
215     *outlen = outptr - gmime_filter->outbuf;
216     *outprespace = gmime_filter->outpre;
217     *outbuf = gmime_filter->outbuf;
218 }
219
220 static void
221 filter_complete (GMimeFilter *filter, char *inbuf, size_t inlen, size_t prespace,
222                  char **outbuf, size_t *outlen, size_t *outprespace)
223 {
224     if (inbuf && inlen)
225         filter_filter (filter, inbuf, inlen, prespace, outbuf, outlen, outprespace);
226 }
227
228 static void
229 filter_reset (GMimeFilter *gmime_filter)
230 {
231     NotmuchFilterDiscardNonTerm *filter = (NotmuchFilterDiscardNonTerm *) gmime_filter;
232
233     filter->state = 0;
234 }
235
236 /**
237  * notmuch_filter_discard_non_term_new:
238  *
239  * Returns: a new #NotmuchFilterDiscardNonTerm filter.
240  **/
241 static GMimeFilter *
242 notmuch_filter_discard_non_term_new (GMimeContentType *content_type)
243 {
244     static GType type = 0;
245     NotmuchFilterDiscardNonTerm *filter;
246
247     if (!type) {
248         static const GTypeInfo info = {
249             sizeof (NotmuchFilterDiscardNonTermClass),
250             NULL, /* base_class_init */
251             NULL, /* base_class_finalize */
252             (GClassInitFunc) notmuch_filter_discard_non_term_class_init,
253             NULL, /* class_finalize */
254             NULL, /* class_data */
255             sizeof (NotmuchFilterDiscardNonTerm),
256             0,    /* n_preallocs */
257             NULL, /* instance_init */
258             NULL  /* value_table */
259         };
260
261         type = g_type_register_static (GMIME_TYPE_FILTER, "NotmuchFilterDiscardNonTerm", &info, (GTypeFlags) 0);
262     }
263
264     filter = (NotmuchFilterDiscardNonTerm *) g_object_new (type, NULL);
265     filter->content_type = content_type;
266     filter->state = 0;
267     if (g_mime_content_type_is_type (content_type, "text", "html")) {
268       filter->states = html_states;
269       filter->first_skipping_state = first_html_skipping_state;
270     } else {
271       filter->states = uuencode_states;
272       filter->first_skipping_state = first_uuencode_skipping_state;
273     }
274
275     return (GMimeFilter *) filter;
276 }
277
278 /* We're finally down to a single (NAME + address) email "mailbox". */
279 static void
280 _index_address_mailbox (notmuch_message_t *message,
281                         const char *prefix_name,
282                         InternetAddress *address)
283 {
284     InternetAddressMailbox *mailbox = INTERNET_ADDRESS_MAILBOX (address);
285     const char *name, *addr, *combined;
286     void *local = talloc_new (message);
287
288     name = internet_address_get_name (address);
289     addr = internet_address_mailbox_get_addr (mailbox);
290
291     /* Combine the name and address and index them as a phrase. */
292     if (name && addr)
293         combined = talloc_asprintf (local, "%s %s", name, addr);
294     else if (name)
295         combined = name;
296     else
297         combined = addr;
298
299     if (combined)
300         _notmuch_message_gen_terms (message, prefix_name, combined);
301
302     talloc_free (local);
303 }
304
305 static void
306 _index_address_list (notmuch_message_t *message,
307                      const char *prefix_name,
308                      InternetAddressList *addresses);
309
310 /* The outer loop over the InternetAddressList wasn't quite enough.
311  * There can actually be a tree here where a single member of the list
312  * is a "group" containing another list. Recurse please.
313  */
314 static void
315 _index_address_group (notmuch_message_t *message,
316                       const char *prefix_name,
317                       InternetAddress *address)
318 {
319     InternetAddressGroup *group;
320     InternetAddressList *list;
321
322     group = INTERNET_ADDRESS_GROUP (address);
323     list = internet_address_group_get_members (group);
324
325     if (! list)
326         return;
327
328     _index_address_list (message, prefix_name, list);
329 }
330
331 static void
332 _index_address_list (notmuch_message_t *message,
333                      const char *prefix_name,
334                      InternetAddressList *addresses)
335 {
336     int i;
337     InternetAddress *address;
338
339     if (addresses == NULL)
340         return;
341
342     for (i = 0; i < internet_address_list_length (addresses); i++) {
343         address = internet_address_list_get_address (addresses, i);
344         if (INTERNET_ADDRESS_IS_MAILBOX (address)) {
345             _index_address_mailbox (message, prefix_name, address);
346         } else if (INTERNET_ADDRESS_IS_GROUP (address)) {
347             _index_address_group (message, prefix_name, address);
348         } else {
349             INTERNAL_ERROR ("GMime InternetAddress is neither a mailbox nor a group.\n");
350         }
351     }
352 }
353
354 static void
355 _index_content_type (notmuch_message_t *message, GMimeObject *part)
356 {
357     GMimeContentType *content_type = g_mime_object_get_content_type (part);
358     if (content_type) {
359         char *mime_string = g_mime_content_type_to_string (content_type);
360         if (mime_string) {
361             _notmuch_message_gen_terms (message, "mimetype", mime_string);
362             g_free (mime_string);
363         }
364     }
365 }
366
367 static void
368 _index_encrypted_mime_part (notmuch_message_t *message, notmuch_indexopts_t *indexopts,
369                             GMimeContentType *content_type,
370                             GMimeMultipartEncrypted *part);
371
372 /* Callback to generate terms for each mime part of a message. */
373 static void
374 _index_mime_part (notmuch_message_t *message,
375                   notmuch_indexopts_t *indexopts,
376                   GMimeObject *part)
377 {
378     GMimeStream *stream, *filter;
379     GMimeFilter *discard_non_term_filter;
380     GMimeDataWrapper *wrapper;
381     GByteArray *byte_array;
382     GMimeContentDisposition *disposition;
383     GMimeContentType *content_type;
384     char *body;
385     const char *charset;
386
387     if (! part) {
388         _notmuch_database_log (_notmuch_message_database (message),
389                               "Warning: Not indexing empty mime part.\n");
390         return;
391     }
392
393     _index_content_type (message, part);
394     content_type = g_mime_object_get_content_type (part);
395
396     if (GMIME_IS_MULTIPART (part)) {
397         GMimeMultipart *multipart = GMIME_MULTIPART (part);
398         int i;
399
400         if (GMIME_IS_MULTIPART_SIGNED (multipart))
401           _notmuch_message_add_term (message, "tag", "signed");
402
403         if (GMIME_IS_MULTIPART_ENCRYPTED (multipart))
404           _notmuch_message_add_term (message, "tag", "encrypted");
405
406         for (i = 0; i < g_mime_multipart_get_count (multipart); i++) {
407             if (GMIME_IS_MULTIPART_SIGNED (multipart)) {
408                 /* Don't index the signature, but index its content type. */
409                 if (i == GMIME_MULTIPART_SIGNED_SIGNATURE) {
410                     _index_content_type (message,
411                                          g_mime_multipart_get_part (multipart, i));
412                     continue;
413                 } else if (i != GMIME_MULTIPART_SIGNED_CONTENT) {
414                     _notmuch_database_log (_notmuch_message_database (message),
415                                            "Warning: Unexpected extra parts of multipart/signed. Indexing anyway.\n");
416                 }
417             }
418             if (GMIME_IS_MULTIPART_ENCRYPTED (multipart)) {
419                 _index_content_type (message,
420                                      g_mime_multipart_get_part (multipart, i));
421                 if (i == GMIME_MULTIPART_ENCRYPTED_CONTENT) {
422                     _index_encrypted_mime_part(message, indexopts,
423                                                content_type,
424                                                GMIME_MULTIPART_ENCRYPTED (part));
425                 } else {
426                     if (i != GMIME_MULTIPART_ENCRYPTED_VERSION) {
427                         _notmuch_database_log (_notmuch_message_database (message),
428                                                "Warning: Unexpected extra parts of multipart/encrypted.\n");
429                     }
430                 }
431                 continue;
432             }
433             _index_mime_part (message, indexopts,
434                               g_mime_multipart_get_part (multipart, i));
435         }
436         return;
437     }
438
439     if (GMIME_IS_MESSAGE_PART (part)) {
440         GMimeMessage *mime_message;
441
442         mime_message = g_mime_message_part_get_message (GMIME_MESSAGE_PART (part));
443
444         _index_mime_part (message, indexopts, g_mime_message_get_mime_part (mime_message));
445
446         return;
447     }
448
449     if (! (GMIME_IS_PART (part))) {
450         _notmuch_database_log (_notmuch_message_database (message),
451                               "Warning: Not indexing unknown mime part: %s.\n",
452                               g_type_name (G_OBJECT_TYPE (part)));
453         return;
454     }
455
456     disposition = g_mime_object_get_content_disposition (part);
457     if (disposition &&
458         strcasecmp (g_mime_content_disposition_get_disposition (disposition),
459                     GMIME_DISPOSITION_ATTACHMENT) == 0)
460     {
461         const char *filename = g_mime_part_get_filename (GMIME_PART (part));
462
463         _notmuch_message_add_term (message, "tag", "attachment");
464         _notmuch_message_gen_terms (message, "attachment", filename);
465
466         /* XXX: Would be nice to call out to something here to parse
467          * the attachment into text and then index that. */
468         return;
469     }
470
471     byte_array = g_byte_array_new ();
472
473     stream = g_mime_stream_mem_new_with_byte_array (byte_array);
474     g_mime_stream_mem_set_owner (GMIME_STREAM_MEM (stream), false);
475
476     filter = g_mime_stream_filter_new (stream);
477
478     discard_non_term_filter = notmuch_filter_discard_non_term_new (content_type);
479
480     g_mime_stream_filter_add (GMIME_STREAM_FILTER (filter),
481                               discard_non_term_filter);
482
483     charset = g_mime_object_get_content_type_parameter (part, "charset");
484     if (charset) {
485         GMimeFilter *charset_filter;
486         charset_filter = g_mime_filter_charset_new (charset, "UTF-8");
487         /* This result can be NULL for things like "unknown-8bit".
488          * Don't set a NULL filter as that makes GMime print
489          * annoying assertion-failure messages on stderr. */
490         if (charset_filter) {
491             g_mime_stream_filter_add (GMIME_STREAM_FILTER (filter),
492                                       charset_filter);
493             g_object_unref (charset_filter);
494         }
495     }
496
497     wrapper = g_mime_part_get_content_object (GMIME_PART (part));
498     if (wrapper)
499         g_mime_data_wrapper_write_to_stream (wrapper, filter);
500
501     g_object_unref (stream);
502     g_object_unref (filter);
503     g_object_unref (discard_non_term_filter);
504
505     g_byte_array_append (byte_array, (guint8 *) "\0", 1);
506     body = (char *) g_byte_array_free (byte_array, false);
507
508     if (body) {
509         _notmuch_message_gen_terms (message, NULL, body);
510
511         free (body);
512     }
513 }
514
515 /* descend (if desired) into the cleartext part of an encrypted MIME
516  * part while indexing. */
517 static void
518 _index_encrypted_mime_part (notmuch_message_t *message,
519                             notmuch_indexopts_t *indexopts,
520                             g_mime_3_unused(GMimeContentType *content_type),
521                             GMimeMultipartEncrypted *encrypted_data)
522 {
523     notmuch_status_t status;
524     GError *err = NULL;
525     notmuch_database_t * notmuch = NULL;
526     GMimeObject *clear = NULL;
527
528     if (!indexopts || (notmuch_indexopts_get_decrypt_policy (indexopts) == NOTMUCH_DECRYPT_FALSE))
529         return;
530
531     notmuch = _notmuch_message_database (message);
532
533     GMimeCryptoContext* crypto_ctx = NULL;
534 #if (GMIME_MAJOR_VERSION < 3)
535     {
536         const char *protocol = NULL;
537         protocol = g_mime_content_type_get_parameter (content_type, "protocol");
538         status = _notmuch_crypto_get_gmime_ctx_for_protocol (&(indexopts->crypto),
539                                                          protocol, &crypto_ctx);
540         if (status) {
541             _notmuch_database_log (notmuch, "Warning: setup failed for decrypting "
542                                    "during indexing. (%d)\n", status);
543             status = notmuch_message_add_property (message, "index.decryption", "failure");
544             if (status)
545                 _notmuch_database_log_append (notmuch, "failed to add index.decryption "
546                                               "property (%d)\n", status);
547             return;
548         }
549     }
550 #endif
551     bool attempted = false;
552     clear = _notmuch_crypto_decrypt (&attempted, notmuch_indexopts_get_decrypt_policy (indexopts),
553                                      message, crypto_ctx, encrypted_data, NULL, &err);
554     if (!attempted)
555         return;
556     if (err || !clear) {
557         if (err) {
558             _notmuch_database_log (notmuch, "Failed to decrypt during indexing. (%d:%d) [%s]\n",
559                                    err->domain, err->code, err->message);
560             g_error_free(err);
561         } else {
562             _notmuch_database_log (notmuch, "Failed to decrypt during indexing. (unknown error)\n");
563         }
564         /* Indicate that we failed to decrypt during indexing */
565         status = notmuch_message_add_property (message, "index.decryption", "failure");
566         if (status)
567             _notmuch_database_log_append (notmuch, "failed to add index.decryption "
568                                           "property (%d)\n", status);
569         return;
570     }
571     _index_mime_part (message, indexopts, clear);
572     g_object_unref (clear);
573
574     status = notmuch_message_add_property (message, "index.decryption", "success");
575     if (status)
576         _notmuch_database_log (notmuch, "failed to add index.decryption "
577                                "property (%d)\n", status);
578
579 }
580
581 notmuch_status_t
582 _notmuch_message_index_file (notmuch_message_t *message,
583                              notmuch_indexopts_t *indexopts,
584                              notmuch_message_file_t *message_file)
585 {
586     GMimeMessage *mime_message;
587     InternetAddressList *addresses;
588     const char *subject;
589     notmuch_status_t status;
590
591     status = _notmuch_message_file_get_mime_message (message_file,
592                                                      &mime_message);
593     if (status)
594         return status;
595
596     addresses = g_mime_message_get_from (mime_message);
597     if (addresses) {
598         _index_address_list (message, "from", addresses);
599         g_mime_2_6_unref (addresses);
600     }
601
602     addresses = g_mime_message_get_all_recipients (mime_message);
603     if (addresses) {
604         _index_address_list (message, "to", addresses);
605         g_object_unref (addresses);
606     }
607
608     subject = g_mime_message_get_subject (mime_message);
609     _notmuch_message_gen_terms (message, "subject", subject);
610
611     _index_mime_part (message, indexopts, g_mime_message_get_mime_part (mime_message));
612
613     return NOTMUCH_STATUS_SUCCESS;
614 }