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