50d051db78aad7a4df66f0ed1f3b0ffae7450c52
[claws.git] / src / plugins / smime / smime.c
1 /* 
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2009 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 #endif
24
25 #ifdef USE_GPGME
26
27 #include "defs.h"
28 #include <glib.h>
29 #include <gpgme.h>
30 #include <ctype.h>
31 #include <glib/gi18n.h>
32
33 #include "utils.h"
34 #include "privacy.h"
35 #include "procmime.h"
36
37 #include "smime.h"
38 #include <plugins/pgpcore/sgpgme.h>
39 #include <plugins/pgpcore/prefs_gpg.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
67         data = g_new0(PrivacyDataPGP, 1);
68         data->data.system = &smime_system;
69         data->done_sigtest = FALSE;
70         data->is_signed = FALSE;
71         data->sigstatus = NULL;
72         gpgme_new(&data->ctx);
73         
74         return data;
75 }
76
77 static void smime_free_privacydata(PrivacyData *_data)
78 {
79         PrivacyDataPGP *data = (PrivacyDataPGP *) _data;
80         gpgme_release(data->ctx);
81         g_free(data);
82 }
83
84 static gboolean smime_is_signed(MimeInfo *mimeinfo)
85 {
86         MimeInfo *parent;
87         MimeInfo *signature;
88         const gchar *protocol, *tmpstr;
89         PrivacyDataPGP *data = NULL;
90         
91         cm_return_val_if_fail(mimeinfo != NULL, FALSE);
92         if (mimeinfo->privacy != NULL) {
93                 data = (PrivacyDataPGP *) mimeinfo->privacy;
94                 if (data->done_sigtest)
95                         return data->is_signed;
96         }
97         
98         if (!g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-mime") ||
99             !g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-mime")) {
100                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
101                 if (tmpstr && !g_ascii_strcasecmp(tmpstr, "signed-data")) {
102                         if (data == NULL) {
103                                 data = smime_new_privacydata();
104                                 mimeinfo->privacy = (PrivacyData *) data;
105                         }
106
107                         data->done_sigtest = TRUE;
108                         data->is_signed = TRUE;
109                         smime_check_signature(mimeinfo);
110                         return TRUE;
111                 }
112         }
113
114         /* check parent */
115         parent = procmime_mimeinfo_parent(mimeinfo);
116         if (parent == NULL)
117                 return FALSE;
118         
119         if ((parent->type != MIMETYPE_MULTIPART) ||
120             g_ascii_strcasecmp(parent->subtype, "signed"))
121                 return FALSE;
122         protocol = procmime_mimeinfo_get_parameter(parent, "protocol");
123         if ((protocol == NULL) || 
124             (g_ascii_strcasecmp(protocol, "application/pkcs7-signature") &&
125              g_ascii_strcasecmp(protocol, "application/x-pkcs7-signature")))
126                 return FALSE;
127
128         /* check if mimeinfo is the first child */
129         if (parent->node->children->data != mimeinfo)
130                 return FALSE;
131
132
133         /* check signature */
134         signature = parent->node->children->next != NULL ? 
135             (MimeInfo *) parent->node->children->next->data : NULL;
136         if (signature == NULL)
137                 return FALSE;
138         if ((signature->type != MIMETYPE_APPLICATION) ||
139             (g_ascii_strcasecmp(signature->subtype, "pkcs7-signature") &&
140              g_ascii_strcasecmp(signature->subtype, "x-pkcs7-signature")))
141                 return FALSE;
142
143         if (data == NULL) {
144                 data = smime_new_privacydata();
145                 mimeinfo->privacy = (PrivacyData *) data;
146         }
147         
148         data->done_sigtest = TRUE;
149         data->is_signed = TRUE;
150
151         return TRUE;
152 }
153
154 static gchar *get_canonical_content(FILE *fp, const gchar *boundary)
155 {
156         gchar *ret;
157         GString *textbuffer;
158         guint boundary_len = 0;
159         gchar buf[BUFFSIZE];
160
161         if (boundary) {
162                 boundary_len = strlen(boundary);
163                 while (fgets(buf, sizeof(buf), fp) != NULL)
164                         if (IS_BOUNDARY(buf, boundary, boundary_len))
165                                 break;
166         }
167         
168         textbuffer = g_string_new("");
169         while (fgets(buf, sizeof(buf), fp) != NULL) {
170                 gchar *buf2;
171
172                 if (boundary && IS_BOUNDARY(buf, boundary, boundary_len))
173                         break;
174                 
175                 buf2 = canonicalize_str(buf);
176                 g_string_append(textbuffer, buf2);
177                 g_free(buf2);
178         }
179         g_string_truncate(textbuffer, textbuffer->len - 2);
180                 
181         ret = textbuffer->str;
182         g_string_free(textbuffer, FALSE);
183
184         return ret;
185 }
186
187 static gint smime_check_signature(MimeInfo *mimeinfo)
188 {
189         PrivacyDataPGP *data;
190         MimeInfo *parent, *signature;
191         FILE *fp;
192         gchar *boundary;
193         gchar *textstr = NULL;
194         const gchar *tmpstr;
195         gpgme_data_t sigdata = NULL, textdata = NULL;
196         gpgme_error_t err;
197         cm_return_val_if_fail(mimeinfo != NULL, -1);
198         cm_return_val_if_fail(mimeinfo->privacy != NULL, -1);
199         data = (PrivacyDataPGP *) mimeinfo->privacy;
200         gpgme_new(&data->ctx);
201         EncodingType oldenc = ENC_BINARY;
202         
203         debug_print("Checking S/MIME signature\n");
204
205         err = gpgme_set_protocol(data->ctx, GPGME_PROTOCOL_CMS);
206
207         if (err) {
208                 debug_print ("gpgme_set_protocol failed: %s\n",
209                    gpgme_strerror (err));
210         }
211         parent = procmime_mimeinfo_parent(mimeinfo);
212
213         fp = g_fopen(parent->data.filename, "rb");
214         cm_return_val_if_fail(fp != NULL, SIGNATURE_INVALID);
215         
216         boundary = g_hash_table_lookup(parent->typeparameters, "boundary");
217         if (!boundary) {
218                 gchar *tmpfile = get_tmp_file();
219                 debug_print("no boundary\n");
220                 if (tmpfile) {
221                         if (mimeinfo->encoding_type != ENC_BASE64) {
222                                 procmime_encode_content(mimeinfo, ENC_BASE64);
223                         }
224                         oldenc = mimeinfo->encoding_type;
225                         if (mimeinfo->encoding_type == ENC_BASE64)
226                                 mimeinfo->encoding_type = ENC_BINARY;
227                         if (procmime_get_part(tmpfile, mimeinfo) == 0) {
228                                 textstr = file_read_to_str(tmpfile);
229                         } else {
230                                 textstr = NULL;
231                         }
232                         if (mimeinfo->encoding_type != oldenc)
233                                 mimeinfo->encoding_type = oldenc;
234                 }
235                 g_free(tmpfile);
236         } else {
237                 textstr = get_canonical_content(fp, boundary);
238         }
239         err = gpgme_data_new_from_mem(&textdata, textstr, textstr?strlen(textstr):0, 0);
240         
241         if (err) {
242                 debug_print ("gpgme_data_new_from_mem failed: %s\n",
243                    gpgme_strerror (err));
244         }
245
246         if (!g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-mime") ||
247             !g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-mime")) {
248                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
249                 if (tmpstr && !g_ascii_strcasecmp(tmpstr, "signed-data")) {
250                         gpgme_data_t cipher;
251                         size_t len;
252                         if (oldenc == ENC_BASE64)
253                                 gpgme_data_set_encoding (textdata, GPGME_DATA_ENCODING_BASE64);
254                         gpgme_data_new(&cipher);
255                         data->sigstatus =
256                                 sgpgme_verify_signature (data->ctx, textdata, NULL, cipher);
257                         gpgme_data_release(textdata);
258                         g_free(textstr);
259                         cm_gpgme_data_rewind(cipher);
260                         textstr = sgpgme_data_release_and_get_mem(cipher, &len);
261                         fclose(fp);
262                         if (textstr && len > 0)
263                                 textstr[len-1]='\0';
264
265                         if (textstr && len) {
266                                 gchar *tmp_file = get_tmp_file();
267                                 MimeInfo *newinfo = NULL, *decinfo = NULL, *parentinfo = NULL;
268                                 gint childnumber = 0;
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                                 childnumber = g_node_child_index(parentinfo->node, mimeinfo);
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                         g_free(fname);
463                         g_free(chars);
464                         gpgme_data_release(plain);
465                         gpgme_release(ctx);
466                         debug_print("can't write!\n");
467                         privacy_set_error(_("Couldn't write to temporary file"));
468                         return NULL;
469                 }
470         }
471         if (fclose(dstfp) == EOF) {
472                 FILE_OP_ERROR(fname, "fclose");
473                 g_free(fname);
474                 g_free(chars);
475                 gpgme_data_release(plain);
476                 gpgme_release(ctx);
477                 debug_print("can't close!\n");
478                 privacy_set_error(_("Couldn't close temporary file"));
479                 return NULL;
480         }
481         g_free(chars);
482
483         parseinfo = procmime_scan_file(fname);
484         g_free(fname);
485         if (parseinfo == NULL) {
486                 privacy_set_error(_("Couldn't parse decrypted file."));
487                 gpgme_release(ctx);
488                 return NULL;
489         }
490         decinfo = g_node_first_child(parseinfo->node) != NULL ?
491                 g_node_first_child(parseinfo->node)->data : NULL;
492         if (decinfo == NULL) {
493                 privacy_set_error(_("Couldn't parse decrypted file parts."));
494                 gpgme_release(ctx);
495                 return NULL;
496         }
497
498         g_node_unlink(decinfo->node);
499         procmime_mimeinfo_free_all(parseinfo);
500
501         decinfo->tmp = TRUE;
502
503         if (sigstat != NULL && sigstat->signatures != NULL) {
504                 if (decinfo->privacy != NULL) {
505                         data = (PrivacyDataPGP *) decinfo->privacy;
506                 } else {
507                         data = smime_new_privacydata();
508                         decinfo->privacy = (PrivacyData *) data;        
509                 }
510                 data->done_sigtest = TRUE;
511                 data->is_signed = TRUE;
512                 data->sigstatus = sigstat;
513                 if (data->ctx)
514                         gpgme_release(data->ctx);
515                 data->ctx = ctx;
516         } else
517                 gpgme_release(ctx);
518         
519         
520         
521         return decinfo;
522 }
523
524 gboolean smime_sign(MimeInfo *mimeinfo, PrefsAccount *account, const gchar *from_addr)
525 {
526         MimeInfo *msgcontent, *sigmultipart, *newinfo;
527         gchar *textstr, *micalg;
528         FILE *fp;
529         gchar *boundary = NULL;
530         gchar *sigcontent;
531         gpgme_ctx_t ctx;
532         gpgme_data_t gpgtext, gpgsig;
533         gpgme_error_t err;
534         size_t len;
535         struct passphrase_cb_info_s info;
536         gpgme_sign_result_t result = NULL;
537         gchar *test_msg;
538         gchar *real_content = NULL;
539         
540         fp = my_tmpfile();
541         if (fp == NULL) {
542                 perror("my_tmpfile");
543                 return FALSE;
544         }
545         procmime_write_mimeinfo(mimeinfo, fp);
546         rewind(fp);
547
548         /* read temporary file into memory */
549         test_msg = file_read_stream_to_str(fp);
550         fclose(fp);
551         
552         memset (&info, 0, sizeof info);
553
554         /* remove content node from message */
555         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
556         g_node_unlink(msgcontent->node);
557
558         /* create temporary multipart for content */
559         sigmultipart = procmime_mimeinfo_new();
560         sigmultipart->type = MIMETYPE_MULTIPART;
561         sigmultipart->subtype = g_strdup("signed");
562         
563         do {
564                 if (boundary)
565                         g_free(boundary);
566                 boundary = generate_mime_boundary("Sig");
567         } while (strstr(test_msg, boundary) != NULL);
568         
569         g_free(test_msg);
570
571         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
572                             g_strdup(boundary));
573         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
574                             g_strdup("application/pkcs7-signature"));
575         g_node_append(sigmultipart->node, msgcontent->node);
576         g_node_append(mimeinfo->node, sigmultipart->node);
577
578         /* write message content to temporary file */
579         fp = my_tmpfile();
580         if (fp == NULL) {
581                 perror("my_tmpfile");
582                 return FALSE;
583         }
584         procmime_write_mimeinfo(sigmultipart, fp);
585         rewind(fp);
586
587         /* read temporary file into memory */
588         textstr = get_canonical_content(fp, boundary);
589
590         g_free(boundary);
591
592         fclose(fp);
593
594         gpgme_data_new_from_mem(&gpgtext, textstr, textstr?strlen(textstr):0, 0);
595         gpgme_data_new(&gpgsig);
596         gpgme_new(&ctx);
597         gpgme_set_armor(ctx, TRUE);
598         gpgme_signers_clear (ctx);
599
600         err = gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
601
602         if (err) {
603                 debug_print ("gpgme_set_protocol failed: %s\n",
604                    gpgme_strerror (err));
605                 gpgme_data_release(gpgtext);
606                 gpgme_release(ctx);
607                 return FALSE;
608         }
609
610         if (!sgpgme_setup_signers(ctx, account, from_addr)) {
611                 debug_print("setup_signers failed\n");
612                 gpgme_data_release(gpgtext);
613                 gpgme_release(ctx);
614                 return FALSE;
615         }
616
617         info.c = ctx;
618         prefs_gpg_enable_agent(TRUE);
619         gpgme_set_passphrase_cb (ctx, NULL, &info);
620         
621         err = gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH);
622         if (err != GPG_ERR_NO_ERROR) {
623                 alertpanel_error("S/MIME : Cannot sign, %s (%d)", gpg_strerror(err), gpg_err_code(err));
624                 gpgme_data_release(gpgtext);
625                 gpgme_release(ctx);
626                 return FALSE;
627         }
628         result = gpgme_op_sign_result(ctx);
629         if (result && result->signatures) {
630             if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
631                 micalg = g_strdup_printf("PGP-%s", gpgme_hash_algo_name(
632                             result->signatures->hash_algo));
633             } else {
634                 micalg = g_strdup(gpgme_hash_algo_name(
635                             result->signatures->hash_algo));
636             }
637         } else {
638             /* can't get result (maybe no signing key?) */
639             debug_print("gpgme_op_sign_result error\n");
640             return FALSE;
641         }
642
643         gpgme_release(ctx);
644         sigcontent = sgpgme_data_release_and_get_mem(gpgsig, &len);
645         gpgme_data_release(gpgtext);
646         g_free(textstr);
647
648         if (!sigcontent) {
649                 gpgme_release(ctx);
650                 return FALSE;
651         }
652         real_content = sigcontent+strlen("-----BEGIN SIGNED MESSAGE-----\n");
653         if (!strstr(real_content, "-----END SIGNED MESSAGE-----")) {
654                 debug_print("missing end\n");
655                 gpgme_release(ctx);
656                 return FALSE;
657         }
658         *strstr(real_content, "-----END SIGNED MESSAGE-----") = '\0';
659         /* add signature */
660         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
661                             micalg);
662
663         newinfo = procmime_mimeinfo_new();
664         newinfo->type = MIMETYPE_APPLICATION;
665         newinfo->subtype = g_strdup("pkcs7-signature");
666         g_hash_table_insert(newinfo->typeparameters, g_strdup("name"),
667                              g_strdup("smime.p7s"));
668         newinfo->content = MIMECONTENT_MEM;
669         newinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
670         g_hash_table_insert(newinfo->dispositionparameters, g_strdup("filename"),
671                             g_strdup("smime.p7s"));
672         newinfo->data.mem = g_malloc(len + 1);
673         g_memmove(newinfo->data.mem, real_content, len);
674         newinfo->data.mem[len] = '\0';
675         newinfo->encoding_type = ENC_BASE64;
676         g_node_append(sigmultipart->node, newinfo->node);
677
678         g_free(sigcontent);
679
680         return TRUE;
681 }
682 gchar *smime_get_encrypt_data(GSList *recp_names)
683 {
684         return sgpgme_get_encrypt_data(recp_names, GPGME_PROTOCOL_CMS);
685 }
686
687 static const gchar *smime_get_encrypt_warning(void)
688 {
689         if (prefs_gpg_should_skip_encryption_warning(smime_system.id))
690                 return NULL;
691         else
692                 return _("Please note that email headers, like Subject, "
693                          "are not encrypted by the S/MIME system.");
694 }
695
696 static void smime_inhibit_encrypt_warning(gboolean inhibit)
697 {
698         if (inhibit)
699                 prefs_gpg_add_skip_encryption_warning(smime_system.id);
700         else
701                 prefs_gpg_remove_skip_encryption_warning(smime_system.id);
702 }
703
704 static gchar *fp_read_noconv(FILE *fp)
705 {
706         GByteArray *array;
707         guchar buf[BUFSIZ];
708         gint n_read;
709         gchar *result = NULL;
710
711         if (!fp)
712                 return NULL;
713         array = g_byte_array_new();
714
715         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
716                 if (n_read < sizeof(buf) && ferror(fp))
717                         break;
718                 g_byte_array_append(array, buf, n_read);
719         }
720
721         if (ferror(fp)) {
722                 FILE_OP_ERROR("file stream", "fread");
723                 g_byte_array_free(array, TRUE);
724                 return NULL;
725         }
726
727         buf[0] = '\0';
728         g_byte_array_append(array, buf, 1);
729         result = (gchar *)array->data;
730         g_byte_array_free(array, FALSE);
731         
732         return result;
733 }
734
735 gboolean smime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
736 {
737         MimeInfo *msgcontent, *encmultipart;
738         FILE *fp;
739         gchar *enccontent;
740         size_t len;
741         gchar *textstr = NULL;
742         gpgme_data_t gpgtext = NULL, gpgenc = NULL;
743         gpgme_ctx_t ctx = NULL;
744         gpgme_key_t *kset = NULL;
745         gchar **fprs = g_strsplit(encrypt_data, " ", -1);
746         gint i = 0;
747         gpgme_error_t err;
748         gchar *tmpfile = NULL;
749
750         while (fprs[i] && strlen(fprs[i])) {
751                 i++;
752         }
753         
754         gpgme_new(&ctx);
755
756         err = gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
757
758         if (err) {
759                 debug_print ("gpgme_set_protocol failed: %s\n",
760                    gpgme_strerror (err));
761                 return FALSE;   
762         }
763
764         kset = g_malloc(sizeof(gpgme_key_t)*(i+1));
765         memset(kset, 0, sizeof(gpgme_key_t)*(i+1));
766         i = 0;
767
768         while (fprs[i] && strlen(fprs[i])) {
769                 gpgme_key_t key;
770                 gpgme_error_t err;
771                 err = gpgme_get_key(ctx, fprs[i], &key, 0);
772                 if (err) {
773                         debug_print("can't add key '%s'[%d] (%s)\n", fprs[i],i, gpgme_strerror(err));
774                         break;
775                 }
776                 debug_print("found %s at %d\n", fprs[i], i);
777                 kset[i] = key;
778                 i++;
779         }
780         
781         debug_print("Encrypting message content\n");
782
783         /* remove content node from message */
784         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
785         g_node_unlink(msgcontent->node);
786
787
788         /* create temporary multipart for content */
789         encmultipart = procmime_mimeinfo_new();
790         encmultipart->type = MIMETYPE_APPLICATION;
791         encmultipart->subtype = g_strdup("x-pkcs7-mime");
792         g_hash_table_insert(encmultipart->typeparameters, g_strdup("name"),
793                             g_strdup("smime.p7m"));
794         g_hash_table_insert(encmultipart->typeparameters,
795                             g_strdup("smime-type"),
796                             g_strdup("enveloped-data"));
797         
798         encmultipart->disposition = DISPOSITIONTYPE_ATTACHMENT;
799         g_hash_table_insert(encmultipart->dispositionparameters, g_strdup("filename"),
800                             g_strdup("smime.p7m"));
801
802         g_node_append(encmultipart->node, msgcontent->node);
803
804         /* write message content to temporary file */
805         tmpfile = get_tmp_file();
806         fp = g_fopen(tmpfile, "wb");
807         if (fp == NULL) {
808                 perror("get_tmp_file");
809                 return FALSE;
810         }
811         procmime_decode_content(msgcontent);
812         procmime_write_mime_header(msgcontent, fp);
813         procmime_write_mimeinfo(msgcontent, fp);
814         fclose(fp);
815         canonicalize_file_replace(tmpfile);
816         fp = g_fopen(tmpfile, "rb");
817         if (fp == NULL) {
818                 perror("get_tmp_file");
819                 return FALSE;
820         }
821         g_free(tmpfile);
822
823         /* read temporary file into memory */
824         textstr = fp_read_noconv(fp);
825
826         fclose(fp);
827
828         /* encrypt data */
829         gpgme_data_new_from_mem(&gpgtext, textstr, textstr?strlen(textstr):0, 0);
830         gpgme_data_new(&gpgenc);
831         cm_gpgme_data_rewind(gpgtext);
832         
833         gpgme_op_encrypt(ctx, kset, GPGME_ENCRYPT_ALWAYS_TRUST, gpgtext, gpgenc);
834
835         gpgme_release(ctx);
836         enccontent = sgpgme_data_release_and_get_mem(gpgenc, &len);
837
838         if (!enccontent) {
839                 g_warning("no enccontent\n");
840                 return FALSE;
841         }
842
843         tmpfile = get_tmp_file();
844         fp = g_fopen(tmpfile, "wb");
845         if (fp) {
846                 if (fwrite(enccontent, 1, len, fp) < len) {
847                         FILE_OP_ERROR(tmpfile, "fwrite");
848                         fclose(fp);
849                         claws_unlink(tmpfile);
850                         g_free(tmpfile);
851                         return FALSE;
852                 }
853                 if (fclose(fp) == EOF) {
854                         FILE_OP_ERROR(tmpfile, "fclose");
855                         claws_unlink(tmpfile);
856                         g_free(tmpfile);
857                         return FALSE;
858                 }
859         } else {
860                 perror("get_tmp_file");
861                 g_free(tmpfile);
862                 return FALSE;
863         }
864         gpgme_data_release(gpgtext);
865         g_free(textstr);
866
867         /* create encrypted multipart */
868         procmime_mimeinfo_free_all(msgcontent);
869         g_node_append(mimeinfo->node, encmultipart->node);
870
871         encmultipart->content = MIMECONTENT_FILE;
872         encmultipart->data.filename = tmpfile;
873         procmime_encode_content(encmultipart, ENC_BASE64);
874
875         g_free(enccontent);
876
877         return TRUE;
878 }
879
880 static PrivacySystem smime_system = {
881         "smime",                        /* id */
882         "S-MIME",                       /* name */
883
884         smime_free_privacydata, /* free_privacydata */
885
886         smime_is_signed,                /* is_signed(MimeInfo *) */
887         smime_check_signature,  /* check_signature(MimeInfo *) */
888         smime_get_sig_status,           /* get_sig_status(MimeInfo *) */
889         smime_get_sig_info_short,       /* get_sig_info_short(MimeInfo *) */
890         smime_get_sig_info_full,        /* get_sig_info_full(MimeInfo *) */
891
892         smime_is_encrypted,             /* is_encrypted(MimeInfo *) */
893         smime_decrypt,                  /* decrypt(MimeInfo *) */
894
895         TRUE,
896         smime_sign,
897
898         TRUE,
899         smime_get_encrypt_data,
900         smime_encrypt,
901         smime_get_encrypt_warning,
902         smime_inhibit_encrypt_warning,
903 };
904
905 void smime_init()
906 {
907         privacy_register_system(&smime_system);
908 }
909
910 void smime_done()
911 {
912         privacy_unregister_system(&smime_system);
913 }
914
915 struct PluginFeature *plugin_provides(void)
916 {
917         static struct PluginFeature features[] = 
918                 { {PLUGIN_PRIVACY, N_("S/MIME")},
919                   {PLUGIN_NOTHING, NULL}};
920         return features;
921 }
922 #endif /* USE_GPGME */