* src/prefs_folder_item.c
[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     partinfo->sig_ok = (status == GPGME_SIG_STAT_GOOD);
415
416     gpgme_data_release (sig);
417     gpgme_data_release (text);
418     gpgme_release (ctx);
419     if (prefs_common.gpg_signature_popup)
420         gpgmegtk_sig_status_destroy (statuswindow);
421 }
422
423 /*
424  * Copy a gpgme data object to a temporary file and
425  * return this filename 
426  */
427 #if 0
428 static char *
429 copy_gpgmedata_to_temp (GpgmeData data, guint *length)
430 {
431     static int id;
432     char *tmp;
433     FILE *fp;
434     char buf[100];
435     size_t nread;
436     GpgmeError err;
437     
438     tmp = g_strdup_printf("%s%cgpgtmp.%08x",
439                           get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id );
440
441     if ((fp = fopen(tmp, "wb")) == NULL) {
442         FILE_OP_ERROR(tmp, "fopen");
443         g_free(tmp);
444         return NULL;
445     }
446
447     err = gpgme_data_rewind ( data );
448     if (err)
449         debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
450
451     while (!(err = gpgme_data_read (data, buf, 100, &nread))) {
452         fwrite ( buf, nread, 1, fp );
453     }
454
455     if (err != GPGME_EOF)
456         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
457
458     fclose (fp);
459     *length = nread;
460
461     return tmp;
462 }
463 #endif
464
465 static GpgmeData
466 pgp_decrypt (MimeInfo *partinfo, FILE *fp)
467 {
468     GpgmeCtx ctx = NULL;
469     GpgmeError err;
470     GpgmeData cipher = NULL, plain = NULL;
471     struct passphrase_cb_info_s info;
472
473     memset (&info, 0, sizeof info);
474
475     err = gpgme_new (&ctx);
476     if (err) {
477         debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
478         goto leave;
479     }
480
481     err = gpgme_data_new_from_filepart (&cipher, NULL, fp,
482                                         partinfo->fpos, partinfo->size);
483     if (err) {
484         debug_print ("gpgme_data_new_from_filepart failed: %s\n",
485                      gpgme_strerror (err));
486         goto leave;
487     }
488
489     err = gpgme_data_new (&plain);
490     if (err) {
491         debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
492         goto leave;
493     }
494
495     if (!getenv("GPG_AGENT_INFO")) {
496         info.c = ctx;
497         gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
498     } 
499
500     err = gpgme_op_decrypt (ctx, cipher, plain);
501
502 leave:
503     gpgme_data_release (cipher);
504     if (err) {
505         gpgmegtk_free_passphrase();
506         debug_print ("decryption failed: %s\n", gpgme_strerror (err));
507         gpgme_data_release (plain);
508         plain = NULL;
509     }
510     else
511         debug_print ("** decryption succeeded\n");
512
513     gpgme_release (ctx);
514     return plain;
515 }
516
517 MimeInfo * rfc2015_find_signature (MimeInfo *mimeinfo)
518 {
519     MimeInfo *partinfo;
520     int n = 0;
521
522     if (!mimeinfo)
523         return NULL;
524     if (g_strcasecmp (mimeinfo->content_type, "multipart/signed"))
525         return NULL;
526
527     debug_print ("** multipart/signed encountered\n");
528
529     /* check that we have at least 2 parts of the correct type */
530     for (partinfo = mimeinfo->children;
531          partinfo != NULL; partinfo = partinfo->next) {
532         if (++n > 1  && !g_strcasecmp (partinfo->content_type,
533                                        "application/pgp-signature"))
534             break;
535     }
536
537     return partinfo;
538 }
539
540 gboolean rfc2015_has_signature (MimeInfo *mimeinfo)
541 {
542     return rfc2015_find_signature (mimeinfo) != NULL;
543 }
544
545 void rfc2015_check_signature (MimeInfo *mimeinfo, FILE *fp)
546 {
547     MimeInfo *partinfo;
548
549     partinfo = rfc2015_find_signature (mimeinfo);
550     if (!partinfo)
551         return;
552
553 #if 0
554     g_message ("** yep, it is a pgp signature");
555     dump_mimeinfo ("gpg-signature", partinfo );
556     dump_part (partinfo, fp );
557     dump_mimeinfo ("signed text", mimeinfo->children );
558     dump_part (mimeinfo->children, fp);
559 #endif
560
561     check_signature (mimeinfo, partinfo, fp);
562 }
563
564 int rfc2015_is_encrypted (MimeInfo *mimeinfo)
565 {
566     if (!mimeinfo || mimeinfo->mime_type != MIME_MULTIPART)
567         return 0;
568     if (g_strcasecmp (mimeinfo->content_type, "multipart/encrypted"))
569         return 0;
570     /* fixme: we should check the protocol parameter */
571     return 1;
572 }
573
574 gboolean rfc2015_msg_is_encrypted (const gchar *file)
575 {
576         FILE *fp;
577         MimeInfo *mimeinfo;
578         int ret;
579
580         if ((fp = fopen(file, "rb")) == NULL)
581                 return FALSE;
582
583         mimeinfo = procmime_scan_mime_header(fp);
584         if(!mimeinfo) {
585                 fclose(fp);
586                 return FALSE;
587         }
588
589         ret = rfc2015_is_encrypted(mimeinfo);
590         procmime_mimeinfo_free_all(mimeinfo);
591         return ret != 0 ? TRUE : FALSE;
592 }
593
594 static int
595 name_cmp(const char *a, const char *b)
596 {
597     for( ; *a && *b; a++, b++) {
598         if(*a != *b
599            && toupper(*(unsigned char *)a) != toupper(*(unsigned char *)b))
600             return 1;
601     }
602
603     return *a != *b;
604 }
605
606 static int
607 headerp(char *p, char **names)
608 {
609     int i, c;
610     char *p2;
611
612     p2 = strchr(p, ':');
613     if(!p2 || p == p2) {
614         return 0;
615     }
616     if(p2[-1] == ' ' || p2[-1] == '\t') {
617         return 0;
618     }
619
620     if(!names[0])
621         return 1;  
622
623     c = *p2;
624     *p2 = 0;
625     for(i = 0 ; names[i] != NULL; i++) {
626         if(!name_cmp (names[i], p))
627             break;
628     }
629     *p2 = c;
630
631     return names[i] != NULL;
632 }
633
634
635 #define DECRYPTION_ABORT() \
636 { \
637     procmime_mimeinfo_free_all(tmpinfo); \
638     msginfo->decryption_failed = 1; \
639     return; \
640 }
641
642 void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
643 {
644     static int id;
645     MimeInfo *tmpinfo, *partinfo;
646     int ver_ok = 0;
647     char *fname;
648     GpgmeData plain;
649     FILE *dstfp;
650     size_t nread;
651     char buf[BUFFSIZE];
652     GpgmeError err;
653
654     g_return_if_fail (msginfo != NULL);
655     g_return_if_fail (mimeinfo != NULL);
656     g_return_if_fail (fp != NULL);
657     g_return_if_fail (mimeinfo->mime_type == MIME_MULTIPART);
658
659     debug_print ("** decrypting multipart/encrypted message\n");
660
661     /* skip headers */
662     if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
663         perror("fseek");
664     tmpinfo = procmime_scan_mime_header(fp);
665     if (!tmpinfo || tmpinfo->mime_type != MIME_MULTIPART) {
666         DECRYPTION_ABORT();
667     }
668
669     procmime_scan_multipart_message(tmpinfo, fp);
670
671     /* check that we have the 2 parts */
672     partinfo = tmpinfo->children;
673     if (!partinfo || !partinfo->next) {
674         DECRYPTION_ABORT();
675     }
676     if (!g_strcasecmp (partinfo->content_type, "application/pgp-encrypted")) {
677         /* Fixme: check that the version is 1 */
678         ver_ok = 1;
679     }
680     partinfo = partinfo->next;
681     if (ver_ok &&
682         !g_strcasecmp (partinfo->content_type, "application/octet-stream")) {
683         if (partinfo->next)
684             g_warning ("oops: pgp_encrypted with more than 2 parts");
685     }
686     else {
687         DECRYPTION_ABORT();
688     }
689
690     debug_print ("** yep, it is pgp encrypted\n");
691
692     plain = pgp_decrypt (partinfo, fp);
693     if (!plain) {
694         DECRYPTION_ABORT();
695     }
696
697     fname = g_strdup_printf("%s%cplaintext.%08x",
698                             get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
699
700     if ((dstfp = fopen(fname, "wb")) == NULL) {
701         FILE_OP_ERROR(fname, "fopen");
702         g_free(fname);
703         DECRYPTION_ABORT();
704     }
705
706     /* write the orginal header to the new file */
707     if (fseek(fp, tmpinfo->fpos, SEEK_SET) < 0)
708         perror("fseek");
709
710     while (fgets(buf, sizeof(buf), fp)) {
711         if (headerp (buf, content_names))
712             continue;
713         if (buf[0] == '\r' || buf[0] == '\n')
714             break;
715         fputs (buf, dstfp);
716     }
717
718     err = gpgme_data_rewind (plain);
719     if (err)
720         debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
721
722     while (!(err = gpgme_data_read (plain, buf, sizeof(buf), &nread))) {
723         fwrite (buf, nread, 1, dstfp);
724     }
725
726     if (err != GPGME_EOF) {
727         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
728     }
729
730     fclose (dstfp);
731     procmime_mimeinfo_free_all(tmpinfo);
732
733     msginfo->plaintext_file = fname;
734     msginfo->decryption_failed = 0;
735 }
736
737 #undef DECRYPTION_ABORT
738
739
740 /*
741  * plain contains an entire mime object.
742  * Encrypt it and return an GpgmeData object with the encrypted version of
743  * the file or NULL in case of error.
744  */
745 static GpgmeData
746 pgp_encrypt ( GpgmeData plain, GpgmeRecipients rset )
747 {
748     GpgmeCtx ctx = NULL;
749     GpgmeError err;
750     GpgmeData cipher = NULL;
751
752     err = gpgme_new (&ctx);
753     if (!err)
754         err = gpgme_data_new (&cipher);
755     if (!err) {
756         gpgme_set_armor (ctx, 1);
757         err = gpgme_op_encrypt (ctx, rset, plain, cipher);
758     }
759
760     if (err) {
761         debug_print ("encryption failed: %s\n", gpgme_strerror (err));
762         gpgme_data_release (cipher);
763         cipher = NULL;
764     }
765     else {
766         debug_print ("** encryption succeeded\n");
767     }
768
769     gpgme_release (ctx);
770     return cipher;
771 }
772
773 /*
774  * Create and return a list of keys matching a key id
775  */
776
777 GSList *rfc2015_create_signers_list (const char *keyid)
778 {
779         GSList *key_list = NULL;
780         GpgmeCtx list_ctx = NULL;
781         GSList *p;
782         GpgmeError err;
783         GpgmeKey key;
784
785         err = gpgme_new (&list_ctx);
786         if (err)
787                 goto leave;
788         err = gpgme_op_keylist_start (list_ctx, keyid, 1);
789         if (err)
790                 goto leave;
791         while ( !(err = gpgme_op_keylist_next (list_ctx, &key)) ) {
792                 key_list = g_slist_append (key_list, key);
793         }
794         if (err != GPGME_EOF)
795                 goto leave;
796         err = 0;
797         if (key_list == NULL) {
798                 debug_print ("no keys found for keyid \"%s\"\n", keyid);
799         }
800
801 leave:
802         if (err) {
803                 debug_print ("rfc2015_create_signers_list failed: %s\n", gpgme_strerror (err));
804                 for (p = key_list; p != NULL; p = p->next)
805                         gpgme_key_unref ((GpgmeKey) p->data);
806                 g_slist_free (key_list);
807         }
808         if (list_ctx)
809                 gpgme_release (list_ctx);
810         return err ? NULL : key_list;
811 }
812
813 /*
814  * Encrypt the file by extracting all recipients and finding the
815  * encryption keys for all of them.  The file content is then replaced
816  * by the encrypted one.  */
817 int
818 rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
819 {
820     FILE *fp = NULL;
821     char buf[BUFFSIZE];
822     int i, clineidx, saved_last;
823     char *clines[3] = {NULL};
824     GpgmeError err;
825     GpgmeData header = NULL;
826     GpgmeData plain = NULL;
827     GpgmeData cipher = NULL;
828     GpgmeRecipients rset = NULL;
829     size_t nread;
830     int mime_version_seen = 0;
831     char *boundary = create_boundary ();
832
833     /* Create the list of recipients */
834     rset = gpgmegtk_recipient_selection (recp_list);
835     if (!rset) {
836         debug_print ("error creating recipient list\n" );
837         goto failure;
838     }
839
840     /* Open the source file */
841     if ((fp = fopen(file, "rb")) == NULL) {
842         FILE_OP_ERROR(file, "fopen");
843         goto failure;
844     }
845
846     err = gpgme_data_new (&header);
847     if (!err)
848         err = gpgme_data_new (&plain);
849     if (err) {
850         debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
851         goto failure;
852     }
853
854     /* get the content header lines from the source */
855     clineidx=0;
856     saved_last = 0;
857     while (!err && fgets(buf, sizeof(buf), fp)) {
858         /* fixme: check for overlong lines */
859         if (headerp (buf, content_names)) {
860             if (clineidx >= DIM (clines)) {
861                 debug_print ("rfc2015_encrypt: too many content lines\n");
862                 goto failure;
863             }
864             clines[clineidx++] = g_strdup (buf);
865             saved_last = 1;
866             continue;
867         }
868         if (saved_last) {
869             saved_last = 0;
870             if (*buf == ' ' || *buf == '\t') {
871                 char *last = clines[clineidx-1];
872                 clines[clineidx-1] = g_strconcat (last, buf, NULL);
873                 g_free (last);
874                 continue;
875             }
876         }
877
878         if (headerp (buf, mime_version_name)) 
879             mime_version_seen = 1;
880
881         if (buf[0] == '\r' || buf[0] == '\n')
882             break;
883         err = gpgme_data_write (header, buf, strlen (buf));
884     }
885     if (ferror (fp)) {
886         FILE_OP_ERROR (file, "fgets");
887         goto failure;
888     }
889
890     /* write them to the temp data and add the rest of the message */
891     for (i = 0; !err && i < clineidx; i++) {
892         debug_print ("%% %s:%d: cline=`%s'", __FILE__ ,__LINE__, clines[i]);
893         err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
894     }
895     if (!err)
896         err = gpgme_data_write (plain, "\r\n", 2);
897     while (!err && fgets(buf, sizeof(buf), fp)) {
898         err = gpgme_data_write (plain, buf, strlen (buf));
899     }
900     if (ferror (fp)) {
901         FILE_OP_ERROR (file, "fgets");
902         goto failure;
903     }
904     if (err) {
905         debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
906         goto failure;
907     }
908
909     cipher = pgp_encrypt (plain, rset);
910     gpgme_data_release (plain); plain = NULL;
911     gpgme_recipients_release (rset); rset = NULL;
912     if (!cipher)
913         goto failure;
914
915     /* we have the encrypted message available in cipher and now we
916      * are going to rewrite the source file. To be sure that file has
917      * been truncated we use an approach which should work everywhere:
918      * close the file and then reopen it for writing. It is important
919      * that this works, otherwise it may happen that parts of the
920      * plaintext are still in the file (The encrypted stuff is, due to
921      * compression, usually shorter than the plaintext). 
922      * 
923      * Yes, there is a race condition here, but everyone, who is so
924      * stupid to store the temp file with the plaintext in a public
925      * directory has to live with this anyway. */
926     if (fclose (fp)) {
927         FILE_OP_ERROR(file, "fclose");
928         goto failure;
929     }
930     if ((fp = fopen(file, "wb")) == NULL) {
931         FILE_OP_ERROR(file, "fopen");
932         goto failure;
933     }
934
935     /* Write the header, append new content lines, part 1 and part 2 header */
936     err = gpgme_data_rewind (header);
937     if (err) {
938         debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
939         goto failure;
940     }
941     while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
942         fwrite (buf, nread, 1, fp);
943     }
944     if (err != GPGME_EOF) {
945         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
946         goto failure;
947     }
948     if (ferror (fp)) {
949         FILE_OP_ERROR (file, "fwrite");
950         goto failure;
951     }
952     gpgme_data_release (header); header = NULL;
953     
954     if (!mime_version_seen) 
955         fputs ("MIME-Version: 1\r\n", fp);
956
957     if (ascii_armored) {
958         fprintf(fp, 
959             "Content-Type: text/plain; charset=US-ASCII\r\n"
960             "Content-Transfer-Encoding: 7bit\r\n"  
961             "\r\n");
962     } else {
963         fprintf (fp,
964                 "Content-Type: multipart/encrypted;"
965                 " protocol=\"application/pgp-encrypted\";\r\n"
966                 " boundary=\"%s\"\r\n"
967                 "\r\n"
968                 "--%s\r\n"
969                 "Content-Type: application/pgp-encrypted\r\n"
970                 "\r\n"
971                 "Version: 1\r\n"
972                 "\r\n"
973                 "--%s\r\n"
974                 "Content-Type: application/octet-stream\r\n"
975                 "\r\n",
976                 boundary, boundary, boundary);
977     }
978
979     /* append the encrypted stuff */
980     err = gpgme_data_rewind (cipher);
981     if (err) {
982         debug_print ("** gpgme_data_rewind on cipher failed: %s\n",
983                    gpgme_strerror (err));
984         goto failure;
985     }
986
987     while (!(err = gpgme_data_read (cipher, buf, BUFFSIZE, &nread))) {
988         fwrite (buf, nread, 1, fp);
989     }
990     if (err != GPGME_EOF) {
991         debug_print ("** gpgme_data_read failed: %s\n", gpgme_strerror (err));
992         goto failure;
993     }
994
995     /* and the final boundary */
996     if (!ascii_armored) {
997         fprintf (fp,
998                  "\r\n"
999                  "--%s--\r\n",
1000                  boundary);
1001     }
1002     fflush (fp);
1003     if (ferror (fp)) {
1004         FILE_OP_ERROR (file, "fwrite");
1005         goto failure;
1006     }
1007     fclose (fp);
1008     gpgme_data_release (cipher);
1009     return 0;
1010
1011 failure:
1012     if (fp) 
1013         fclose (fp);
1014     gpgme_data_release (header);
1015     gpgme_data_release (plain);
1016     gpgme_data_release (cipher);
1017     gpgme_recipients_release (rset);
1018     g_free (boundary);
1019     return -1; /* error */
1020 }
1021
1022 /* 
1023  * plain contains an entire mime object.  Sign it and return an
1024  * GpgmeData object with the signature of it or NULL in case of error.
1025  * r_siginfo returns an XML object with information about the signature.
1026  */
1027 static GpgmeData
1028 pgp_sign (GpgmeData plain, GSList *key_list, gboolean clearsign,
1029           char **r_siginfo)
1030 {
1031     GSList *p;
1032     GpgmeCtx ctx = NULL;
1033     GpgmeError err;
1034     GpgmeData sig = NULL;
1035     struct passphrase_cb_info_s info;
1036
1037     *r_siginfo = NULL;
1038     memset (&info, 0, sizeof info);
1039
1040     err = gpgme_new (&ctx);
1041     if (err)
1042         goto leave;
1043     err = gpgme_data_new (&sig);
1044     if (err)
1045         goto leave;
1046
1047     if (!getenv("GPG_AGENT_INFO")) {
1048         info.c = ctx;
1049         gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
1050     }
1051     gpgme_set_textmode (ctx, 1);
1052     gpgme_set_armor (ctx, 1);
1053     gpgme_signers_clear (ctx);
1054     for (p = key_list; p != NULL; p = p->next) {
1055         err = gpgme_signers_add (ctx, (GpgmeKey) p->data);
1056         if (err)
1057             goto leave;
1058     }
1059     for (p = key_list; p != NULL; p = p->next)
1060         gpgme_key_unref ((GpgmeKey) p->data);
1061     g_slist_free (key_list);
1062
1063     if (err)
1064         goto leave;
1065     err = gpgme_op_sign
1066         (ctx, plain, sig,
1067          clearsign ? GPGME_SIG_MODE_CLEAR : GPGME_SIG_MODE_DETACH);
1068     if (!err)
1069         *r_siginfo = gpgme_get_op_info (ctx, 0);
1070
1071 leave:
1072     if (err) {
1073         gpgmegtk_free_passphrase();
1074         debug_print ("signing failed: %s\n", gpgme_strerror (err));
1075         gpgme_data_release (sig);
1076         sig = NULL;
1077     }
1078     else {
1079         debug_print ("signing succeeded\n");
1080     }
1081
1082     gpgme_release (ctx);
1083     return sig;
1084 }
1085
1086 /*
1087  * Find TAG in XML and return a pointer into xml set just behind the
1088  * closing angle.  Return NULL if not found. 
1089  */
1090 static const char *
1091 find_xml_tag (const char *xml, const char *tag)
1092 {
1093     int taglen = strlen (tag);
1094     const char *s = xml;
1095  
1096     while ( (s = strchr (s, '<')) ) {
1097         s++;
1098         if (!strncmp (s, tag, taglen)) {
1099             const char *s2 = s + taglen;
1100             if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
1101                 /* found */
1102                 while (*s2 && *s2 != '>') /* skip attributes */
1103                     s2++;
1104                 /* fixme: do need to handle angles inside attribute vallues? */
1105                 return *s2? (s2+1):NULL;
1106             }
1107         }
1108         while (*s && *s != '>') /* skip to end of tag */
1109             s++;
1110     }
1111     return NULL;
1112 }
1113
1114
1115 /*
1116  * Extract the micalg from an GnupgOperationInfo XML container.
1117  */
1118 static char *
1119 extract_micalg (char *xml)
1120 {
1121     const char *s;
1122
1123     s = find_xml_tag (xml, "GnupgOperationInfo");
1124     if (s) {
1125         const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
1126         s = find_xml_tag (s, "signature");
1127         if (s && s_end && s < s_end) {
1128             const char *s_end2 = find_xml_tag (s, "/signature");
1129             if (s_end2 && s_end2 < s_end) {
1130                 s = find_xml_tag (s, "micalg");
1131                 if (s && s < s_end2) {
1132                     s_end = strchr (s, '<');
1133                     if (s_end) {
1134                         char *p = g_malloc (s_end - s + 1);
1135                         memcpy (p, s, s_end - s);
1136                         p[s_end-s] = 0;
1137                         return p;
1138                     }
1139                 }
1140             }
1141         }
1142     }
1143     return NULL;
1144 }
1145
1146
1147 /*
1148  * Sign the file and replace its content with the signed one.
1149  */
1150 int
1151 rfc2015_sign (const char *file, GSList *key_list)
1152 {
1153     FILE *fp = NULL;
1154     char buf[BUFFSIZE];
1155     int i, clineidx, saved_last;
1156     char *clines[3] = {NULL};
1157     GpgmeError err;
1158     GpgmeData header = NULL;
1159     GpgmeData plain = NULL;
1160     GpgmeData sigdata = NULL;
1161     size_t nread;
1162     int mime_version_seen = 0;
1163     char *boundary = create_boundary ();
1164     char *micalg = NULL;
1165     char *siginfo;
1166
1167     /* Open the source file */
1168     if ((fp = fopen(file, "rb")) == NULL) {
1169         FILE_OP_ERROR(file, "fopen");
1170         goto failure;
1171     }
1172
1173     err = gpgme_data_new (&header);
1174     if (!err)
1175         err = gpgme_data_new (&plain);
1176     if (err) {
1177         debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
1178         goto failure;
1179     }
1180
1181     /* get the content header lines from the source */
1182     clineidx = 0;
1183     saved_last = 0;
1184     while (!err && fgets(buf, sizeof(buf), fp)) {
1185         /* fixme: check for overlong lines */
1186         if (headerp (buf, content_names)) {
1187             if (clineidx >= DIM (clines)) {
1188                 debug_print ("rfc2015_sign: too many content lines\n");
1189                 goto failure;
1190             }
1191             clines[clineidx++] = g_strdup (buf);
1192             saved_last = 1;
1193             continue;
1194         }
1195         if (saved_last) {
1196             saved_last = 0;
1197             if (*buf == ' ' || *buf == '\t') {
1198                 char *last = clines[clineidx - 1];
1199                 clines[clineidx - 1] = g_strconcat (last, buf, NULL);
1200                 g_free (last);
1201                 continue;
1202             }
1203         }
1204
1205         if (headerp (buf, mime_version_name)) 
1206             mime_version_seen = 1;
1207
1208         if (buf[0] == '\r' || buf[0] == '\n')
1209             break;
1210         err = gpgme_data_write (header, buf, strlen (buf));
1211     }
1212     if (ferror (fp)) {
1213         FILE_OP_ERROR (file, "fgets");
1214         goto failure;
1215     }
1216
1217     /* write them to the temp data and add the rest of the message */
1218     for (i = 0; !err && i < clineidx; i++) {
1219         err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
1220     }
1221     if (!err)
1222         err = gpgme_data_write (plain, "\r\n", 2 );
1223     while (!err && fgets(buf, sizeof(buf), fp)) {
1224         err = gpgme_data_write (plain, buf, strlen (buf));
1225     }
1226     if (ferror (fp)) {
1227         FILE_OP_ERROR (file, "fgets");
1228         goto failure;
1229     }
1230     if (err) {
1231         debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
1232         goto failure;
1233     }
1234
1235     sigdata = pgp_sign (plain, key_list, FALSE, &siginfo); 
1236     if (siginfo) {
1237         micalg = extract_micalg (siginfo);
1238         free (siginfo);
1239     }
1240     if (!sigdata) 
1241         goto failure;
1242
1243     /* we have the signed message available in sigdata and now we are
1244      * going to rewrite the original file. To be sure that file has
1245      * been truncated we use an approach which should work everywhere:
1246      * close the file and then reopen it for writing. */
1247     if (fclose (fp)) {
1248         FILE_OP_ERROR(file, "fclose");
1249         goto failure;
1250     }
1251     if ((fp = fopen(file, "wb")) == NULL) {
1252         FILE_OP_ERROR(file, "fopen");
1253         goto failure;
1254     }
1255
1256     /* Write the rfc822 header and add new content lines */
1257     err = gpgme_data_rewind (header);
1258     if (err)
1259         debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
1260     while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
1261         fwrite (buf, nread, 1, fp);
1262     }
1263     if (err != GPGME_EOF) {
1264         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1265         goto failure;
1266     }
1267     if (ferror (fp)) {
1268         FILE_OP_ERROR (file, "fwrite");
1269         goto failure;
1270     }
1271     gpgme_data_release (header);
1272     header = NULL;
1273
1274     if (!mime_version_seen) 
1275         fputs ("MIME-Version: 1.0\r\n", fp);
1276     fprintf (fp, "Content-Type: multipart/signed; "
1277              "protocol=\"application/pgp-signature\";\r\n");
1278     if (micalg)
1279         fprintf (fp, " micalg=\"%s\";", micalg);
1280     fprintf (fp, " boundary=\"%s\"\r\n", boundary);
1281
1282     /* Part 1: signed material */
1283     fprintf (fp, "\r\n"
1284                  "--%s\r\n",
1285                  boundary);
1286     err = gpgme_data_rewind (plain);
1287     if (err) {
1288         debug_print ("gpgme_data_rewind on plain failed: %s\n",
1289                    gpgme_strerror (err));
1290         goto failure;
1291     }
1292     while (!(err = gpgme_data_read (plain, buf, BUFFSIZE, &nread))) {
1293         fwrite (buf, nread, 1, fp);   
1294     }
1295     if (err != GPGME_EOF) {
1296         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1297         goto failure;
1298     }
1299
1300     /* Part 2: signature */
1301     fprintf (fp, "\r\n"
1302                  "--%s\r\n",
1303                  boundary);
1304     fputs ("Content-Type: application/pgp-signature\r\n"
1305            "\r\n", fp);
1306
1307     err = gpgme_data_rewind (sigdata);
1308     if (err) {
1309         debug_print ("gpgme_data_rewind on sigdata failed: %s\n",
1310                    gpgme_strerror (err));
1311         goto failure;
1312     }
1313
1314     while (!(err = gpgme_data_read (sigdata, buf, BUFFSIZE, &nread))) {
1315         fwrite (buf, nread, 1, fp);
1316     }
1317     if (err != GPGME_EOF) {
1318         debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1319         goto failure;
1320     }
1321
1322     /* Final boundary */
1323     fprintf (fp, "\r\n"
1324                  "--%s--\r\n",
1325                  boundary);
1326     fflush (fp);
1327     if (ferror (fp)) {
1328         FILE_OP_ERROR (file, "fwrite");
1329         goto failure;
1330     }
1331     fclose (fp);
1332     gpgme_data_release (header);
1333     gpgme_data_release (plain);
1334     gpgme_data_release (sigdata);
1335     g_free (boundary);
1336     g_free (micalg);
1337     return 0;
1338
1339 failure:
1340     if (fp) 
1341         fclose (fp);
1342     gpgme_data_release (header);
1343     gpgme_data_release (plain);
1344     gpgme_data_release (sigdata);
1345     g_free (boundary);
1346     g_free (micalg);
1347     return -1; /* error */
1348 }
1349
1350
1351 /*
1352  * Sign the file with clear text and replace its content with the signed one.
1353  */
1354 gint
1355 rfc2015_clearsign (const gchar *file, GSList *key_list)
1356 {
1357     FILE *fp;
1358     gchar buf[BUFFSIZE];
1359     GpgmeError err;
1360     GpgmeData text = NULL;
1361     GpgmeData sigdata = NULL;
1362     size_t nread;
1363     gchar *siginfo;
1364
1365     if ((fp = fopen(file, "rb")) == NULL) {
1366         FILE_OP_ERROR(file, "fopen");
1367         goto failure;
1368     }
1369
1370     err = gpgme_data_new(&text);
1371     if (err) {
1372         debug_print("gpgme_data_new failed: %s\n", gpgme_strerror(err));
1373         goto failure;
1374     }
1375
1376     while (!err && fgets(buf, sizeof(buf), fp)) {
1377         err = gpgme_data_write(text, buf, strlen(buf));
1378     }
1379     if (ferror(fp)) {
1380         FILE_OP_ERROR(file, "fgets");
1381         goto failure;
1382     }
1383     if (err) {
1384         debug_print("gpgme_data_write failed: %s\n", gpgme_strerror(err));
1385         goto failure;
1386     }
1387
1388     sigdata = pgp_sign(text, key_list, TRUE, &siginfo);
1389     if (siginfo) {
1390         g_free(siginfo);
1391     }
1392     if (!sigdata)
1393         goto failure;
1394
1395     if (fclose(fp) == EOF) {
1396         FILE_OP_ERROR(file, "fclose");
1397         fp = NULL;
1398         goto failure;
1399     }
1400     if ((fp = fopen(file, "wb")) == NULL) {
1401         FILE_OP_ERROR(file, "fopen");
1402         goto failure;
1403     }
1404
1405     err = gpgme_data_rewind(sigdata);
1406     if (err) {
1407         debug_print("gpgme_data_rewind on sigdata failed: %s\n",
1408                     gpgme_strerror(err));
1409         goto failure;
1410     }
1411
1412     while (!(err = gpgme_data_read(sigdata, buf, sizeof(buf), &nread))) {
1413         fwrite(buf, nread, 1, fp);
1414     }
1415     if (err != GPGME_EOF) {
1416         debug_print("gpgme_data_read failed: %s\n", gpgme_strerror(err));
1417         goto failure;
1418     }
1419
1420     if (fclose(fp) == EOF) {
1421         FILE_OP_ERROR(file, "fclose");
1422         fp = NULL;
1423         goto failure;
1424     }
1425     gpgme_data_release(text);
1426     gpgme_data_release(sigdata);
1427     return 0;
1428
1429 failure:
1430     if (fp)
1431         fclose(fp);
1432     gpgme_data_release(text);
1433     gpgme_data_release(sigdata);
1434     return -1;
1435 }
1436
1437
1438 /****************
1439  * Create a new boundary in a way that it is very unlikely that this
1440  * will occur in the following text.  It would be easy to ensure
1441  * uniqueness if everything is either quoted-printable or base64
1442  * encoded (note that conversion is allowed), but because MIME bodies
1443  * may be nested, it may happen that the same boundary has already
1444  * been used. We avoid scanning the message for conflicts and hope the
1445  * best.
1446  *
1447  *   boundary := 0*69<bchars> bcharsnospace
1448  *   bchars := bcharsnospace / " "
1449  *   bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
1450  *                    "+" / "_" / "," / "-" / "." /
1451  *                    "/" / ":" / "=" / "?"  
1452  */
1453
1454 static char *
1455 create_boundary (void)
1456 {
1457     static char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1458                         "abcdefghijklmnopqrstuvwxyz"
1459                         "1234567890'()+_,./:=?";
1460     char buf[17];
1461     int i, equal;
1462     int pid;
1463
1464     pid = getpid();
1465
1466     /* We make the boundary depend on the pid, so that all running
1467      * processed generate different values even when they have been
1468      * started within the same second and srand48(time(NULL)) has been
1469      * used.  I can't see whether this is really an advantage but it
1470      * doesn't do any harm.
1471      */
1472     equal = -1;
1473     for(i = 0; i < sizeof(buf) - 1; i++) {
1474         buf[i] = tbl[(lrand48() ^ pid) % (sizeof(tbl) - 1)]; /* fill with random */
1475         if(buf[i] == '=' && equal == -1)
1476             equal = i;
1477     }
1478     buf[i] = 0;
1479
1480     /* now make sure that we do have the sequence "=." in it which cannot
1481      * be matched by quoted-printable or base64 encoding */
1482     if(equal != -1 && (equal+1) < i)
1483         buf[equal+1] = '.';
1484     else {
1485         buf[0] = '=';
1486         buf[1] = '.';
1487     }
1488
1489     return g_strdup(buf);
1490 }
1491
1492 #endif /* USE_GPGME */