Fix a leak, CID #1220437.
[claws.git] / src / plugins / smime / smime.c
1 /* 
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2016 Colin Leroy and 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 <gpgme.h>
29 #include <ctype.h>
30 #include <glib/gi18n.h>
31
32 #include "utils.h"
33 #include "privacy.h"
34 #include "procmime.h"
35
36 #include "smime.h"
37 #include <plugins/pgpcore/sgpgme.h>
38 #include <plugins/pgpcore/prefs_gpg.h>
39 #include <plugins/pgpcore/pgp_utils.h>
40 #include <plugins/pgpcore/passphrase.h>
41
42 #include "alertpanel.h"
43 #include "prefs_common.h"
44 #include "procmime.h"
45 #include "plugin.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 smime_system;
60
61 static gint smime_check_signature(MimeInfo *mimeinfo);
62
63 static PrivacyDataPGP *smime_new_privacydata()
64 {
65         PrivacyDataPGP *data;
66         gpgme_ctx_t     ctx;
67
68         if (gpgme_new(&ctx) != GPG_ERR_NO_ERROR) {
69                 debug_print("gpgme_new failed\n");
70                 return NULL;
71         }
72
73         data = g_new0(PrivacyDataPGP, 1);
74         data->data.system = &smime_system;
75         data->done_sigtest = FALSE;
76         data->is_signed = FALSE;
77         data->sigstatus = NULL;
78         data->ctx = ctx;
79         
80         return data;
81 }
82
83 static void smime_free_privacydata(PrivacyData *_data)
84 {
85         PrivacyDataPGP *data = (PrivacyDataPGP *) _data;
86         gpgme_release(data->ctx);
87         g_free(data);
88 }
89
90 static gboolean smime_is_signed(MimeInfo *mimeinfo)
91 {
92         MimeInfo *parent;
93         MimeInfo *signature;
94         const gchar *protocol, *tmpstr;
95         PrivacyDataPGP *data = NULL;
96         
97         cm_return_val_if_fail(mimeinfo != NULL, FALSE);
98         if (mimeinfo->privacy != NULL) {
99                 data = (PrivacyDataPGP *) mimeinfo->privacy;
100                 if (data->done_sigtest)
101                         return data->is_signed;
102         }
103         
104         if (!g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-mime") ||
105             !g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-mime")) {
106                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
107                 if (tmpstr && !g_ascii_strcasecmp(tmpstr, "signed-data")) {
108                         if (data == NULL) {
109                                 data = smime_new_privacydata();
110                                 if (!data)
111                                         return FALSE;
112                                 mimeinfo->privacy = (PrivacyData *) data;
113                         }
114
115                         data->done_sigtest = TRUE;
116                         data->is_signed = TRUE;
117                         smime_check_signature(mimeinfo);
118                         return TRUE;
119                 }
120         }
121
122         /* check parent */
123         parent = procmime_mimeinfo_parent(mimeinfo);
124         if (parent == NULL)
125                 return FALSE;
126         
127         if ((parent->type != MIMETYPE_MULTIPART) ||
128             g_ascii_strcasecmp(parent->subtype, "signed"))
129                 return FALSE;
130         protocol = procmime_mimeinfo_get_parameter(parent, "protocol");
131         if ((protocol == NULL) || 
132             (g_ascii_strcasecmp(protocol, "application/pkcs7-signature") &&
133              g_ascii_strcasecmp(protocol, "application/x-pkcs7-signature")))
134                 return FALSE;
135
136         /* check if mimeinfo is the first child */
137         if (parent->node->children->data != mimeinfo)
138                 return FALSE;
139
140
141         /* check signature */
142         signature = parent->node->children->next != NULL ? 
143             (MimeInfo *) parent->node->children->next->data : NULL;
144         if (signature == NULL)
145                 return FALSE;
146         if ((signature->type != MIMETYPE_APPLICATION) ||
147             (g_ascii_strcasecmp(signature->subtype, "pkcs7-signature") &&
148              g_ascii_strcasecmp(signature->subtype, "x-pkcs7-signature")))
149                 return FALSE;
150
151         if (data == NULL) {
152                 data = smime_new_privacydata();
153                 if (!data)
154                         return FALSE;
155                 mimeinfo->privacy = (PrivacyData *) data;
156         }
157         
158         data->done_sigtest = TRUE;
159         data->is_signed = TRUE;
160
161         return TRUE;
162 }
163
164 static gchar *get_canonical_content(FILE *fp, const gchar *boundary)
165 {
166         gchar *ret;
167         GString *textbuffer;
168         guint boundary_len = 0;
169         gchar buf[BUFFSIZE];
170
171         if (boundary) {
172                 boundary_len = strlen(boundary);
173                 while (fgets(buf, sizeof(buf), fp) != NULL)
174                         if (IS_BOUNDARY(buf, boundary, boundary_len))
175                                 break;
176         }
177         
178         textbuffer = g_string_new("");
179         while (fgets(buf, sizeof(buf), fp) != NULL) {
180                 gchar *buf2;
181
182                 if (boundary && IS_BOUNDARY(buf, boundary, boundary_len))
183                         break;
184                 
185                 buf2 = canonicalize_str(buf);
186                 g_string_append(textbuffer, buf2);
187                 g_free(buf2);
188         }
189         g_string_truncate(textbuffer, textbuffer->len - 2);
190                 
191         ret = textbuffer->str;
192         g_string_free(textbuffer, FALSE);
193
194         return ret;
195 }
196
197 static gint smime_check_signature(MimeInfo *mimeinfo)
198 {
199         PrivacyDataPGP *data;
200         MimeInfo *parent, *signature;
201         FILE *fp;
202         gchar *boundary;
203         gchar *textstr = NULL;
204         const gchar *tmpstr;
205         gpgme_data_t sigdata = NULL, textdata = NULL;
206         gpgme_error_t err;
207         EncodingType oldenc = ENC_BINARY;
208
209         cm_return_val_if_fail(mimeinfo != NULL, -1);
210         cm_return_val_if_fail(mimeinfo->privacy != NULL, -1);
211
212         data = (PrivacyDataPGP *) mimeinfo->privacy;
213
214         if (!data->ctx) {
215                 if ((err = gpgme_new(&data->ctx)) != GPG_ERR_NO_ERROR) {
216                         debug_print("gpgme_new failed: %s\n",
217                                 gpgme_strerror(err));
218                         return -1;
219                 }
220         }
221
222         debug_print("Checking S/MIME signature\n");
223
224         err = gpgme_set_protocol(data->ctx, GPGME_PROTOCOL_CMS);
225
226         if (err) {
227                 debug_print ("gpgme_set_protocol failed: %s\n",
228                    gpgme_strerror (err));
229         }
230         parent = procmime_mimeinfo_parent(mimeinfo);
231
232         fp = g_fopen(parent->data.filename, "rb");
233         cm_return_val_if_fail(fp != NULL, SIGNATURE_INVALID);
234         
235         boundary = g_hash_table_lookup(parent->typeparameters, "boundary");
236         if (!boundary) {
237                 gchar *tmpfile = get_tmp_file();
238                 debug_print("no boundary\n");
239                 if (tmpfile) {
240                         if (mimeinfo->encoding_type != ENC_BASE64) {
241                                 procmime_encode_content(mimeinfo, ENC_BASE64);
242                         }
243                         oldenc = mimeinfo->encoding_type;
244                         if (mimeinfo->encoding_type == ENC_BASE64)
245                                 mimeinfo->encoding_type = ENC_BINARY;
246                         if (procmime_get_part(tmpfile, mimeinfo) == 0) {
247                                 textstr = file_read_to_str(tmpfile);
248                         } else {
249                                 textstr = NULL;
250                         }
251                         if (mimeinfo->encoding_type != oldenc)
252                                 mimeinfo->encoding_type = oldenc;
253                 }
254                 g_free(tmpfile);
255         } else {
256                 textstr = get_canonical_content(fp, boundary);
257         }
258         err = gpgme_data_new_from_mem(&textdata, textstr, textstr?strlen(textstr):0, 0);
259         
260         if (err) {
261                 debug_print ("gpgme_data_new_from_mem failed: %s\n",
262                    gpgme_strerror (err));
263         }
264
265         if (!g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-mime") ||
266             !g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-mime")) {
267                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
268                 if (tmpstr && !g_ascii_strcasecmp(tmpstr, "signed-data")) {
269                         gpgme_data_t cipher;
270                         size_t len;
271                         if (oldenc == ENC_BASE64)
272                                 gpgme_data_set_encoding (textdata, GPGME_DATA_ENCODING_BASE64);
273                         gpgme_data_new(&cipher);
274                         data->sigstatus =
275                                 sgpgme_verify_signature (data->ctx, textdata, NULL, cipher);
276                         gpgme_data_release(textdata);
277                         g_free(textstr);
278                         cm_gpgme_data_rewind(cipher);
279                         textstr = sgpgme_data_release_and_get_mem(cipher, &len);
280                         fclose(fp);
281                         if (textstr && len > 0)
282                                 textstr[len-1]='\0';
283
284                         if (textstr && len) {
285                                 gchar *tmp_file = get_tmp_file();
286                                 MimeInfo *newinfo = NULL, *decinfo = NULL, *parentinfo = NULL;
287
288                                 str_write_to_file(textstr, tmp_file);
289                                 newinfo = procmime_scan_file(tmp_file);
290                                 decinfo = g_node_first_child(newinfo->node) != NULL ?
291                                         g_node_first_child(newinfo->node)->data : NULL;
292
293                                 if (decinfo == NULL) {
294                                         g_free(textstr);
295                                         return -1;
296                                 }
297
298                                 g_node_unlink(decinfo->node);
299                                 procmime_mimeinfo_free_all(&newinfo);
300                                 decinfo->tmp = TRUE;
301                                 parentinfo = procmime_mimeinfo_parent(mimeinfo);
302
303                                 if (parentinfo->type == MIMETYPE_MESSAGE && 
304                                     !strcmp(parentinfo->subtype, "rfc822")) {
305                                         procmime_decode_content(parentinfo);
306                                         procmime_encode_content(parentinfo, ENC_BASE64);
307                                         procmime_encode_content(parentinfo, ENC_8BIT);
308                                         if (parentinfo->content == MIMECONTENT_MEM) {
309                                                 gint newlen = 
310                                                         (gint)(strstr(parentinfo->data.mem, "\n\n") - parentinfo->data.mem);
311                                                 if (newlen > 0)
312                                                         parentinfo->length = newlen;
313                                         }
314                                 }
315                                 g_node_prepend(parentinfo->node, decinfo->node);
316                                 return 0;
317                         } else {
318                                 g_free(textstr);
319                                 return -1;
320                         }
321                 }
322         }
323
324         signature = (MimeInfo *) mimeinfo->node->next->data;
325         sigdata = sgpgme_data_from_mimeinfo(signature);
326
327         err = 0;
328         if (signature->encoding_type == ENC_BASE64) {
329                 err = gpgme_data_set_encoding (sigdata, GPGME_DATA_ENCODING_BASE64);
330         }
331         
332         if (err) {
333                 debug_print ("gpgme_data_set_encoding failed: %s\n",
334                         gpgme_strerror (err));
335         }
336
337         data->sigstatus =
338                 sgpgme_verify_signature (data->ctx, sigdata, textdata, NULL);
339
340         gpgme_data_release(sigdata);
341         gpgme_data_release(textdata);
342         g_free(textstr);
343         fclose(fp);
344         
345         return 0;
346 }
347
348 static SignatureStatus smime_get_sig_status(MimeInfo *mimeinfo)
349 {
350         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
351         
352         cm_return_val_if_fail(data != NULL, SIGNATURE_INVALID);
353
354         return sgpgme_sigstat_gpgme_to_privacy(data->ctx, data->sigstatus);
355 }
356
357 static gchar *smime_get_sig_info_short(MimeInfo *mimeinfo)
358 {
359         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
360         
361         cm_return_val_if_fail(data != NULL, g_strdup("Error"));
362
363         return sgpgme_sigstat_info_short(data->ctx, data->sigstatus);
364 }
365
366 static gchar *smime_get_sig_info_full(MimeInfo *mimeinfo)
367 {
368         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
369         
370         cm_return_val_if_fail(data != NULL, g_strdup("Error"));
371
372         return sgpgme_sigstat_info_full(data->ctx, data->sigstatus);
373 }
374
375 static gboolean smime_is_encrypted(MimeInfo *mimeinfo)
376 {
377         const gchar *tmpstr;
378         
379         if (mimeinfo->type != MIMETYPE_APPLICATION)
380                 return FALSE;
381         if (!g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-mime")) {
382                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
383                 if (tmpstr && g_ascii_strcasecmp(tmpstr, "enveloped-data"))
384                         return FALSE;
385                 else 
386                         return TRUE;
387
388         } else if (!g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-mime")) {
389                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
390                 if (tmpstr && g_ascii_strcasecmp(tmpstr, "enveloped-data"))
391                         return FALSE;
392                 else 
393                         return TRUE;
394         }
395         return FALSE;
396 }
397
398 static MimeInfo *smime_decrypt(MimeInfo *mimeinfo)
399 {
400         MimeInfo *encinfo, *decinfo, *parseinfo;
401         gpgme_data_t cipher = NULL, plain = NULL;
402         static gint id = 0;
403         FILE *dstfp;
404         gchar *fname;
405         gpgme_verify_result_t sigstat = NULL;
406         PrivacyDataPGP *data = NULL;
407         gpgme_ctx_t ctx;
408         gpgme_error_t err;
409         gchar *chars;
410         size_t len;
411
412         cm_return_val_if_fail(smime_is_encrypted(mimeinfo), NULL);
413         
414         if ((err = gpgme_new(&ctx)) != GPG_ERR_NO_ERROR) {
415                 privacy_set_error(_("Couldn't initialize GPG context, %s"), gpgme_strerror(err));
416                 return NULL;
417         }
418
419         err = gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
420         if (err) {
421                 debug_print ("gpgme_set_protocol failed: %s\n",
422                    gpgme_strerror (err));
423                 privacy_set_error(_("Couldn't set GPG protocol, %s"), gpgme_strerror(err));
424                 gpgme_release(ctx);
425                 return NULL;
426         }
427         gpgme_set_armor(ctx, TRUE);
428
429         encinfo = mimeinfo;
430
431         cipher = sgpgme_data_from_mimeinfo(encinfo);
432         
433         plain = sgpgme_decrypt_verify(cipher, &sigstat, ctx);
434
435         gpgme_data_release(cipher);
436         if (plain == NULL) {
437                 debug_print("plain is null!\n");
438                 gpgme_release(ctx);
439                 return NULL;
440         }
441
442         fname = g_strdup_printf("%s%cplaintext.%08x",
443                 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
444
445         if ((dstfp = g_fopen(fname, "wb")) == NULL) {
446                 FILE_OP_ERROR(fname, "g_fopen");
447                 g_free(fname);
448                 gpgme_data_release(plain);
449                 gpgme_release(ctx);
450                 debug_print("can't open!\n");
451                 privacy_set_error(_("Couldn't open temporary file"));
452                 return NULL;
453         }
454
455         if (fprintf(dstfp, "MIME-Version: 1.0\n") < 0) {
456                 FILE_OP_ERROR(fname, "fprintf");
457                 g_free(fname);
458                 fclose(dstfp);
459                 gpgme_data_release(plain);
460                 gpgme_release(ctx);
461                 debug_print("can't close!\n");
462                 privacy_set_error(_("Couldn't write to temporary file"));
463                 return NULL;
464         }
465
466         chars = sgpgme_data_release_and_get_mem(plain, &len);
467
468         if (len > 0) {
469                 if (fwrite(chars, 1, len, dstfp) < len) {
470                         FILE_OP_ERROR(fname, "fwrite");
471                         fclose(dstfp);
472                         g_free(fname);
473                         g_free(chars);
474                         gpgme_data_release(plain);
475                         gpgme_release(ctx);
476                         debug_print("can't write!\n");
477                         privacy_set_error(_("Couldn't write to temporary file"));
478                         return NULL;
479                 }
480         }
481         if (fclose(dstfp) == EOF) {
482                 FILE_OP_ERROR(fname, "fclose");
483                 g_free(fname);
484                 g_free(chars);
485                 gpgme_data_release(plain);
486                 gpgme_release(ctx);
487                 debug_print("can't close!\n");
488                 privacy_set_error(_("Couldn't close temporary file"));
489                 return NULL;
490         }
491         g_free(chars);
492
493         parseinfo = procmime_scan_file(fname);
494         g_free(fname);
495         if (parseinfo == NULL) {
496                 privacy_set_error(_("Couldn't parse decrypted file."));
497                 gpgme_release(ctx);
498                 return NULL;
499         }
500         decinfo = g_node_first_child(parseinfo->node) != NULL ?
501                 g_node_first_child(parseinfo->node)->data : NULL;
502         if (decinfo == NULL) {
503                 privacy_set_error(_("Couldn't parse decrypted file parts."));
504                 gpgme_release(ctx);
505                 return NULL;
506         }
507
508         g_node_unlink(decinfo->node);
509         procmime_mimeinfo_free_all(&parseinfo);
510
511         decinfo->tmp = TRUE;
512
513         if (sigstat != NULL && sigstat->signatures != NULL) {
514                 if (decinfo->privacy != NULL) {
515                         data = (PrivacyDataPGP *) decinfo->privacy;
516                 } else {
517                         data = smime_new_privacydata();
518                         if (!data) {
519                                 gpgme_release(ctx);
520                                 return NULL;
521                         }
522                         decinfo->privacy = (PrivacyData *) data;        
523                 }
524                 data->done_sigtest = TRUE;
525                 data->is_signed = TRUE;
526                 data->sigstatus = sigstat;
527                 if (data->ctx)
528                         gpgme_release(data->ctx);
529                 data->ctx = ctx;
530         } else
531                 gpgme_release(ctx);
532         
533         
534         
535         return decinfo;
536 }
537
538 gboolean smime_sign(MimeInfo *mimeinfo, PrefsAccount *account, const gchar *from_addr)
539 {
540         MimeInfo *msgcontent, *sigmultipart, *newinfo;
541         gchar *textstr, *micalg = NULL;
542         FILE *fp;
543         gchar *boundary = NULL;
544         gchar *sigcontent;
545         gpgme_ctx_t ctx;
546         gpgme_data_t gpgtext, gpgsig;
547         gpgme_error_t err;
548         size_t len;
549         struct passphrase_cb_info_s info;
550         gpgme_sign_result_t result = NULL;
551         gchar *test_msg;
552         gchar *real_content = NULL;
553         
554         fp = my_tmpfile();
555         if (fp == NULL) {
556                 perror("my_tmpfile");
557                 return FALSE;
558         }
559         procmime_write_mimeinfo(mimeinfo, fp);
560         rewind(fp);
561
562         /* read temporary file into memory */
563         test_msg = file_read_stream_to_str(fp);
564         fclose(fp);
565         
566         memset (&info, 0, sizeof info);
567
568         /* remove content node from message */
569         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
570         g_node_unlink(msgcontent->node);
571
572         /* create temporary multipart for content */
573         sigmultipart = procmime_mimeinfo_new();
574         sigmultipart->type = MIMETYPE_MULTIPART;
575         sigmultipart->subtype = g_strdup("signed");
576         
577         do {
578                 if (boundary)
579                         g_free(boundary);
580                 boundary = generate_mime_boundary("Sig");
581         } while (strstr(test_msg, boundary) != NULL);
582         
583         g_free(test_msg);
584
585         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
586                             g_strdup(boundary));
587         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
588                             g_strdup("application/pkcs7-signature"));
589         g_node_append(sigmultipart->node, msgcontent->node);
590         g_node_append(mimeinfo->node, sigmultipart->node);
591
592         /* write message content to temporary file */
593         fp = my_tmpfile();
594         if (fp == NULL) {
595                 perror("my_tmpfile");
596                 return FALSE;
597         }
598         procmime_write_mimeinfo(sigmultipart, fp);
599         rewind(fp);
600
601         /* read temporary file into memory */
602         textstr = get_canonical_content(fp, boundary);
603
604         g_free(boundary);
605
606         fclose(fp);
607
608         gpgme_data_new_from_mem(&gpgtext, textstr, textstr?strlen(textstr):0, 0);
609         gpgme_data_new(&gpgsig);
610         gpgme_new(&ctx);
611         gpgme_set_armor(ctx, TRUE);
612         gpgme_signers_clear (ctx);
613
614         err = gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
615
616         if (err) {
617                 debug_print ("gpgme_set_protocol failed: %s\n",
618                    gpgme_strerror (err));
619                 gpgme_data_release(gpgtext);
620                 gpgme_release(ctx);
621                 return FALSE;
622         }
623
624         if (!sgpgme_setup_signers(ctx, account, from_addr)) {
625                 debug_print("setup_signers failed\n");
626                 gpgme_data_release(gpgtext);
627                 gpgme_release(ctx);
628                 return FALSE;
629         }
630
631         info.c = ctx;
632         prefs_gpg_enable_agent(TRUE);
633         gpgme_set_passphrase_cb (ctx, NULL, &info);
634         
635         err = gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH);
636         if (err != GPG_ERR_NO_ERROR) {
637                 alertpanel_error("S/MIME : Cannot sign, %s (%d)", gpg_strerror(err), gpg_err_code(err));
638                 gpgme_data_release(gpgtext);
639                 gpgme_release(ctx);
640                 return FALSE;
641         }
642         result = gpgme_op_sign_result(ctx);
643         if (result && result->signatures) {
644             if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
645                 gchar *down_algo = g_ascii_strdown(gpgme_hash_algo_name(
646                             result->signatures->hash_algo), -1);
647                 micalg = g_strdup_printf("pgp-%s", down_algo);
648                 g_free(down_algo);
649             } else {
650                 micalg = g_strdup(gpgme_hash_algo_name(
651                             result->signatures->hash_algo));
652             }
653         } else {
654             /* can't get result (maybe no signing key?) */
655             debug_print("gpgme_op_sign_result error\n");
656             return FALSE;
657         }
658
659         gpgme_release(ctx);
660         sigcontent = sgpgme_data_release_and_get_mem(gpgsig, &len);
661         gpgme_data_release(gpgtext);
662         g_free(textstr);
663
664         if (!sigcontent) {
665                 gpgme_release(ctx);
666                 g_free(micalg);
667                 return FALSE;
668         }
669         real_content = sigcontent+strlen("-----BEGIN SIGNED MESSAGE-----\n");
670         if (!strstr(real_content, "-----END SIGNED MESSAGE-----")) {
671                 debug_print("missing end\n");
672                 gpgme_release(ctx);
673                 g_free(micalg);
674                 return FALSE;
675         }
676         *strstr(real_content, "-----END SIGNED MESSAGE-----") = '\0';
677         /* add signature */
678         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
679                             micalg);
680
681         newinfo = procmime_mimeinfo_new();
682         newinfo->type = MIMETYPE_APPLICATION;
683         newinfo->subtype = g_strdup("pkcs7-signature");
684         g_hash_table_insert(newinfo->typeparameters, g_strdup("name"),
685                              g_strdup("smime.p7s"));
686         newinfo->content = MIMECONTENT_MEM;
687         newinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
688         g_hash_table_insert(newinfo->dispositionparameters, g_strdup("filename"),
689                             g_strdup("smime.p7s"));
690         newinfo->data.mem = g_malloc(len + 1);
691         g_memmove(newinfo->data.mem, real_content, len);
692         newinfo->data.mem[len] = '\0';
693         newinfo->encoding_type = ENC_BASE64;
694         g_node_append(sigmultipart->node, newinfo->node);
695
696         g_free(sigcontent);
697
698         return TRUE;
699 }
700 gchar *smime_get_encrypt_data(GSList *recp_names)
701 {
702         return sgpgme_get_encrypt_data(recp_names, GPGME_PROTOCOL_CMS);
703 }
704
705 static const gchar *smime_get_encrypt_warning(void)
706 {
707         if (prefs_gpg_should_skip_encryption_warning(smime_system.id))
708                 return NULL;
709         else
710                 return _("Please note that email headers, like Subject, "
711                          "are not encrypted by the S/MIME system.");
712 }
713
714 static void smime_inhibit_encrypt_warning(gboolean inhibit)
715 {
716         if (inhibit)
717                 prefs_gpg_add_skip_encryption_warning(smime_system.id);
718         else
719                 prefs_gpg_remove_skip_encryption_warning(smime_system.id);
720 }
721
722 gboolean smime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
723 {
724         MimeInfo *msgcontent, *encmultipart;
725         FILE *fp;
726         gchar *enccontent;
727         size_t len;
728         gchar *textstr = NULL;
729         gpgme_data_t gpgtext = NULL, gpgenc = NULL;
730         gpgme_ctx_t ctx = NULL;
731         gpgme_key_t *kset = NULL;
732         gchar **fprs = g_strsplit(encrypt_data, " ", -1);
733         gint i = 0;
734         gpgme_error_t err;
735         gchar *tmpfile = NULL;
736
737         while (fprs[i] && strlen(fprs[i])) {
738                 i++;
739         }
740
741         if ((err = gpgme_new(&ctx)) != GPG_ERR_NO_ERROR) {
742                 debug_print ("gpgme_new failed: %s\n", gpgme_strerror(err));
743                 return FALSE;
744         }
745
746         err = gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
747
748         if (err) {
749                 debug_print ("gpgme_set_protocol failed: %s\n",
750                    gpgme_strerror (err));
751                 return FALSE;
752         }
753
754         kset = g_malloc(sizeof(gpgme_key_t)*(i+1));
755         memset(kset, 0, sizeof(gpgme_key_t)*(i+1));
756         i = 0;
757
758         while (fprs[i] && strlen(fprs[i])) {
759                 gpgme_key_t key;
760                 gpgme_error_t err;
761                 err = gpgme_get_key(ctx, fprs[i], &key, 0);
762                 if (err) {
763                         debug_print("can't add key '%s'[%d] (%s)\n", fprs[i],i, gpgme_strerror(err));
764                         break;
765                 }
766                 debug_print("found %s at %d\n", fprs[i], i);
767                 kset[i] = key;
768                 i++;
769         }
770         
771         debug_print("Encrypting message content\n");
772
773         /* remove content node from message */
774         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
775         g_node_unlink(msgcontent->node);
776
777
778         /* create temporary multipart for content */
779         encmultipart = procmime_mimeinfo_new();
780         encmultipart->type = MIMETYPE_APPLICATION;
781         encmultipart->subtype = g_strdup("x-pkcs7-mime");
782         g_hash_table_insert(encmultipart->typeparameters, g_strdup("name"),
783                             g_strdup("smime.p7m"));
784         g_hash_table_insert(encmultipart->typeparameters,
785                             g_strdup("smime-type"),
786                             g_strdup("enveloped-data"));
787         
788         encmultipart->disposition = DISPOSITIONTYPE_ATTACHMENT;
789         g_hash_table_insert(encmultipart->dispositionparameters, g_strdup("filename"),
790                             g_strdup("smime.p7m"));
791
792         g_node_append(encmultipart->node, msgcontent->node);
793
794         /* write message content to temporary file */
795         tmpfile = get_tmp_file();
796         fp = g_fopen(tmpfile, "wb");
797         if (fp == NULL) {
798                 FILE_OP_ERROR(tmpfile, "create");
799                 g_free(kset);
800                 return FALSE;
801         }
802         procmime_decode_content(msgcontent);
803         procmime_write_mime_header(msgcontent, fp);
804         procmime_write_mimeinfo(msgcontent, fp);
805         fclose(fp);
806         canonicalize_file_replace(tmpfile);
807         fp = g_fopen(tmpfile, "rb");
808         if (fp == NULL) {
809                 FILE_OP_ERROR(tmpfile, "open");
810                 g_free(kset);
811                 return FALSE;
812         }
813         g_free(tmpfile);
814
815         /* read temporary file into memory */
816         textstr = fp_read_noconv(fp);
817
818         fclose(fp);
819
820         /* encrypt data */
821         gpgme_data_new_from_mem(&gpgtext, textstr, textstr?strlen(textstr):0, 0);
822         gpgme_data_new(&gpgenc);
823         cm_gpgme_data_rewind(gpgtext);
824         
825         gpgme_op_encrypt(ctx, kset, GPGME_ENCRYPT_ALWAYS_TRUST, gpgtext, gpgenc);
826
827         gpgme_release(ctx);
828         g_free(kset);
829         enccontent = sgpgme_data_release_and_get_mem(gpgenc, &len);
830
831         if (!enccontent) {
832                 g_warning("no enccontent");
833                 return FALSE;
834         }
835
836         tmpfile = get_tmp_file();
837         fp = g_fopen(tmpfile, "wb");
838         if (fp) {
839                 if (fwrite(enccontent, 1, len, fp) < len) {
840                         FILE_OP_ERROR(tmpfile, "fwrite");
841                         fclose(fp);
842                         claws_unlink(tmpfile);
843                         g_free(tmpfile);
844                         g_free(enccontent);
845                         return FALSE;
846                 }
847                 if (fclose(fp) == EOF) {
848                         FILE_OP_ERROR(tmpfile, "fclose");
849                         claws_unlink(tmpfile);
850                         g_free(tmpfile);
851                         g_free(enccontent);
852                         return FALSE;
853                 }
854         } else {
855                 FILE_OP_ERROR(tmpfile, "create");
856                 g_free(tmpfile);
857                 g_free(enccontent);
858                 return FALSE;
859         }
860         gpgme_data_release(gpgtext);
861         g_free(textstr);
862
863         /* create encrypted multipart */
864         procmime_mimeinfo_free_all(&msgcontent);
865         g_node_append(mimeinfo->node, encmultipart->node);
866
867         encmultipart->content = MIMECONTENT_FILE;
868         encmultipart->data.filename = tmpfile;
869         procmime_encode_content(encmultipart, ENC_BASE64);
870
871         g_free(enccontent);
872
873         return TRUE;
874 }
875
876 static PrivacySystem smime_system = {
877         "smime",                        /* id */
878         "S-MIME",                       /* name */
879
880         smime_free_privacydata, /* free_privacydata */
881
882         smime_is_signed,                /* is_signed(MimeInfo *) */
883         smime_check_signature,  /* check_signature(MimeInfo *) */
884         smime_get_sig_status,           /* get_sig_status(MimeInfo *) */
885         smime_get_sig_info_short,       /* get_sig_info_short(MimeInfo *) */
886         smime_get_sig_info_full,        /* get_sig_info_full(MimeInfo *) */
887
888         smime_is_encrypted,             /* is_encrypted(MimeInfo *) */
889         smime_decrypt,                  /* decrypt(MimeInfo *) */
890
891         TRUE,
892         smime_sign,
893
894         TRUE,
895         smime_get_encrypt_data,
896         smime_encrypt,
897         smime_get_encrypt_warning,
898         smime_inhibit_encrypt_warning,
899         prefs_gpg_auto_check_signatures,
900 };
901
902 void smime_init()
903 {
904         privacy_register_system(&smime_system);
905 }
906
907 void smime_done()
908 {
909         privacy_unregister_system(&smime_system);
910 }
911
912 struct PluginFeature *plugin_provides(void)
913 {
914         static struct PluginFeature features[] = 
915                 { {PLUGIN_PRIVACY, N_("S/MIME")},
916                   {PLUGIN_NOTHING, NULL}};
917         return features;
918 }
919 #endif /* USE_GPGME */