2005-07-13 [colin] 1.9.12cvs41
[claws.git] / src / plugins / pgpmime / pgpmime.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto & the Sylpheed-Claws 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 2 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, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.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
31 #include "utils.h"
32 #include "privacy.h"
33 #include "procmime.h"
34 #include "pgpmime.h"
35 #include "sgpgme.h"
36 #include "prefs_common.h"
37 #include "prefs_gpg.h"
38 #include "passphrase.h"
39
40 typedef struct _PrivacyDataPGP PrivacyDataPGP;
41
42 struct _PrivacyDataPGP
43 {
44         PrivacyData     data;
45         
46         gboolean        done_sigtest;
47         gboolean        is_signed;
48         gpgme_verify_result_t   sigstatus;
49         gpgme_ctx_t     ctx;
50 };
51
52 static PrivacySystem pgpmime_system;
53
54 static gint pgpmime_check_signature(MimeInfo *mimeinfo);
55
56 static PrivacyDataPGP *pgpmime_new_privacydata()
57 {
58         PrivacyDataPGP *data;
59
60         data = g_new0(PrivacyDataPGP, 1);
61         data->data.system = &pgpmime_system;
62         data->done_sigtest = FALSE;
63         data->is_signed = FALSE;
64         data->sigstatus = NULL;
65         gpgme_new(&data->ctx);
66         
67         return data;
68 }
69
70 static void pgpmime_free_privacydata(PrivacyData *_data)
71 {
72         PrivacyDataPGP *data = (PrivacyDataPGP *) _data;
73         gpgme_release(data->ctx);
74         g_free(data);
75 }
76
77 static gboolean pgpmime_is_signed(MimeInfo *mimeinfo)
78 {
79         MimeInfo *parent;
80         MimeInfo *signature;
81         const gchar *protocol;
82         PrivacyDataPGP *data = NULL;
83         
84         g_return_val_if_fail(mimeinfo != NULL, FALSE);
85         if (mimeinfo->privacy != NULL) {
86                 data = (PrivacyDataPGP *) mimeinfo->privacy;
87                 if (data->done_sigtest)
88                         return data->is_signed;
89         }
90         
91         /* check parent */
92         parent = procmime_mimeinfo_parent(mimeinfo);
93         if (parent == NULL)
94                 return FALSE;
95         if ((parent->type != MIMETYPE_MULTIPART) ||
96             g_ascii_strcasecmp(parent->subtype, "signed"))
97                 return FALSE;
98         protocol = procmime_mimeinfo_get_parameter(parent, "protocol");
99         if ((protocol == NULL) || g_ascii_strcasecmp(protocol, "application/pgp-signature"))
100                 return FALSE;
101
102         /* check if mimeinfo is the first child */
103         if (parent->node->children->data != mimeinfo)
104                 return FALSE;
105
106         /* check signature */
107         signature = parent->node->children->next != NULL ? 
108             (MimeInfo *) parent->node->children->next->data : NULL;
109         if (signature == NULL)
110                 return FALSE;
111         if ((signature->type != MIMETYPE_APPLICATION) ||
112             g_ascii_strcasecmp(signature->subtype, "pgp-signature"))
113                 return FALSE;
114
115         if (data == NULL) {
116                 data = pgpmime_new_privacydata();
117                 mimeinfo->privacy = (PrivacyData *) data;
118         }
119         data->done_sigtest = TRUE;
120         data->is_signed = TRUE;
121
122         return TRUE;
123 }
124
125 static gchar *get_canonical_content(FILE *fp, const gchar *boundary)
126 {
127         gchar *ret;
128         GString *textbuffer;
129         guint boundary_len;
130         gchar buf[BUFFSIZE];
131
132         boundary_len = strlen(boundary);
133         while (fgets(buf, sizeof(buf), fp) != NULL)
134                 if (IS_BOUNDARY(buf, boundary, boundary_len))
135                         break;
136
137         textbuffer = g_string_new("");
138         while (fgets(buf, sizeof(buf), fp) != NULL) {
139                 gchar *buf2;
140
141                 if (IS_BOUNDARY(buf, boundary, boundary_len))
142                         break;
143                 
144                 buf2 = canonicalize_str(buf);
145                 g_string_append(textbuffer, buf2);
146                 g_free(buf2);
147         }
148         g_string_truncate(textbuffer, textbuffer->len - 2);
149                 
150         ret = textbuffer->str;
151         g_string_free(textbuffer, FALSE);
152
153         return ret;
154 }
155
156 static gint pgpmime_check_signature(MimeInfo *mimeinfo)
157 {
158         PrivacyDataPGP *data;
159         MimeInfo *parent, *signature;
160         FILE *fp;
161         gchar *boundary;
162         gchar *textstr;
163         gpgme_data_t sigdata = NULL, textdata = NULL;
164         gpgme_error_t err;
165         g_return_val_if_fail(mimeinfo != NULL, -1);
166         g_return_val_if_fail(mimeinfo->privacy != NULL, -1);
167         data = (PrivacyDataPGP *) mimeinfo->privacy;
168         gpgme_new(&data->ctx);
169         
170         debug_print("Checking PGP/MIME signature\n");
171         parent = procmime_mimeinfo_parent(mimeinfo);
172
173         fp = fopen(parent->data.filename, "rb");
174         g_return_val_if_fail(fp != NULL, SIGNATURE_INVALID);
175         
176         boundary = g_hash_table_lookup(parent->typeparameters, "boundary");
177         if (!boundary)
178                 return 0;
179
180         textstr = get_canonical_content(fp, boundary);
181
182         err = gpgme_data_new_from_mem(&textdata, textstr, strlen(textstr), 0);
183         if (err) {
184                 debug_print ("gpgme_data_new_from_mem failed: %s\n",
185                    gpgme_strerror (err));
186         }
187         signature = (MimeInfo *) mimeinfo->node->next->data;
188         sigdata = sgpgme_data_from_mimeinfo(signature);
189
190         data->sigstatus =
191                 sgpgme_verify_signature (data->ctx, sigdata, textdata, NULL);
192
193         gpgme_data_release(sigdata);
194         gpgme_data_release(textdata);
195         g_free(textstr);
196         fclose(fp);
197         
198         return 0;
199 }
200
201 static SignatureStatus pgpmime_get_sig_status(MimeInfo *mimeinfo)
202 {
203         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
204         
205         g_return_val_if_fail(data != NULL, SIGNATURE_INVALID);
206
207         if (data->sigstatus == NULL && 
208             prefs_gpg_get_config()->auto_check_signatures)
209                 pgpmime_check_signature(mimeinfo);
210         
211         return sgpgme_sigstat_gpgme_to_privacy(data->ctx, data->sigstatus);
212 }
213
214 static gchar *pgpmime_get_sig_info_short(MimeInfo *mimeinfo)
215 {
216         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
217         
218         g_return_val_if_fail(data != NULL, g_strdup("Error"));
219
220         if (data->sigstatus == NULL && 
221             prefs_gpg_get_config()->auto_check_signatures)
222                 pgpmime_check_signature(mimeinfo);
223         
224         return sgpgme_sigstat_info_short(data->ctx, data->sigstatus);
225 }
226
227 static gchar *pgpmime_get_sig_info_full(MimeInfo *mimeinfo)
228 {
229         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
230         
231         g_return_val_if_fail(data != NULL, g_strdup("Error"));
232
233         if (data->sigstatus == NULL && 
234             prefs_gpg_get_config()->auto_check_signatures)
235                 pgpmime_check_signature(mimeinfo);
236         
237         return sgpgme_sigstat_info_full(data->ctx, data->sigstatus);
238 }
239
240 static gboolean pgpmime_is_encrypted(MimeInfo *mimeinfo)
241 {
242         MimeInfo *tmpinfo;
243         const gchar *tmpstr;
244         
245         if (mimeinfo->type != MIMETYPE_MULTIPART)
246                 return FALSE;
247         if (g_ascii_strcasecmp(mimeinfo->subtype, "encrypted"))
248                 return FALSE;
249         tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "protocol");
250         if ((tmpstr == NULL) || g_ascii_strcasecmp(tmpstr, "application/pgp-encrypted"))
251                 return FALSE;
252         if (g_node_n_children(mimeinfo->node) != 2)
253                 return FALSE;
254         
255         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 0)->data;
256         if (tmpinfo->type != MIMETYPE_APPLICATION)
257                 return FALSE;
258         if (g_ascii_strcasecmp(tmpinfo->subtype, "pgp-encrypted"))
259                 return FALSE;
260         
261         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
262         if (tmpinfo->type != MIMETYPE_APPLICATION)
263                 return FALSE;
264         if (g_ascii_strcasecmp(tmpinfo->subtype, "octet-stream"))
265                 return FALSE;
266         
267         return TRUE;
268 }
269
270 static MimeInfo *pgpmime_decrypt(MimeInfo *mimeinfo)
271 {
272         MimeInfo *encinfo, *decinfo, *parseinfo;
273         gpgme_data_t cipher = NULL, plain = NULL;
274         static gint id = 0;
275         FILE *dstfp;
276         gchar *fname;
277         gpgme_verify_result_t sigstat = NULL;
278         PrivacyDataPGP *data = NULL;
279         gpgme_ctx_t ctx;
280         gchar *chars;
281         int len;
282
283         if (gpgme_new(&ctx) != GPG_ERR_NO_ERROR)
284                 return NULL;
285
286         
287         g_return_val_if_fail(pgpmime_is_encrypted(mimeinfo), NULL);
288         
289         encinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
290
291         cipher = sgpgme_data_from_mimeinfo(encinfo);
292         plain = sgpgme_decrypt_verify(cipher, &sigstat, ctx);
293
294         gpgme_data_release(cipher);
295         if (plain == NULL) {
296                 debug_print("plain is null!\n");
297                 gpgme_release(ctx);
298                 return NULL;
299         }
300
301         fname = g_strdup_printf("%s%cplaintext.%08x",
302                 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
303
304         if ((dstfp = fopen(fname, "wb")) == NULL) {
305                 FILE_OP_ERROR(fname, "fopen");
306                 g_free(fname);
307                 gpgme_data_release(plain);
308                 gpgme_release(ctx);
309                 debug_print("can't open!\n");
310                 return NULL;
311         }
312
313         fprintf(dstfp, "MIME-Version: 1.0\n");
314
315         chars = gpgme_data_release_and_get_mem(plain, &len);
316         if (len > 0)
317                 fwrite(chars, len, 1, dstfp);
318         fclose(dstfp);
319
320         parseinfo = procmime_scan_file(fname);
321         g_free(fname);
322         if (parseinfo == NULL) {
323                 gpgme_release(ctx);
324                 return NULL;
325         }
326         decinfo = g_node_first_child(parseinfo->node) != NULL ?
327                 g_node_first_child(parseinfo->node)->data : NULL;
328         if (decinfo == NULL) {
329                 gpgme_release(ctx);
330                 return NULL;
331         }
332
333         g_node_unlink(decinfo->node);
334         procmime_mimeinfo_free_all(parseinfo);
335
336         decinfo->tmp = TRUE;
337
338         if (sigstat != NULL && sigstat->signatures != NULL) {
339                 if (decinfo->privacy != NULL) {
340                         data = (PrivacyDataPGP *) decinfo->privacy;
341                 } else {
342                         data = pgpmime_new_privacydata();
343                         decinfo->privacy = (PrivacyData *) data;        
344                 }
345                 data->done_sigtest = TRUE;
346                 data->is_signed = TRUE;
347                 data->sigstatus = sigstat;
348                 if (data->ctx)
349                         gpgme_release(data->ctx);
350                 data->ctx = ctx;
351         } else
352                 gpgme_release(ctx);
353
354         return decinfo;
355 }
356
357 gboolean pgpmime_sign(MimeInfo *mimeinfo, PrefsAccount *account)
358 {
359         MimeInfo *msgcontent, *sigmultipart, *newinfo;
360         gchar *textstr, *micalg;
361         FILE *fp;
362         gchar *boundary, *sigcontent;
363         gpgme_ctx_t ctx;
364         gpgme_data_t gpgtext, gpgsig;
365         size_t len;
366         struct passphrase_cb_info_s info;
367         gpgme_sign_result_t result = NULL;
368
369         memset (&info, 0, sizeof info);
370
371         /* remove content node from message */
372         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
373         g_node_unlink(msgcontent->node);
374
375         /* create temporary multipart for content */
376         sigmultipart = procmime_mimeinfo_new();
377         sigmultipart->type = MIMETYPE_MULTIPART;
378         sigmultipart->subtype = g_strdup("signed");
379         boundary = generate_mime_boundary("Signature");
380         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
381                             g_strdup(boundary));
382         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
383                             g_strdup("application/pgp-signature"));
384         g_node_append(sigmultipart->node, msgcontent->node);
385         g_node_append(mimeinfo->node, sigmultipart->node);
386
387         /* write message content to temporary file */
388         fp = my_tmpfile();
389         procmime_write_mimeinfo(sigmultipart, fp);
390         rewind(fp);
391
392         /* read temporary file into memory */
393         textstr = get_canonical_content(fp, boundary);
394
395         fclose(fp);
396
397         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
398         gpgme_data_new(&gpgsig);
399         gpgme_new(&ctx);
400         gpgme_set_textmode(ctx, 1);
401         gpgme_set_armor(ctx, 1);
402         gpgme_signers_clear (ctx);
403
404         if (!sgpgme_setup_signers(ctx, account)) {
405                 gpgme_release(ctx);
406                 return FALSE;
407         }
408
409         if (!getenv("GPG_AGENT_INFO")) {
410                 info.c = ctx;
411                 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
412         }
413
414         if (gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH) != GPG_ERR_NO_ERROR) {
415                 gpgme_release(ctx);
416                 return FALSE;
417         }
418         result = gpgme_op_sign_result(ctx);
419         if (result && result->signatures) {
420             if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
421                 micalg = g_strdup_printf("PGP-%s", gpgme_hash_algo_name(
422                             result->signatures->hash_algo));
423             } else {
424                 micalg = g_strdup(gpgme_hash_algo_name(
425                             result->signatures->hash_algo));
426             }
427         } else {
428             /* can't get result (maybe no signing key?) */
429             return FALSE;
430         }
431
432         gpgme_release(ctx);
433         sigcontent = gpgme_data_release_and_get_mem(gpgsig, &len);
434         gpgme_data_release(gpgtext);
435         g_free(textstr);
436
437         /* add signature */
438         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
439                             micalg);
440
441         newinfo = procmime_mimeinfo_new();
442         newinfo->type = MIMETYPE_APPLICATION;
443         newinfo->subtype = g_strdup("pgp-signature");
444         newinfo->content = MIMECONTENT_MEM;
445         newinfo->data.mem = g_malloc(len + 1);
446         g_memmove(newinfo->data.mem, sigcontent, len);
447         newinfo->data.mem[len] = '\0';
448         g_node_append(sigmultipart->node, newinfo->node);
449
450         g_free(sigcontent);
451
452         return TRUE;
453 }
454 gchar *pgpmime_get_encrypt_data(GSList *recp_names)
455 {
456         return sgpgme_get_encrypt_data(recp_names);
457 }
458
459 gboolean pgpmime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
460 {
461         MimeInfo *msgcontent, *encmultipart, *newinfo;
462         FILE *fp;
463         gchar *boundary, *enccontent;
464         size_t len;
465         gchar *textstr;
466         gpgme_data_t gpgtext = NULL, gpgenc = NULL;
467         gpgme_ctx_t ctx = NULL;
468         gpgme_key_t *kset = NULL;
469         gchar **fprs = g_strsplit(encrypt_data, " ", -1);
470         gint i = 0;
471         while (fprs[i] && strlen(fprs[i])) {
472                 i++;
473         }
474         
475         kset = g_malloc(sizeof(gpgme_key_t)*(i+1));
476         memset(kset, 0, sizeof(gpgme_key_t)*(i+1));
477         gpgme_new(&ctx);
478         i = 0;
479         while (fprs[i] && strlen(fprs[i])) {
480                 gpgme_key_t key;
481                 gpgme_error_t err;
482                 err = gpgme_get_key(ctx, fprs[i], &key, 0);
483                 if (err) {
484                         debug_print("can't add key '%s'[%d] (%s)\n", fprs[i],i, gpgme_strerror(err));
485                         break;
486                 }
487                 debug_print("found %s at %d\n", fprs[i], i);
488                 kset[i] = key;
489                 i++;
490         }
491         
492         debug_print("Encrypting message content\n");
493
494         /* remove content node from message */
495         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
496         g_node_unlink(msgcontent->node);
497
498         /* create temporary multipart for content */
499         encmultipart = procmime_mimeinfo_new();
500         encmultipart->type = MIMETYPE_MULTIPART;
501         encmultipart->subtype = g_strdup("encrypted");
502         boundary = generate_mime_boundary("Encrypt");
503         g_hash_table_insert(encmultipart->typeparameters, g_strdup("boundary"),
504                             g_strdup(boundary));
505         g_hash_table_insert(encmultipart->typeparameters, g_strdup("protocol"),
506                             g_strdup("application/pgp-encrypted"));
507         g_node_append(encmultipart->node, msgcontent->node);
508
509         /* write message content to temporary file */
510         fp = my_tmpfile();
511         procmime_write_mimeinfo(encmultipart, fp);
512         rewind(fp);
513
514         /* read temporary file into memory */
515         textstr = get_canonical_content(fp, boundary);
516
517         fclose(fp);
518
519         /* encrypt data */
520         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
521         gpgme_data_new(&gpgenc);
522         gpgme_set_armor(ctx, 1);
523         gpgme_data_seek(gpgtext, 0, SEEK_SET);
524         
525         gpgme_op_encrypt(ctx, kset, GPGME_ENCRYPT_ALWAYS_TRUST, gpgtext, gpgenc);
526
527         gpgme_release(ctx);
528         enccontent = gpgme_data_release_and_get_mem(gpgenc, &len);
529         gpgme_data_release(gpgtext);
530         g_free(textstr);
531
532         /* create encrypted multipart */
533         g_node_unlink(msgcontent->node);
534         procmime_mimeinfo_free_all(msgcontent);
535         g_node_append(mimeinfo->node, encmultipart->node);
536
537         newinfo = procmime_mimeinfo_new();
538         newinfo->type = MIMETYPE_APPLICATION;
539         newinfo->subtype = g_strdup("pgp-encrypted");
540         newinfo->content = MIMECONTENT_MEM;
541         newinfo->data.mem = g_strdup("Version: 1\n");
542         g_node_append(encmultipart->node, newinfo->node);
543
544         newinfo = procmime_mimeinfo_new();
545         newinfo->type = MIMETYPE_APPLICATION;
546         newinfo->subtype = g_strdup("octet-stream");
547         newinfo->content = MIMECONTENT_MEM;
548         newinfo->data.mem = g_malloc(len + 1);
549         g_memmove(newinfo->data.mem, enccontent, len);
550         newinfo->data.mem[len] = '\0';
551         g_node_append(encmultipart->node, newinfo->node);
552
553         g_free(enccontent);
554
555         return TRUE;
556 }
557
558 static PrivacySystem pgpmime_system = {
559         "pgpmime",                      /* id */
560         "PGP MIME",                     /* name */
561
562         pgpmime_free_privacydata,       /* free_privacydata */
563
564         pgpmime_is_signed,              /* is_signed(MimeInfo *) */
565         pgpmime_check_signature,        /* check_signature(MimeInfo *) */
566         pgpmime_get_sig_status,         /* get_sig_status(MimeInfo *) */
567         pgpmime_get_sig_info_short,     /* get_sig_info_short(MimeInfo *) */
568         pgpmime_get_sig_info_full,      /* get_sig_info_full(MimeInfo *) */
569
570         pgpmime_is_encrypted,           /* is_encrypted(MimeInfo *) */
571         pgpmime_decrypt,                /* decrypt(MimeInfo *) */
572
573         TRUE,
574         pgpmime_sign,
575
576         TRUE,
577         pgpmime_get_encrypt_data,
578         pgpmime_encrypt,
579 };
580
581 void pgpmime_init()
582 {
583         privacy_register_system(&pgpmime_system);
584 }
585
586 void pgpmime_done()
587 {
588         privacy_unregister_system(&pgpmime_system);
589 }
590
591 #endif /* USE_GPGME */