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