]> git.notmuchmail.org Git - notmuch/blob - mime-node.c
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / mime-node.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  * Copyright © 2009 Keith Packard
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see https://www.gnu.org/licenses/ .
18  *
19  * Authors: Carl Worth <cworth@cworth.org>
20  *          Keith Packard <keithp@keithp.com>
21  *          Austin Clements <aclements@csail.mit.edu>
22  */
23
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <fcntl.h>
27
28 #include "notmuch-client.h"
29
30 /* Context that gets inherited from the root node. */
31 typedef struct mime_node_context {
32     /* Per-message resources.  These are allocated internally and must
33      * be destroyed. */
34     GMimeStream *stream;
35     GMimeParser *parser;
36     GMimeMessage *mime_message;
37     _notmuch_message_crypto_t *msg_crypto;
38
39     /* repaired/unmangled parts that will need to be cleaned up */
40     GSList *repaired_parts;
41
42     /* Context provided by the caller. */
43     _notmuch_crypto_t *crypto;
44 } mime_node_context_t;
45
46 static int
47 _mime_node_context_free (mime_node_context_t *res)
48 {
49     if (res->mime_message)
50         g_object_unref (res->mime_message);
51
52     if (res->parser)
53         g_object_unref (res->parser);
54
55     if (res->stream)
56         g_object_unref (res->stream);
57
58     if (res->repaired_parts)
59         g_slist_free_full (res->repaired_parts, g_object_unref);
60
61     return 0;
62 }
63
64 /* keep track of objects that need to be destroyed when the mime node
65  * context goes away. */
66 static void
67 _mime_node_context_track_repaired_part (mime_node_context_t *ctx, GMimeObject *part)
68 {
69     if (part)
70         ctx->repaired_parts = g_slist_prepend (ctx->repaired_parts, part);
71 }
72
73 const _notmuch_message_crypto_t *
74 mime_node_get_message_crypto_status (mime_node_t *node)
75 {
76     return node->ctx->msg_crypto;
77 }
78
79 notmuch_status_t
80 mime_node_open (const void *ctx, notmuch_message_t *message,
81                 int duplicate,
82                 _notmuch_crypto_t *crypto, mime_node_t **root_out)
83 {
84     const char *filename = notmuch_message_get_filename (message);
85     mime_node_context_t *mctx;
86     mime_node_t *root;
87     notmuch_status_t status;
88     int fd = -1;
89
90     root = talloc_zero (ctx, mime_node_t);
91     if (root == NULL) {
92         fprintf (stderr, "Out of memory.\n");
93         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
94         goto DONE;
95     }
96
97     /* Create the tree-wide context */
98     mctx = talloc_zero (root, mime_node_context_t);
99     if (mctx == NULL) {
100         fprintf (stderr, "Out of memory.\n");
101         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
102         goto DONE;
103     }
104     talloc_set_destructor (mctx, _mime_node_context_free);
105
106     /* Fast path */
107     if (duplicate <= 0)
108         fd = open (filename, O_RDONLY);
109     if (fd == -1) {
110         /* Slow path - Either we are trying to open a specific file, or
111          * for some reason the first file in the list is
112          * not available anymore. The latter is clearly a problem in the
113          * database, but we are not going to let this problem be a
114          * show stopper */
115         notmuch_filenames_t *filenames;
116         int i = 1;
117
118         for (filenames = notmuch_message_get_filenames (message);
119              notmuch_filenames_valid (filenames);
120              notmuch_filenames_move_to_next (filenames), i++) {
121             if (i >= duplicate) {
122                 filename = notmuch_filenames_get (filenames);
123                 fd = open (filename, O_RDONLY);
124                 if (fd != -1) {
125                     break;
126                 } else {
127                     if (duplicate > 0) {
128                         fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
129                         status = NOTMUCH_STATUS_FILE_ERROR;
130                         goto DONE;
131                     }
132                 }
133             }
134         }
135
136         talloc_free (filenames);
137         if (fd == -1) {
138             /* Give up */
139             fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
140             status = NOTMUCH_STATUS_FILE_ERROR;
141             goto DONE;
142         }
143     }
144
145     mctx->stream = g_mime_stream_gzfile_new (fd);
146     if (! mctx->stream) {
147         fprintf (stderr, "Out of memory.\n");
148         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
149         goto DONE;
150     }
151
152     mctx->parser = g_mime_parser_new_with_stream (mctx->stream);
153     if (! mctx->parser) {
154         fprintf (stderr, "Out of memory.\n");
155         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
156         goto DONE;
157     }
158
159     mctx->mime_message = g_mime_parser_construct_message (mctx->parser, NULL);
160     if (! mctx->mime_message) {
161         fprintf (stderr, "Failed to parse %s\n", filename);
162         status = NOTMUCH_STATUS_FILE_ERROR;
163         goto DONE;
164     }
165
166     mctx->msg_crypto = _notmuch_message_crypto_new (mctx);
167
168     mctx->crypto = crypto;
169
170     /* Create the root node */
171     root->part = GMIME_OBJECT (mctx->mime_message);
172     root->envelope_file = message;
173     root->nchildren = 1;
174     root->ctx = mctx;
175
176     root->parent = NULL;
177     root->part_num = 0;
178     root->next_child = 0;
179     root->next_part_num = 1;
180
181     *root_out = root;
182     return NOTMUCH_STATUS_SUCCESS;
183
184   DONE:
185     talloc_free (root);
186     return status;
187 }
188
189 /* Signature list destructor */
190 static int
191 _signature_list_free (GMimeSignatureList **proxy)
192 {
193     g_object_unref (*proxy);
194     return 0;
195 }
196
197 /* Set up signature list destructor */
198 static void
199 set_signature_list_destructor (mime_node_t *node)
200 {
201     GMimeSignatureList **proxy = talloc (node, GMimeSignatureList *);
202
203     if (proxy) {
204         *proxy = node->sig_list;
205         talloc_set_destructor (proxy, _signature_list_free);
206     }
207 }
208
209 /* Unwrapped MIME part destructor */
210 static int
211 _unwrapped_child_free (GMimeObject **proxy)
212 {
213     g_object_unref (*proxy);
214     return 0;
215 }
216
217 /* Set up unwrapped MIME part destructor */
218 static void
219 set_unwrapped_child_destructor (mime_node_t *node)
220 {
221     GMimeObject **proxy = talloc (node, GMimeObject *);
222
223     if (proxy) {
224         *proxy = node->unwrapped_child;
225         talloc_set_destructor (proxy, _unwrapped_child_free);
226     }
227 }
228
229 /* Verify a signed mime node */
230 static void
231 node_verify (mime_node_t *node, GMimeObject *part)
232 {
233     GError *err = NULL;
234     notmuch_status_t status;
235
236     node->verify_attempted = true;
237     if (GMIME_IS_APPLICATION_PKCS7_MIME (part))
238         node->sig_list = g_mime_application_pkcs7_mime_verify (
239             GMIME_APPLICATION_PKCS7_MIME (part), GMIME_VERIFY_NONE, &node->unwrapped_child, &err);
240     else
241         node->sig_list = g_mime_multipart_signed_verify (
242             GMIME_MULTIPART_SIGNED (part), GMIME_VERIFY_NONE, &err);
243
244     if (node->unwrapped_child) {
245         node->nchildren = 1;
246         set_unwrapped_child_destructor (node);
247     }
248
249     if (node->sig_list)
250         set_signature_list_destructor (node);
251     else
252         fprintf (stderr, "Failed to verify signed part: %s\n",
253                  err ? err->message : "no error explanation given");
254
255     if (err)
256         g_error_free (err);
257
258     status = _notmuch_message_crypto_potential_sig_list (node->ctx->msg_crypto, node->sig_list);
259     if (status) /* this is a warning, not an error */
260         fprintf (stderr, "Warning: failed to note signature status: %s.\n", notmuch_status_to_string (
261                      status));
262 }
263
264 /* Decrypt and optionally verify an encrypted mime node */
265 static void
266 node_decrypt_and_verify (mime_node_t *node, GMimeObject *part)
267 {
268     GError *err = NULL;
269     GMimeDecryptResult *decrypt_result = NULL;
270     notmuch_status_t status;
271     notmuch_message_t *message = NULL;
272
273     if (! node->unwrapped_child) {
274         for (mime_node_t *parent = node; parent; parent = parent->parent)
275             if (parent->envelope_file) {
276                 message = parent->envelope_file;
277                 break;
278             }
279
280         node->unwrapped_child = _notmuch_crypto_decrypt (&node->decrypt_attempted,
281                                                          node->ctx->crypto->decrypt,
282                                                          message,
283                                                          part, &decrypt_result, &err);
284         if (node->unwrapped_child)
285             set_unwrapped_child_destructor (node);
286     }
287     if (! node->unwrapped_child) {
288         fprintf (stderr, "Failed to decrypt part: %s\n",
289                  err ? err->message : "no error explanation given");
290         goto DONE;
291     }
292
293     node->decrypt_success = true;
294     status = _notmuch_message_crypto_successful_decryption (node->ctx->msg_crypto);
295     if (status) /* this is a warning, not an error */
296         fprintf (stderr, "Warning: failed to note decryption status: %s.\n",
297                  notmuch_status_to_string (status));
298
299     if (decrypt_result) {
300         /* This may be NULL if the part is not signed. */
301         node->sig_list = g_mime_decrypt_result_get_signatures (decrypt_result);
302         if (node->sig_list) {
303             node->verify_attempted = true;
304             g_object_ref (node->sig_list);
305             set_signature_list_destructor (node);
306             status = _notmuch_message_crypto_potential_sig_list (node->ctx->msg_crypto,
307                                                                  node->sig_list);
308             if (status) /* this is a warning, not an error */
309                 fprintf (stderr, "Warning: failed to note signature status: %s.\n",
310                          notmuch_status_to_string (status));
311         }
312
313         if (node->ctx->crypto->decrypt == NOTMUCH_DECRYPT_TRUE && message) {
314             notmuch_database_t *db = notmuch_message_get_database (message);
315             const char *session_key = g_mime_decrypt_result_get_session_key (decrypt_result);
316             if (db && session_key)
317                 print_status_message ("Failed to stash session key in the database",
318                                       message,
319                                       notmuch_message_add_property (message, "session-key",
320                                                                     session_key));
321         }
322         g_object_unref (decrypt_result);
323     }
324
325   DONE:
326     if (err)
327         g_error_free (err);
328 }
329
330 static bool
331 _mime_node_set_up_part (mime_node_t *node, GMimeObject *part, int numchild);
332
333 static mime_node_t *
334 _mime_node_create (mime_node_t *parent, GMimeObject *part, int numchild)
335 {
336     mime_node_t *node = talloc_zero (parent, mime_node_t);
337
338     /* Set basic node properties */
339     node->ctx = parent->ctx;
340     if (! talloc_reference (node, node->ctx)) {
341         fprintf (stderr, "Out of memory.\n");
342         talloc_free (node);
343         return NULL;
344     }
345     node->parent = parent;
346     node->part_num = node->next_part_num = -1;
347     node->next_child = 0;
348
349     if (_mime_node_set_up_part (node, part, numchild))
350         return node;
351     talloc_free (node);
352     return NULL;
353 }
354
355 /* associate a MIME part with a node. */
356 static bool
357 _mime_node_set_up_part (mime_node_t *node, GMimeObject *part, int numchild)
358 {
359     /* Deal with the different types of parts */
360     if (GMIME_IS_PART (part)) {
361         node->part = part;
362         node->nchildren = 0;
363     } else if (GMIME_IS_MULTIPART (part)) {
364         GMimeObject *repaired_part = _notmuch_repair_mixed_up_mangled (part);
365         if (repaired_part) {
366             /* This was likely "Mixed Up" in transit!  We replace it
367              * with the more likely-to-be-correct variant. */
368             _mime_node_context_track_repaired_part (node->ctx, repaired_part);
369             part = repaired_part;
370         }
371         node->part = part;
372         node->nchildren = g_mime_multipart_get_count (GMIME_MULTIPART (part));
373     } else if (GMIME_IS_MESSAGE_PART (part)) {
374         /* Promote part to an envelope and open it */
375         GMimeMessagePart *message_part = GMIME_MESSAGE_PART (part);
376         GMimeMessage *message = g_mime_message_part_get_message (message_part);
377         node->envelope_part = message_part;
378         node->part = GMIME_OBJECT (message);
379         node->nchildren = 1;
380     } else {
381         fprintf (stderr, "Warning: Unknown mime part type: %s.\n",
382                  g_type_name (G_OBJECT_TYPE (part)));
383         return false;
384     }
385
386     /* Handle PGP/MIME parts (by definition not cryptographic payload parts) */
387     if (GMIME_IS_MULTIPART_ENCRYPTED (part) && (node->ctx->crypto->decrypt !=
388                                                 NOTMUCH_DECRYPT_FALSE)) {
389         if (node->nchildren != 2) {
390             /* this violates RFC 3156 section 4, so we won't bother with it. */
391             fprintf (stderr, "Error: %d part(s) for a multipart/encrypted "
392                      "message (must be exactly 2)\n",
393                      node->nchildren);
394         } else {
395             node_decrypt_and_verify (node, part);
396         }
397     } else if (GMIME_IS_MULTIPART_SIGNED (part) && node->ctx->crypto->verify) {
398         if (node->nchildren != 2) {
399             /* this violates RFC 3156 section 5, so we won't bother with it. */
400             fprintf (stderr, "Error: %d part(s) for a multipart/signed message "
401                      "(must be exactly 2)\n",
402                      node->nchildren);
403         } else {
404             node_verify (node, part);
405         }
406     } else if (GMIME_IS_APPLICATION_PKCS7_MIME (part) &&
407                GMIME_SECURE_MIME_TYPE_SIGNED_DATA == g_mime_application_pkcs7_mime_get_smime_type (
408                    GMIME_APPLICATION_PKCS7_MIME (part))) {
409         /* If node->ctx->crypto->verify is false, it would be better
410          * to just unwrap (instead of verifying), but
411          * https://github.com/jstedfast/gmime/issues/67 */
412         node_verify (node, part);
413     } else if (GMIME_IS_APPLICATION_PKCS7_MIME (part) &&
414                GMIME_SECURE_MIME_TYPE_ENVELOPED_DATA == g_mime_application_pkcs7_mime_get_smime_type (
415                    GMIME_APPLICATION_PKCS7_MIME (part)) &&
416                (node->ctx->crypto->decrypt != NOTMUCH_DECRYPT_FALSE)) {
417         node_decrypt_and_verify (node, part);
418         if (node->unwrapped_child && node->nchildren == 0)
419             node->nchildren = 1;
420     } else {
421         if (_notmuch_message_crypto_potential_payload (node->ctx->msg_crypto, part, node->parent ?
422                                                        node->parent->part : NULL, numchild) &&
423             node->ctx->msg_crypto->decryption_status == NOTMUCH_MESSAGE_DECRYPTED_FULL) {
424             GMimeObject *clean_payload = _notmuch_repair_crypto_payload_skip_legacy_display (part);
425             if (clean_payload != part) {
426                 /* only one layer of recursion is possible here
427                  * because there can be only a single cryptographic
428                  * payload: */
429                 return _mime_node_set_up_part (node, clean_payload, numchild);
430             }
431         }
432     }
433
434     return true;
435 }
436
437 mime_node_t *
438 mime_node_child (mime_node_t *parent, int child)
439 {
440     GMimeObject *sub;
441     mime_node_t *node;
442
443     if (! parent || ! parent->part || child < 0 || child >= parent->nchildren)
444         return NULL;
445
446     if (GMIME_IS_MULTIPART (parent->part)) {
447         if (child == GMIME_MULTIPART_ENCRYPTED_CONTENT && parent->unwrapped_child)
448             sub = parent->unwrapped_child;
449         else
450             sub = g_mime_multipart_get_part (
451                 GMIME_MULTIPART (parent->part), child);
452     } else if (GMIME_IS_MESSAGE (parent->part)) {
453         sub = g_mime_message_get_mime_part (GMIME_MESSAGE (parent->part));
454     } else if (GMIME_IS_APPLICATION_PKCS7_MIME (parent->part) &&
455                parent->unwrapped_child &&
456                child == 0) {
457         sub = parent->unwrapped_child;
458     } else {
459         /* This should have been caught by _mime_node_set_up_part */
460         INTERNAL_ERROR ("Unexpected GMimeObject type: %s",
461                         g_type_name (G_OBJECT_TYPE (parent->part)));
462     }
463     node = _mime_node_create (parent, sub, child);
464
465     if (child == parent->next_child && parent->next_part_num != -1) {
466         /* We're traversing in depth-first order.  Record the child's
467          * depth-first numbering. */
468         node->part_num = parent->next_part_num;
469         node->next_part_num = node->part_num + 1;
470
471         /* Prepare the parent for its next depth-first child. */
472         parent->next_child++;
473         parent->next_part_num = -1;
474
475         if (node->nchildren == 0) {
476             /* We've reached a leaf, so find the parent that has more
477              * children and set it up to number its next child. */
478             mime_node_t *iter = node->parent;
479             while (iter && iter->next_child == iter->nchildren)
480                 iter = iter->parent;
481             if (iter)
482                 iter->next_part_num = node->part_num + 1;
483         }
484     }
485
486     return node;
487 }
488
489 static mime_node_t *
490 _mime_node_seek_dfs_walk (mime_node_t *node, int *n)
491 {
492     int i;
493
494     if (*n == 0)
495         return node;
496
497     *n -= 1;
498     for (i = 0; i < node->nchildren; i++) {
499         mime_node_t *child = mime_node_child (node, i);
500         mime_node_t *ret = _mime_node_seek_dfs_walk (child, n);
501         if (ret)
502             return ret;
503
504         talloc_free (child);
505     }
506     return NULL;
507 }
508
509 mime_node_t *
510 mime_node_seek_dfs (mime_node_t *node, int n)
511 {
512     if (n < 0)
513         return NULL;
514     return _mime_node_seek_dfs_walk (node, &n);
515 }