0.9.6claws14
[claws.git] / src / rfc2015.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2001 Werner Koch (dd9jn)
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 #if USE_GPGME
25
26 #include "defs.h"
27
28 #include <glib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <locale.h>
32 #include <ctype.h>
33
34 #include <gpgme.h>
35
36 #include "intl.h"
37 #include "procmime.h"
38 #include "procheader.h"
39 #include "base64.h"
40 #include "uuencode.h"
41 #include "unmime.h"
42 #include "codeconv.h"
43 #include "utils.h"
44 #include "prefs_common.h"
45 #include "passphrase.h"
46 #include "select-keys.h"
47 #include "sigstatus.h"
48 #include "rfc2015.h"
49 #include "alertpanel.h"
50
51 #define DIM(v)     (sizeof(v)/sizeof((v)[0]))
52
53 static char *content_names[] = {
54     "Content-Type",
55     "Content-Disposition",
56     "Content-Transfer-Encoding",
57     NULL
58 };
59
60 static char *mime_version_name[] = {
61     "Mime-Version",
62     NULL
63 };
64
65 static void sig_expiration_check        (GString        *str,
66                                          GpgmeCtx        ctx,
67                                          GpgmeKey        key, 
68                                          GpgmeSigStat    status,
69                                          int             idx);
70 static void sig_expired                 (GString        *str,
71                                          GpgmeCtx        ctx,
72                                          int             idx);
73 static void sig_key_expired             (GString        *str,
74                                          GpgmeKey        key,
75                                          int             idx);
76
77 #if 0
78 static void dump_mimeinfo (const char *text, MimeInfo *x)
79 {
80     debug_print ("MimeInfo[%s] %p  level=%d\n",
81                text, x, x? x->level:0 );
82     if (!x)
83         return;
84
85     debug_print ("      enc=`%s' enc_type=%d mime_type=%d\n",
86                x->encoding, x->encoding_type, x->mime_type );
87     debug_print ("      cont_type=`%s' cs=`%s' name=`%s' bnd=`%s'\n",
88                x->content_type, x->charset, x->name, x->boundary );
89     debug_print ("      cont_disp=`%s' fname=`%s' fpos=%ld size=%u, lvl=%d\n",
90                x->content_disposition, x->filename, x->fpos, x->size,
91                x->level );
92     dump_mimeinfo (".main", x->main );
93     dump_mimeinfo (".sub", x->sub );
94     dump_mimeinfo (".next", x->next );
95     debug_print ("MimeInfo[.parent] %p\n", x ); 
96     dump_mimeinfo (".children", x->children );
97     dump_mimeinfo (".plaintext", x->plaintext );
98 }
99
100 static void dump_part ( MimeInfo *mimeinfo, FILE *fp )
101 {
102     unsigned int size = mimeinfo->size;
103     int c;
104
105     if (fseek (fp, mimeinfo->fpos, SEEK_SET)) {
106         debug_print ("dump_part: fseek error\n");
107         return;
108     }
109
110     debug_print ("--- begin dump_part ----\n");
111     while (size-- && (c = getc (fp)) != EOF) 
112         putc (c, stderr);
113     if (ferror (fp))
114         debug_print ("dump_part: read error\n");
115     debug_print ("--- end dump_part ----\n");
116 }
117 #endif
118
119 void
120 rfc2015_disable_all (void)
121 {
122     /* FIXME: set a flag, so that we don't bother the user with failed
123      * gpgme messages */
124 }
125
126
127 void
128 rfc2015_secure_remove (const char *fname)
129 {
130     if (!fname)
131         return;
132     /* fixme: overwrite the file first */
133     remove (fname);
134 }
135
136
137 static const gchar *
138 sig_status_to_string (GpgmeSigStat status)
139 {
140     const gchar *result;
141
142     switch (status) {
143       case GPGME_SIG_STAT_NONE:
144         result = _("Oops: Signature not verified");
145         break;
146       case GPGME_SIG_STAT_NOSIG:
147         result = _("No signature found");
148         break;
149       case GPGME_SIG_STAT_GOOD:
150         result = _("Good signature");
151         break;
152       case GPGME_SIG_STAT_GOOD_EXP:     
153         result = _("Good signature but it has expired");
154         break;
155       case GPGME_SIG_STAT_GOOD_EXPKEY:
156         result = _("Good signature but the key has expired");
157         break;
158       case GPGME_SIG_STAT_BAD:
159         result = _("BAD signature");
160         break;
161       case GPGME_SIG_STAT_NOKEY:
162         result = _("No public key to verify the signature");
163         break;
164       case GPGME_SIG_STAT_ERROR:
165         result = _("Error verifying the signature");
166         break;
167       case GPGME_SIG_STAT_DIFF:
168         result = _("Different results for signatures");
169         break;
170       default:
171         result = _("Error: Unknown status");
172         break;
173     }
174
175     return result;
176 }
177
178 static const gchar *
179 sig_status_with_name (GpgmeSigStat status)
180 {
181     const gchar *result;
182
183     switch (status) {
184       case GPGME_SIG_STAT_NONE:
185         result = _("Oops: Signature not verified");
186         break;
187       case GPGME_SIG_STAT_NOSIG:
188         result = _("No signature found");
189         break;
190       case GPGME_SIG_STAT_GOOD:
191         result = _("Good signature from \"%s\"");
192         break;
193       case GPGME_SIG_STAT_GOOD_EXP:
194         result = _("Good signature from \"%s\" but it has expired");
195         break;
196       case GPGME_SIG_STAT_GOOD_EXPKEY:
197         result = _("Good signature from \"%s\" but the key has expired");
198         break;
199       case GPGME_SIG_STAT_BAD:
200         result = _("BAD signature from \"%s\"");
201         break;
202       case GPGME_SIG_STAT_NOKEY:
203         result = _("No public key to verify the signature");
204         break;
205       case GPGME_SIG_STAT_ERROR:
206         result = _("Error verifying the signature");
207         break;
208       case GPGME_SIG_STAT_DIFF:
209         result = _("Different results for signatures");
210         break;
211       default:
212         result = _("Error: Unknown status");
213         break;
214     }
215
216     return result;
217 }
218
219 static void
220 sig_status_for_key(GString *str, GpgmeCtx ctx, GpgmeSigStat status, 
221                    GpgmeKey key, const gchar *fpr)
222 {
223         gint idx = 0;
224         const char *uid;
225
226         uid = gpgme_key_get_string_attr (key, GPGME_ATTR_USERID, NULL, idx);
227         if (uid == NULL) {
228                 g_string_sprintfa (str, "%s\n",
229                                    sig_status_to_string (status));
230                 if ((fpr != NULL) && (*fpr != '\0'))
231                         g_string_sprintfa (str, "Key fingerprint: %s\n", fpr);
232                 g_string_append (str, _("Cannot find user ID for this key."));
233                 sig_expiration_check(str, ctx, key, status, 0);
234                 return;
235         }
236         g_string_sprintfa (str, sig_status_with_name (status), uid);
237         g_string_append (str, "\n");
238
239         while (1) {
240                 uid = gpgme_key_get_string_attr (key, GPGME_ATTR_USERID,
241                                                  NULL, ++idx);
242                 if (uid == NULL)
243                         break;
244                 g_string_sprintfa (str, _("                aka \"%s\"\n"),
245                                    uid);
246         }
247         sig_expiration_check(str, ctx, key, status, 0);
248 }
249
250 static void
251 sig_expiration_check(GString *str, GpgmeCtx ctx, GpgmeKey key, 
252                      GpgmeSigStat status, int idx)
253 {
254         if (status == GPGME_SIG_STAT_GOOD_EXP)
255                 sig_expired(str, ctx, idx);
256         else if (status == GPGME_SIG_STAT_GOOD_EXPKEY)
257                 sig_key_expired(str, key, idx);
258 }
259
260 static void
261 sig_expired(GString *str, GpgmeCtx ctx, int idx)
262 {
263         unsigned long exp_time;
264         exp_time = gpgme_get_sig_ulong_attr(ctx, idx, GPGME_ATTR_EXPIRE, 0);
265         g_string_sprintfa(str, _("Signature expired %s"), ctime(&exp_time));    
266 }
267
268 static void
269 sig_key_expired(GString *str, GpgmeKey key, int idx)
270 {
271         unsigned long exp_time;
272         exp_time = gpgme_key_get_ulong_attr(key, GPGME_ATTR_EXPIRE, NULL, idx);
273         g_string_sprintfa(str, _("Key expired %s"), ctime(&exp_time));  
274 }
275
276 static gchar *
277 sig_status_full (GpgmeCtx ctx)
278 {
279         GString *str;
280         gint sig_idx = 0;
281         GpgmeError err;
282         GpgmeSigStat status;
283         GpgmeKey key;
284         const char *fpr;
285         time_t created;
286         struct tm *ctime_val;
287         char ctime_str[80];
288         gchar *retval;
289
290         str = g_string_new ("");
291
292         fpr = gpgme_get_sig_status (ctx, sig_idx, &status, &created);
293         while (fpr != NULL) {
294                 if (created != 0) {
295                         ctime_val = localtime (&created);
296                         strftime (ctime_str, sizeof (ctime_str), "%c", 
297                                   ctime_val);
298                         g_string_sprintfa (str,
299                                            _("Signature made at %s\n"),
300                                            ctime_str);
301                 }
302                 err = gpgme_get_sig_key (ctx, sig_idx, &key);
303                 if (err != 0) {
304                         g_string_sprintfa (str, "%s\n",
305                                            sig_status_to_string (status));
306                         if ((fpr != NULL) && (*fpr != '\0'))
307                                 g_string_sprintfa (str, 
308                                                    _("Key fingerprint: %s\n"),
309                                                    fpr);
310                 } else {
311                         const char *key_id_str;
312                         
313                         sig_status_for_key (str, ctx, status, key, fpr);
314                         key_id_str = gpgme_key_get_string_attr(key, 
315                                                 GPGME_ATTR_KEYID, NULL, 0);
316                         key_id_str += 8;
317                         g_string_sprintfa (str, _("Key ID: %s\n"), key_id_str);
318                         gpgme_key_unref (key);
319                 }
320                 g_string_append (str, "\n\n");
321
322                 fpr = gpgme_get_sig_status (ctx, ++sig_idx, &status, &created);
323         }
324
325         retval = str->str;
326         g_string_free (str, FALSE);
327         return retval;
328 }
329
330 static void check_signature (MimeInfo *mimeinfo, MimeInfo *partinfo, FILE *fp)
331 {
332 #if 0 /* FIXME */
333     GpgmeCtx ctx = NULL;
334     GpgmeError err;
335     GpgmeData sig = NULL, text = NULL;
336     GpgmeSigStat status = GPGME_SIG_STAT_NONE;
337     GpgmegtkSigStatus statuswindow = NULL;
338     const char *result = NULL;
339     gchar *tmp_file;
340     gint n_exclude_chars = 0;
341
342     if (prefs_common.gpg_signature_popup)
343         statuswindow = gpgmegtk_sig_status_create ();
344
345     err = gpgme_new (&ctx);
346     if (err) {
347         debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
348         goto leave;
349     }
350
351     /* don't include the last empty line.
352        It does not belong to the signed text */
353     if (mimeinfo->children->length > 0) {
354         if (fseek(fp, mimeinfo->children->offset + mimeinfo->children->length - 1,
355                   SEEK_SET) < 0) {
356             perror("fseek");
357             goto leave;
358         }
359         if (fgetc(fp) == '\n') {
360             n_exclude_chars++;
361             if (mimeinfo->children->length > 1) {
362                 if (fseek(fp, mimeinfo->children->offset + mimeinfo->children->length - 2,
363                           SEEK_SET) < 0) {
364                     perror("fseek");
365                     goto leave;
366                 }
367                 if (fgetc(fp) == '\r')
368                     n_exclude_chars++;
369             }
370         }
371     }
372
373     /* canonicalize the file part. */
374     tmp_file = get_tmp_file();
375     if (copy_file_part(fp, mimeinfo->children->offset,
376                        mimeinfo->children->length - n_exclude_chars,
377                        tmp_file) < 0) {
378         g_free(tmp_file);
379         goto leave;
380     }
381     if (canonicalize_file_replace(tmp_file) < 0) {
382         unlink(tmp_file);
383         g_free(tmp_file);
384         goto leave;
385     }
386
387     err = gpgme_data_new_from_file(&text, tmp_file, 1);
388
389     unlink(tmp_file);
390     g_free(tmp_file);
391
392     if (!err)
393         err = gpgme_data_new_from_filepart (&sig, NULL, fp,
394                                             partinfo->offset, partinfo->length);
395     if (err) {
396         debug_print ("gpgme_data_new_from_filepart failed: %s\n",
397                    gpgme_strerror (err));
398         goto leave;
399     }
400
401     err = gpgme_op_verify (ctx, sig, text, &status);
402     if (err)  {
403         debug_print ("gpgme_op_verify failed: %s\n", gpgme_strerror (err));
404         goto leave;
405     }
406
407     /* FIXME: check what the heck this sig_status_full stuff is.
408      * it should better go into sigstatus.c */
409     g_free (partinfo->sigstatus_full);
410     partinfo->sigstatus_full = sig_status_full (ctx);
411
412 leave:
413     result = gpgmegtk_sig_status_to_string(status);
414     debug_print("verification status: %s\n", result);
415     if (prefs_common.gpg_signature_popup)
416         gpgmegtk_sig_status_update (statuswindow, ctx);
417
418     g_free (partinfo->sigstatus);
419     partinfo->sigstatus = g_strdup (result);
420     partinfo->sig_ok = (status == GPGME_SIG_STAT_GOOD);
421     partinfo->sig_unknown = (status == GPGME_SIG_STAT_NOKEY);
422     partinfo->sig_expired = (status == GPGME_SIG_STAT_GOOD_EXP);
423     partinfo->key_expired = (status == GPGME_SIG_STAT_GOOD_EXPKEY);
424
425     gpgme_data_release (sig);
426     gpgme_data_release (text);
427     gpgme_release (ctx);
428     if (prefs_common.gpg_signature_popup)
429         gpgmegtk_sig_status_destroy (statuswindow);
430 #endif
431 }
432
433 /*
434  * Copy a gpgme data object to a temporary file and
435  * return this filename 
436  */
437 #if 0
438 static char *
439 copy_gpgmedata_to_temp (GpgmeData data, guint *length)
440 {
441     static int id;
442     char *tmp;
443     FILE *fp;
444     char buf[100];
445     size_t nread;
446     GpgmeError err;
447     
448     tmp = g_strdup_printf("%s%cgpgtmp.%08x",
449                           get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id );
450
451     if ((fp = fopen(tmp, "wb")) == NULL) {
452         FILE_OP_ERROR(tmp, "fopen");
453         g_free(tmp);
454         return NULL;
455     }
456
457     err = gpgme_data_rewind ( data );
458     if (err)
459         debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
460
461     while (!(err = gpgme_data_read (data, buf, 100, &nread))) {
462         fwrite ( buf, nread, 1, fp );
463     }
464
465     if (err != GPGME_EOF)
466         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
467
468     fclose (fp);
469     *length = nread;
470
471     return tmp;
472 }
473 #endif
474
475 static GpgmeData
476 pgp_decrypt (MimeInfo *partinfo, FILE *fp)
477 {
478     GpgmeCtx ctx = NULL;
479     GpgmeError err;
480     GpgmeData cipher = NULL, plain = NULL;
481     struct passphrase_cb_info_s info;
482
483     memset (&info, 0, sizeof info);
484
485     err = gpgme_new (&ctx);
486     if (err) {
487         debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
488         goto leave;
489     }
490
491     err = gpgme_data_new_from_filepart (&cipher, NULL, fp,
492                                         partinfo->offset, partinfo->length);
493     if (err) {
494         debug_print ("gpgme_data_new_from_filepart failed: %s\n",
495                      gpgme_strerror (err));
496         goto leave;
497     }
498
499     err = gpgme_data_new (&plain);
500     if (err) {
501         debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
502         goto leave;
503     }
504
505     if (!getenv("GPG_AGENT_INFO")) {
506         info.c = ctx;
507         gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
508     } 
509
510     err = gpgme_op_decrypt (ctx, cipher, plain);
511
512 leave:
513     gpgme_data_release (cipher);
514     if (err) {
515         gpgmegtk_free_passphrase();
516         debug_print ("decryption failed: %s\n", gpgme_strerror (err));
517         gpgme_data_release (plain);
518         plain = NULL;
519     }
520     else
521         debug_print ("** decryption succeeded\n");
522
523     gpgme_release (ctx);
524     return plain;
525 }
526
527 MimeInfo * rfc2015_find_signature (MimeInfo *mimeinfo)
528 {
529     MimeInfo *partinfo;
530     int n = 0;
531
532     if (!mimeinfo)
533         return NULL;
534     if (!((mimeinfo->type == MIMETYPE_MULTIPART) && !g_strcasecmp(mimeinfo->subtype, "signed")))
535         return NULL;
536
537     debug_print ("** multipart/signed encountered\n");
538
539     /* check that we have at least 2 parts of the correct type */
540     for (partinfo = mimeinfo->children;
541          partinfo != NULL; partinfo = partinfo->next) {
542         if (++n > 1 && (partinfo->type == MIMETYPE_APPLICATION && 
543                 !g_strcasecmp (partinfo->subtype, "pgp-signature")))
544             break;
545     }
546
547     return partinfo;
548 }
549
550 gboolean rfc2015_has_signature (MimeInfo *mimeinfo)
551 {
552     return rfc2015_find_signature (mimeinfo) != NULL;
553 }
554
555 void rfc2015_check_signature (MimeInfo *mimeinfo, FILE *fp)
556 {
557     MimeInfo *partinfo;
558
559     partinfo = rfc2015_find_signature (mimeinfo);
560     if (!partinfo)
561         return;
562
563 #if 0
564     g_message ("** yep, it is a pgp signature");
565     dump_mimeinfo ("gpg-signature", partinfo );
566     dump_part (partinfo, fp );
567     dump_mimeinfo ("signed text", mimeinfo->children );
568     dump_part (mimeinfo->children, fp);
569 #endif
570
571     check_signature (mimeinfo, partinfo, fp);
572 }
573
574 int rfc2015_is_encrypted (MimeInfo *mimeinfo)
575 {
576     if (!mimeinfo || mimeinfo->type != MIMETYPE_MULTIPART)
577         return 0;
578     if (g_strcasecmp (mimeinfo->subtype, "encrypted"))
579         return 0;
580     /* fixme: we should check the protocol parameter */
581     return 1;
582 }
583
584 gboolean rfc2015_msg_is_encrypted (const gchar *file)
585 {
586         FILE *fp;
587         MimeInfo *mimeinfo;
588         int ret = 0;
589
590 #if 0   /* FIXME */
591         if ((fp = fopen(file, "rb")) == NULL)
592                 return FALSE;
593
594         mimeinfo = procmime_scan_mime_header(fp);
595         if(!mimeinfo) {
596                 fclose(fp);
597                 return FALSE;
598         }
599
600         ret = rfc2015_is_encrypted(mimeinfo);
601         procmime_mimeinfo_free_all(mimeinfo);
602 #endif
603         return ret != 0 ? TRUE : FALSE;
604 }
605
606 static int
607 name_cmp(const char *a, const char *b)
608 {
609     for( ; *a && *b; a++, b++) {
610         if(*a != *b
611            && toupper(*(unsigned char *)a) != toupper(*(unsigned char *)b))
612             return 1;
613     }
614
615     return *a != *b;
616 }
617
618 static int
619 headerp(char *p, char **names)
620 {
621     int i, c;
622     char *p2;
623
624     p2 = strchr(p, ':');
625     if(!p2 || p == p2) {
626         return 0;
627     }
628     if(p2[-1] == ' ' || p2[-1] == '\t') {
629         return 0;
630     }
631
632     if(!names[0])
633         return 1;  
634
635     c = *p2;
636     *p2 = 0;
637     for(i = 0 ; names[i] != NULL; i++) {
638         if(!name_cmp (names[i], p))
639             break;
640     }
641     *p2 = c;
642
643     return names[i] != NULL;
644 }
645
646
647 #define DECRYPTION_ABORT() \
648 { \
649     procmime_mimeinfo_free_all(tmpinfo); \
650     msginfo->decryption_failed = 1; \
651     return; \
652 }
653
654 void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
655 {
656     static int id;
657     MimeInfo *tmpinfo, *partinfo;
658     int ver_ok = 0;
659     char *fname;
660     GpgmeData plain;
661     FILE *dstfp;
662     size_t nread;
663     char buf[BUFFSIZE];
664     int in_cline;
665     GpgmeError err;
666
667     g_return_if_fail (msginfo != NULL);
668     g_return_if_fail (mimeinfo != NULL);
669     g_return_if_fail (fp != NULL);
670     g_return_if_fail (mimeinfo->type == MIMETYPE_MULTIPART);
671
672     debug_print ("** decrypting multipart/encrypted message\n");
673
674 #if 0 /* FIXME */
675
676     /* skip headers */
677     if (fseek(fp, mimeinfo->offset, SEEK_SET) < 0)
678         perror("fseek");
679     tmpinfo = procmime_scan_mime_header(fp);
680     if (!tmpinfo || tmpinfo->type != MIMETYPE_MULTIPART) {
681         DECRYPTION_ABORT();
682     }
683
684     procmime_scan_message(tmpinfo);
685
686     /* check that we have the 2 parts */
687     partinfo = tmpinfo->children;
688     if (!partinfo || !partinfo->next) {
689         DECRYPTION_ABORT();
690     }
691     if ((partinfo->type == MIMETYPE_APPLICATION) && !g_strcasecmp(partinfo->subtype, "pgp-encrypted")) {
692         /* Fixme: check that the version is 1 */
693         ver_ok = 1;
694     }
695     partinfo = partinfo->next;
696     if (ver_ok && (partinfo->type == MIMETYPE_APPLICATION) &&
697         !g_strcasecmp (partinfo->subtype, "octet-stream")) {
698         if (partinfo->next)
699             g_warning ("oops: pgp_encrypted with more than 2 parts");
700     }
701     else {
702         DECRYPTION_ABORT();
703     }
704
705     debug_print ("** yep, it is pgp encrypted\n");
706
707     plain = pgp_decrypt (partinfo, fp);
708     if (!plain) {
709         DECRYPTION_ABORT();
710     }
711
712     fname = g_strdup_printf("%s%cplaintext.%08x",
713                             get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
714
715     if ((dstfp = fopen(fname, "wb")) == NULL) {
716         FILE_OP_ERROR(fname, "fopen");
717         g_free(fname);
718         DECRYPTION_ABORT();
719     }
720
721     /* write the orginal header to the new file */
722     if (fseek(fp, tmpinfo->offset, SEEK_SET) < 0)
723         perror("fseek");
724
725     in_cline = 0;
726     while (fgets(buf, sizeof(buf), fp)) {
727         if (headerp (buf, content_names)) {
728             in_cline = 1;
729             continue;
730         }
731         if (in_cline) {
732             if (buf[0] == ' ' || buf[0] == '\t')
733                 continue;
734             in_cline = 0;
735         }
736         if (buf[0] == '\r' || buf[0] == '\n')
737             break;
738         fputs (buf, dstfp);
739     }
740
741     err = gpgme_data_rewind (plain);
742     if (err)
743         debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
744
745     while (!(err = gpgme_data_read (plain, buf, sizeof(buf), &nread))) {
746         fwrite (buf, nread, 1, dstfp);
747     }
748
749     if (err != GPGME_EOF) {
750         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
751     }
752
753     fclose (dstfp);
754     procmime_mimeinfo_free_all(tmpinfo);
755
756     msginfo->plaintext_file = fname;
757     msginfo->decryption_failed = 0;
758
759 #endif
760 }
761
762 #undef DECRYPTION_ABORT
763
764
765 /*
766  * plain contains an entire mime object.
767  * Encrypt it and return an GpgmeData object with the encrypted version of
768  * the file or NULL in case of error.
769  */
770 static GpgmeData
771 pgp_encrypt ( GpgmeData plain, GpgmeRecipients rset )
772 {
773     GpgmeCtx ctx = NULL;
774     GpgmeError err;
775     GpgmeData cipher = NULL;
776
777     err = gpgme_new (&ctx);
778     if (!err)
779         err = gpgme_data_new (&cipher);
780     if (!err) {
781         gpgme_set_armor (ctx, 1);
782         err = gpgme_op_encrypt (ctx, rset, plain, cipher);
783     }
784
785     if (err) {
786         debug_print ("encryption failed: %s\n", gpgme_strerror (err));
787         gpgme_data_release (cipher);
788         cipher = NULL;
789     }
790     else {
791         debug_print ("** encryption succeeded\n");
792     }
793
794     gpgme_release (ctx);
795     return cipher;
796 }
797
798 /*
799  * Create and return a list of keys matching a key id
800  */
801
802 GSList *rfc2015_create_signers_list (const char *keyid)
803 {
804         GSList *key_list = NULL;
805         GpgmeCtx list_ctx = NULL;
806         GSList *p;
807         GpgmeError err;
808         GpgmeKey key;
809
810         err = gpgme_new (&list_ctx);
811         if (err)
812                 goto leave;
813         err = gpgme_op_keylist_start (list_ctx, keyid, 1);
814         if (err)
815                 goto leave;
816         while ( !(err = gpgme_op_keylist_next (list_ctx, &key)) ) {
817                 key_list = g_slist_append (key_list, key);
818         }
819         if (err != GPGME_EOF)
820                 goto leave;
821         err = 0;
822         if (key_list == NULL) {
823                 debug_print ("no keys found for keyid \"%s\"\n", keyid);
824         }
825
826 leave:
827         if (err) {
828                 debug_print ("rfc2015_create_signers_list failed: %s\n", gpgme_strerror (err));
829                 for (p = key_list; p != NULL; p = p->next)
830                         gpgme_key_unref ((GpgmeKey) p->data);
831                 g_slist_free (key_list);
832         }
833         if (list_ctx)
834                 gpgme_release (list_ctx);
835         return err ? NULL : key_list;
836 }
837
838 /*
839  * Encrypt the file by extracting all recipients and finding the
840  * encryption keys for all of them.  The file content is then replaced
841  * by the encrypted one.  */
842 int
843 rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
844 {
845     FILE *fp = NULL;
846     char buf[BUFFSIZE];
847     int i, clineidx, saved_last;
848     char *clines[3] = {NULL};
849     GpgmeError err;
850     GpgmeData header = NULL;
851     GpgmeData plain = NULL;
852     GpgmeData cipher = NULL;
853     GpgmeRecipients rset = NULL;
854     size_t nread;
855     int mime_version_seen = 0;
856     char *boundary;
857
858     boundary = generate_mime_boundary ("Encrypt");
859
860     /* Create the list of recipients */
861     rset = gpgmegtk_recipient_selection (recp_list);
862     if (!rset) {
863         debug_print ("error creating recipient list\n" );
864         goto failure;
865     }
866
867     /* Open the source file */
868     if ((fp = fopen(file, "rb")) == NULL) {
869         FILE_OP_ERROR(file, "fopen");
870         goto failure;
871     }
872
873     err = gpgme_data_new (&header);
874     if (!err)
875         err = gpgme_data_new (&plain);
876     if (err) {
877         debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
878         goto failure;
879     }
880
881     /* get the content header lines from the source */
882     clineidx = 0;
883     saved_last = 0;
884     while (!err && fgets(buf, sizeof(buf), fp)) {
885         /* fixme: check for overlong lines */
886         if (headerp (buf, content_names)) {
887             if (clineidx >= DIM (clines)) {
888                 debug_print ("rfc2015_encrypt: too many content lines\n");
889                 goto failure;
890             }
891             clines[clineidx++] = g_strdup (buf);
892             saved_last = 1;
893             continue;
894         }
895         if (saved_last) {
896             if (*buf == ' ' || *buf == '\t') {
897                 char *last = clines[clineidx - 1];
898                 clines[clineidx - 1] = g_strconcat (last, buf, NULL);
899                 g_free (last);
900                 continue;
901             }
902             saved_last = 0;
903         }
904
905         if (headerp (buf, mime_version_name)) 
906             mime_version_seen = 1;
907
908         if (buf[0] == '\r' || buf[0] == '\n')
909             break;
910         err = gpgme_data_write (header, buf, strlen (buf));
911     }
912     if (ferror (fp)) {
913         FILE_OP_ERROR (file, "fgets");
914         goto failure;
915     }
916
917     /* write them to the temp data and add the rest of the message */
918     for (i = 0; !err && i < clineidx; i++) {
919         debug_print ("%% %s:%d: cline=`%s'", __FILE__ ,__LINE__, clines[i]);
920         err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
921     }
922     if (!err)
923         err = gpgme_data_write (plain, "\r\n", 2);
924     while (!err && fgets(buf, sizeof(buf), fp)) {
925         err = gpgme_data_write (plain, buf, strlen (buf));
926     }
927     if (ferror (fp)) {
928         FILE_OP_ERROR (file, "fgets");
929         goto failure;
930     }
931     if (err) {
932         debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
933         goto failure;
934     }
935
936     cipher = pgp_encrypt (plain, rset);
937     gpgme_data_release (plain); plain = NULL;
938     gpgme_recipients_release (rset); rset = NULL;
939     if (!cipher)
940         goto failure;
941
942     /* we have the encrypted message available in cipher and now we
943      * are going to rewrite the source file. To be sure that file has
944      * been truncated we use an approach which should work everywhere:
945      * close the file and then reopen it for writing. It is important
946      * that this works, otherwise it may happen that parts of the
947      * plaintext are still in the file (The encrypted stuff is, due to
948      * compression, usually shorter than the plaintext). 
949      * 
950      * Yes, there is a race condition here, but everyone, who is so
951      * stupid to store the temp file with the plaintext in a public
952      * directory has to live with this anyway. */
953     if (fclose (fp)) {
954         FILE_OP_ERROR(file, "fclose");
955         goto failure;
956     }
957     if ((fp = fopen(file, "wb")) == NULL) {
958         FILE_OP_ERROR(file, "fopen");
959         goto failure;
960     }
961
962     /* Write the header, append new content lines, part 1 and part 2 header */
963     err = gpgme_data_rewind (header);
964     if (err) {
965         debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
966         goto failure;
967     }
968     while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
969         fwrite (buf, nread, 1, fp);
970     }
971     if (err != GPGME_EOF) {
972         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
973         goto failure;
974     }
975     if (ferror (fp)) {
976         FILE_OP_ERROR (file, "fwrite");
977         goto failure;
978     }
979     gpgme_data_release (header); header = NULL;
980     
981     if (!mime_version_seen) 
982         fputs ("MIME-Version: 1\r\n", fp);
983
984     if (ascii_armored) {
985         fprintf(fp, 
986             "Content-Type: text/plain; charset=US-ASCII\r\n"
987             "Content-Transfer-Encoding: 7bit\r\n"  
988             "\r\n");
989     } else {
990         fprintf (fp,
991                 "Content-Type: multipart/encrypted;"
992                 " protocol=\"application/pgp-encrypted\";\r\n"
993                 " boundary=\"%s\"\r\n"
994                 "\r\n"
995                 "--%s\r\n"
996                 "Content-Type: application/pgp-encrypted\r\n"
997                 "\r\n"
998                 "Version: 1\r\n"
999                 "\r\n"
1000                 "--%s\r\n"
1001                 "Content-Type: application/octet-stream\r\n"
1002                 "\r\n",
1003                 boundary, boundary, boundary);
1004     }
1005
1006     /* append the encrypted stuff */
1007     err = gpgme_data_rewind (cipher);
1008     if (err) {
1009         debug_print ("** gpgme_data_rewind on cipher failed: %s\n",
1010                    gpgme_strerror (err));
1011         goto failure;
1012     }
1013
1014     while (!(err = gpgme_data_read (cipher, buf, BUFFSIZE, &nread))) {
1015         fwrite (buf, nread, 1, fp);
1016     }
1017     if (err != GPGME_EOF) {
1018         debug_print ("** gpgme_data_read failed: %s\n", gpgme_strerror (err));
1019         goto failure;
1020     }
1021
1022     /* and the final boundary */
1023     if (!ascii_armored) {
1024         fprintf (fp,
1025                  "\r\n"
1026                  "--%s--\r\n",
1027                  boundary);
1028     }
1029     fflush (fp);
1030     if (ferror (fp)) {
1031         FILE_OP_ERROR (file, "fwrite");
1032         goto failure;
1033     }
1034     fclose (fp);
1035     gpgme_data_release (cipher);
1036     return 0;
1037
1038 failure:
1039     if (fp) 
1040         fclose (fp);
1041     gpgme_data_release (header);
1042     gpgme_data_release (plain);
1043     gpgme_data_release (cipher);
1044     gpgme_recipients_release (rset);
1045     g_free (boundary);
1046     return -1; /* error */
1047 }
1048
1049 /* 
1050  * plain contains an entire mime object.  Sign it and return an
1051  * GpgmeData object with the signature of it or NULL in case of error.
1052  * r_siginfo returns an XML object with information about the signature.
1053  */
1054 static GpgmeData
1055 pgp_sign (GpgmeData plain, GSList *key_list, gboolean clearsign,
1056           char **r_siginfo)
1057 {
1058     GSList *p;
1059     GpgmeCtx ctx = NULL;
1060     GpgmeError err;
1061     GpgmeData sig = NULL;
1062     struct passphrase_cb_info_s info;
1063
1064     *r_siginfo = NULL;
1065     memset (&info, 0, sizeof info);
1066
1067     err = gpgme_new (&ctx);
1068     if (err)
1069         goto leave;
1070     err = gpgme_data_new (&sig);
1071     if (err)
1072         goto leave;
1073
1074     if (!getenv("GPG_AGENT_INFO")) {
1075         info.c = ctx;
1076         gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
1077     }
1078     gpgme_set_textmode (ctx, 1);
1079     gpgme_set_armor (ctx, 1);
1080     gpgme_signers_clear (ctx);
1081     for (p = key_list; p != NULL; p = p->next) {
1082         err = gpgme_signers_add (ctx, (GpgmeKey) p->data);
1083         if (err)
1084             goto leave;
1085     }
1086     for (p = key_list; p != NULL; p = p->next)
1087         gpgme_key_unref ((GpgmeKey) p->data);
1088     g_slist_free (key_list);
1089
1090     if (err)
1091         goto leave;
1092     err = gpgme_op_sign
1093         (ctx, plain, sig,
1094          clearsign ? GPGME_SIG_MODE_CLEAR : GPGME_SIG_MODE_DETACH);
1095     if (!err)
1096         *r_siginfo = gpgme_get_op_info (ctx, 0);
1097
1098 leave:
1099     if (err) {
1100         gpgmegtk_free_passphrase();
1101         debug_print ("signing failed: %s\n", gpgme_strerror (err));
1102         gpgme_data_release (sig);
1103         sig = NULL;
1104     }
1105     else {
1106         debug_print ("signing succeeded\n");
1107     }
1108
1109     gpgme_release (ctx);
1110     return sig;
1111 }
1112
1113 /*
1114  * Find TAG in XML and return a pointer into xml set just behind the
1115  * closing angle.  Return NULL if not found. 
1116  */
1117 static const char *
1118 find_xml_tag (const char *xml, const char *tag)
1119 {
1120     int taglen = strlen (tag);
1121     const char *s = xml;
1122  
1123     while ( (s = strchr (s, '<')) ) {
1124         s++;
1125         if (!strncmp (s, tag, taglen)) {
1126             const char *s2 = s + taglen;
1127             if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
1128                 /* found */
1129                 while (*s2 && *s2 != '>') /* skip attributes */
1130                     s2++;
1131                 /* fixme: do need to handle angles inside attribute vallues? */
1132                 return *s2? (s2+1):NULL;
1133             }
1134         }
1135         while (*s && *s != '>') /* skip to end of tag */
1136             s++;
1137     }
1138     return NULL;
1139 }
1140
1141
1142 /*
1143  * Extract the micalg from an GnupgOperationInfo XML container.
1144  */
1145 static char *
1146 extract_micalg (char *xml)
1147 {
1148     const char *s;
1149
1150     s = find_xml_tag (xml, "GnupgOperationInfo");
1151     if (s) {
1152         const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
1153         s = find_xml_tag (s, "signature");
1154         if (s && s_end && s < s_end) {
1155             const char *s_end2 = find_xml_tag (s, "/signature");
1156             if (s_end2 && s_end2 < s_end) {
1157                 s = find_xml_tag (s, "micalg");
1158                 if (s && s < s_end2) {
1159                     s_end = strchr (s, '<');
1160                     if (s_end) {
1161                         char *p = g_malloc (s_end - s + 1);
1162                         memcpy (p, s, s_end - s);
1163                         p[s_end-s] = 0;
1164                         return p;
1165                     }
1166                 }
1167             }
1168         }
1169     }
1170     return NULL;
1171 }
1172
1173
1174 /*
1175  * Sign the file and replace its content with the signed one.
1176  */
1177 int
1178 rfc2015_sign (const char *file, GSList *key_list)
1179 {
1180     FILE *fp = NULL;
1181     char buf[BUFFSIZE];
1182     int i, clineidx, saved_last;
1183     char *clines[3] = {NULL};
1184     GpgmeError err;
1185     GpgmeData header = NULL;
1186     GpgmeData plain = NULL;
1187     GpgmeData sigdata = NULL;
1188     size_t nread;
1189     int mime_version_seen = 0;
1190     char *boundary;
1191     char *micalg = NULL;
1192     char *siginfo;
1193
1194     boundary = generate_mime_boundary ("Signature");
1195
1196     /* Open the source file */
1197     if ((fp = fopen(file, "rb")) == NULL) {
1198         FILE_OP_ERROR(file, "fopen");
1199         goto failure;
1200     }
1201
1202     err = gpgme_data_new (&header);
1203     if (!err)
1204         err = gpgme_data_new (&plain);
1205     if (err) {
1206         debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
1207         goto failure;
1208     }
1209
1210     /* get the content header lines from the source */
1211     clineidx = 0;
1212     saved_last = 0;
1213     while (!err && fgets(buf, sizeof(buf), fp)) {
1214         /* fixme: check for overlong lines */
1215         if (headerp (buf, content_names)) {
1216             if (clineidx >= DIM (clines)) {
1217                 debug_print ("rfc2015_sign: too many content lines\n");
1218                 goto failure;
1219             }
1220             clines[clineidx++] = g_strdup (buf);
1221             saved_last = 1;
1222             continue;
1223         }
1224         if (saved_last) {
1225             if (*buf == ' ' || *buf == '\t') {
1226                 char *last = clines[clineidx - 1];
1227                 clines[clineidx - 1] = g_strconcat (last, buf, NULL);
1228                 g_free (last);
1229                 continue;
1230             }
1231             saved_last = 0;
1232         }
1233
1234         if (headerp (buf, mime_version_name)) 
1235             mime_version_seen = 1;
1236
1237         if (buf[0] == '\r' || buf[0] == '\n')
1238             break;
1239         err = gpgme_data_write (header, buf, strlen (buf));
1240     }
1241     if (ferror (fp)) {
1242         FILE_OP_ERROR (file, "fgets");
1243         goto failure;
1244     }
1245
1246     /* write them to the temp data and add the rest of the message */
1247     for (i = 0; !err && i < clineidx; i++) {
1248         err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
1249     }
1250     if (!err)
1251         err = gpgme_data_write (plain, "\r\n", 2 );
1252     while (!err && fgets(buf, sizeof(buf), fp)) {
1253         err = gpgme_data_write (plain, buf, strlen (buf));
1254     }
1255     if (ferror (fp)) {
1256         FILE_OP_ERROR (file, "fgets");
1257         goto failure;
1258     }
1259     if (err) {
1260         debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
1261         goto failure;
1262     }
1263
1264     sigdata = pgp_sign (plain, key_list, FALSE, &siginfo); 
1265     if (siginfo) {
1266         micalg = extract_micalg (siginfo);
1267         free (siginfo);
1268     }
1269     if (!sigdata) 
1270         goto failure;
1271
1272     /* we have the signed message available in sigdata and now we are
1273      * going to rewrite the original file. To be sure that file has
1274      * been truncated we use an approach which should work everywhere:
1275      * close the file and then reopen it for writing. */
1276     if (fclose (fp)) {
1277         FILE_OP_ERROR(file, "fclose");
1278         goto failure;
1279     }
1280     if ((fp = fopen(file, "wb")) == NULL) {
1281         FILE_OP_ERROR(file, "fopen");
1282         goto failure;
1283     }
1284
1285     /* Write the rfc822 header and add new content lines */
1286     err = gpgme_data_rewind (header);
1287     if (err)
1288         debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
1289     while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
1290         fwrite (buf, nread, 1, fp);
1291     }
1292     if (err != GPGME_EOF) {
1293         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1294         goto failure;
1295     }
1296     if (ferror (fp)) {
1297         FILE_OP_ERROR (file, "fwrite");
1298         goto failure;
1299     }
1300     gpgme_data_release (header);
1301     header = NULL;
1302
1303     if (!mime_version_seen) 
1304         fputs ("MIME-Version: 1.0\r\n", fp);
1305     fprintf (fp, "Content-Type: multipart/signed; "
1306              "protocol=\"application/pgp-signature\";\r\n");
1307     if (micalg)
1308         fprintf (fp, " micalg=\"%s\";\r\n", micalg);
1309     fprintf (fp, " boundary=\"%s\"\r\n", boundary);
1310
1311     /* Part 1: signed material */
1312     fprintf (fp, "\r\n"
1313                  "--%s\r\n",
1314                  boundary);
1315     err = gpgme_data_rewind (plain);
1316     if (err) {
1317         debug_print ("gpgme_data_rewind on plain failed: %s\n",
1318                    gpgme_strerror (err));
1319         goto failure;
1320     }
1321     while (!(err = gpgme_data_read (plain, buf, BUFFSIZE, &nread))) {
1322         fwrite (buf, nread, 1, fp);   
1323     }
1324     if (err != GPGME_EOF) {
1325         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1326         goto failure;
1327     }
1328
1329     /* Part 2: signature */
1330     fprintf (fp, "\r\n"
1331                  "--%s\r\n",
1332                  boundary);
1333     fputs ("Content-Type: application/pgp-signature\r\n"
1334            "\r\n", fp);
1335
1336     err = gpgme_data_rewind (sigdata);
1337     if (err) {
1338         debug_print ("gpgme_data_rewind on sigdata failed: %s\n",
1339                    gpgme_strerror (err));
1340         goto failure;
1341     }
1342
1343     while (!(err = gpgme_data_read (sigdata, buf, BUFFSIZE, &nread))) {
1344         fwrite (buf, nread, 1, fp);
1345     }
1346     if (err != GPGME_EOF) {
1347         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1348         goto failure;
1349     }
1350
1351     /* Final boundary */
1352     fprintf (fp, "\r\n"
1353                  "--%s--\r\n",
1354                  boundary);
1355     fflush (fp);
1356     if (ferror (fp)) {
1357         FILE_OP_ERROR (file, "fwrite");
1358         goto failure;
1359     }
1360     fclose (fp);
1361     gpgme_data_release (header);
1362     gpgme_data_release (plain);
1363     gpgme_data_release (sigdata);
1364     g_free (boundary);
1365     g_free (micalg);
1366     return 0;
1367
1368 failure:
1369     if (fp) 
1370         fclose (fp);
1371     gpgme_data_release (header);
1372     gpgme_data_release (plain);
1373     gpgme_data_release (sigdata);
1374     g_free (boundary);
1375     g_free (micalg);
1376     return -1; /* error */
1377 }
1378
1379
1380 /*
1381  * Sign the file with clear text and replace its content with the signed one.
1382  */
1383 gint
1384 rfc2015_clearsign (const gchar *file, GSList *key_list)
1385 {
1386     FILE *fp;
1387     gchar buf[BUFFSIZE];
1388     GpgmeError err;
1389     GpgmeData text = NULL;
1390     GpgmeData sigdata = NULL;
1391     size_t nread;
1392     gchar *siginfo;
1393
1394     if ((fp = fopen(file, "rb")) == NULL) {
1395         FILE_OP_ERROR(file, "fopen");
1396         goto failure;
1397     }
1398
1399     err = gpgme_data_new(&text);
1400     if (err) {
1401         debug_print("gpgme_data_new failed: %s\n", gpgme_strerror(err));
1402         goto failure;
1403     }
1404
1405     while (!err && fgets(buf, sizeof(buf), fp)) {
1406         err = gpgme_data_write(text, buf, strlen(buf));
1407     }
1408     if (ferror(fp)) {
1409         FILE_OP_ERROR(file, "fgets");
1410         goto failure;
1411     }
1412     if (err) {
1413         debug_print("gpgme_data_write failed: %s\n", gpgme_strerror(err));
1414         goto failure;
1415     }
1416
1417     sigdata = pgp_sign(text, key_list, TRUE, &siginfo);
1418     if (siginfo) {
1419         g_free(siginfo);
1420     }
1421     if (!sigdata)
1422         goto failure;
1423
1424     if (fclose(fp) == EOF) {
1425         FILE_OP_ERROR(file, "fclose");
1426         fp = NULL;
1427         goto failure;
1428     }
1429     if ((fp = fopen(file, "wb")) == NULL) {
1430         FILE_OP_ERROR(file, "fopen");
1431         goto failure;
1432     }
1433
1434     err = gpgme_data_rewind(sigdata);
1435     if (err) {
1436         debug_print("gpgme_data_rewind on sigdata failed: %s\n",
1437                     gpgme_strerror(err));
1438         goto failure;
1439     }
1440
1441     while (!(err = gpgme_data_read(sigdata, buf, sizeof(buf), &nread))) {
1442         fwrite(buf, nread, 1, fp);
1443     }
1444     if (err != GPGME_EOF) {
1445         debug_print("gpgme_data_read failed: %s\n", gpgme_strerror(err));
1446         goto failure;
1447     }
1448
1449     if (fclose(fp) == EOF) {
1450         FILE_OP_ERROR(file, "fclose");
1451         fp = NULL;
1452         goto failure;
1453     }
1454     gpgme_data_release(text);
1455     gpgme_data_release(sigdata);
1456     return 0;
1457
1458 failure:
1459     if (fp)
1460         fclose(fp);
1461     gpgme_data_release(text);
1462     gpgme_data_release(sigdata);
1463     return -1;
1464 }
1465
1466 static gboolean rfc2015_is_signed(MimeInfo *mimeinfo)
1467 {
1468         MimeInfo *parent;
1469         MimeInfo *signature;
1470         gchar *protocol;
1471
1472         g_return_val_if_fail(mimeinfo != NULL, FALSE);
1473         
1474         /* check parent */
1475         parent = mimeinfo->parent;
1476         if (parent == NULL)
1477                 return FALSE;
1478         if ((parent->type != MIMETYPE_MULTIPART) ||
1479             g_strcasecmp(parent->subtype, "signed"))
1480                 return FALSE;
1481         protocol = g_hash_table_lookup(parent->parameters, "protocol");
1482         if ((protocol == NULL) || g_strcasecmp(protocol, "application/pgp-signature"))
1483                 return FALSE;
1484
1485         /* check if mimeinfo is the first child */
1486         if (parent->children != mimeinfo)
1487                 return FALSE;
1488
1489         /* check signature */
1490         signature = parent->children->next;
1491         if (signature == NULL)
1492                 return FALSE;
1493         if ((signature->type != MIMETYPE_APPLICATION) ||
1494             g_strcasecmp(signature->subtype, "pgp-signature"))
1495                 return FALSE;
1496
1497         return TRUE;
1498 }
1499
1500 static void idle_function_for_gpgme(void)
1501 {
1502         while (gtk_events_pending())
1503                 gtk_main_iteration();
1504 }
1505
1506 static PrivacySystem rfc2015_system = {
1507         "PGP/Mime",             /* name */
1508
1509         g_free,                 /* free_privacydata */
1510
1511         rfc2015_is_signed,      /* is_signed(MimeInfo *) */
1512         NULL,                   /* get_signer(MimeInfo *) */
1513         NULL,                   /* check_signature(MimeInfo *) */
1514
1515         /* NOT YET */
1516         NULL,                   /* is_encrypted(MimeInfo *) */
1517         NULL,                   /* decrypt(MimeInfo *) */
1518 };
1519
1520 void rfc2015_init()
1521 {
1522         if (gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP) != 
1523                         GPGME_No_Error) {  /* Also does some gpgme init */
1524                 rfc2015_disable_all();
1525                 debug_print("gpgme_engine_version:\n%s\n",
1526                             gpgme_get_engine_info());
1527
1528                 if (prefs_common.gpg_warning) {
1529                         AlertValue val;
1530
1531                         val = alertpanel_message_with_disable
1532                                 (_("Warning"),
1533                                  _("GnuPG is not installed properly, or needs to be upgraded.\n"
1534                                    "OpenPGP support disabled."));
1535                         if (val & G_ALERTDISABLE)
1536                                 prefs_common.gpg_warning = FALSE;
1537                 }
1538         } else
1539                 privacy_register_system(&rfc2015_system);
1540
1541         gpgme_register_idle(idle_function_for_gpgme);
1542 }
1543
1544 void rfc2015_done()
1545 {
1546         privacy_unregister_system(&rfc2015_system);
1547         gpgmegtk_free_passphrase();
1548 }
1549
1550 #endif /* USE_GPGME */