Removed config.h.in; added it (and also stamp-h, tags, TAGS) to .cvsignore
[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 #ifdef USE_GPGME
24
25 #include "defs.h"
26
27 #include <glib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <locale.h>
31 #include <ctype.h>
32
33 #include <gpgme.h>
34
35 #include "intl.h"
36 #include "procmime.h"
37 #include "procheader.h"
38 #include "base64.h"
39 #include "uuencode.h"
40 #include "unmime.h"
41 #include "codeconv.h"
42 #include "utils.h"
43 #include "prefs_common.h"
44 #include "passphrase.h"
45 #include "select-keys.h"
46 #include "rfc2015.h"
47
48 #define DIM(v)     (sizeof(v)/sizeof((v)[0]))
49
50 static char *content_names[] = {
51     "Content-Type",
52     "Content-Disposition",
53     "Content-Transfer-Encoding",
54     NULL
55 };
56
57 static char *mime_version_name[] = {
58     "Mime-Version",
59     NULL
60 };
61
62
63 struct passphrase_cb_info_s {
64     GpgmeCtx c;
65     int did_it;
66 };
67
68 static char *create_boundary (void);
69
70 static void dump_mimeinfo (const char *text, MimeInfo *x)
71 {
72     g_message ("** MimeInfo[%s] %p  level=%d",
73                text, x, x? x->level:0 );
74     if (!x)
75         return;
76
77     g_message ("**      enc=`%s' enc_type=%d mime_type=%d",
78                x->encoding, x->encoding_type, x->mime_type );
79     g_message ("**      cont_type=`%s' cs=`%s' name=`%s' bnd=`%s'",
80                x->content_type, x->charset, x->name, x->boundary );
81     g_message ("**      cont_disp=`%s' fname=`%s' fpos=%ld size=%u, lvl=%d",
82                x->content_disposition, x->filename, x->fpos, x->size,
83                x->level );
84     dump_mimeinfo (".main", x->main );
85     dump_mimeinfo (".sub", x->sub );
86     dump_mimeinfo (".next", x->next );
87     g_message ("** MimeInfo[.parent] %p", x ); 
88     dump_mimeinfo (".children", x->children );
89     dump_mimeinfo (".plaintext", x->plaintext );
90 }
91
92 static void dump_part ( MimeInfo *mimeinfo, FILE *fp )
93 {
94     unsigned int size = mimeinfo->size;
95     int c;
96
97     if (fseek (fp, mimeinfo->fpos, SEEK_SET)) {
98         g_warning ("dump_part: fseek error");
99         return;
100     }
101
102     g_message ("** --- begin dump_part ----");
103     while (size-- && (c = getc (fp)) != EOF) 
104         putc (c, stderr);
105     if (ferror (fp))
106         g_warning ("dump_part: read error");
107     g_message ("** --- end dump_part ----");
108 }
109
110 void
111 rfc2015_disable_all (void)
112 {
113     /* FIXME: set a flag, so that we don't bother the user with failed
114      * gpgme messages */
115 }
116
117
118 void
119 rfc2015_secure_remove (const char *fname)
120 {
121     if (!fname)
122         return;
123     /* fixme: overwrite the file first */
124     remove (fname);
125 }
126
127
128 static const gchar *
129 sig_status_to_string (GpgmeSigStat status)
130 {
131     const gchar *result;
132
133     switch (status) {
134       case GPGME_SIG_STAT_NONE:
135         result = _("Oops: Signature not verified");
136         break;
137       case GPGME_SIG_STAT_NOSIG:
138         result = _("No signature found");
139         break;
140       case GPGME_SIG_STAT_GOOD:
141         result = _("Good signature");
142         break;
143       case GPGME_SIG_STAT_BAD:
144         result = _("BAD signature");
145         break;
146       case GPGME_SIG_STAT_NOKEY:
147         result = _("No public key to verify the signature");
148         break;
149       case GPGME_SIG_STAT_ERROR:
150         result = _("Error verifying the signature");
151         break;
152       case GPGME_SIG_STAT_DIFF:
153         result = _("Different results for signatures");
154         break;
155       default:
156         result = _("Error: Unknown status");
157         break;
158     }
159
160     return result;
161 }
162
163 static const gchar *
164 sig_status_with_name (GpgmeSigStat status)
165 {
166     const gchar *result;
167
168     switch (status) {
169       case GPGME_SIG_STAT_NONE:
170         result = _("Oops: Signature not verified");
171         break;
172       case GPGME_SIG_STAT_NOSIG:
173         result = _("No signature found");
174         break;
175       case GPGME_SIG_STAT_GOOD:
176         result = _("Good signature from \"%s\"");
177         break;
178       case GPGME_SIG_STAT_BAD:
179         result = _("BAD signature  from \"%s\"");
180         break;
181       case GPGME_SIG_STAT_NOKEY:
182         result = _("No public key to verify the signature");
183         break;
184       case GPGME_SIG_STAT_ERROR:
185         result = _("Error verifying the signature");
186         break;
187       case GPGME_SIG_STAT_DIFF:
188         result = _("Different results for signatures");
189         break;
190       default:
191         result = _("Error: Unknown status");
192         break;
193     }
194
195     return result;
196 }
197
198 static void
199 sig_status_for_key(GString *str, GpgmeCtx ctx, GpgmeSigStat status, 
200                    GpgmeKey key, const gchar *fpr)
201 {
202         gint idx = 0;
203         const char *uid;
204
205         uid = gpgme_key_get_string_attr (key, GPGME_ATTR_USERID, NULL, idx);
206         if (uid == NULL) {
207                 g_string_sprintfa (str, "%s\n",
208                                    sig_status_to_string (status));
209                 if ((fpr != NULL) && (*fpr != '\0'))
210                         g_string_sprintfa (str, "Key fingerprint: %s\n", fpr);
211                 g_string_append (str, _("Cannot find user ID for this key."));
212                 return;
213         }
214         g_string_sprintfa (str, sig_status_with_name (status), uid);
215         g_string_append (str, "\n");
216
217         while (1) {
218                 uid = gpgme_key_get_string_attr (key, GPGME_ATTR_USERID,
219                                                  NULL, ++idx);
220                 if (uid == NULL)
221                         break;
222                 g_string_sprintfa (str, _("                aka \"%s\"\n"),
223                                    uid);
224         }
225 }
226
227 static gchar *
228 sig_status_full (GpgmeCtx ctx)
229 {
230         GString *str;
231         gint sig_idx = 0;
232         GpgmeError err;
233         GpgmeSigStat status;
234         GpgmeKey key;
235         const char *fpr;
236         time_t created;
237         struct tm *ctime_val;
238         char ctime_str[80];
239         gchar *retval;
240
241         str = g_string_new ("");
242
243         fpr = gpgme_get_sig_status (ctx, sig_idx, &status, &created);
244         while (fpr != NULL) {
245                 if (created != 0) {
246                         ctime_val = localtime (&created);
247                         strftime (ctime_str, sizeof (ctime_str), "%c", 
248                                   ctime_val);
249                         g_string_sprintfa (str,
250                                            _("Signature made %s\n"),
251                                            ctime_str);
252                 }
253                 err = gpgme_get_sig_key (ctx, sig_idx, &key);
254                 if (err != 0) {
255                         g_string_sprintfa (str, "%s\n",
256                                            sig_status_to_string (status));
257                         if ((fpr != NULL) && (*fpr != '\0'))
258                                 g_string_sprintfa (str, 
259                                                    _("Key fingerprint: %s\n"),
260                                                    fpr);
261                 } else {
262                         sig_status_for_key (str, ctx, status, key, fpr);
263                         gpgme_key_unref (key);
264                 }
265                 g_string_append (str, "\n\n");
266
267                 fpr = gpgme_get_sig_status (ctx, ++sig_idx, &status, &created);
268         }
269
270         retval = str->str;
271         g_string_free (str, FALSE);
272         return retval;
273 }
274
275 static void check_signature (MimeInfo *mimeinfo, MimeInfo *partinfo, FILE *fp)
276 {
277     GpgmeCtx ctx = NULL;
278     GpgmeError err;
279     GpgmeData sig = NULL, text = NULL;
280     GpgmeSigStat status = GPGME_SIG_STAT_NONE;
281     const char *result = NULL;
282
283     err = gpgme_new (&ctx);
284     if (err) {
285         g_warning ("gpgme_new failed: %s", gpgme_strerror (err));
286         goto leave;
287     }
288
289     /* don't include the last character (LF). It does not belong to the
290      * signed text */
291     err = gpgme_data_new_from_filepart (&text, NULL, fp,
292                                         mimeinfo->children->fpos,
293                                         mimeinfo->children->size ?
294                                         (mimeinfo->children->size - 1) : 0 );
295     if (!err)
296         err = gpgme_data_new_from_filepart (&sig, NULL, fp,
297                                             partinfo->fpos, partinfo->size);
298     if (err) {
299         g_message ("gpgme_data_new_from_filepart failed: %s",
300                    gpgme_strerror (err));
301         goto leave;
302     }
303
304     err = gpgme_op_verify (ctx, sig, text, &status);
305     if (err) 
306         g_message ("gpgme_op_verify failed: %s", gpgme_strerror (err));
307
308     g_free (partinfo->sigstatus_full);
309     partinfo->sigstatus_full = sig_status_full (ctx);
310
311 leave:
312     result = sig_status_to_string(status);
313     debug_print("verification status: %s\n", result);
314
315     g_assert (!err);
316     g_free (partinfo->sigstatus);
317     partinfo->sigstatus = g_strdup (result);
318
319     gpgme_data_release (sig);
320     gpgme_data_release (text);
321     gpgme_release (ctx);
322 }
323
324 static const char *
325 passphrase_cb (void *opaque, const char *desc, void *r_hd)
326 {
327     struct passphrase_cb_info_s *info = opaque;
328     GpgmeCtx ctx = info ? info->c : NULL;
329     const char *pass;
330
331     if (!desc) {
332         /* FIXME: cleanup by looking at *r_hd */
333         return NULL;
334     }
335
336     gpgmegtk_set_passphrase_grab (prefs_common.passphrase_grab);
337     g_message ("%% requesting passphrase for `%s': ", desc );
338     pass = gpgmegtk_passphrase_mbox (desc);
339     if (!pass) {
340         g_message ("%% cancel passphrase entry");
341         gpgme_cancel (ctx);
342     }
343     else
344         g_message ("%% sending passphrase");
345
346     return pass;
347 }
348
349 /*
350  * Copy a gpgme data object to a temporary file and
351  * return this filename 
352  */
353 static char *
354 copy_gpgmedata_to_temp (GpgmeData data, guint *length)
355 {
356     static int id;
357     char *tmp;
358     FILE *fp;
359     char buf[100];
360     size_t nread;
361     GpgmeError err;
362     
363     tmp = g_strdup_printf("%s%cgpgtmp.%08x",
364                           get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id );
365
366     if ((fp = fopen(tmp, "w")) == NULL) {
367         FILE_OP_ERROR(tmp, "fopen");
368         g_free(tmp);
369         return NULL;
370     }
371
372     err = gpgme_data_rewind ( data );
373     if (err)
374         g_message ("** gpgme_data_rewind failed: %s", gpgme_strerror (err));
375
376     while (!(err = gpgme_data_read (data, buf, 100, &nread))) {
377         fwrite ( buf, nread, 1, fp );
378     }
379
380     if (err != GPGME_EOF)
381         g_warning ("** gpgme_data_read failed: %s", gpgme_strerror (err));
382
383     fclose (fp);
384     *length = nread;
385
386     return tmp;
387 }
388
389 static GpgmeData
390 pgp_decrypt (MimeInfo *partinfo, FILE *fp)
391 {
392     GpgmeCtx ctx = NULL;
393     GpgmeError err;
394     GpgmeData cipher = NULL, plain = NULL;
395     struct passphrase_cb_info_s info;
396
397     memset (&info, 0, sizeof info);
398
399     err = gpgme_new (&ctx);
400     if (err) {
401         g_message ("gpgme_new failed: %s", gpgme_strerror (err));
402         goto leave;
403     }
404
405     err = gpgme_data_new_from_filepart (&cipher, NULL, fp,
406                                         partinfo->fpos, partinfo->size);
407     if (err) {
408         g_message ("gpgme_data_new_from_filepart failed: %s",
409                    gpgme_strerror (err));
410         goto leave;
411     }
412
413     err = gpgme_data_new (&plain);
414     if (err) {
415         g_message ("gpgme_new failed: %s", gpgme_strerror (err));
416         goto leave;
417     }
418
419     if (!getenv("GPG_AGENT_INFO")) {
420         info.c = ctx;
421         gpgme_set_passphrase_cb (ctx, passphrase_cb, &info);
422     } 
423
424     err = gpgme_op_decrypt (ctx, cipher, plain);
425
426 leave:
427     gpgme_data_release (cipher);
428     if (err) {
429         g_warning ("** decryption failed: %s", gpgme_strerror (err));
430         gpgme_data_release (plain);
431         plain = NULL;
432     }
433     else
434         g_message ("** decryption succeeded");
435
436     gpgme_release (ctx);
437     return plain;
438 }
439
440 MimeInfo * rfc2015_find_signature (MimeInfo *mimeinfo)
441 {
442     MimeInfo *partinfo;
443     int n = 0;
444
445     if (!mimeinfo)
446         return NULL;
447     if (g_strcasecmp (mimeinfo->content_type, "multipart/signed"))
448         return NULL;
449
450     g_message ("** multipart/signed encountered");
451
452     /* check that we have at least 2 parts of the correct type */
453     for (partinfo = mimeinfo->children;
454          partinfo != NULL; partinfo = partinfo->next) {
455         if (++n > 1  && !g_strcasecmp (partinfo->content_type,
456                                        "application/pgp-signature"))
457             break;
458     }
459
460     return partinfo;
461 }
462
463 gboolean rfc2015_has_signature (MimeInfo *mimeinfo)
464 {
465     return rfc2015_find_signature (mimeinfo) != NULL;
466 }
467
468 void rfc2015_check_signature (MimeInfo *mimeinfo, FILE *fp)
469 {
470     MimeInfo *partinfo;
471
472     partinfo = rfc2015_find_signature (mimeinfo);
473     if (!partinfo)
474         return;
475
476 #if 0
477     g_message ("** yep, it is a pgp signature");
478     dump_mimeinfo ("gpg-signature", partinfo );
479     dump_part (partinfo, fp );
480     dump_mimeinfo ("signed text", mimeinfo->children );
481     dump_part (mimeinfo->children, fp);
482 #endif
483
484     check_signature (mimeinfo, partinfo, fp);
485 }
486
487 int rfc2015_is_encrypted (MimeInfo *mimeinfo)
488 {
489     if (!mimeinfo)
490         return 0;
491     if (strcasecmp (mimeinfo->content_type, "multipart/encrypted"))
492         return 0;
493     /* fixme: we should schek the protocol parameter */
494     return 1;
495 }
496
497 static int
498 name_cmp(const char *a, const char *b)
499 {
500     for( ; *a && *b; a++, b++) {
501         if(*a != *b
502            && toupper(*(unsigned char *)a) != toupper(*(unsigned char *)b))
503             return 1;
504     }
505
506     return *a != *b;
507 }
508
509 static int
510 headerp(char *p, char **names)
511 {
512     int i, c;
513     char *p2;
514
515     p2 = strchr(p, ':');
516     if(!p2 || p == p2) {
517         return 0;
518     }
519     if(p2[-1] == ' ' || p2[-1] == '\t') {
520         return 0;
521     }
522
523     if(!names[0])
524         return 1;  
525
526     c = *p2;
527     *p2 = 0;
528     for(i = 0 ; names[i] != NULL; i++) {
529         if(!name_cmp (names[i], p))
530             break;
531     }
532     *p2 = c;
533
534     return names[i] != NULL;
535 }
536
537
538 void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
539 {
540     static int id;
541     MimeInfo *partinfo;
542     int n, found;
543     int ver_okay=0;
544     char *fname;
545     GpgmeData plain;
546     FILE *dstfp;
547     size_t nread;
548     char buf[BUFFSIZE];
549     GpgmeError err;
550
551     g_return_if_fail (mimeinfo->mime_type == MIME_MULTIPART);
552
553     g_message ("** multipart/encrypted encountered");
554
555     /* skip headers */
556     if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
557         perror("fseek");
558     while (fgets(buf, sizeof(buf), fp) != NULL)
559         if (buf[0] == '\r' || buf[0] == '\n') break;
560     
561     procmime_scan_multipart_message(mimeinfo, fp);
562
563     /* check that we have the 2 parts */
564     n = found = 0;
565     for (partinfo = mimeinfo->children; partinfo; partinfo = partinfo->next) {
566         if (++n == 1 && !strcmp (partinfo->content_type,
567                                  "application/pgp-encrypted")) {
568             /* Fixme: check that the version is 1 */
569             ver_okay = 1;
570         }
571         else if (n == 2 && !strcmp (partinfo->content_type,
572                                     "application/octet-stream")) {
573             if (partinfo->next)
574                 g_warning ("** oops: pgp_encrypted with more than 2 parts");
575             break;
576         }
577     }
578
579     if (!ver_okay || !partinfo) {
580         msginfo->decryption_failed = 1;
581         /* fixme: remove the stuff, that the above procmime_scan_multiparts() 
582          * has appended to mimeino */
583         return;
584     }
585
586     g_message ("** yep, it is pgp encrypted");
587
588     plain = pgp_decrypt (partinfo, fp);
589     if (!plain) {
590         msginfo->decryption_failed = 1;
591         return;
592     }
593     
594     fname = g_strdup_printf("%s%cplaintext.%08x",
595                             get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
596
597     if ((dstfp = fopen(fname, "w")) == NULL) {
598         FILE_OP_ERROR(fname, "fopen");
599         g_free(fname);
600         msginfo->decryption_failed = 1;
601         return;
602     }
603
604     /* write the orginal header to the new file */
605     if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
606         perror("fseek");
607
608     while (fgets(buf, sizeof(buf), fp)) {
609         if (headerp (buf, content_names))
610             continue;
611         if (buf[0] == '\r' || buf[0] == '\n')
612             break;
613         fputs (buf, dstfp);
614     }
615
616     err = gpgme_data_rewind (plain);
617     if (err)
618         g_message ("** gpgme_data_rewind failed: %s", gpgme_strerror (err));
619
620     while (!(err = gpgme_data_read (plain, buf, sizeof(buf), &nread))) {
621         fwrite (buf, nread, 1, dstfp);
622     }
623
624     if (err != GPGME_EOF) {
625         g_warning ("** gpgme_data_read failed: %s", gpgme_strerror (err));
626     }
627
628     fclose (dstfp);
629
630     msginfo->plaintext_file = fname;
631     msginfo->decryption_failed = 0;
632 }
633
634
635 /* 
636  * plain contains an entire mime object.
637  * Encrypt it and return an GpgmeData object with the encrypted version of
638  * the file or NULL in case of error.
639  */
640 static GpgmeData
641 pgp_encrypt ( GpgmeData plain, GpgmeRecipients rset )
642 {
643     GpgmeCtx ctx = NULL;
644     GpgmeError err;
645     GpgmeData cipher = NULL;
646
647     err = gpgme_new (&ctx);
648     if (!err)
649         err = gpgme_data_new (&cipher);
650     if (!err) {
651         gpgme_set_armor (ctx, 1);
652         err = gpgme_op_encrypt (ctx, rset, plain, cipher);
653     }
654
655     if (err) {
656         g_warning ("** encryption failed: %s", gpgme_strerror (err));
657         gpgme_data_release (cipher);
658         cipher = NULL;
659     }
660     else {
661         g_message ("** encryption succeeded");
662     }
663
664     gpgme_release (ctx);
665     return cipher;
666 }
667
668
669 /*
670  * Encrypt the file by extracting all recipients and finding the
671  * encryption keys for all of them.  The file content is then replaced
672  * by the encrypted one.  */
673 int
674 rfc2015_encrypt (const char *file, GSList *recp_list)
675 {
676     FILE *fp = NULL;
677     char buf[BUFFSIZE];
678     int i, clineidx, saved_last;
679     char *clines[3] = {NULL};
680     GpgmeError err;
681     GpgmeData header = NULL;
682     GpgmeData plain = NULL;
683     GpgmeData cipher = NULL;
684     GpgmeRecipients rset = NULL;
685     size_t nread;
686     int mime_version_seen = 0;
687     char *boundary = create_boundary ();
688
689     /* Create the list of recipients */
690     rset = gpgmegtk_recipient_selection (recp_list);
691     if (!rset) {
692         g_warning ("error creating recipient list" );
693         goto failure;
694     }
695
696     /* Open the source file */
697     if ((fp = fopen(file, "rb")) == NULL) {
698         FILE_OP_ERROR(file, "fopen");
699         goto failure;
700     }
701
702     err = gpgme_data_new (&header);
703     if (!err)
704         err = gpgme_data_new (&plain);
705     if (err) {
706         g_message ("gpgme_data_new failed: %s", gpgme_strerror (err));
707         goto failure;
708     }
709
710     /* get the content header lines from the source */
711     clineidx=0;
712     saved_last = 0;
713     while (!err && fgets(buf, sizeof(buf), fp)) {
714         /* fixme: check for overlong lines */
715         if (headerp (buf, content_names)) {
716             if (clineidx >= DIM (clines)) {
717                 g_message ("rfc2015_encrypt: too many content lines");
718                 goto failure;
719             }
720             clines[clineidx++] = g_strdup (buf);
721             saved_last = 1;
722             continue;
723         }
724         if (saved_last) {
725             saved_last = 0;
726             if (*buf == ' ' || *buf == '\t') {
727                 char *last = clines[clineidx-1];
728                 clines[clineidx-1] = g_strconcat (last, buf, NULL);
729                 g_free (last);
730                 continue;
731             }
732         }
733
734         if (headerp (buf, mime_version_name)) 
735             mime_version_seen = 1;
736
737         if (buf[0] == '\r' || buf[0] == '\n')
738             break;
739         err = gpgme_data_write (header, buf, strlen (buf));
740     }
741     if (ferror (fp)) {
742         FILE_OP_ERROR (file, "fgets");
743         goto failure;
744     }
745
746     /* write them to the temp data and add the rest of the message */
747     for (i = 0; !err && i < clineidx; i++) {
748         g_message ("%% %s:%d: cline=`%s'", __FILE__ ,__LINE__, clines[i]);
749         err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
750     }
751     if (!err)
752         err = gpgme_data_write (plain, "\r\n", 2);
753     while (!err && fgets(buf, sizeof(buf), fp)) {
754         err = gpgme_data_write (plain, buf, strlen (buf));
755     }
756     if (ferror (fp)) {
757         FILE_OP_ERROR (file, "fgets");
758         goto failure;
759     }
760     if (err) {
761         g_warning ("** gpgme_data_write failed: %s", gpgme_strerror (err));
762         goto failure;
763     }
764
765     cipher = pgp_encrypt (plain, rset);
766     gpgme_data_release (plain); plain = NULL;
767     gpgme_recipients_release (rset); rset = NULL;
768     if (!cipher)
769         goto failure;
770
771     /* we have the encrypted message available in cipher and now we
772      * are going to rewrite the source file. To be sure that file has
773      * been truncated we use an approach which should work everywhere:
774      * close the file and then reopen it for writing. It is important
775      * that this works, otherwise it may happen that parts of the
776      * plaintext are still in the file (The encrypted stuff is, due to
777      * compression, usually shorter than the plaintext). 
778      * 
779      * Yes, there is a race condition here, but everyone, who is so
780      * stupid to store the temp file with the plaintext in a public
781      * directory has to live with this anyway. */
782     if (fclose (fp)) {
783         FILE_OP_ERROR(file, "fclose");
784         goto failure;
785     }
786     if ((fp = fopen(file, "wb")) == NULL) {
787         FILE_OP_ERROR(file, "fopen");
788         goto failure;
789     }
790
791     /* Write the header, append new content lines, part 1 and part 2 header */
792     err = gpgme_data_rewind (header);
793     if (err) {
794         g_message ("gpgme_data_rewind failed: %s", gpgme_strerror (err));
795         goto failure;
796     }
797     while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
798         fwrite (buf, nread, 1, fp);
799     }
800     if (err != GPGME_EOF) {
801         g_warning ("** gpgme_data_read failed: %s", gpgme_strerror (err));
802         goto failure;
803     }
804     if (ferror (fp)) {
805         FILE_OP_ERROR (file, "fwrite");
806         goto failure;
807     }
808     gpgme_data_release (header); header = NULL;
809     
810     if (!mime_version_seen) 
811         fputs ("MIME-Version: 1\r\n", fp);
812
813     fprintf (fp,
814              "Content-Type: multipart/encrypted;"
815              " protocol=\"application/pgp-encrypted\";\r\n"
816              " boundary=\"%s\"\r\n"
817              "\r\n"
818              "--%s\r\n"
819              "Content-Type: application/pgp-encrypted\r\n"
820              "\r\n"
821              "Version: 1\r\n"
822              "\r\n"
823              "--%s\r\n"
824              "Content-Type: application/octet-stream\r\n"
825              "\r\n",
826              boundary, boundary, boundary);
827
828     /* append the encrypted stuff */
829     err = gpgme_data_rewind (cipher);
830     if (err) {
831         g_warning ("** gpgme_data_rewind on cipher failed: %s",
832                    gpgme_strerror (err));
833         goto failure;
834     }
835
836     while (!(err = gpgme_data_read (cipher, buf, BUFFSIZE, &nread))) {
837         fwrite (buf, nread, 1, fp);
838     }
839     if (err != GPGME_EOF) {
840         g_warning ("** gpgme_data_read failed: %s", gpgme_strerror (err));
841         goto failure;
842     }
843
844     /* and the final boundary */
845     fprintf (fp,
846              "\r\n"
847              "--%s--\r\n"
848              "\r\n",
849              boundary);
850     fflush (fp);
851     if (ferror (fp)) {
852         FILE_OP_ERROR (file, "fwrite");
853         goto failure;
854     }
855     fclose (fp);
856     gpgme_data_release (cipher);
857     return 0;
858
859 failure:
860     if (fp) 
861         fclose (fp);
862     gpgme_data_release (header);
863     gpgme_data_release (plain);
864     gpgme_data_release (cipher);
865     gpgme_recipients_release (rset);
866     g_free (boundary);
867     return -1; /* error */
868 }
869
870 static int
871 set_signers (GpgmeCtx ctx, PrefsAccount *ac)
872 {
873     GSList *key_list = NULL;
874     GpgmeCtx list_ctx = NULL;
875     const char *keyid = NULL;
876     GSList *p;
877     GpgmeError err;
878     GpgmeKey key;
879
880     if (ac == NULL)
881         return 0;
882
883     switch (ac->sign_key) {
884     case SIGN_KEY_DEFAULT:
885         return 0;               /* nothing to do */
886
887     case SIGN_KEY_BY_FROM:
888         keyid = ac->address;
889         break;
890
891     case SIGN_KEY_CUSTOM:
892         keyid = ac->sign_key_id;
893         break;
894
895     default:
896         g_assert_not_reached ();
897     }
898
899     err = gpgme_new (&list_ctx);
900     if (err)
901         goto leave;
902     err = gpgme_op_keylist_start (list_ctx, keyid, 1);
903     if (err)
904         goto leave;
905     while ( !(err = gpgme_op_keylist_next (list_ctx, &key)) ) {
906         key_list = g_slist_append (key_list, key);
907     }
908     if (err != GPGME_EOF)
909         goto leave;
910     if (key_list == NULL) {
911         g_warning ("no keys found for keyid \"%s\"", keyid);
912     }
913     gpgme_signers_clear (ctx);
914     for (p = key_list; p != NULL; p = p->next) {
915         err = gpgme_signers_add (ctx, (GpgmeKey) p->data);
916         if (err)
917             goto leave;
918     }
919
920 leave:
921     if (err)
922         g_message ("** set_signers failed: %s", gpgme_strerror (err));
923     for (p = key_list; p != NULL; p = p->next)
924         gpgme_key_unref ((GpgmeKey) p->data);
925     g_slist_free (key_list);
926     if (list_ctx)
927         gpgme_release (list_ctx);
928     return err;
929 }
930
931 /* 
932  * plain contains an entire mime object.  Sign it and return an
933  * GpgmeData object with the signature of it or NULL in case of error.
934  */
935 static GpgmeData
936 pgp_sign (GpgmeData plain, PrefsAccount *ac)
937 {
938     GpgmeCtx ctx = NULL;
939     GpgmeError err;
940     GpgmeData sig = NULL;
941     struct passphrase_cb_info_s info;
942
943     memset (&info, 0, sizeof info);
944
945     err = gpgme_new (&ctx);
946     if (err)
947         goto leave;
948     err = gpgme_data_new (&sig);
949     if (err)
950         goto leave;
951
952     if (!getenv("GPG_AGENT_INFO")) {
953         info.c = ctx;
954         gpgme_set_passphrase_cb (ctx, passphrase_cb, &info);
955     }
956     gpgme_set_textmode (ctx, 1);
957     gpgme_set_armor (ctx, 1);
958     err = set_signers (ctx, ac);
959     if (err)
960         goto leave;
961     err = gpgme_op_sign (ctx, plain, sig, GPGME_SIG_MODE_DETACH);
962
963 leave:
964     if (err) {
965         g_message ("** signing failed: %s", gpgme_strerror (err));
966         gpgme_data_release (sig);
967         sig = NULL;
968     }
969     else {
970         g_message ("** signing succeeded");
971     }
972
973     gpgme_release (ctx);
974     return sig;
975 }
976
977 /*
978  * Sign the file and replace its content with the signed one.
979  */
980 int
981 rfc2015_sign (const char *file, PrefsAccount *ac)
982 {
983     FILE *fp = NULL;
984     char buf[BUFFSIZE];
985     int i, clineidx, saved_last;
986     char *clines[3] = {NULL};
987     GpgmeError err;
988     GpgmeData header = NULL;
989     GpgmeData plain = NULL;
990     GpgmeData sigdata = NULL;
991     size_t nread;
992     int mime_version_seen = 0;
993     char *boundary = create_boundary ();
994
995     /* Open the source file */
996     if ((fp = fopen(file, "rb")) == NULL) {
997         FILE_OP_ERROR(file, "fopen");
998         goto failure;
999     }
1000
1001     err = gpgme_data_new (&header);
1002     if (!err)
1003         err = gpgme_data_new (&plain);
1004     if (err) {
1005         g_message ("gpgme_data_new failed: %s", gpgme_strerror (err));
1006         goto failure;
1007     }
1008
1009     /* get the content header lines from the source */
1010     clineidx = 0;
1011     saved_last = 0;
1012     while (!err && fgets(buf, sizeof(buf), fp)) {
1013         /* fixme: check for overlong lines */
1014         if (headerp (buf, content_names)) {
1015             if (clineidx >= DIM (clines)) {
1016                 g_message ("rfc2015_sign: too many content lines");
1017                 goto failure;
1018             }
1019             clines[clineidx++] = g_strdup (buf);
1020             saved_last = 1;
1021             continue;
1022         }
1023         if (saved_last) {
1024             saved_last = 0;
1025             if (*buf == ' ' || *buf == '\t') {
1026                 char *last = clines[clineidx - 1];
1027                 clines[clineidx - 1] = g_strconcat (last, buf, NULL);
1028                 g_free (last);
1029                 continue;
1030             }
1031         }
1032
1033         if (headerp (buf, mime_version_name)) 
1034             mime_version_seen = 1;
1035
1036         if (buf[0] == '\r' || buf[0] == '\n')
1037             break;
1038         err = gpgme_data_write (header, buf, strlen (buf));
1039     }
1040     if (ferror (fp)) {
1041         FILE_OP_ERROR (file, "fgets");
1042         goto failure;
1043     }
1044
1045     /* write them to the temp data and add the rest of the message */
1046     for (i = 0; !err && i < clineidx; i++) {
1047         err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
1048     }
1049     if (!err)
1050         err = gpgme_data_write (plain, "\r\n", 2 );
1051     while (!err && fgets(buf, sizeof(buf), fp)) {
1052         err = gpgme_data_write (plain, buf, strlen (buf));
1053     }
1054     if (ferror (fp)) {
1055         FILE_OP_ERROR (file, "fgets");
1056         goto failure;
1057     }
1058     if (err) {
1059         g_message ("** gpgme_data_write failed: %s", gpgme_strerror (err));
1060         goto failure;
1061     }
1062
1063     sigdata = pgp_sign (plain, ac);
1064     if (!sigdata) 
1065         goto failure;
1066
1067     /* we have the signed message available in sigdata and now we are
1068      * going to rewrite the original file. To be sure that file has
1069      * been truncated we use an approach which should work everywhere:
1070      * close the file and then reopen it for writing. */
1071     if (fclose (fp)) {
1072         FILE_OP_ERROR(file, "fclose");
1073         goto failure;
1074     }
1075     if ((fp = fopen(file, "wb")) == NULL) {
1076         FILE_OP_ERROR(file, "fopen");
1077         goto failure;
1078     }
1079
1080     /* Write the rfc822 header and add new content lines */
1081     err = gpgme_data_rewind (header);
1082     if (err)
1083         g_message ("** gpgme_data_rewind failed: %s", gpgme_strerror (err));
1084     while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
1085         fwrite (buf, nread, 1, fp);
1086     }
1087     if (err != GPGME_EOF) {
1088         g_message ("** gpgme_data_read failed: %s", gpgme_strerror (err));
1089         goto failure;
1090     }
1091     if (ferror (fp)) {
1092         FILE_OP_ERROR (file, "fwrite");
1093         goto failure;
1094     }
1095     gpgme_data_release (header);
1096     header = NULL;
1097
1098     if (!mime_version_seen) 
1099         fputs ("MIME-Version: 1\r\n", fp);
1100     fprintf (fp, "Content-Type: multipart/signed; "
1101                  "protocol=\"application/pgp-signature\";\r\n"
1102                  " boundary=\"%s\"\r\n", boundary );
1103
1104     /* Part 1: signed material */
1105     fprintf (fp, "\r\n--%s\r\n", boundary);
1106     err = gpgme_data_rewind (plain);
1107     if (err) {
1108         g_message ("** gpgme_data_rewind on plain failed: %s",
1109                    gpgme_strerror (err));
1110         goto failure;
1111     }
1112     while (!(err = gpgme_data_read (plain, buf, BUFFSIZE, &nread))) {
1113         fwrite (buf, nread, 1, fp);   
1114     }
1115     if (err != GPGME_EOF) {
1116         g_message ("** gpgme_data_read failed: %s", gpgme_strerror (err));
1117         goto failure;
1118     }
1119
1120     /* Part 2: signature */
1121     fprintf (fp, "\r\n--%s\r\n", boundary);
1122     fputs ("Content-Type: application/pgp-signature\r\n"
1123            "\r\n", fp);
1124
1125     err = gpgme_data_rewind (sigdata);
1126     if (err) {
1127         g_message ("** gpgme_data_rewind on sigdata failed: %s",
1128                    gpgme_strerror (err));
1129         goto failure;
1130     }
1131
1132     while (!(err = gpgme_data_read (sigdata, buf, BUFFSIZE, &nread))) {
1133         fwrite (buf, nread, 1, fp);
1134     }
1135     if (err != GPGME_EOF) {
1136         g_message ("** gpgme_data_read failed: %s", gpgme_strerror (err));
1137         goto failure;
1138     }
1139
1140     /* Final boundary */
1141     fprintf (fp, "\r\n--%s--\r\n\r\n", boundary);
1142     fflush (fp);
1143     if (ferror (fp)) {
1144         FILE_OP_ERROR (file, "fwrite");
1145         goto failure;
1146     }
1147     fclose (fp);
1148     gpgme_data_release (header);
1149     gpgme_data_release (plain);
1150     gpgme_data_release (sigdata);
1151     g_free (boundary);
1152     return 0;
1153
1154 failure:
1155     if (fp) 
1156         fclose (fp);
1157     gpgme_data_release (header);
1158     gpgme_data_release (plain);
1159     gpgme_data_release (sigdata);
1160     g_free (boundary);
1161     return -1; /* error */
1162 }
1163
1164
1165 /****************
1166  * Create a new boundary in a way that it is very unlikely that this
1167  * will occur in the following text.  It would be easy to ensure
1168  * uniqueness if everything is either quoted-printable or base64
1169  * encoded (note that conversion is allowed), but because MIME bodies
1170  * may be nested, it may happen that the same boundary has already
1171  * been used. We avoid scanning the message for conflicts and hope the
1172  * best.
1173  *
1174  *   boundary := 0*69<bchars> bcharsnospace
1175  *   bchars := bcharsnospace / " "
1176  *   bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
1177  *                    "+" / "_" / "," / "-" / "." /
1178  *                    "/" / ":" / "=" / "?"  
1179  */
1180
1181 static char *
1182 create_boundary (void)
1183 {
1184     static char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1185                         "abcdefghijklmnopqrstuvwxyz"
1186                         "1234567890'()+_,./:=?";
1187     char buf[17];
1188     int i, equal;
1189     int pid;
1190
1191     pid = getpid();
1192
1193     /* We make the boundary depend on the pid, so that all running
1194      * processed generate different values even when they have been
1195      * started within the same second and srand48(time(NULL)) has been
1196      * used.  I can't see whether this is really an advantage but it
1197      * doesn't do any harm.
1198      */
1199     equal = -1;
1200     for(i = 0; i < sizeof(buf) - 1; i++) {
1201         buf[i] = tbl[(lrand48() ^ pid) % (sizeof(tbl) - 1)]; /* fill with random */
1202         if(buf[i] == '=' && equal == -1)
1203             equal = i;
1204     }
1205     buf[i] = 0;
1206
1207     /* now make sure that we do have the sequence "=." in it which cannot
1208      * be matched by quoted-printable or base64 encoding */
1209     if(equal != -1 && (equal+1) < i)
1210         buf[equal+1] = '.';
1211     else {
1212         buf[0] = '=';
1213         buf[1] = '.';
1214     }
1215
1216     return g_strdup(buf);
1217 }
1218
1219 #endif /* USE_GPGME */