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