2005-02-18 [colin] 1.0.1cvs12
[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         GpgmeSigStat    sigstatus;
49         GpgmeCtx        ctx;
50 };
51
52 PGPMIME pgpmime_system;
53
54 static PrivacyDataPGP *pgpmime_new_privacydata()
55 {
56         PrivacyDataPGP *data;
57
58         data = g_new0(PrivacyDataPGP, 1);
59         data->data.system = &pgpmime_system;
60         data->done_sigtest = FALSE;
61         data->is_signed = FALSE;
62         data->sigstatus = GPGME_SIG_STAT_NONE;
63         gpgme_new(&data->ctx);
64         
65         return data;
66 }
67
68 PGPMIME::PGPMIME()
69 {
70 }
71
72 const gchar *PGPMIME::getId()
73 {
74         return "pgpmime";
75 }
76
77 const gchar *PGPMIME::getName()
78 {
79         return "PGP/MIME";
80 }
81
82 void PGPMIME::freePrivacyData(PrivacyData *_data)
83 {
84         PrivacyDataPGP *data = (PrivacyDataPGP *) _data;
85         gpgme_release(data->ctx);
86
87         PrivacySystem::freePrivacyData(_data);
88 }
89
90 gboolean PGPMIME::isSigned(MimeInfo *mimeinfo)
91 {
92         MimeInfo *parent;
93         MimeInfo *signature;
94         const gchar *protocol;
95         PrivacyDataPGP *data = NULL;
96         
97         g_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         /* check parent */
105         parent = procmime_mimeinfo_parent(mimeinfo);
106         if (parent == NULL)
107                 return FALSE;
108         if ((parent->type != MIMETYPE_MULTIPART) ||
109             g_strcasecmp(parent->subtype, "signed"))
110                 return FALSE;
111         protocol = procmime_mimeinfo_get_parameter(parent, "protocol");
112         if ((protocol == NULL) || g_strcasecmp(protocol, "application/pgp-signature"))
113                 return FALSE;
114
115         /* check if mimeinfo is the first child */
116         if (parent->node->children->data != mimeinfo)
117                 return FALSE;
118
119         /* check signature */
120         signature = parent->node->children->next != NULL ? 
121             (MimeInfo *) parent->node->children->next->data : NULL;
122         if (signature == NULL)
123                 return FALSE;
124         if ((signature->type != MIMETYPE_APPLICATION) ||
125             g_strcasecmp(signature->subtype, "pgp-signature"))
126                 return FALSE;
127
128         if (data == NULL) {
129                 data = pgpmime_new_privacydata();
130                 mimeinfo->privacy = (PrivacyData *) data;
131         }
132         data->done_sigtest = TRUE;
133         data->is_signed = TRUE;
134
135         return TRUE;
136 }
137
138 static gchar *get_canonical_content(FILE *fp, const gchar *boundary)
139 {
140         gchar *ret;
141         GString *textbuffer;
142         guint boundary_len;
143         gchar buf[BUFFSIZE];
144
145         boundary_len = strlen(boundary);
146         while (fgets(buf, sizeof(buf), fp) != NULL)
147                 if (IS_BOUNDARY(buf, boundary, boundary_len))
148                         break;
149
150         textbuffer = g_string_new("");
151         while (fgets(buf, sizeof(buf), fp) != NULL) {
152                 gchar *buf2;
153
154                 if (IS_BOUNDARY(buf, boundary, boundary_len))
155                         break;
156                 
157                 buf2 = canonicalize_str(buf);
158                 g_string_append(textbuffer, buf2);
159                 g_free(buf2);
160         }
161         g_string_truncate(textbuffer, textbuffer->len - 2);
162                 
163         ret = textbuffer->str;
164         g_string_free(textbuffer, FALSE);
165
166         return ret;
167 }
168
169 gint PGPMIME::checkSignature(MimeInfo *mimeinfo)
170 {
171         PrivacyDataPGP *data;
172         MimeInfo *parent, *signature;
173         FILE *fp;
174         gchar *boundary;
175         gchar *textstr;
176         GpgmeData sigdata, textdata;
177         
178         g_return_val_if_fail(mimeinfo != NULL, -1);
179         g_return_val_if_fail(mimeinfo->privacy != NULL, -1);
180         data = (PrivacyDataPGP *) mimeinfo->privacy;
181         
182         debug_print("Checking PGP/MIME signature\n");
183         parent = procmime_mimeinfo_parent(mimeinfo);
184
185         fp = fopen(parent->data.filename, "rb");
186         g_return_val_if_fail(fp != NULL, SIGNATURE_INVALID);
187         
188         boundary = (gchar *) g_hash_table_lookup(parent->typeparameters, "boundary");
189         if (!boundary)
190                 return 0;
191
192         textstr = get_canonical_content(fp, boundary);
193
194         gpgme_data_new_from_mem(&textdata, textstr, strlen(textstr), 0);
195         signature = (MimeInfo *) mimeinfo->node->next->data;
196         sigdata = sgpgme_data_from_mimeinfo(signature);
197
198         data->sigstatus =
199                 sgpgme_verify_signature (data->ctx, sigdata, textdata);
200         
201         gpgme_data_release(sigdata);
202         gpgme_data_release(textdata);
203         g_free(textstr);
204         fclose(fp);
205         
206         return 0;
207 }
208
209 SignatureStatus PGPMIME::getSigStatus(MimeInfo *mimeinfo)
210 {
211         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
212         
213         g_return_val_if_fail(data != NULL, SIGNATURE_INVALID);
214
215         if (data->sigstatus == GPGME_SIG_STAT_NONE && 
216             prefs_gpg_get_config()->auto_check_signatures)
217                 checkSignature(mimeinfo);
218         
219         return sgpgme_sigstat_gpgme_to_privacy(data->ctx, data->sigstatus);
220 }
221
222 gchar *PGPMIME::getSigInfoShort(MimeInfo *mimeinfo)
223 {
224         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
225         
226         g_return_val_if_fail(data != NULL, g_strdup("Error"));
227
228         if (data->sigstatus == GPGME_SIG_STAT_NONE && 
229             prefs_gpg_get_config()->auto_check_signatures)
230                 checkSignature(mimeinfo);
231         
232         return sgpgme_sigstat_info_short(data->ctx, data->sigstatus);
233 }
234
235 gchar *PGPMIME::getSigInfoFull(MimeInfo *mimeinfo)
236 {
237         PrivacyDataPGP *data = (PrivacyDataPGP *) mimeinfo->privacy;
238         
239         g_return_val_if_fail(data != NULL, g_strdup("Error"));
240
241         if (data->sigstatus == GPGME_SIG_STAT_NONE && 
242             prefs_gpg_get_config()->auto_check_signatures)
243                 checkSignature(mimeinfo);
244         
245         return sgpgme_sigstat_info_full(data->ctx, data->sigstatus);
246 }
247
248 gboolean PGPMIME::isEncrypted(MimeInfo *mimeinfo)
249 {
250         MimeInfo *tmpinfo;
251         const gchar *tmpstr;
252         
253         if (mimeinfo->type != MIMETYPE_MULTIPART)
254                 return FALSE;
255         if (g_strcasecmp(mimeinfo->subtype, "encrypted"))
256                 return FALSE;
257         tmpstr = procmime_mimeinfo_get_parameter(mimeinfo, "protocol");
258         if ((tmpstr == NULL) || g_strcasecmp(tmpstr, "application/pgp-encrypted"))
259                 return FALSE;
260         if (g_node_n_children(mimeinfo->node) != 2)
261                 return FALSE;
262         
263         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 0)->data;
264         if (tmpinfo->type != MIMETYPE_APPLICATION)
265                 return FALSE;
266         if (g_strcasecmp(tmpinfo->subtype, "pgp-encrypted"))
267                 return FALSE;
268         
269         tmpinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
270         if (tmpinfo->type != MIMETYPE_APPLICATION)
271                 return FALSE;
272         if (g_strcasecmp(tmpinfo->subtype, "octet-stream"))
273                 return FALSE;
274         
275         return TRUE;
276 }
277
278 MimeInfo *PGPMIME::decrypt(MimeInfo *mimeinfo)
279 {
280         MimeInfo *encinfo, *decinfo, *parseinfo;
281         GpgmeData cipher, plain;
282         static gint id = 0;
283         FILE *dstfp;
284         size_t nread;
285         gchar *fname;
286         gchar buf[BUFFSIZE];
287         GpgmeSigStat sigstat = GPGME_SIG_STAT_NONE;
288         PrivacyDataPGP *data = NULL;
289         GpgmeCtx ctx;
290         
291         if (gpgme_new(&ctx) != GPGME_No_Error)
292                 return NULL;
293
294         
295         g_return_val_if_fail(isEncrypted(mimeinfo), NULL);
296         
297         encinfo = (MimeInfo *) g_node_nth_child(mimeinfo->node, 1)->data;
298
299         cipher = sgpgme_data_from_mimeinfo(encinfo);
300         plain = sgpgme_decrypt_verify(cipher, &sigstat, ctx);
301
302         gpgme_data_release(cipher);
303         if (plain == NULL) {
304                 gpgme_release(ctx);
305                 return NULL;
306         }
307
308         fname = g_strdup_printf("%s%cplaintext.%08x",
309                 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
310
311         if ((dstfp = fopen(fname, "wb")) == NULL) {
312                 FILE_OP_ERROR(fname, "fopen");
313                 g_free(fname);
314                 gpgme_data_release(plain);
315                 gpgme_release(ctx);
316                 return NULL;
317         }
318
319         fprintf(dstfp, "MIME-Version: 1.0\n");
320         gpgme_data_rewind (plain);
321         while (gpgme_data_read(plain, buf, sizeof(buf), &nread) == GPGME_No_Error) {
322                 fwrite (buf, nread, 1, dstfp);
323         }
324         fclose(dstfp);
325         
326         gpgme_data_release(plain);
327
328         parseinfo = procmime_scan_file(fname);
329         g_free(fname);
330         if (parseinfo == NULL) {
331                 gpgme_release(ctx);
332                 return NULL;
333         }
334         decinfo = g_node_first_child(parseinfo->node) != NULL ?
335                 (MimeInfo *) g_node_first_child(parseinfo->node)->data : NULL;
336         if (decinfo == NULL) {
337                 gpgme_release(ctx);
338                 return NULL;
339         }
340
341         g_node_unlink(decinfo->node);
342         procmime_mimeinfo_free_all(parseinfo);
343
344         decinfo->tmp = TRUE;
345
346         if (sigstat != GPGME_SIG_STAT_NONE) {
347                 if (decinfo->privacy != NULL) {
348                         data = (PrivacyDataPGP *) decinfo->privacy;
349                 } else {
350                         data = pgpmime_new_privacydata();
351                         decinfo->privacy = (PrivacyData *) data;        
352                 }
353                 data->done_sigtest = TRUE;
354                 data->is_signed = TRUE;
355                 data->sigstatus = sigstat;
356                 if (data->ctx)
357                         gpgme_release(data->ctx);
358                 data->ctx = ctx;
359         } else
360                 gpgme_release(ctx);
361
362         return decinfo;
363 }
364
365 #if 0
366 /*
367  * Find TAG in XML and return a pointer into xml set just behind the
368  * closing angle.  Return NULL if not found. 
369  */
370 static const char *
371 find_xml_tag (const char *xml, const char *tag)
372 {
373     int taglen = strlen (tag);
374     const char *s = xml;
375  
376     while ( (s = strchr (s, '<')) ) {
377         s++;
378         if (!strncmp (s, tag, taglen)) {
379             const char *s2 = s + taglen;
380             if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
381                 /* found */
382                 while (*s2 && *s2 != '>') /* skip attributes */
383                     s2++;
384                 /* fixme: do need to handle angles inside attribute vallues? */
385                 return *s2? (s2+1):NULL;
386             }
387         }
388         while (*s && *s != '>') /* skip to end of tag */
389             s++;
390     }
391     return NULL;
392 }
393
394
395 /*
396  * Extract the micalg from an GnupgOperationInfo XML container.
397  */
398 static char *
399 extract_micalg (char *xml)
400 {
401     const char *s;
402
403     s = find_xml_tag (xml, "GnupgOperationInfo");
404     if (s) {
405         const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
406         s = find_xml_tag (s, "signature");
407         if (s && s_end && s < s_end) {
408             const char *s_end2 = find_xml_tag (s, "/signature");
409             if (s_end2 && s_end2 < s_end) {
410                 s = find_xml_tag (s, "micalg");
411                 if (s && s < s_end2) {
412                     s_end = strchr (s, '<');
413                     if (s_end) {
414                         char *p = (gchar *) g_malloc (s_end - s + 1);
415                         memcpy (p, s, s_end - s);
416                         p[s_end-s] = 0;
417                         return p;
418                     }
419                 }
420             }
421         }
422     }
423     return NULL;
424 }
425
426 gboolean PGPMIME::sign(MimeInfo *mimeinfo, PrefsAccount *account)
427 {
428         MimeInfo *msgcontent, *sigmultipart, *newinfo;
429         gchar *textstr, *opinfo, *micalg;
430         FILE *fp;
431         gchar *boundary, *sigcontent;
432         GpgmeCtx ctx;
433         GpgmeData gpgtext, gpgsig;
434         guint len;
435         struct passphrase_cb_info_s info;
436
437         memset (&info, 0, sizeof info);
438
439         /* remove content node from message */
440         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
441         g_node_unlink(msgcontent->node);
442
443         /* create temporary multipart for content */
444         sigmultipart = procmime_mimeinfo_new();
445         sigmultipart->type = MIMETYPE_MULTIPART;
446         sigmultipart->subtype = g_strdup("signed");
447         boundary = generate_mime_boundary("Signature");
448         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("boundary"),
449                             g_strdup(boundary));
450         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("protocol"),
451                             g_strdup("application/pgp-signature"));
452         g_node_append(sigmultipart->node, msgcontent->node);
453         g_node_append(mimeinfo->node, sigmultipart->node);
454
455         /* write message content to temporary file */
456         fp = my_tmpfile();
457         procmime_write_mimeinfo(sigmultipart, fp);
458         rewind(fp);
459
460         /* read temporary file into memory */
461         textstr = get_canonical_content(fp, boundary);
462
463         fclose(fp);
464
465         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
466         gpgme_data_new(&gpgsig);
467         gpgme_new(&ctx);
468         gpgme_set_textmode(ctx, 1);
469         gpgme_set_armor(ctx, 1);
470
471         if (!sgpgme_setup_signers(ctx, account)) {
472                 gpgme_release(ctx);
473                 return FALSE;
474         }
475
476         if (!getenv("GPG_AGENT_INFO")) {
477                 info.c = ctx;
478                 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
479         }
480
481         if (gpgme_op_sign(ctx, gpgtext, gpgsig, GPGME_SIG_MODE_DETACH) != GPGME_No_Error) {
482                 gpgme_release(ctx);
483                 return FALSE;
484         }
485         opinfo = gpgme_get_op_info(ctx, 0);
486         micalg = extract_micalg(opinfo);
487         g_free(opinfo);
488
489         gpgme_release(ctx);
490         sigcontent = gpgme_data_release_and_get_mem(gpgsig, &len);
491         gpgme_data_release(gpgtext);
492         g_free(textstr);
493
494         /* add signature */
495         g_hash_table_insert(sigmultipart->typeparameters, g_strdup("micalg"),
496                             micalg);
497
498         newinfo = procmime_mimeinfo_new();
499         newinfo->type = MIMETYPE_APPLICATION;
500         newinfo->subtype = g_strdup("pgp-signature");
501         newinfo->content = MIMECONTENT_MEM;
502         newinfo->data.mem = g_malloc(len + 1);
503         g_memmove(newinfo->data.mem, sigcontent, len);
504         newinfo->data.mem[len] = '\0';
505         g_node_append(sigmultipart->node, newinfo->node);
506
507         g_free(sigcontent);
508
509         return TRUE;
510 }
511
512 gchar *PGPMIME::getEncryptData(GSList *recp_names)
513 {
514         return sgpgme_get_encrypt_data(recp_names);
515 }
516
517 gboolean PGPMIME::encrypt(MimeInfo *mimeinfo, const gchar *encrypt_data)
518 {
519         MimeInfo *msgcontent, *encmultipart, *newinfo;
520         FILE *fp;
521         gchar *boundary, *enccontent;
522         guint len;
523         gchar *textstr;
524         GpgmeData gpgtext, gpgenc;
525         gchar **recipients, **nextrecp;
526         GpgmeRecipients recp;
527         GpgmeCtx ctx;
528
529         /* build GpgmeRecipients from encrypt_data */
530         recipients = g_strsplit(encrypt_data, " ", 0);
531         gpgme_recipients_new(&recp);
532         for (nextrecp = recipients; *nextrecp != NULL; nextrecp++) {
533                 gpgme_recipients_add_name_with_validity(recp, *nextrecp,
534                                                         GPGME_VALIDITY_FULL);
535         }
536         g_strfreev(recipients);
537
538         debug_print("Encrypting message content\n");
539
540         /* remove content node from message */
541         msgcontent = (MimeInfo *) mimeinfo->node->children->data;
542         g_node_unlink(msgcontent->node);
543
544         /* create temporary multipart for content */
545         encmultipart = procmime_mimeinfo_new();
546         encmultipart->type = MIMETYPE_MULTIPART;
547         encmultipart->subtype = g_strdup("encrypted");
548         boundary = generate_mime_boundary("Encrypt");
549         g_hash_table_insert(encmultipart->typeparameters, g_strdup("boundary"),
550                             g_strdup(boundary));
551         g_hash_table_insert(encmultipart->typeparameters, g_strdup("protocol"),
552                             g_strdup("application/pgp-encrypted"));
553         g_node_append(encmultipart->node, msgcontent->node);
554
555         /* write message content to temporary file */
556         fp = my_tmpfile();
557         procmime_write_mimeinfo(encmultipart, fp);
558         rewind(fp);
559
560         /* read temporary file into memory */
561         textstr = get_canonical_content(fp, boundary);
562
563         fclose(fp);
564
565         /* encrypt data */
566         gpgme_data_new_from_mem(&gpgtext, textstr, strlen(textstr), 0);
567         gpgme_data_new(&gpgenc);
568         gpgme_new(&ctx);
569         gpgme_set_armor(ctx, 1);
570
571         gpgme_op_encrypt(ctx, recp, gpgtext, gpgenc);
572
573         gpgme_release(ctx);
574         enccontent = gpgme_data_release_and_get_mem(gpgenc, &len);
575         gpgme_recipients_release(recp);
576         gpgme_data_release(gpgtext);
577         g_free(textstr);
578
579         /* create encrypted multipart */
580         g_node_unlink(msgcontent->node);
581         procmime_mimeinfo_free_all(msgcontent);
582         g_node_append(mimeinfo->node, encmultipart->node);
583
584         newinfo = procmime_mimeinfo_new();
585         newinfo->type = MIMETYPE_APPLICATION;
586         newinfo->subtype = g_strdup("pgp-encrypted");
587         newinfo->content = MIMECONTENT_MEM;
588         newinfo->data.mem = g_strdup("Version: 1\n");
589         g_node_append(encmultipart->node, newinfo->node);
590
591         newinfo = procmime_mimeinfo_new();
592         newinfo->type = MIMETYPE_APPLICATION;
593         newinfo->subtype = g_strdup("octet-stream");
594         newinfo->content = MIMECONTENT_MEM;
595         newinfo->data.mem = g_malloc(len + 1);
596         g_memmove(newinfo->data.mem, enccontent, len);
597         newinfo->data.mem[len] = '\0';
598         g_node_append(encmultipart->node, newinfo->node);
599
600         g_free(enccontent);
601
602         return TRUE;
603 }
604
605 #endif
606
607 void pgpmime_init()
608 {
609         privacy_register_system(&pgpmime_system);
610 }
611
612 void pgpmime_done()
613 {
614         privacy_unregister_system(&pgpmime_system);
615 }
616
617 #endif /* USE_GPGME */