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