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