Fix string leaks
[claws.git] / src / plugins / smime / smime.c
1 /* 
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2012 Colin Leroy <colin@colino.net> and 
4  * the Claws Mail team
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  */
20
21 #ifdef HAVE_CONFIG_H
22 #  include "config.h"
23 #include "claws-features.h"
24 #endif
25
26 #ifdef USE_GPGME
27
28 #include "defs.h"
29 #include <glib.h>
30 #include <gpgme.h>
31 #include <ctype.h>
32 #include <glib/gi18n.h>
33
34 #include "utils.h"
35 #include "privacy.h"
36 #include "procmime.h"
37
38 #include "smime.h"
39 #include <plugins/pgpcore/sgpgme.h>
40 #include <plugins/pgpcore/prefs_gpg.h>
41 #include <plugins/pgpcore/pgp_utils.h>
42 #include <plugins/pgpcore/passphrase.h>
43
44 #include "alertpanel.h"
45 #include "prefs_common.h"
46 #include "procmime.h"
47 #include "plugin.h"
48
49 typedef struct _PrivacyDataPGP PrivacyDataPGP;
50
51 struct _PrivacyDataPGP
52 {
53         PrivacyData     data;
54         
55         gboolean        done_sigtest;
56         gboolean        is_signed;
57         gpgme_verify_result_t   sigstatus;
58         gpgme_ctx_t     ctx;
59 };
60
61 static PrivacySystem smime_system;
62
63 static gint smime_check_signature(MimeInfo *mimeinfo);
64
65 static PrivacyDataPGP *smime_new_privacydata()
66 {
67         PrivacyDataPGP *data;
68         gpgme_ctx_t     ctx;
69
70         if (gpgme_new(&ctx) != GPG_ERR_NO_ERROR) {
71                 debug_print("gpgme_new failed");
72                 return NULL;
73         }
74
75         data = g_new0(PrivacyDataPGP, 1);
76         data->data.system = &smime_system;
77         data->done_sigtest = FALSE;
78         data->is_signed = FALSE;
79         data->sigstatus = NULL;
80         data->ctx = ctx;
81         
82         return data;
83 }
84
85 static void smime_free_privacydata(PrivacyData *_data)
86 {
87         PrivacyDataPGP *data = (PrivacyDataPGP *) _data;
88         gpgme_release(data->ctx);
89         g_free(data);
90 }
91
92 static gboolean smime_is_signed(MimeInfo *mimeinfo)
93 {
94         MimeInfo *parent;
95         MimeInfo *signature;
96         const gchar *protocol, *tmpstr;
97         PrivacyDataPGP *data = NULL;
98         
99         cm_return_val_if_fail(mimeinfo != NULL, FALSE);
100         if (mimeinfo->privacy != NULL) {
101                 data = (PrivacyDataPGP *) mimeinfo->privacy;
102                 if (data->done_sigtest)
103                         return data->is_signed;
104         }
105         
106         if (!g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-mime") ||
107             !g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-mime")) {
108                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
109                 if (tmpstr && !g_ascii_strcasecmp(tmpstr, "signed-data")) {
110                         if (data == NULL) {
111                                 data = smime_new_privacydata();
112                                 if (!data)
113                                         return FALSE;
114                                 mimeinfo->privacy = (PrivacyData *) data;
115                         }
116
117                         data->done_sigtest = TRUE;
118                         data->is_signed = TRUE;
119                         smime_check_signature(mimeinfo);
120                         return TRUE;
121                 }
122         }
123
124         /* check parent */
125         parent = procmime_mimeinfo_parent(mimeinfo);
126         if (parent == NULL)
127                 return FALSE;
128         
129         if ((parent->type != MIMETYPE_MULTIPART) ||
130             g_ascii_strcasecmp(parent->subtype, "signed"))
131                 return FALSE;
132         protocol = procmime_mimeinfo_get_parameter(parent, "protocol");
133         if ((protocol == NULL) || 
134             (g_ascii_strcasecmp(protocol, "application/pkcs7-signature") &&
135              g_ascii_strcasecmp(protocol, "application/x-pkcs7-signature")))
136                 return FALSE;
137
138         /* check if mimeinfo is the first child */
139         if (parent->node->children->data != mimeinfo)
140                 return FALSE;
141
142
143         /* check signature */
144         signature = parent->node->children->next != NULL ? 
145             (MimeInfo *) parent->node->children->next->data : NULL;
146         if (signature == NULL)
147                 return FALSE;
148         if ((signature->type != MIMETYPE_APPLICATION) ||
149             (g_ascii_strcasecmp(signature->subtype, "pkcs7-signature") &&
150              g_ascii_strcasecmp(signature->subtype, "x-pkcs7-signature")))
151                 return FALSE;
152
153         if (data == NULL) {
154                 data = smime_new_privacydata();
155                 if (!data)
156                         return FALSE;
157                 mimeinfo->privacy = (PrivacyData *) data;
158         }
159         
160         data->done_sigtest = TRUE;
161         data->is_signed = TRUE;
162
163         return TRUE;
164 }
165
166 static gchar *get_canonical_content(FILE *fp, const gchar *boundary)
167 {
168         gchar *ret;
169         GString *textbuffer;
170         guint boundary_len = 0;
171         gchar buf[BUFFSIZE];
172
173         if (boundary) {
174                 boundary_len = strlen(boundary);
175                 while (fgets(buf, sizeof(buf), fp) != NULL)
176                         if (IS_BOUNDARY(buf, boundary, boundary_len))
177                                 break;
178         }
179         
180         textbuffer = g_string_new("");
181         while (fgets(buf, sizeof(buf), fp) != NULL) {
182                 gchar *buf2;
183
184                 if (boundary && IS_BOUNDARY(buf, boundary, boundary_len))
185                         break;
186                 
187                 buf2 = canonicalize_str(buf);
188                 g_string_append(textbuffer, buf2);
189                 g_free(buf2);
190         }
191         g_string_truncate(textbuffer, textbuffer->len - 2);
192                 
193         ret = textbuffer->str;
194         g_string_free(textbuffer, FALSE);
195
196         return ret;
197 }
198
199 static gint smime_check_signature(MimeInfo *mimeinfo)
200 {
201         PrivacyDataPGP *data;
202         MimeInfo *parent, *signature;
203         FILE *fp;
204         gchar *boundary;
205         gchar *textstr = NULL;
206         const gchar *tmpstr;
207         gpgme_data_t sigdata = NULL, textdata = NULL;
208         gpgme_error_t err;
209         EncodingType oldenc = ENC_BINARY;
210
211         cm_return_val_if_fail(mimeinfo != NULL, -1);
212         cm_return_val_if_fail(mimeinfo->privacy != NULL, -1);
213
214         data = (PrivacyDataPGP *) mimeinfo->privacy;
215
216         if (!data->ctx) {
217                 if ((err = gpgme_new(&data->ctx)) != GPG_ERR_NO_ERROR) {
218                         debug_print("gpgme_new failed: %s\n",
219                                 gpgme_strerror(err));
220                         return -1;
221                 }
222         }
223
224         debug_print("Checking S/MIME signature\n");
225
226         err = gpgme_set_protocol(data->ctx, GPGME_PROTOCOL_CMS);
227
228         if (err) {
229                 debug_print ("gpgme_set_protocol failed: %s\n",
230                    gpgme_strerror (err));
231         }
232         parent = procmime_mimeinfo_parent(mimeinfo);
233
234         fp = g_fopen(parent->data.filename, "rb");
235         cm_return_val_if_fail(fp != NULL, SIGNATURE_INVALID);
236         
237         boundary = g_hash_table_lookup(parent->typeparameters, "boundary");
238         if (!boundary) {
239                 gchar *tmpfile = get_tmp_file();
240                 debug_print("no boundary\n");
241                 if (tmpfile) {
242                         if (mimeinfo->encoding_type != ENC_BASE64) {
243                                 procmime_encode_content(mimeinfo, ENC_BASE64);
244                         }
245                         oldenc = mimeinfo->encoding_type;
246                         if (mimeinfo->encoding_type == ENC_BASE64)
247                                 mimeinfo->encoding_type = ENC_BINARY;
248                         if (procmime_get_part(tmpfile, mimeinfo) == 0) {
249                                 textstr = file_read_to_str(tmpfile);
250                         } else {
251                                 textstr = NULL;
252                         }
253                         if (mimeinfo->encoding_type != oldenc)
254                                 mimeinfo->encoding_type = oldenc;
255                 }
256                 g_free(tmpfile);
257         } else {
258                 textstr = get_canonical_content(fp, boundary);
259         }
260         err = gpgme_data_new_from_mem(&textdata, textstr, textstr?strlen(textstr):0, 0);
261         
262         if (err) {
263                 debug_print ("gpgme_data_new_from_mem failed: %s\n",
264                    gpgme_strerror (err));
265         }
266
267         if (!g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-mime") ||
268             !g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-mime")) {
269                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
270                 if (tmpstr && !g_ascii_strcasecmp(tmpstr, "signed-data")) {
271                         gpgme_data_t cipher;
272                         size_t len;
273                         if (oldenc == ENC_BASE64)
274                                 gpgme_data_set_encoding (textdata, GPGME_DATA_ENCODING_BASE64);
275                         gpgme_data_new(&cipher);
276                         data->sigstatus =
277                                 sgpgme_verify_signature (data->ctx, textdata, NULL, cipher);
278                         gpgme_data_release(textdata);
279                         g_free(textstr);
280                         cm_gpgme_data_rewind(cipher);
281                         textstr = sgpgme_data_release_and_get_mem(cipher, &len);
282                         fclose(fp);
283                         if (textstr && len > 0)
284                                 textstr[len-1]='\0';
285
286                         if (textstr && len) {
287                                 gchar *tmp_file = get_tmp_file();
288                                 MimeInfo *newinfo = NULL, *decinfo = NULL, *parentinfo = NULL;
289
290                                 str_write_to_file(textstr, tmp_file);
291                                 newinfo = procmime_scan_file(tmp_file);
292                                 decinfo = g_node_first_child(newinfo->node) != NULL ?
293                                         g_node_first_child(newinfo->node)->data : NULL;
294
295                                 if (decinfo == NULL)
296                                         return -1;
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                 perror("get_tmp_file");
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                 perror("get_tmp_file");
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\n");
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                         return FALSE;
845                 }
846                 if (fclose(fp) == EOF) {
847                         FILE_OP_ERROR(tmpfile, "fclose");
848                         claws_unlink(tmpfile);
849                         g_free(tmpfile);
850                         return FALSE;
851                 }
852         } else {
853                 perror("get_tmp_file");
854                 g_free(tmpfile);
855                 g_free(enccontent);
856                 return FALSE;
857         }
858         gpgme_data_release(gpgtext);
859         g_free(textstr);
860
861         /* create encrypted multipart */
862         procmime_mimeinfo_free_all(msgcontent);
863         g_node_append(mimeinfo->node, encmultipart->node);
864
865         encmultipart->content = MIMECONTENT_FILE;
866         encmultipart->data.filename = tmpfile;
867         procmime_encode_content(encmultipart, ENC_BASE64);
868
869         g_free(enccontent);
870
871         return TRUE;
872 }
873
874 static PrivacySystem smime_system = {
875         "smime",                        /* id */
876         "S-MIME",                       /* name */
877
878         smime_free_privacydata, /* free_privacydata */
879
880         smime_is_signed,                /* is_signed(MimeInfo *) */
881         smime_check_signature,  /* check_signature(MimeInfo *) */
882         smime_get_sig_status,           /* get_sig_status(MimeInfo *) */
883         smime_get_sig_info_short,       /* get_sig_info_short(MimeInfo *) */
884         smime_get_sig_info_full,        /* get_sig_info_full(MimeInfo *) */
885
886         smime_is_encrypted,             /* is_encrypted(MimeInfo *) */
887         smime_decrypt,                  /* decrypt(MimeInfo *) */
888
889         TRUE,
890         smime_sign,
891
892         TRUE,
893         smime_get_encrypt_data,
894         smime_encrypt,
895         smime_get_encrypt_warning,
896         smime_inhibit_encrypt_warning,
897         prefs_gpg_auto_check_signatures,
898 };
899
900 void smime_init()
901 {
902         privacy_register_system(&smime_system);
903 }
904
905 void smime_done()
906 {
907         privacy_unregister_system(&smime_system);
908 }
909
910 struct PluginFeature *plugin_provides(void)
911 {
912         static struct PluginFeature features[] = 
913                 { {PLUGIN_PRIVACY, N_("S/MIME")},
914                   {PLUGIN_NOTHING, NULL}};
915         return features;
916 }
917 #endif /* USE_GPGME */