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