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