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