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