2005-07-13 [colin] 1.9.12cvs40
[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         gint nread;
277         gchar *fname;
278         gchar buf[BUFFSIZE];
279         gpgme_verify_result_t sigstat = NULL;
280         PrivacyDataPGP *data = NULL;
281         gpgme_ctx_t ctx;
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         while ((nread = gpgme_data_read(plain, buf, sizeof(buf))) > 0) {
316                 debug_print("read %d:%s\n", nread, buf);
317                 fwrite (buf, nread, 1, dstfp);
318         }
319         debug_print("nread %d!\n", nread);
320         fclose(dstfp);
321         
322         gpgme_data_release(plain);
323
324         parseinfo = procmime_scan_file(fname);
325         g_free(fname);
326         if (parseinfo == NULL) {
327                 gpgme_release(ctx);
328                 return NULL;
329         }
330         decinfo = g_node_first_child(parseinfo->node) != NULL ?
331                 g_node_first_child(parseinfo->node)->data : NULL;
332         if (decinfo == NULL) {
333                 gpgme_release(ctx);
334                 return NULL;
335         }
336
337         g_node_unlink(decinfo->node);
338         procmime_mimeinfo_free_all(parseinfo);
339
340         decinfo->tmp = TRUE;
341
342         if (sigstat != NULL && sigstat->signatures != NULL) {
343                 if (decinfo->privacy != NULL) {
344                         data = (PrivacyDataPGP *) decinfo->privacy;
345                 } else {
346                         data = pgpmime_new_privacydata();
347                         decinfo->privacy = (PrivacyData *) data;        
348                 }
349                 data->done_sigtest = TRUE;
350                 data->is_signed = TRUE;
351                 data->sigstatus = sigstat;
352                 if (data->ctx)
353                         gpgme_release(data->ctx);
354                 data->ctx = ctx;
355         } else
356                 gpgme_release(ctx);
357
358         return decinfo;
359 }
360
361 gboolean pgpmime_sign(MimeInfo *mimeinfo, PrefsAccount *account)
362 {
363         MimeInfo *msgcontent, *sigmultipart, *newinfo;
364         gchar *textstr, *micalg;
365         FILE *fp;
366         gchar *boundary, *sigcontent;
367         gpgme_ctx_t ctx;
368         gpgme_data_t gpgtext, gpgsig;
369         size_t len;
370         struct passphrase_cb_info_s info;
371         gpgme_sign_result_t result = NULL;
372
373         memset (&info, 0, sizeof info);
374
375         /* remove content node from message */
376         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
377         g_node_unlink(msgcontent->node);
378
379         /* create temporary multipart for content */
380         sigmultipart = procmime_mimeinfo_new();
381         sigmultipart->type = MIMETYPE_MULTIPART;
382         sigmultipart->subtype = g_strdup("signed");
383         boundary = generate_mime_boundary("Signature");
384         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
385                             g_strdup(boundary));
386         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
387                             g_strdup("application/pgp-signature"));
388         g_node_append(sigmultipart->node, msgcontent->node);
389         g_node_append(mimeinfo->node, sigmultipart->node);
390
391         /* write message content to temporary file */
392         fp = my_tmpfile();
393         procmime_write_mimeinfo(sigmultipart, fp);
394         rewind(fp);
395
396         /* read temporary file into memory */
397         textstr = get_canonical_content(fp, boundary);
398
399         fclose(fp);
400
401         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
402         gpgme_data_new(&gpgsig);
403         gpgme_new(&ctx);
404         gpgme_set_textmode(ctx, 1);
405         gpgme_set_armor(ctx, 1);
406         gpgme_signers_clear (ctx);
407
408         if (!sgpgme_setup_signers(ctx, account)) {
409                 gpgme_release(ctx);
410                 return FALSE;
411         }
412
413         if (!getenv("GPG_AGENT_INFO")) {
414                 info.c = ctx;
415                 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
416         }
417
418         if (gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH) != GPG_ERR_NO_ERROR) {
419                 gpgme_release(ctx);
420                 return FALSE;
421         }
422         result = gpgme_op_sign_result(ctx);
423         if (result && result->signatures) {
424             if (gpgme_get_protocol(ctx) == GPGME_PROTOCOL_OpenPGP) {
425                 micalg = g_strdup_printf("PGP-%s", gpgme_hash_algo_name(
426                             result->signatures->hash_algo));
427             } else {
428                 micalg = g_strdup(gpgme_hash_algo_name(
429                             result->signatures->hash_algo));
430             }
431         } else {
432             /* can't get result (maybe no signing key?) */
433             return FALSE;
434         }
435
436         gpgme_release(ctx);
437         sigcontent = gpgme_data_release_and_get_mem(gpgsig, &len);
438         gpgme_data_release(gpgtext);
439         g_free(textstr);
440
441         /* add signature */
442         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
443                             micalg);
444
445         newinfo = procmime_mimeinfo_new();
446         newinfo->type = MIMETYPE_APPLICATION;
447         newinfo->subtype = g_strdup("pgp-signature");
448         newinfo->content = MIMECONTENT_MEM;
449         newinfo->data.mem = g_malloc(len + 1);
450         g_memmove(newinfo->data.mem, sigcontent, len);
451         newinfo->data.mem[len] = '\0';
452         g_node_append(sigmultipart->node, newinfo->node);
453
454         g_free(sigcontent);
455
456         return TRUE;
457 }
458 gchar *pgpmime_get_encrypt_data(GSList *recp_names)
459 {
460         return sgpgme_get_encrypt_data(recp_names);
461 }
462
463 gboolean pgpmime_encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
464 {
465         MimeInfo *msgcontent, *encmultipart, *newinfo;
466         FILE *fp;
467         gchar *boundary, *enccontent;
468         size_t len;
469         gchar *textstr;
470         gpgme_data_t gpgtext = NULL, gpgenc = NULL;
471         gpgme_ctx_t ctx = NULL;
472         gpgme_key_t *kset = NULL;
473         gchar **fprs = g_strsplit(encrypt_data, " ", -1);
474         gint i = 0;
475         while (fprs[i] && strlen(fprs[i])) {
476                 i++;
477         }
478         
479         kset = g_malloc(sizeof(gpgme_key_t)*(i+1));
480         memset(kset, 0, sizeof(gpgme_key_t)*(i+1));
481         gpgme_new(&ctx);
482         i = 0;
483         while (fprs[i] && strlen(fprs[i])) {
484                 gpgme_key_t key;
485                 gpgme_error_t err;
486                 err = gpgme_get_key(ctx, fprs[i], &key, 0);
487                 if (err) {
488                         debug_print("can't add key '%s'[%d] (%s)\n", fprs[i],i, gpgme_strerror(err));
489                         break;
490                 }
491                 debug_print("found %s at %d\n", fprs[i], i);
492                 kset[i] = key;
493                 i++;
494         }
495         
496         debug_print("Encrypting message content\n");
497
498         /* remove content node from message */
499         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
500         g_node_unlink(msgcontent->node);
501
502         /* create temporary multipart for content */
503         encmultipart = procmime_mimeinfo_new();
504         encmultipart->type = MIMETYPE_MULTIPART;
505         encmultipart->subtype = g_strdup("encrypted");
506         boundary = generate_mime_boundary("Encrypt");
507         g_hash_table_insert(encmultipart->typeparameters, g_strdup("boundary"),
508                             g_strdup(boundary));
509         g_hash_table_insert(encmultipart->typeparameters, g_strdup("protocol"),
510                             g_strdup("application/pgp-encrypted"));
511         g_node_append(encmultipart->node, msgcontent->node);
512
513         /* write message content to temporary file */
514         fp = my_tmpfile();
515         procmime_write_mimeinfo(encmultipart, fp);
516         rewind(fp);
517
518         /* read temporary file into memory */
519         textstr = get_canonical_content(fp, boundary);
520
521         fclose(fp);
522
523         /* encrypt data */
524         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
525         gpgme_data_new(&gpgenc);
526         gpgme_set_armor(ctx, 1);
527         gpgme_data_seek(gpgtext, 0, SEEK_SET);
528         
529         gpgme_op_encrypt(ctx, kset, GPGME_ENCRYPT_ALWAYS_TRUST, gpgtext, gpgenc);
530
531         gpgme_release(ctx);
532         enccontent = gpgme_data_release_and_get_mem(gpgenc, &len);
533         gpgme_data_release(gpgtext);
534         g_free(textstr);
535
536         /* create encrypted multipart */
537         g_node_unlink(msgcontent->node);
538         procmime_mimeinfo_free_all(msgcontent);
539         g_node_append(mimeinfo->node, encmultipart->node);
540
541         newinfo = procmime_mimeinfo_new();
542         newinfo->type = MIMETYPE_APPLICATION;
543         newinfo->subtype = g_strdup("pgp-encrypted");
544         newinfo->content = MIMECONTENT_MEM;
545         newinfo->data.mem = g_strdup("Version: 1\n");
546         g_node_append(encmultipart->node, newinfo->node);
547
548         newinfo = procmime_mimeinfo_new();
549         newinfo->type = MIMETYPE_APPLICATION;
550         newinfo->subtype = g_strdup("octet-stream");
551         newinfo->content = MIMECONTENT_MEM;
552         newinfo->data.mem = g_malloc(len + 1);
553         g_memmove(newinfo->data.mem, enccontent, len);
554         newinfo->data.mem[len] = '\0';
555         g_node_append(encmultipart->node, newinfo->node);
556
557         g_free(enccontent);
558
559         return TRUE;
560 }
561
562 static PrivacySystem pgpmime_system = {
563         "pgpmime",                      /* id */
564         "PGP MIME",                     /* name */
565
566         pgpmime_free_privacydata,       /* free_privacydata */
567
568         pgpmime_is_signed,              /* is_signed(MimeInfo *) */
569         pgpmime_check_signature,        /* check_signature(MimeInfo *) */
570         pgpmime_get_sig_status,         /* get_sig_status(MimeInfo *) */
571         pgpmime_get_sig_info_short,     /* get_sig_info_short(MimeInfo *) */
572         pgpmime_get_sig_info_full,      /* get_sig_info_full(MimeInfo *) */
573
574         pgpmime_is_encrypted,           /* is_encrypted(MimeInfo *) */
575         pgpmime_decrypt,                /* decrypt(MimeInfo *) */
576
577         TRUE,
578         pgpmime_sign,
579
580         TRUE,
581         pgpmime_get_encrypt_data,
582         pgpmime_encrypt,
583 };
584
585 void pgpmime_init()
586 {
587         privacy_register_system(&pgpmime_system);
588 }
589
590 void pgpmime_done()
591 {
592         privacy_unregister_system(&pgpmime_system);
593 }
594
595 #endif /* USE_GPGME */