Fix exports
[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         return sgpgme_sigstat_gpgme_to_privacy(data->ctx, data->sigstatus);
334 }
335
336 static gchar *smime_get_sig_info_short(MimeInfo *mimeinfo)
337 {
338         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
339         
340         cm_return_val_if_fail(data != NULL, g_strdup("Error"));
341
342         return sgpgme_sigstat_info_short(data->ctx, data->sigstatus);
343 }
344
345 static gchar *smime_get_sig_info_full(MimeInfo *mimeinfo)
346 {
347         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
348         
349         cm_return_val_if_fail(data != NULL, g_strdup("Error"));
350
351         return sgpgme_sigstat_info_full(data->ctx, data->sigstatus);
352 }
353
354 static gboolean smime_is_encrypted(MimeInfo *mimeinfo)
355 {
356         const gchar *tmpstr;
357         
358         if (mimeinfo->type != MIMETYPE_APPLICATION)
359                 return FALSE;
360         if (!g_ascii_strcasecmp(mimeinfo->subtype, "pkcs7-mime")) {
361                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
362                 if (tmpstr && g_ascii_strcasecmp(tmpstr, "enveloped-data"))
363                         return FALSE;
364                 else 
365                         return TRUE;
366
367         } else if (!g_ascii_strcasecmp(mimeinfo->subtype, "x-pkcs7-mime")) {
368                 tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "smime-type");
369                 if (tmpstr && g_ascii_strcasecmp(tmpstr, "enveloped-data"))
370                         return FALSE;
371                 else 
372                         return TRUE;
373         }
374         return FALSE;
375 }
376
377 static MimeInfo *smime_decrypt(MimeInfo *mimeinfo)
378 {
379         MimeInfo *encinfo, *decinfo, *parseinfo;
380         gpgme_data_t cipher = NULL, plain = NULL;
381         static gint id = 0;
382         FILE *dstfp;
383         gchar *fname;
384         gpgme_verify_result_t sigstat = NULL;
385         PrivacyDataPGP *data = NULL;
386         gpgme_ctx_t ctx;
387         gpgme_error_t err;
388         gchar *chars;
389         size_t len;
390
391         cm_return_val_if_fail(smime_is_encrypted(mimeinfo), NULL);
392         
393         if ((err = gpgme_new(&ctx)) != GPG_ERR_NO_ERROR) {
394                 privacy_set_error(_("Couldn't initialize GPG context, %s"), gpgme_strerror(err));
395                 return NULL;
396         }
397
398         err = gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
399         if (err) {
400                 debug_print ("gpgme_set_protocol failed: %s\n",
401                    gpgme_strerror (err));
402                 privacy_set_error(_("Couldn't set GPG protocol, %s"), gpgme_strerror(err));
403                 gpgme_release(ctx);
404                 return NULL;
405         }
406         gpgme_set_armor(ctx, TRUE);
407
408         encinfo = mimeinfo;
409
410         cipher = sgpgme_data_from_mimeinfo(encinfo);
411         
412         plain = sgpgme_decrypt_verify(cipher, &sigstat, ctx);
413
414         gpgme_data_release(cipher);
415         if (plain == NULL) {
416                 debug_print("plain is null!\n");
417                 gpgme_release(ctx);
418                 return NULL;
419         }
420
421         fname = g_strdup_printf("%s%cplaintext.%08x",
422                 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
423
424         if ((dstfp = g_fopen(fname, "wb")) == NULL) {
425                 FILE_OP_ERROR(fname, "g_fopen");
426                 g_free(fname);
427                 gpgme_data_release(plain);
428                 gpgme_release(ctx);
429                 debug_print("can't open!\n");
430                 privacy_set_error(_("Couldn't open temporary file"));
431                 return NULL;
432         }
433
434         if (fprintf(dstfp, "MIME-Version: 1.0\n") < 0) {
435                 FILE_OP_ERROR(fname, "fprintf");
436                 g_free(fname);
437                 fclose(dstfp);
438                 gpgme_data_release(plain);
439                 gpgme_release(ctx);
440                 debug_print("can't close!\n");
441                 privacy_set_error(_("Couldn't write to temporary file"));
442                 return NULL;
443         }
444
445         chars = sgpgme_data_release_and_get_mem(plain, &len);
446
447         if (len > 0) {
448                 if (fwrite(chars, 1, len, dstfp) < len) {
449                         FILE_OP_ERROR(fname, "fwrite");
450                         fclose(dstfp);
451                         g_free(fname);
452                         g_free(chars);
453                         gpgme_data_release(plain);
454                         gpgme_release(ctx);
455                         debug_print("can't write!\n");
456                         privacy_set_error(_("Couldn't write to temporary file"));
457                         return NULL;
458                 }
459         }
460         if (fclose(dstfp) == EOF) {
461                 FILE_OP_ERROR(fname, "fclose");
462                 g_free(fname);
463                 g_free(chars);
464                 gpgme_data_release(plain);
465                 gpgme_release(ctx);
466                 debug_print("can't close!\n");
467                 privacy_set_error(_("Couldn't close temporary file"));
468                 return NULL;
469         }
470         g_free(chars);
471
472         parseinfo = procmime_scan_file(fname);
473         g_free(fname);
474         if (parseinfo == NULL) {
475                 privacy_set_error(_("Couldn't parse decrypted file."));
476                 gpgme_release(ctx);
477                 return NULL;
478         }
479         decinfo = g_node_first_child(parseinfo->node) != NULL ?
480                 g_node_first_child(parseinfo->node)->data : NULL;
481         if (decinfo == NULL) {
482                 privacy_set_error(_("Couldn't parse decrypted file parts."));
483                 gpgme_release(ctx);
484                 return NULL;
485         }
486
487         g_node_unlink(decinfo->node);
488         procmime_mimeinfo_free_all(parseinfo);
489
490         decinfo->tmp = TRUE;
491
492         if (sigstat != NULL && sigstat->signatures != NULL) {
493                 if (decinfo->privacy != NULL) {
494                         data = (PrivacyDataPGP *) decinfo->privacy;
495                 } else {
496                         data = smime_new_privacydata();
497                         decinfo->privacy = (PrivacyData *) data;        
498                 }
499                 data->done_sigtest = TRUE;
500                 data->is_signed = TRUE;
501                 data->sigstatus = sigstat;
502                 if (data->ctx)
503                         gpgme_release(data->ctx);
504                 data->ctx = ctx;
505         } else
506                 gpgme_release(ctx);
507         
508         
509         
510         return decinfo;
511 }
512
513 gboolean smime_sign(MimeInfo *mimeinfo, PrefsAccount *account, const gchar *from_addr)
514 {
515         MimeInfo *msgcontent, *sigmultipart, *newinfo;
516         gchar *textstr, *micalg = NULL;
517         FILE *fp;
518         gchar *boundary = NULL;
519         gchar *sigcontent;
520         gpgme_ctx_t ctx;
521         gpgme_data_t gpgtext, gpgsig;
522         gpgme_error_t err;
523         size_t len;
524         struct passphrase_cb_info_s info;
525         gpgme_sign_result_t result = NULL;
526         gchar *test_msg;
527         gchar *real_content = NULL;
528         
529         fp = my_tmpfile();
530         if (fp == NULL) {
531                 perror("my_tmpfile");
532                 return FALSE;
533         }
534         procmime_write_mimeinfo(mimeinfo, fp);
535         rewind(fp);
536
537         /* read temporary file into memory */
538         test_msg = file_read_stream_to_str(fp);
539         fclose(fp);
540         
541         memset (&info, 0, sizeof info);
542
543         /* remove content node from message */
544         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
545         g_node_unlink(msgcontent->node);
546
547         /* create temporary multipart for content */
548         sigmultipart = procmime_mimeinfo_new();
549         sigmultipart->type = MIMETYPE_MULTIPART;
550         sigmultipart->subtype = g_strdup("signed");
551         
552         do {
553                 if (boundary)
554                         g_free(boundary);
555                 boundary = generate_mime_boundary("Sig");
556         } while (strstr(test_msg, boundary) != NULL);
557         
558         g_free(test_msg);
559
560         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
561                             g_strdup(boundary));
562         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
563                             g_strdup("application/pkcs7-signature"));
564         g_node_append(sigmultipart->node, msgcontent->node);
565         g_node_append(mimeinfo->node, sigmultipart->node);
566
567         /* write message content to temporary file */
568         fp = my_tmpfile();
569         if (fp == NULL) {
570                 perror("my_tmpfile");
571                 return FALSE;
572         }
573         procmime_write_mimeinfo(sigmultipart, fp);
574         rewind(fp);
575
576         /* read temporary file into memory */
577         textstr = get_canonical_content(fp, boundary);
578
579         g_free(boundary);
580
581         fclose(fp);
582
583         gpgme_data_new_from_mem(&gpgtext, textstr, textstr?strlen(textstr):0, 0);
584         gpgme_data_new(&gpgsig);
585         gpgme_new(&ctx);
586         gpgme_set_armor(ctx, TRUE);
587         gpgme_signers_clear (ctx);
588
589         err = gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
590
591         if (err) {
592                 debug_print ("gpgme_set_protocol failed: %s\n",
593                    gpgme_strerror (err));
594                 gpgme_data_release(gpgtext);
595                 gpgme_release(ctx);
596                 return FALSE;
597         }
598
599         if (!sgpgme_setup_signers(ctx, account, from_addr)) {
600                 debug_print("setup_signers failed\n");
601                 gpgme_data_release(gpgtext);
602                 gpgme_release(ctx);
603                 return FALSE;
604         }
605
606         info.c = ctx;
607         prefs_gpg_enable_agent(TRUE);
608         gpgme_set_passphrase_cb (ctx, NULL, &info);
609         
610         err = gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH);
611         if (err != GPG_ERR_NO_ERROR) {
612                 alertpanel_error("S/MIME : Cannot sign, %s (%d)", gpg_strerror(err), gpg_err_code(err));
613                 gpgme_data_release(gpgtext);
614                 gpgme_release(ctx);
615                 return FALSE;
616         }
617         result = gpgme_op_sign_result(ctx);
618         if (result && result->signatures) {
619             if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
620                 micalg = g_strdup_printf("pgp-%s", g_ascii_strdown(gpgme_hash_algo_name(
621                             result->signatures->hash_algo),-1));
622             } else {
623                 micalg = g_strdup(gpgme_hash_algo_name(
624                             result->signatures->hash_algo));
625             }
626         } else {
627             /* can't get result (maybe no signing key?) */
628             debug_print("gpgme_op_sign_result error\n");
629             return FALSE;
630         }
631
632         gpgme_release(ctx);
633         sigcontent = sgpgme_data_release_and_get_mem(gpgsig, &len);
634         gpgme_data_release(gpgtext);
635         g_free(textstr);
636
637         if (!sigcontent) {
638                 gpgme_release(ctx);
639                 g_free(micalg);
640                 return FALSE;
641         }
642         real_content = sigcontent+strlen("-----BEGIN SIGNED MESSAGE-----\n");
643         if (!strstr(real_content, "-----END SIGNED MESSAGE-----")) {
644                 debug_print("missing end\n");
645                 gpgme_release(ctx);
646                 g_free(micalg);
647                 return FALSE;
648         }
649         *strstr(real_content, "-----END SIGNED MESSAGE-----") = '\0';
650         /* add signature */
651         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
652                             micalg);
653
654         newinfo = procmime_mimeinfo_new();
655         newinfo->type = MIMETYPE_APPLICATION;
656         newinfo->subtype = g_strdup("pkcs7-signature");
657         g_hash_table_insert(newinfo->typeparameters, g_strdup("name"),
658                              g_strdup("smime.p7s"));
659         newinfo->content = MIMECONTENT_MEM;
660         newinfo->disposition = DISPOSITIONTYPE_ATTACHMENT;
661         g_hash_table_insert(newinfo->dispositionparameters, g_strdup("filename"),
662                             g_strdup("smime.p7s"));
663         newinfo->data.mem = g_malloc(len + 1);
664         g_memmove(newinfo->data.mem, real_content, len);
665         newinfo->data.mem[len] = '\0';
666         newinfo->encoding_type = ENC_BASE64;
667         g_node_append(sigmultipart->node, newinfo->node);
668
669         g_free(sigcontent);
670
671         return TRUE;
672 }
673 gchar *smime_get_encrypt_data(GSList *recp_names)
674 {
675         return sgpgme_get_encrypt_data(recp_names, GPGME_PROTOCOL_CMS);
676 }
677
678 static const gchar *smime_get_encrypt_warning(void)
679 {
680         if (prefs_gpg_should_skip_encryption_warning(smime_system.id))
681                 return NULL;
682         else
683                 return _("Please note that email headers, like Subject, "
684                          "are not encrypted by the S/MIME system.");
685 }
686
687 static void smime_inhibit_encrypt_warning(gboolean inhibit)
688 {
689         if (inhibit)
690                 prefs_gpg_add_skip_encryption_warning(smime_system.id);
691         else
692                 prefs_gpg_remove_skip_encryption_warning(smime_system.id);
693 }
694
695 static gchar *fp_read_noconv(FILE *fp)
696 {
697         GByteArray *array;
698         guchar buf[BUFSIZ];
699         gint n_read;
700         gchar *result = NULL;
701
702         if (!fp)
703                 return NULL;
704         array = g_byte_array_new();
705
706         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
707                 if (n_read < sizeof(buf) && ferror(fp))
708                         break;
709                 g_byte_array_append(array, buf, n_read);
710         }
711
712         if (ferror(fp)) {
713                 FILE_OP_ERROR("file stream", "fread");
714                 g_byte_array_free(array, TRUE);
715                 return NULL;
716         }
717
718         buf[0] = '\0';
719         g_byte_array_append(array, buf, 1);
720         result = (gchar *)array->data;
721         g_byte_array_free(array, FALSE);
722         
723         return result;
724 }
725
726 gboolean smime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
727 {
728         MimeInfo *msgcontent, *encmultipart;
729         FILE *fp;
730         gchar *enccontent;
731         size_t len;
732         gchar *textstr = NULL;
733         gpgme_data_t gpgtext = NULL, gpgenc = NULL;
734         gpgme_ctx_t ctx = NULL;
735         gpgme_key_t *kset = NULL;
736         gchar **fprs = g_strsplit(encrypt_data, " ", -1);
737         gint i = 0;
738         gpgme_error_t err;
739         gchar *tmpfile = NULL;
740
741         while (fprs[i] && strlen(fprs[i])) {
742                 i++;
743         }
744         
745         gpgme_new(&ctx);
746
747         err = gpgme_set_protocol(ctx, GPGME_PROTOCOL_CMS);
748
749         if (err) {
750                 debug_print ("gpgme_set_protocol failed: %s\n",
751                    gpgme_strerror (err));
752                 return FALSE;   
753         }
754
755         kset = g_malloc(sizeof(gpgme_key_t)*(i+1));
756         memset(kset, 0, sizeof(gpgme_key_t)*(i+1));
757         i = 0;
758
759         while (fprs[i] && strlen(fprs[i])) {
760                 gpgme_key_t key;
761                 gpgme_error_t err;
762                 err = gpgme_get_key(ctx, fprs[i], &key, 0);
763                 if (err) {
764                         debug_print("can't add key '%s'[%d] (%s)\n", fprs[i],i, gpgme_strerror(err));
765                         break;
766                 }
767                 debug_print("found %s at %d\n", fprs[i], i);
768                 kset[i] = key;
769                 i++;
770         }
771         
772         debug_print("Encrypting message content\n");
773
774         /* remove content node from message */
775         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
776         g_node_unlink(msgcontent->node);
777
778
779         /* create temporary multipart for content */
780         encmultipart = procmime_mimeinfo_new();
781         encmultipart->type = MIMETYPE_APPLICATION;
782         encmultipart->subtype = g_strdup("x-pkcs7-mime");
783         g_hash_table_insert(encmultipart->typeparameters, g_strdup("name"),
784                             g_strdup("smime.p7m"));
785         g_hash_table_insert(encmultipart->typeparameters,
786                             g_strdup("smime-type"),
787                             g_strdup("enveloped-data"));
788         
789         encmultipart->disposition = DISPOSITIONTYPE_ATTACHMENT;
790         g_hash_table_insert(encmultipart->dispositionparameters, g_strdup("filename"),
791                             g_strdup("smime.p7m"));
792
793         g_node_append(encmultipart->node, msgcontent->node);
794
795         /* write message content to temporary file */
796         tmpfile = get_tmp_file();
797         fp = g_fopen(tmpfile, "wb");
798         if (fp == NULL) {
799                 perror("get_tmp_file");
800                 g_free(kset);
801                 return FALSE;
802         }
803         procmime_decode_content(msgcontent);
804         procmime_write_mime_header(msgcontent, fp);
805         procmime_write_mimeinfo(msgcontent, fp);
806         fclose(fp);
807         canonicalize_file_replace(tmpfile);
808         fp = g_fopen(tmpfile, "rb");
809         if (fp == NULL) {
810                 perror("get_tmp_file");
811                 g_free(kset);
812                 return FALSE;
813         }
814         g_free(tmpfile);
815
816         /* read temporary file into memory */
817         textstr = fp_read_noconv(fp);
818
819         fclose(fp);
820
821         /* encrypt data */
822         gpgme_data_new_from_mem(&gpgtext, textstr, textstr?strlen(textstr):0, 0);
823         gpgme_data_new(&gpgenc);
824         cm_gpgme_data_rewind(gpgtext);
825         
826         gpgme_op_encrypt(ctx, kset, GPGME_ENCRYPT_ALWAYS_TRUST, gpgtext, gpgenc);
827
828         gpgme_release(ctx);
829         g_free(kset);
830         enccontent = sgpgme_data_release_and_get_mem(gpgenc, &len);
831
832         if (!enccontent) {
833                 g_warning("no enccontent\n");
834                 return FALSE;
835         }
836
837         tmpfile = get_tmp_file();
838         fp = g_fopen(tmpfile, "wb");
839         if (fp) {
840                 if (fwrite(enccontent, 1, len, fp) < len) {
841                         FILE_OP_ERROR(tmpfile, "fwrite");
842                         fclose(fp);
843                         claws_unlink(tmpfile);
844                         g_free(tmpfile);
845                         return FALSE;
846                 }
847                 if (fclose(fp) == EOF) {
848                         FILE_OP_ERROR(tmpfile, "fclose");
849                         claws_unlink(tmpfile);
850                         g_free(tmpfile);
851                         return FALSE;
852                 }
853         } else {
854                 perror("get_tmp_file");
855                 g_free(tmpfile);
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 */