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