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