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