]> 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                 _notmuch_crypto_t *crypto, mime_node_t **root_out)
82 {
83     const char *filename = notmuch_message_get_filename (message);
84     mime_node_context_t *mctx;
85     mime_node_t *root;
86     notmuch_status_t status;
87     int fd;
88
89     root = talloc_zero (ctx, mime_node_t);
90     if (root == NULL) {
91         fprintf (stderr, "Out of memory.\n");
92         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
93         goto DONE;
94     }
95
96     /* Create the tree-wide context */
97     mctx = talloc_zero (root, mime_node_context_t);
98     if (mctx == NULL) {
99         fprintf (stderr, "Out of memory.\n");
100         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
101         goto DONE;
102     }
103     talloc_set_destructor (mctx, _mime_node_context_free);
104
105     /* Fast path */
106     fd = open (filename, O_RDONLY);
107     if (fd == -1) {
108         /* Slow path - for some reason the first file in the list is
109          * not available anymore. This is clearly a problem in the
110          * database, but we are not going to let this problem be a
111          * show stopper */
112         notmuch_filenames_t *filenames;
113         for (filenames = notmuch_message_get_filenames (message);
114              notmuch_filenames_valid (filenames);
115              notmuch_filenames_move_to_next (filenames)) {
116             filename = notmuch_filenames_get (filenames);
117             fd = open (filename, O_RDONLY);
118             if (fd != -1)
119                 break;
120         }
121
122         talloc_free (filenames);
123         if (fd == -1) {
124             /* Give up */
125             fprintf (stderr, "Error opening %s: %s\n", filename, strerror (errno));
126             status = NOTMUCH_STATUS_FILE_ERROR;
127             goto DONE;
128         }
129     }
130
131     mctx->stream = g_mime_stream_gzfile_new (fd);
132     if (! mctx->stream) {
133         fprintf (stderr, "Out of memory.\n");
134         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
135         goto DONE;
136     }
137
138     mctx->parser = g_mime_parser_new_with_stream (mctx->stream);
139     if (! mctx->parser) {
140         fprintf (stderr, "Out of memory.\n");
141         status = NOTMUCH_STATUS_OUT_OF_MEMORY;
142         goto DONE;
143     }
144
145     mctx->mime_message = g_mime_parser_construct_message (mctx->parser, NULL);
146     if (! mctx->mime_message) {
147         fprintf (stderr, "Failed to parse %s\n", filename);
148         status = NOTMUCH_STATUS_FILE_ERROR;
149         goto DONE;
150     }
151
152     mctx->msg_crypto = _notmuch_message_crypto_new (mctx);
153
154     mctx->crypto = crypto;
155
156     /* Create the root node */
157     root->part = GMIME_OBJECT (mctx->mime_message);
158     root->envelope_file = message;
159     root->nchildren = 1;
160     root->ctx = mctx;
161
162     root->parent = NULL;
163     root->part_num = 0;
164     root->next_child = 0;
165     root->next_part_num = 1;
166
167     *root_out = root;
168     return NOTMUCH_STATUS_SUCCESS;
169
170   DONE:
171     talloc_free (root);
172     return status;
173 }
174
175 /* Signature list destructor */
176 static int
177 _signature_list_free (GMimeSignatureList **proxy)
178 {
179     g_object_unref (*proxy);
180     return 0;
181 }
182
183 /* Set up signature list destructor */
184 static void
185 set_signature_list_destructor (mime_node_t *node)
186 {
187     GMimeSignatureList **proxy = talloc (node, GMimeSignatureList *);
188
189     if (proxy) {
190         *proxy = node->sig_list;
191         talloc_set_destructor (proxy, _signature_list_free);
192     }
193 }
194
195 /* Unwrapped MIME part destructor */
196 static int
197 _unwrapped_child_free (GMimeObject **proxy)
198 {
199     g_object_unref (*proxy);
200     return 0;
201 }
202
203 /* Set up unwrapped MIME part destructor */
204 static void
205 set_unwrapped_child_destructor (mime_node_t *node)
206 {
207     GMimeObject **proxy = talloc (node, GMimeObject *);
208
209     if (proxy) {
210         *proxy = node->unwrapped_child;
211         talloc_set_destructor (proxy, _unwrapped_child_free);
212     }
213 }
214
215 /* Verify a signed mime node */
216 static void
217 node_verify (mime_node_t *node, GMimeObject *part)
218 {
219     GError *err = NULL;
220     notmuch_status_t status;
221
222     node->verify_attempted = true;
223     node->sig_list = g_mime_multipart_signed_verify (
224         GMIME_MULTIPART_SIGNED (part), GMIME_VERIFY_NONE, &err);
225
226     if (node->sig_list)
227         set_signature_list_destructor (node);
228     else
229         fprintf (stderr, "Failed to verify signed part: %s\n",
230                  err ? err->message : "no error explanation given");
231
232     if (err)
233         g_error_free (err);
234
235     status = _notmuch_message_crypto_potential_sig_list (node->ctx->msg_crypto, node->sig_list);
236     if (status) /* this is a warning, not an error */
237         fprintf (stderr, "Warning: failed to note signature status: %s.\n", notmuch_status_to_string (status));
238 }
239
240 /* Decrypt and optionally verify an encrypted mime node */
241 static void
242 node_decrypt_and_verify (mime_node_t *node, GMimeObject *part)
243 {
244     GError *err = NULL;
245     GMimeDecryptResult *decrypt_result = NULL;
246     notmuch_status_t status;
247     GMimeMultipartEncrypted *encrypteddata = GMIME_MULTIPART_ENCRYPTED (part);
248     notmuch_message_t *message = NULL;
249
250     if (! node->unwrapped_child) {
251         for (mime_node_t *parent = node; parent; parent = parent->parent)
252             if (parent->envelope_file) {
253                 message = parent->envelope_file;
254                 break;
255             }
256
257         node->unwrapped_child = _notmuch_crypto_decrypt (&node->decrypt_attempted,
258                                                          node->ctx->crypto->decrypt,
259                                                          message,
260                                                          encrypteddata, &decrypt_result, &err);
261         if (node->unwrapped_child)
262             set_unwrapped_child_destructor (node);
263     }
264     if (! node->unwrapped_child) {
265         fprintf (stderr, "Failed to decrypt part: %s\n",
266                  err ? err->message : "no error explanation given");
267         goto DONE;
268     }
269
270     node->decrypt_success = true;
271     status = _notmuch_message_crypto_successful_decryption (node->ctx->msg_crypto);
272     if (status) /* this is a warning, not an error */
273         fprintf (stderr, "Warning: failed to note decryption status: %s.\n", notmuch_status_to_string (status));
274
275     if (decrypt_result) {
276         /* This may be NULL if the part is not signed. */
277         node->sig_list = g_mime_decrypt_result_get_signatures (decrypt_result);
278         if (node->sig_list) {
279             node->verify_attempted = true;
280             g_object_ref (node->sig_list);
281             set_signature_list_destructor (node);
282             status = _notmuch_message_crypto_potential_sig_list (node->ctx->msg_crypto, node->sig_list);
283             if (status) /* this is a warning, not an error */
284                 fprintf (stderr, "Warning: failed to note signature status: %s.\n", notmuch_status_to_string (status));
285         }
286
287         if (node->ctx->crypto->decrypt == NOTMUCH_DECRYPT_TRUE && message) {
288             notmuch_database_t *db = notmuch_message_get_database (message);
289             const char *session_key = g_mime_decrypt_result_get_session_key (decrypt_result);
290             if (db && session_key)
291                 print_status_message ("Failed to stash session key in the database",
292                                       message,
293                                       notmuch_message_add_property (message, "session-key",
294                                                                     session_key));
295         }
296         g_object_unref (decrypt_result);
297     }
298
299   DONE:
300     if (err)
301         g_error_free (err);
302 }
303
304 static bool
305 _mime_node_set_up_part (mime_node_t *node, GMimeObject *part, int numchild);
306
307 static mime_node_t *
308 _mime_node_create (mime_node_t *parent, GMimeObject *part, int numchild)
309 {
310     mime_node_t *node = talloc_zero (parent, mime_node_t);
311
312     /* Set basic node properties */
313     node->ctx = parent->ctx;
314     if (! talloc_reference (node, node->ctx)) {
315         fprintf (stderr, "Out of memory.\n");
316         talloc_free (node);
317         return NULL;
318     }
319     node->parent = parent;
320     node->part_num = node->next_part_num = -1;
321     node->next_child = 0;
322
323     if (_mime_node_set_up_part (node, part, numchild))
324         return node;
325     talloc_free (node);
326     return NULL;
327 }
328
329 /* associate a MIME part with a node. */
330 static bool
331 _mime_node_set_up_part (mime_node_t *node, GMimeObject *part, int numchild)
332 {
333     /* Deal with the different types of parts */
334     if (GMIME_IS_PART (part)) {
335         node->part = part;
336         node->nchildren = 0;
337     } else if (GMIME_IS_MULTIPART (part)) {
338         GMimeObject *repaired_part = _notmuch_repair_mixed_up_mangled (part);
339         if (repaired_part) {
340             /* This was likely "Mixed Up" in transit!  We replace it
341              * with the more likely-to-be-correct variant. */
342             _mime_node_context_track_repaired_part (node->ctx, repaired_part);
343             part = repaired_part;
344         }
345         node->part = part;
346         node->nchildren = g_mime_multipart_get_count (GMIME_MULTIPART (part));
347     } else if (GMIME_IS_MESSAGE_PART (part)) {
348         /* Promote part to an envelope and open it */
349         GMimeMessagePart *message_part = GMIME_MESSAGE_PART (part);
350         GMimeMessage *message = g_mime_message_part_get_message (message_part);
351         node->envelope_part = message_part;
352         node->part = GMIME_OBJECT (message);
353         node->nchildren = 1;
354     } else {
355         fprintf (stderr, "Warning: Unknown mime part type: %s.\n",
356                  g_type_name (G_OBJECT_TYPE (part)));
357         return false;
358     }
359
360     /* Handle PGP/MIME parts (by definition not cryptographic payload parts) */
361     if (GMIME_IS_MULTIPART_ENCRYPTED (part) && (node->ctx->crypto->decrypt != NOTMUCH_DECRYPT_FALSE)) {
362         if (node->nchildren != 2) {
363             /* this violates RFC 3156 section 4, so we won't bother with it. */
364             fprintf (stderr, "Error: %d part(s) for a multipart/encrypted "
365                      "message (must be exactly 2)\n",
366                      node->nchildren);
367         } else {
368             node_decrypt_and_verify (node, part);
369         }
370     } else if (GMIME_IS_MULTIPART_SIGNED (part) && node->ctx->crypto->verify) {
371         if (node->nchildren != 2) {
372             /* this violates RFC 3156 section 5, so we won't bother with it. */
373             fprintf (stderr, "Error: %d part(s) for a multipart/signed message "
374                      "(must be exactly 2)\n",
375                      node->nchildren);
376         } else {
377             node_verify (node, part);
378         }
379     } else {
380         if (_notmuch_message_crypto_potential_payload (node->ctx->msg_crypto, part, node->parent ? node->parent->part : NULL, numchild) &&
381             node->ctx->msg_crypto->decryption_status == NOTMUCH_MESSAGE_DECRYPTED_FULL) {
382             GMimeObject *clean_payload = _notmuch_repair_crypto_payload_skip_legacy_display (part);
383             if (clean_payload != part) {
384                 /* only one layer of recursion is possible here
385                  * because there can be only a single cryptographic
386                  * payload: */
387                 return _mime_node_set_up_part (node, clean_payload, numchild);
388             }
389         }
390     }
391
392     return true;
393 }
394
395 mime_node_t *
396 mime_node_child (mime_node_t *parent, int child)
397 {
398     GMimeObject *sub;
399     mime_node_t *node;
400
401     if (! parent || ! parent->part || child < 0 || child >= parent->nchildren)
402         return NULL;
403
404     if (GMIME_IS_MULTIPART (parent->part)) {
405         if (child == GMIME_MULTIPART_ENCRYPTED_CONTENT && parent->unwrapped_child)
406             sub = parent->unwrapped_child;
407         else
408             sub = g_mime_multipart_get_part (
409                 GMIME_MULTIPART (parent->part), child);
410     } else if (GMIME_IS_MESSAGE (parent->part)) {
411         sub = g_mime_message_get_mime_part (GMIME_MESSAGE (parent->part));
412     } else {
413         /* This should have been caught by _mime_node_set_up_part */
414         INTERNAL_ERROR ("Unexpected GMimeObject type: %s",
415                         g_type_name (G_OBJECT_TYPE (parent->part)));
416     }
417     node = _mime_node_create (parent, sub, child);
418
419     if (child == parent->next_child && parent->next_part_num != -1) {
420         /* We're traversing in depth-first order.  Record the child's
421          * depth-first numbering. */
422         node->part_num = parent->next_part_num;
423         node->next_part_num = node->part_num + 1;
424
425         /* Prepare the parent for its next depth-first child. */
426         parent->next_child++;
427         parent->next_part_num = -1;
428
429         if (node->nchildren == 0) {
430             /* We've reached a leaf, so find the parent that has more
431              * children and set it up to number its next child. */
432             mime_node_t *iter = node->parent;
433             while (iter && iter->next_child == iter->nchildren)
434                 iter = iter->parent;
435             if (iter)
436                 iter->next_part_num = node->part_num + 1;
437         }
438     }
439
440     return node;
441 }
442
443 static mime_node_t *
444 _mime_node_seek_dfs_walk (mime_node_t *node, int *n)
445 {
446     int i;
447
448     if (*n == 0)
449         return node;
450
451     *n -= 1;
452     for (i = 0; i < node->nchildren; i++) {
453         mime_node_t *child = mime_node_child (node, i);
454         mime_node_t *ret = _mime_node_seek_dfs_walk (child, n);
455         if (ret)
456             return ret;
457
458         talloc_free (child);
459     }
460     return NULL;
461 }
462
463 mime_node_t *
464 mime_node_seek_dfs (mime_node_t *node, int n)
465 {
466     if (n < 0)
467         return NULL;
468     return _mime_node_seek_dfs_walk (node, &n);
469 }