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