Pgpmime: fix two memory leak in MIME boundary handling.
[claws.git] / src / plugins / pgpmime / pgpmime.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2016 the Claws Mail team
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
19 #ifdef HAVE_CONFIG_H
20 #  include "config.h"
21 #include "claws-features.h"
22 #endif
23
24 #ifdef USE_GPGME
25
26 #include "defs.h"
27 #include <glib.h>
28 #include <glib/gi18n.h>
29 #include <gpgme.h>
30 #include <ctype.h>
31 #include <errno.h>
32
33 #include "utils.h"
34 #include "privacy.h"
35 #include "procmime.h"
36 #include "plugin.h"
37
38 #include "pgpmime.h"
39 #include <plugins/pgpcore/sgpgme.h>
40 #include <plugins/pgpcore/prefs_gpg.h>
41 #include <plugins/pgpcore/passphrase.h>
42 #include <plugins/pgpcore/pgp_utils.h>
43
44 #include "prefs_common.h"
45
46 typedef struct _PrivacyDataPGP PrivacyDataPGP;
47
48 struct _PrivacyDataPGP
49 {
50         PrivacyData     data;
51         
52         gboolean        done_sigtest;
53         gboolean        is_signed;
54         gpgme_verify_result_t   sigstatus;
55         gpgme_ctx_t     ctx;
56 };
57
58 static PrivacySystem pgpmime_system;
59
60 static gint pgpmime_check_signature(MimeInfo *mimeinfo);
61
62 static PrivacyDataPGP *pgpmime_new_privacydata()
63 {
64         PrivacyDataPGP *data;
65         gpgme_error_t err;
66
67         data = g_new0(PrivacyDataPGP, 1);
68         data->data.system = &pgpmime_system;
69         data->done_sigtest = FALSE;
70         data->is_signed = FALSE;
71         data->sigstatus = NULL;
72         if ((err = gpgme_new(&data->ctx)) != GPG_ERR_NO_ERROR) {
73                 g_warning("Couldn't initialize GPG context: %s", gpgme_strerror(err));
74                 return NULL;
75         }
76         
77         return data;
78 }
79
80 static void pgpmime_free_privacydata(PrivacyData *_data)
81 {
82         PrivacyDataPGP *data = (PrivacyDataPGP *) _data;
83         gpgme_release(data->ctx);
84         g_free(data);
85 }
86
87 static gboolean pgpmime_is_signed(MimeInfo *mimeinfo)
88 {
89         MimeInfo *parent;
90         MimeInfo *signature;
91         const gchar *protocol;
92         PrivacyDataPGP *data = NULL;
93         
94         cm_return_val_if_fail(mimeinfo != NULL, FALSE);
95         if (mimeinfo->privacy != NULL) {
96                 data = (PrivacyDataPGP *) mimeinfo->privacy;
97                 if (data->done_sigtest)
98                         return data->is_signed;
99         }
100         
101         /* check parent */
102         parent = procmime_mimeinfo_parent(mimeinfo);
103         if (parent == NULL)
104                 return FALSE;
105         if ((parent->type != MIMETYPE_MULTIPART) ||
106             g_ascii_strcasecmp(parent->subtype, "signed"))
107                 return FALSE;
108         protocol = procmime_mimeinfo_get_parameter(parent, "protocol");
109         if ((protocol == NULL) || 
110             (g_ascii_strcasecmp(protocol, "application/pgp-signature")))
111                 return FALSE;
112
113         /* check if mimeinfo is the first child */
114         if (parent->node->children->data != mimeinfo)
115                 return FALSE;
116
117         /* check signature */
118         signature = parent->node->children->next != NULL ? 
119             (MimeInfo *) parent->node->children->next->data : NULL;
120         if (signature == NULL)
121                 return FALSE;
122         if ((signature->type != MIMETYPE_APPLICATION) ||
123             (g_ascii_strcasecmp(signature->subtype, "pgp-signature")))
124                 return FALSE;
125
126         if (data == NULL) {
127                 data = pgpmime_new_privacydata();
128                 mimeinfo->privacy = (PrivacyData *) data;
129         }
130         if (data != NULL) {
131                 data->done_sigtest = TRUE;
132                 data->is_signed = TRUE;
133         }
134
135         return TRUE;
136 }
137
138 static gchar *get_canonical_content(FILE *fp, const gchar *boundary)
139 {
140         gchar *ret;
141         GString *textbuffer;
142         guint boundary_len;
143         gchar buf[BUFFSIZE];
144
145         boundary_len = strlen(boundary);
146         while (fgets(buf, sizeof(buf), fp) != NULL)
147                 if (IS_BOUNDARY(buf, boundary, boundary_len))
148                         break;
149
150         textbuffer = g_string_new("");
151         while (fgets(buf, sizeof(buf), fp) != NULL) {
152                 gchar *buf2;
153
154                 if (IS_BOUNDARY(buf, boundary, boundary_len))
155                         break;
156                 
157                 buf2 = canonicalize_str(buf);
158                 g_string_append(textbuffer, buf2);
159                 g_free(buf2);
160         }
161         g_string_truncate(textbuffer, textbuffer->len - 2);
162                 
163         ret = textbuffer->str;
164         g_string_free(textbuffer, FALSE);
165
166         return ret;
167 }
168
169 static gint pgpmime_check_signature(MimeInfo *mimeinfo)
170 {
171         PrivacyDataPGP *data;
172         MimeInfo *parent, *signature;
173         FILE *fp;
174         gchar *boundary;
175         gchar *textstr;
176         gpgme_data_t sigdata = NULL, textdata = NULL;
177         gpgme_error_t err;
178         cm_return_val_if_fail(mimeinfo != NULL, -1);
179         cm_return_val_if_fail(mimeinfo->privacy != NULL, -1);
180         data = (PrivacyDataPGP *) mimeinfo->privacy;
181         if ((err = gpgme_new(&data->ctx)) != GPG_ERR_NO_ERROR) {
182                 debug_print(("Couldn't initialize GPG context, %s\n"), gpgme_strerror(err));
183                 privacy_set_error(_("Couldn't initialize GPG context, %s"), gpgme_strerror(err));
184                 return 0;
185         }
186
187         
188         debug_print("Checking PGP/MIME signature\n");
189
190         err = gpgme_set_protocol(data->ctx, GPGME_PROTOCOL_OpenPGP);
191
192         if (err) {
193                 debug_print ("gpgme_set_protocol failed: %s\n",
194                    gpgme_strerror (err));
195         }
196         parent = procmime_mimeinfo_parent(mimeinfo);
197
198         fp = g_fopen(parent->data.filename, "rb");
199         cm_return_val_if_fail(fp != NULL, SIGNATURE_INVALID);
200         
201         boundary = g_hash_table_lookup(parent->typeparameters, "boundary");
202         if (!boundary) {
203                 privacy_set_error(_("Signature boundary not found."));
204                 fclose(fp);
205                 return 0;
206         }
207         textstr = get_canonical_content(fp, boundary);
208
209         err = gpgme_data_new_from_mem(&textdata, textstr, (size_t)strlen(textstr), 0);
210         if (err) {
211                 debug_print ("gpgme_data_new_from_mem failed: %s\n",
212                    gpgme_strerror (err));
213         }
214         signature = (MimeInfo *) mimeinfo->node->next->data;
215         sigdata = sgpgme_data_from_mimeinfo(signature);
216
217         err = 0;
218         if (signature->encoding_type == ENC_BASE64) {
219                 err = gpgme_data_set_encoding (sigdata, GPGME_DATA_ENCODING_BASE64);
220         }
221         
222         if (err) {
223                 debug_print ("gpgme_data_set_encoding failed: %s\n",
224                         gpgme_strerror (err));
225         }
226
227         data->sigstatus =
228                 sgpgme_verify_signature (data->ctx, sigdata, textdata, NULL);
229
230         gpgme_data_release(sigdata);
231         gpgme_data_release(textdata);
232         g_free(textstr);
233         fclose(fp);
234         
235         return 0;
236 }
237
238 static SignatureStatus pgpmime_get_sig_status(MimeInfo *mimeinfo)
239 {
240         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
241         
242         cm_return_val_if_fail(data != NULL, SIGNATURE_INVALID);
243
244         return sgpgme_sigstat_gpgme_to_privacy(data->ctx, data->sigstatus);
245 }
246
247 static gchar *pgpmime_get_sig_info_short(MimeInfo *mimeinfo)
248 {
249         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
250         
251         cm_return_val_if_fail(data != NULL, g_strdup("Error"));
252
253         return sgpgme_sigstat_info_short(data->ctx, data->sigstatus);
254 }
255
256 static gchar *pgpmime_get_sig_info_full(MimeInfo *mimeinfo)
257 {
258         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
259
260         cm_return_val_if_fail(data != NULL, g_strdup("Error"));
261
262         return sgpgme_sigstat_info_full(data->ctx, data->sigstatus);
263 }
264
265 static gboolean pgpmime_is_encrypted(MimeInfo *mimeinfo)
266 {
267         MimeInfo *tmpinfo;
268         const gchar *tmpstr;
269         const gchar *begin_indicator = "-----BEGIN PGP MESSAGE-----";
270         const gchar *end_indicator = "-----END PGP MESSAGE-----";
271         gchar *textdata;
272
273         if (mimeinfo->type != MIMETYPE_MULTIPART)
274                 return FALSE;
275         if (g_ascii_strcasecmp(mimeinfo->subtype, "encrypted"))
276                 return FALSE;
277         tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "protocol");
278         if ((tmpstr == NULL) || g_ascii_strcasecmp(tmpstr, "application/pgp-encrypted"))
279                 return FALSE;
280         if (g_node_n_children(mimeinfo->node) != 2)
281                 return FALSE;
282         
283         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 0)->data;
284         if (tmpinfo->type != MIMETYPE_APPLICATION)
285                 return FALSE;
286         if (g_ascii_strcasecmp(tmpinfo->subtype, "pgp-encrypted"))
287                 return FALSE;
288         
289         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
290         if (tmpinfo->type != MIMETYPE_APPLICATION)
291                 return FALSE;
292         if (g_ascii_strcasecmp(tmpinfo->subtype, "octet-stream"))
293                 return FALSE;
294         
295         textdata = get_part_as_string(tmpinfo);
296         if (!textdata)
297                 return FALSE;
298         
299         if (!pgp_locate_armor_header(textdata, begin_indicator)) {
300                 g_free(textdata);
301                 return FALSE;
302         }
303         if (!pgp_locate_armor_header(textdata, end_indicator)) {
304                 g_free(textdata);
305                 return FALSE;
306         }
307
308         g_free(textdata);
309
310         return TRUE;
311 }
312
313 static MimeInfo *pgpmime_decrypt(MimeInfo *mimeinfo)
314 {
315         MimeInfo *encinfo, *decinfo, *parseinfo;
316         gpgme_data_t cipher = NULL, plain = NULL;
317         static gint id = 0;
318         FILE *dstfp;
319         gchar *fname;
320         gpgme_verify_result_t sigstat = NULL;
321         PrivacyDataPGP *data = NULL;
322         gpgme_ctx_t ctx;
323         gchar *chars;
324         size_t len;
325         gpgme_error_t err;
326
327         if ((err = gpgme_new(&ctx)) != GPG_ERR_NO_ERROR) {
328                 debug_print(("Couldn't initialize GPG context, %s\n"), gpgme_strerror(err));
329                 privacy_set_error(_("Couldn't initialize GPG context, %s"), gpgme_strerror(err));
330                 return NULL;
331         }
332         
333         cm_return_val_if_fail(pgpmime_is_encrypted(mimeinfo), NULL);
334         
335         encinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
336
337         cipher = sgpgme_data_from_mimeinfo(encinfo);
338         plain = sgpgme_decrypt_verify(cipher, &sigstat, ctx);
339
340         gpgme_data_release(cipher);
341         if (plain == NULL) {
342                 debug_print("plain is null!\n");
343                 gpgme_release(ctx);
344                 return NULL;
345         }
346
347         fname = g_strdup_printf("%s%cplaintext.%08x",
348                 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
349
350         if ((dstfp = g_fopen(fname, "wb")) == NULL) {
351                 FILE_OP_ERROR(fname, "fopen");
352                 privacy_set_error(_("Couldn't open decrypted file %s"), fname);
353                 g_free(fname);
354                 gpgme_data_release(plain);
355                 gpgme_release(ctx);
356                 debug_print("can't open!\n");
357                 return NULL;
358         }
359
360         if (fprintf(dstfp, "MIME-Version: 1.0\n") < 0) {
361                 FILE_OP_ERROR(fname, "fprintf");
362                 fclose(dstfp);
363                 privacy_set_error(_("Couldn't write to decrypted file %s"), fname);
364                 g_free(fname);
365                 gpgme_data_release(plain);
366                 gpgme_release(ctx);
367                 debug_print("can't open!\n");
368                 return NULL;
369         }
370
371         chars = sgpgme_data_release_and_get_mem(plain, &len);
372         if (len > 0) {
373                 if (fwrite(chars, 1, len, dstfp) < len) {
374                         FILE_OP_ERROR(fname, "fwrite");
375                         g_free(chars);
376                         fclose(dstfp);
377                         privacy_set_error(_("Couldn't write to decrypted file %s"), fname);
378                         g_free(fname);
379                         gpgme_data_release(plain);
380                         gpgme_release(ctx);
381                         debug_print("can't open!\n");
382                         return NULL;
383                 }
384         }
385         g_free(chars);
386
387         if (fclose(dstfp) == EOF) {
388                 FILE_OP_ERROR(fname, "fclose");
389                 privacy_set_error(_("Couldn't close decrypted file %s"), fname);
390                 g_free(fname);
391                 gpgme_data_release(plain);
392                 gpgme_release(ctx);
393                 debug_print("can't open!\n");
394                 return NULL;
395         }
396
397         parseinfo = procmime_scan_file(fname);
398         g_free(fname);
399         if (parseinfo == NULL) {
400                 gpgme_release(ctx);
401                 privacy_set_error(_("Couldn't parse decrypted file."));
402                 return NULL;
403         }
404         decinfo = g_node_first_child(parseinfo->node) != NULL ?
405                 g_node_first_child(parseinfo->node)->data : NULL;
406         if (decinfo == NULL) {
407                 privacy_set_error(_("Couldn't parse decrypted file parts."));
408                 gpgme_release(ctx);
409                 return NULL;
410         }
411
412         g_node_unlink(decinfo->node);
413         procmime_mimeinfo_free_all(&parseinfo);
414
415         decinfo->tmp = TRUE;
416
417         if (sigstat != NULL && sigstat->signatures != NULL) {
418                 if (decinfo->privacy != NULL) {
419                         data = (PrivacyDataPGP *) decinfo->privacy;
420                 } else {
421                         data = pgpmime_new_privacydata();
422                         decinfo->privacy = (PrivacyData *) data;        
423                 }
424                 if (data != NULL) {
425                         data->done_sigtest = TRUE;
426                         data->is_signed = TRUE;
427                         data->sigstatus = sigstat;
428                         if (data->ctx)
429                                 gpgme_release(data->ctx);
430                         data->ctx = ctx;
431                 }
432         } else
433                 gpgme_release(ctx);
434
435         return decinfo;
436 }
437
438 gboolean pgpmime_sign(MimeInfo *mimeinfo, PrefsAccount *account, const gchar *from_addr)
439 {
440         MimeInfo *msgcontent, *sigmultipart, *newinfo;
441         gchar *textstr, *micalg = NULL;
442         FILE *fp;
443         gchar *boundary = NULL;
444         gchar *sigcontent;
445         gpgme_ctx_t ctx;
446         gpgme_data_t gpgtext, gpgsig;
447         gpgme_error_t err;
448         size_t len;
449         struct passphrase_cb_info_s info;
450         gpgme_sign_result_t result = NULL;
451         gchar *test_msg;
452         
453         fp = my_tmpfile();
454         if (fp == NULL) {
455                 perror("my_tmpfile");
456                 privacy_set_error(_("Couldn't create temporary file: %s"), g_strerror(errno));
457                 return FALSE;
458         }
459         procmime_write_mimeinfo(mimeinfo, fp);
460         rewind(fp);
461
462         /* read temporary file into memory */
463         test_msg = file_read_stream_to_str(fp);
464         fclose(fp);
465         
466         memset (&info, 0, sizeof info);
467
468         /* remove content node from message */
469         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
470         g_node_unlink(msgcontent->node);
471
472         /* create temporary multipart for content */
473         sigmultipart = procmime_mimeinfo_new();
474         sigmultipart->type = MIMETYPE_MULTIPART;
475         sigmultipart->subtype = g_strdup("signed");
476         
477         do {
478                 g_free(boundary);
479                 boundary = generate_mime_boundary("Sig");
480         } while (strstr(test_msg, boundary) != NULL);
481         
482         g_free(test_msg);
483
484         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
485                             g_strdup(boundary));
486         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
487                             g_strdup("application/pgp-signature"));
488         g_node_append(sigmultipart->node, msgcontent->node);
489         g_node_append(mimeinfo->node, sigmultipart->node);
490
491         /* write message content to temporary file */
492         fp = my_tmpfile();
493         if (fp == NULL) {
494                 perror("my_tmpfile");
495                 privacy_set_error(_("Couldn't create temporary file: %s"), g_strerror(errno));
496                 return FALSE;
497         }
498         procmime_write_mimeinfo(sigmultipart, fp);
499         rewind(fp);
500
501         /* read temporary file into memory */
502         textstr = get_canonical_content(fp, boundary);
503
504         g_free(boundary);
505         fclose(fp);
506
507         gpgme_data_new_from_mem(&gpgtext, textstr, (size_t)strlen(textstr), 0);
508         gpgme_data_new(&gpgsig);
509         if ((err = gpgme_new(&ctx)) != GPG_ERR_NO_ERROR) {
510                 debug_print(("Couldn't initialize GPG context, %s\n"), gpgme_strerror(err));
511                 privacy_set_error(_("Couldn't initialize GPG context, %s"), gpgme_strerror(err));
512                 return FALSE;
513         }
514         gpgme_set_textmode(ctx, 1);
515         gpgme_set_armor(ctx, 1);
516         gpgme_signers_clear (ctx);
517
518         if (!sgpgme_setup_signers(ctx, account, from_addr)) {
519                 gpgme_release(ctx);
520                 return FALSE;
521         }
522
523         prefs_gpg_enable_agent(prefs_gpg_get_config()->use_gpg_agent);
524         if (g_getenv("GPG_AGENT_INFO") && prefs_gpg_get_config()->use_gpg_agent) {
525                 debug_print("GPG_AGENT_INFO environment defined, running without passphrase callback\n");
526         } else {
527                 info.c = ctx;
528                 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
529         }
530
531         err = gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH);
532         if (err != GPG_ERR_NO_ERROR) {
533                 if (err == GPG_ERR_CANCELED) {
534                         /* ignore cancelled signing */
535                         privacy_reset_error();
536                         debug_print("gpgme_op_sign cancelled\n");
537                 } else {
538                         privacy_set_error(_("Data signing failed, %s"), gpgme_strerror(err));
539                         debug_print("gpgme_op_sign error : %x\n", err);
540                 }
541                 gpgme_release(ctx);
542                 return FALSE;
543         }
544         result = gpgme_op_sign_result(ctx);
545         if (result && result->signatures) {
546                 gpgme_new_signature_t sig = result->signatures;
547                 if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
548                         gchar *down_algo = g_ascii_strdown(gpgme_hash_algo_name(
549                                 result->signatures->hash_algo), -1);
550                         micalg = g_strdup_printf("pgp-%s", down_algo);
551                         g_free(down_algo);
552                 } else {
553                         micalg = g_strdup(gpgme_hash_algo_name(
554                                 result->signatures->hash_algo));
555                 }
556                 while (sig) {
557                         debug_print("valid signature: %s\n", sig->fpr);
558                         sig = sig->next;
559                 }
560         } else if (result && result->invalid_signers) {
561                 gpgme_invalid_key_t invalid = result->invalid_signers;
562                 while (invalid) {
563                         g_warning("invalid signer: %s (%s)", invalid->fpr, 
564                                 gpgme_strerror(invalid->reason));
565                         privacy_set_error(_("Data signing failed due to invalid signer: %s"), 
566                                 gpgme_strerror(invalid->reason));
567                         invalid = invalid->next;
568                 }
569                 gpgme_release(ctx);
570                 return FALSE;
571         } else {
572                 /* can't get result (maybe no signing key?) */
573                 debug_print("gpgme_op_sign_result error\n");
574                 privacy_set_error(_("Data signing failed, no results."));
575                 gpgme_release(ctx);
576                 return FALSE;
577         }
578
579         sigcontent = sgpgme_data_release_and_get_mem(gpgsig, &len);
580         gpgme_data_release(gpgtext);
581         g_free(textstr);
582
583         if (sigcontent == NULL || len <= 0) {
584                 g_warning("sgpgme_data_release_and_get_mem failed");
585                 privacy_set_error(_("Data signing failed, no contents."));
586                 g_free(micalg);
587                 g_free(sigcontent);
588                 return FALSE;
589         }
590
591         /* add signature */
592         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
593                             micalg);
594
595         newinfo = procmime_mimeinfo_new();
596         newinfo->type = MIMETYPE_APPLICATION;
597         newinfo->subtype = g_strdup("pgp-signature");
598         newinfo->description = g_strdup(_("OpenPGP digital signature"));
599         newinfo->content = MIMECONTENT_MEM;
600         newinfo->data.mem = g_malloc(len + 1);
601         g_memmove(newinfo->data.mem, sigcontent, len);
602         newinfo->data.mem[len] = '\0';
603         g_node_append(sigmultipart->node, newinfo->node);
604
605         g_free(sigcontent);
606         gpgme_release(ctx);
607
608         return TRUE;
609 }
610 gchar *pgpmime_get_encrypt_data(GSList *recp_names)
611 {
612         return sgpgme_get_encrypt_data(recp_names, GPGME_PROTOCOL_OpenPGP);
613 }
614
615 static const gchar *pgpmime_get_encrypt_warning(void)
616 {
617         if (prefs_gpg_should_skip_encryption_warning(pgpmime_system.id))
618                 return NULL;
619         else
620                 return _("Please note that email headers, like Subject, "
621                          "are not encrypted by the PGP/Mime system.");
622 }
623
624 static void pgpmime_inhibit_encrypt_warning(gboolean inhibit)
625 {
626         if (inhibit)
627                 prefs_gpg_add_skip_encryption_warning(pgpmime_system.id);
628         else
629                 prefs_gpg_remove_skip_encryption_warning(pgpmime_system.id);
630 }
631
632 gboolean pgpmime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
633 {
634         MimeInfo *msgcontent, *encmultipart, *newinfo;
635         FILE *fp;
636         gchar *boundary, *enccontent;
637         size_t len;
638         gchar *textstr;
639         gpgme_data_t gpgtext = NULL, gpgenc = NULL;
640         gpgme_ctx_t ctx = NULL;
641         gpgme_key_t *kset = NULL;
642         gchar **fprs = g_strsplit(encrypt_data, " ", -1);
643         gint i = 0;
644         gpgme_error_t err;
645         
646         while (fprs[i] && strlen(fprs[i])) {
647                 i++;
648         }
649         
650         kset = g_malloc(sizeof(gpgme_key_t)*(i+1));
651         memset(kset, 0, sizeof(gpgme_key_t)*(i+1));
652         if ((err = gpgme_new(&ctx)) != GPG_ERR_NO_ERROR) {
653                 debug_print(("Couldn't initialize GPG context, %s\n"), gpgme_strerror(err));
654                 privacy_set_error(_("Couldn't initialize GPG context, %s"), gpgme_strerror(err));
655                 g_free(kset);
656                 return FALSE;
657         }
658         i = 0;
659         while (fprs[i] && strlen(fprs[i])) {
660                 gpgme_key_t key;
661                 err = gpgme_get_key(ctx, fprs[i], &key, 0);
662                 if (err) {
663                         debug_print("can't add key '%s'[%d] (%s)\n", fprs[i],i, gpgme_strerror(err));
664                         privacy_set_error(_("Couldn't add GPG key %s, %s"), fprs[i], gpgme_strerror(err));
665                         g_free(kset);
666                         return FALSE;
667                 }
668                 debug_print("found %s at %d\n", fprs[i], i);
669                 kset[i] = key;
670                 i++;
671         }
672         
673         debug_print("Encrypting message content\n");
674
675         /* remove content node from message */
676         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
677         g_node_unlink(msgcontent->node);
678
679         /* create temporary multipart for content */
680         encmultipart = procmime_mimeinfo_new();
681         encmultipart->type = MIMETYPE_MULTIPART;
682         encmultipart->subtype = g_strdup("encrypted");
683         boundary = generate_mime_boundary("Encrypt");
684         g_hash_table_insert(encmultipart->typeparameters, g_strdup("boundary"),
685                             g_strdup(boundary));
686         g_hash_table_insert(encmultipart->typeparameters, g_strdup("protocol"),
687                             g_strdup("application/pgp-encrypted"));
688         g_node_append(encmultipart->node, msgcontent->node);
689
690         /* write message content to temporary file */
691         fp = my_tmpfile();
692         if (fp == NULL) {
693                 perror("my_tmpfile");
694                 privacy_set_error(_("Couldn't create temporary file, %s"), g_strerror(errno));
695                 g_free(kset);
696                 return FALSE;
697         }
698         procmime_write_mimeinfo(encmultipart, fp);
699         rewind(fp);
700
701         /* read temporary file into memory */
702         textstr = get_canonical_content(fp, boundary);
703
704         g_free(boundary);
705         fclose(fp);
706
707         /* encrypt data */
708         gpgme_data_new_from_mem(&gpgtext, textstr, (size_t)strlen(textstr), 0);
709         gpgme_data_new(&gpgenc);
710         gpgme_set_armor(ctx, 1);
711         cm_gpgme_data_rewind(gpgtext);
712         
713         err = gpgme_op_encrypt(ctx, kset, GPGME_ENCRYPT_ALWAYS_TRUST, gpgtext, gpgenc);
714
715         enccontent = sgpgme_data_release_and_get_mem(gpgenc, &len);
716         gpgme_data_release(gpgtext);
717         g_free(textstr);
718         g_free(kset);
719
720         if (enccontent == NULL || len <= 0) {
721                 g_warning("sgpgme_data_release_and_get_mem failed");
722                 privacy_set_error(_("Encryption failed, %s"), gpgme_strerror(err));
723                 gpgme_release(ctx);
724                 g_free(enccontent);
725                 return FALSE;
726         }
727
728         /* create encrypted multipart */
729         g_node_unlink(msgcontent->node);
730         procmime_mimeinfo_free_all(&msgcontent);
731         g_node_append(mimeinfo->node, encmultipart->node);
732
733         newinfo = procmime_mimeinfo_new();
734         newinfo->type = MIMETYPE_APPLICATION;
735         newinfo->subtype = g_strdup("pgp-encrypted");
736         newinfo->content = MIMECONTENT_MEM;
737         newinfo->data.mem = g_strdup("Version: 1\n");
738         g_node_append(encmultipart->node, newinfo->node);
739
740         newinfo = procmime_mimeinfo_new();
741         newinfo->type = MIMETYPE_APPLICATION;
742         newinfo->subtype = g_strdup("octet-stream");
743         newinfo->content = MIMECONTENT_MEM;
744         newinfo->data.mem = g_malloc(len + 1);
745         g_memmove(newinfo->data.mem, enccontent, len);
746         newinfo->data.mem[len] = '\0';
747         g_node_append(encmultipart->node, newinfo->node);
748
749         g_free(enccontent);
750         gpgme_release(ctx);
751
752         return TRUE;
753 }
754
755 static PrivacySystem pgpmime_system = {
756         "pgpmime",                      /* id */
757         "PGP MIME",                     /* name */
758
759         pgpmime_free_privacydata,       /* free_privacydata */
760
761         pgpmime_is_signed,              /* is_signed(MimeInfo *) */
762         pgpmime_check_signature,        /* check_signature(MimeInfo *) */
763         pgpmime_get_sig_status,         /* get_sig_status(MimeInfo *) */
764         pgpmime_get_sig_info_short,     /* get_sig_info_short(MimeInfo *) */
765         pgpmime_get_sig_info_full,      /* get_sig_info_full(MimeInfo *) */
766
767         pgpmime_is_encrypted,           /* is_encrypted(MimeInfo *) */
768         pgpmime_decrypt,                /* decrypt(MimeInfo *) */
769
770         TRUE,
771         pgpmime_sign,
772
773         TRUE,
774         pgpmime_get_encrypt_data,
775         pgpmime_encrypt,
776         pgpmime_get_encrypt_warning,
777         pgpmime_inhibit_encrypt_warning,
778         prefs_gpg_auto_check_signatures,
779 };
780
781 void pgpmime_init()
782 {
783         privacy_register_system(&pgpmime_system);
784 }
785
786 void pgpmime_done()
787 {
788         privacy_unregister_system(&pgpmime_system);
789 }
790
791 struct PluginFeature *plugin_provides(void)
792 {
793         static struct PluginFeature features[] = 
794                 { {PLUGIN_PRIVACY, N_("PGP/Mime")},
795                   {PLUGIN_NOTHING, NULL}};
796         return features;
797 }
798 #endif /* USE_GPGME */