2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 2001 Werner Koch (dd9jn)
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.
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.
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.
38 #include "procheader.h"
44 #include "prefs_common.h"
45 #include "passphrase.h"
46 #include "select-keys.h"
47 #include "sigstatus.h"
50 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
52 static char *content_names[] = {
54 "Content-Disposition",
55 "Content-Transfer-Encoding",
59 static char *mime_version_name[] = {
64 static char *create_boundary (void);
66 static void sig_expiration_check (GString *str,
71 static void sig_expired (GString *str,
74 static void sig_key_expired (GString *str,
79 static void dump_mimeinfo (const char *text, MimeInfo *x)
81 debug_print ("MimeInfo[%s] %p level=%d\n",
82 text, x, x? x->level:0 );
86 debug_print (" enc=`%s' enc_type=%d mime_type=%d\n",
87 x->encoding, x->encoding_type, x->mime_type );
88 debug_print (" cont_type=`%s' cs=`%s' name=`%s' bnd=`%s'\n",
89 x->content_type, x->charset, x->name, x->boundary );
90 debug_print (" cont_disp=`%s' fname=`%s' fpos=%ld size=%u, lvl=%d\n",
91 x->content_disposition, x->filename, x->fpos, x->size,
93 dump_mimeinfo (".main", x->main );
94 dump_mimeinfo (".sub", x->sub );
95 dump_mimeinfo (".next", x->next );
96 debug_print ("MimeInfo[.parent] %p\n", x );
97 dump_mimeinfo (".children", x->children );
98 dump_mimeinfo (".plaintext", x->plaintext );
101 static void dump_part ( MimeInfo *mimeinfo, FILE *fp )
103 unsigned int size = mimeinfo->size;
106 if (fseek (fp, mimeinfo->fpos, SEEK_SET)) {
107 debug_print ("dump_part: fseek error\n");
111 debug_print ("--- begin dump_part ----\n");
112 while (size-- && (c = getc (fp)) != EOF)
115 debug_print ("dump_part: read error\n");
116 debug_print ("--- end dump_part ----\n");
121 rfc2015_disable_all (void)
123 /* FIXME: set a flag, so that we don't bother the user with failed
129 rfc2015_secure_remove (const char *fname)
133 /* fixme: overwrite the file first */
139 sig_status_to_string (GpgmeSigStat status)
144 case GPGME_SIG_STAT_NONE:
145 result = _("Oops: Signature not verified");
147 case GPGME_SIG_STAT_NOSIG:
148 result = _("No signature found");
150 case GPGME_SIG_STAT_GOOD:
151 result = _("Good signature");
153 case GPGME_SIG_STAT_GOOD_EXP:
154 result = _("Good signature but it has expired");
156 case GPGME_SIG_STAT_GOOD_EXPKEY:
157 result = _("Good signature but the key has expired");
159 case GPGME_SIG_STAT_BAD:
160 result = _("BAD signature");
162 case GPGME_SIG_STAT_NOKEY:
163 result = _("No public key to verify the signature");
165 case GPGME_SIG_STAT_ERROR:
166 result = _("Error verifying the signature");
168 case GPGME_SIG_STAT_DIFF:
169 result = _("Different results for signatures");
172 result = _("Error: Unknown status");
180 sig_status_with_name (GpgmeSigStat status)
185 case GPGME_SIG_STAT_NONE:
186 result = _("Oops: Signature not verified");
188 case GPGME_SIG_STAT_NOSIG:
189 result = _("No signature found");
191 case GPGME_SIG_STAT_GOOD:
192 result = _("Good signature from \"%s\"");
194 case GPGME_SIG_STAT_GOOD_EXP:
195 result = _("Good signature from \"%s\" but it has expired");
197 case GPGME_SIG_STAT_GOOD_EXPKEY:
198 result = _("Good signature from \"%s\" but the key has expired");
200 case GPGME_SIG_STAT_BAD:
201 result = _("BAD signature from \"%s\"");
203 case GPGME_SIG_STAT_NOKEY:
204 result = _("No public key to verify the signature");
206 case GPGME_SIG_STAT_ERROR:
207 result = _("Error verifying the signature");
209 case GPGME_SIG_STAT_DIFF:
210 result = _("Different results for signatures");
213 result = _("Error: Unknown status");
221 sig_status_for_key(GString *str, GpgmeCtx ctx, GpgmeSigStat status,
222 GpgmeKey key, const gchar *fpr)
227 uid = gpgme_key_get_string_attr (key, GPGME_ATTR_USERID, NULL, idx);
229 g_string_sprintfa (str, "%s\n",
230 sig_status_to_string (status));
231 if ((fpr != NULL) && (*fpr != '\0'))
232 g_string_sprintfa (str, "Key fingerprint: %s\n", fpr);
233 g_string_append (str, _("Cannot find user ID for this key."));
234 sig_expiration_check(str, ctx, key, status, 0);
237 g_string_sprintfa (str, sig_status_with_name (status), uid);
238 g_string_append (str, "\n");
241 uid = gpgme_key_get_string_attr (key, GPGME_ATTR_USERID,
245 g_string_sprintfa (str, _(" aka \"%s\"\n"),
248 sig_expiration_check(str, ctx, key, status, 0);
252 sig_expiration_check(GString *str, GpgmeCtx ctx, GpgmeKey key,
253 GpgmeSigStat status, int idx)
255 if (status == GPGME_SIG_STAT_GOOD_EXP)
256 sig_expired(str, ctx, idx);
257 else if (status == GPGME_SIG_STAT_GOOD_EXPKEY)
258 sig_key_expired(str, key, idx);
262 sig_expired(GString *str, GpgmeCtx ctx, int idx)
264 unsigned long exp_time;
265 exp_time = gpgme_get_sig_ulong_attr(ctx, idx, GPGME_ATTR_EXPIRE, 0);
266 g_string_sprintfa(str, _("Signature expired %s"), ctime(&exp_time));
270 sig_key_expired(GString *str, GpgmeKey key, int idx)
272 unsigned long exp_time;
273 exp_time = gpgme_key_get_ulong_attr(key, GPGME_ATTR_EXPIRE, NULL, idx);
274 g_string_sprintfa(str, _("Key expired %s"), ctime(&exp_time));
278 sig_status_full (GpgmeCtx ctx)
287 struct tm *ctime_val;
291 str = g_string_new ("");
293 fpr = gpgme_get_sig_status (ctx, sig_idx, &status, &created);
294 while (fpr != NULL) {
296 ctime_val = localtime (&created);
297 strftime (ctime_str, sizeof (ctime_str), "%c",
299 g_string_sprintfa (str,
300 _("Signature made at %s\n"),
303 err = gpgme_get_sig_key (ctx, sig_idx, &key);
305 g_string_sprintfa (str, "%s\n",
306 sig_status_to_string (status));
307 if ((fpr != NULL) && (*fpr != '\0'))
308 g_string_sprintfa (str,
309 _("Key fingerprint: %s\n"),
312 sig_status_for_key (str, ctx, status, key, fpr);
313 gpgme_key_unref (key);
315 g_string_append (str, "\n\n");
317 fpr = gpgme_get_sig_status (ctx, ++sig_idx, &status, &created);
321 g_string_free (str, FALSE);
325 static void check_signature (MimeInfo *mimeinfo, MimeInfo *partinfo, FILE *fp)
329 GpgmeData sig = NULL, text = NULL;
330 GpgmeSigStat status = GPGME_SIG_STAT_NONE;
331 GpgmegtkSigStatus statuswindow = NULL;
332 const char *result = NULL;
334 gint n_exclude_chars = 0;
336 if (prefs_common.gpg_signature_popup)
337 statuswindow = gpgmegtk_sig_status_create ();
339 err = gpgme_new (&ctx);
341 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
345 /* don't include the last empty line.
346 It does not belong to the signed text */
347 if (mimeinfo->children->size > 0) {
348 if (fseek(fp, mimeinfo->children->fpos + mimeinfo->children->size - 1,
353 if (fgetc(fp) == '\n') {
355 if (mimeinfo->children->size > 1) {
356 if (fseek(fp, mimeinfo->children->fpos + mimeinfo->children->size - 2,
361 if (fgetc(fp) == '\r')
367 /* canonicalize the file part. */
368 tmp_file = get_tmp_file();
369 if (copy_file_part(fp, mimeinfo->children->fpos,
370 mimeinfo->children->size - n_exclude_chars,
375 if (canonicalize_file_replace(tmp_file) < 0) {
381 err = gpgme_data_new_from_file(&text, tmp_file, 1);
387 err = gpgme_data_new_from_filepart (&sig, NULL, fp,
388 partinfo->fpos, partinfo->size);
390 debug_print ("gpgme_data_new_from_filepart failed: %s\n",
391 gpgme_strerror (err));
395 err = gpgme_op_verify (ctx, sig, text, &status);
397 debug_print ("gpgme_op_verify failed: %s\n", gpgme_strerror (err));
401 /* FIXME: check what the heck this sig_status_full stuff is.
402 * it should better go into sigstatus.c */
403 g_free (partinfo->sigstatus_full);
404 partinfo->sigstatus_full = sig_status_full (ctx);
407 result = gpgmegtk_sig_status_to_string(status);
408 debug_print("verification status: %s\n", result);
409 if (prefs_common.gpg_signature_popup)
410 gpgmegtk_sig_status_update (statuswindow, ctx);
412 g_free (partinfo->sigstatus);
413 partinfo->sigstatus = g_strdup (result);
414 partinfo->sig_ok = (status == GPGME_SIG_STAT_GOOD);
416 gpgme_data_release (sig);
417 gpgme_data_release (text);
419 if (prefs_common.gpg_signature_popup)
420 gpgmegtk_sig_status_destroy (statuswindow);
424 * Copy a gpgme data object to a temporary file and
425 * return this filename
429 copy_gpgmedata_to_temp (GpgmeData data, guint *length)
438 tmp = g_strdup_printf("%s%cgpgtmp.%08x",
439 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id );
441 if ((fp = fopen(tmp, "wb")) == NULL) {
442 FILE_OP_ERROR(tmp, "fopen");
447 err = gpgme_data_rewind ( data );
449 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
451 while (!(err = gpgme_data_read (data, buf, 100, &nread))) {
452 fwrite ( buf, nread, 1, fp );
455 if (err != GPGME_EOF)
456 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
466 pgp_decrypt (MimeInfo *partinfo, FILE *fp)
470 GpgmeData cipher = NULL, plain = NULL;
471 struct passphrase_cb_info_s info;
473 memset (&info, 0, sizeof info);
475 err = gpgme_new (&ctx);
477 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
481 err = gpgme_data_new_from_filepart (&cipher, NULL, fp,
482 partinfo->fpos, partinfo->size);
484 debug_print ("gpgme_data_new_from_filepart failed: %s\n",
485 gpgme_strerror (err));
489 err = gpgme_data_new (&plain);
491 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
495 if (!getenv("GPG_AGENT_INFO")) {
497 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
500 err = gpgme_op_decrypt (ctx, cipher, plain);
503 gpgme_data_release (cipher);
505 gpgmegtk_free_passphrase();
506 debug_print ("decryption failed: %s\n", gpgme_strerror (err));
507 gpgme_data_release (plain);
511 debug_print ("** decryption succeeded\n");
517 MimeInfo * rfc2015_find_signature (MimeInfo *mimeinfo)
524 if (g_strcasecmp (mimeinfo->content_type, "multipart/signed"))
527 debug_print ("** multipart/signed encountered\n");
529 /* check that we have at least 2 parts of the correct type */
530 for (partinfo = mimeinfo->children;
531 partinfo != NULL; partinfo = partinfo->next) {
532 if (++n > 1 && !g_strcasecmp (partinfo->content_type,
533 "application/pgp-signature"))
540 gboolean rfc2015_has_signature (MimeInfo *mimeinfo)
542 return rfc2015_find_signature (mimeinfo) != NULL;
545 void rfc2015_check_signature (MimeInfo *mimeinfo, FILE *fp)
549 partinfo = rfc2015_find_signature (mimeinfo);
554 g_message ("** yep, it is a pgp signature");
555 dump_mimeinfo ("gpg-signature", partinfo );
556 dump_part (partinfo, fp );
557 dump_mimeinfo ("signed text", mimeinfo->children );
558 dump_part (mimeinfo->children, fp);
561 check_signature (mimeinfo, partinfo, fp);
564 int rfc2015_is_encrypted (MimeInfo *mimeinfo)
566 if (!mimeinfo || mimeinfo->mime_type != MIME_MULTIPART)
568 if (g_strcasecmp (mimeinfo->content_type, "multipart/encrypted"))
570 /* fixme: we should check the protocol parameter */
574 gboolean rfc2015_msg_is_encrypted (const gchar *file)
580 if ((fp = fopen(file, "rb")) == NULL)
583 mimeinfo = procmime_scan_mime_header(fp);
589 ret = rfc2015_is_encrypted(mimeinfo);
590 procmime_mimeinfo_free_all(mimeinfo);
591 return ret != 0 ? TRUE : FALSE;
595 name_cmp(const char *a, const char *b)
597 for( ; *a && *b; a++, b++) {
599 && toupper(*(unsigned char *)a) != toupper(*(unsigned char *)b))
607 headerp(char *p, char **names)
616 if(p2[-1] == ' ' || p2[-1] == '\t') {
625 for(i = 0 ; names[i] != NULL; i++) {
626 if(!name_cmp (names[i], p))
631 return names[i] != NULL;
635 #define DECRYPTION_ABORT() \
637 procmime_mimeinfo_free_all(tmpinfo); \
638 msginfo->decryption_failed = 1; \
642 void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
645 MimeInfo *tmpinfo, *partinfo;
654 g_return_if_fail (msginfo != NULL);
655 g_return_if_fail (mimeinfo != NULL);
656 g_return_if_fail (fp != NULL);
657 g_return_if_fail (mimeinfo->mime_type == MIME_MULTIPART);
659 debug_print ("** decrypting multipart/encrypted message\n");
662 if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
664 tmpinfo = procmime_scan_mime_header(fp);
665 if (!tmpinfo || tmpinfo->mime_type != MIME_MULTIPART) {
669 procmime_scan_multipart_message(tmpinfo, fp);
671 /* check that we have the 2 parts */
672 partinfo = tmpinfo->children;
673 if (!partinfo || !partinfo->next) {
676 if (!g_strcasecmp (partinfo->content_type, "application/pgp-encrypted")) {
677 /* Fixme: check that the version is 1 */
680 partinfo = partinfo->next;
682 !g_strcasecmp (partinfo->content_type, "application/octet-stream")) {
684 g_warning ("oops: pgp_encrypted with more than 2 parts");
690 debug_print ("** yep, it is pgp encrypted\n");
692 plain = pgp_decrypt (partinfo, fp);
697 fname = g_strdup_printf("%s%cplaintext.%08x",
698 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
700 if ((dstfp = fopen(fname, "wb")) == NULL) {
701 FILE_OP_ERROR(fname, "fopen");
706 /* write the orginal header to the new file */
707 if (fseek(fp, tmpinfo->fpos, SEEK_SET) < 0)
710 while (fgets(buf, sizeof(buf), fp)) {
711 if (headerp (buf, content_names))
713 if (buf[0] == '\r' || buf[0] == '\n')
718 err = gpgme_data_rewind (plain);
720 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
722 while (!(err = gpgme_data_read (plain, buf, sizeof(buf), &nread))) {
723 fwrite (buf, nread, 1, dstfp);
726 if (err != GPGME_EOF) {
727 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
731 procmime_mimeinfo_free_all(tmpinfo);
733 msginfo->plaintext_file = fname;
734 msginfo->decryption_failed = 0;
737 #undef DECRYPTION_ABORT
741 * plain contains an entire mime object.
742 * Encrypt it and return an GpgmeData object with the encrypted version of
743 * the file or NULL in case of error.
746 pgp_encrypt ( GpgmeData plain, GpgmeRecipients rset )
750 GpgmeData cipher = NULL;
752 err = gpgme_new (&ctx);
754 err = gpgme_data_new (&cipher);
756 gpgme_set_armor (ctx, 1);
757 err = gpgme_op_encrypt (ctx, rset, plain, cipher);
761 debug_print ("encryption failed: %s\n", gpgme_strerror (err));
762 gpgme_data_release (cipher);
766 debug_print ("** encryption succeeded\n");
774 * Create and return a list of keys matching a key id
777 GSList *rfc2015_create_signers_list (const char *keyid)
779 GSList *key_list = NULL;
780 GpgmeCtx list_ctx = NULL;
785 err = gpgme_new (&list_ctx);
788 err = gpgme_op_keylist_start (list_ctx, keyid, 1);
791 while ( !(err = gpgme_op_keylist_next (list_ctx, &key)) ) {
792 key_list = g_slist_append (key_list, key);
794 if (err != GPGME_EOF)
797 if (key_list == NULL) {
798 debug_print ("no keys found for keyid \"%s\"\n", keyid);
803 debug_print ("rfc2015_create_signers_list failed: %s\n", gpgme_strerror (err));
804 for (p = key_list; p != NULL; p = p->next)
805 gpgme_key_unref ((GpgmeKey) p->data);
806 g_slist_free (key_list);
809 gpgme_release (list_ctx);
810 return err ? NULL : key_list;
814 * Encrypt the file by extracting all recipients and finding the
815 * encryption keys for all of them. The file content is then replaced
816 * by the encrypted one. */
818 rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
822 int i, clineidx, saved_last;
823 char *clines[3] = {NULL};
825 GpgmeData header = NULL;
826 GpgmeData plain = NULL;
827 GpgmeData cipher = NULL;
828 GpgmeRecipients rset = NULL;
830 int mime_version_seen = 0;
831 char *boundary = create_boundary ();
833 /* Create the list of recipients */
834 rset = gpgmegtk_recipient_selection (recp_list);
836 debug_print ("error creating recipient list\n" );
840 /* Open the source file */
841 if ((fp = fopen(file, "rb")) == NULL) {
842 FILE_OP_ERROR(file, "fopen");
846 err = gpgme_data_new (&header);
848 err = gpgme_data_new (&plain);
850 debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
854 /* get the content header lines from the source */
857 while (!err && fgets(buf, sizeof(buf), fp)) {
858 /* fixme: check for overlong lines */
859 if (headerp (buf, content_names)) {
860 if (clineidx >= DIM (clines)) {
861 debug_print ("rfc2015_encrypt: too many content lines\n");
864 clines[clineidx++] = g_strdup (buf);
870 if (*buf == ' ' || *buf == '\t') {
871 char *last = clines[clineidx-1];
872 clines[clineidx-1] = g_strconcat (last, buf, NULL);
878 if (headerp (buf, mime_version_name))
879 mime_version_seen = 1;
881 if (buf[0] == '\r' || buf[0] == '\n')
883 err = gpgme_data_write (header, buf, strlen (buf));
886 FILE_OP_ERROR (file, "fgets");
890 /* write them to the temp data and add the rest of the message */
891 for (i = 0; !err && i < clineidx; i++) {
892 debug_print ("%% %s:%d: cline=`%s'", __FILE__ ,__LINE__, clines[i]);
893 err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
896 err = gpgme_data_write (plain, "\r\n", 2);
897 while (!err && fgets(buf, sizeof(buf), fp)) {
898 err = gpgme_data_write (plain, buf, strlen (buf));
901 FILE_OP_ERROR (file, "fgets");
905 debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
909 cipher = pgp_encrypt (plain, rset);
910 gpgme_data_release (plain); plain = NULL;
911 gpgme_recipients_release (rset); rset = NULL;
915 /* we have the encrypted message available in cipher and now we
916 * are going to rewrite the source file. To be sure that file has
917 * been truncated we use an approach which should work everywhere:
918 * close the file and then reopen it for writing. It is important
919 * that this works, otherwise it may happen that parts of the
920 * plaintext are still in the file (The encrypted stuff is, due to
921 * compression, usually shorter than the plaintext).
923 * Yes, there is a race condition here, but everyone, who is so
924 * stupid to store the temp file with the plaintext in a public
925 * directory has to live with this anyway. */
927 FILE_OP_ERROR(file, "fclose");
930 if ((fp = fopen(file, "wb")) == NULL) {
931 FILE_OP_ERROR(file, "fopen");
935 /* Write the header, append new content lines, part 1 and part 2 header */
936 err = gpgme_data_rewind (header);
938 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
941 while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
942 fwrite (buf, nread, 1, fp);
944 if (err != GPGME_EOF) {
945 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
949 FILE_OP_ERROR (file, "fwrite");
952 gpgme_data_release (header); header = NULL;
954 if (!mime_version_seen)
955 fputs ("MIME-Version: 1\r\n", fp);
959 "Content-Type: text/plain; charset=US-ASCII\r\n"
960 "Content-Transfer-Encoding: 7bit\r\n"
964 "Content-Type: multipart/encrypted;"
965 " protocol=\"application/pgp-encrypted\";\r\n"
966 " boundary=\"%s\"\r\n"
969 "Content-Type: application/pgp-encrypted\r\n"
974 "Content-Type: application/octet-stream\r\n"
976 boundary, boundary, boundary);
979 /* append the encrypted stuff */
980 err = gpgme_data_rewind (cipher);
982 debug_print ("** gpgme_data_rewind on cipher failed: %s\n",
983 gpgme_strerror (err));
987 while (!(err = gpgme_data_read (cipher, buf, BUFFSIZE, &nread))) {
988 fwrite (buf, nread, 1, fp);
990 if (err != GPGME_EOF) {
991 debug_print ("** gpgme_data_read failed: %s\n", gpgme_strerror (err));
995 /* and the final boundary */
996 if (!ascii_armored) {
1004 FILE_OP_ERROR (file, "fwrite");
1008 gpgme_data_release (cipher);
1014 gpgme_data_release (header);
1015 gpgme_data_release (plain);
1016 gpgme_data_release (cipher);
1017 gpgme_recipients_release (rset);
1019 return -1; /* error */
1023 * plain contains an entire mime object. Sign it and return an
1024 * GpgmeData object with the signature of it or NULL in case of error.
1025 * r_siginfo returns an XML object with information about the signature.
1028 pgp_sign (GpgmeData plain, GSList *key_list, gboolean clearsign,
1032 GpgmeCtx ctx = NULL;
1034 GpgmeData sig = NULL;
1035 struct passphrase_cb_info_s info;
1038 memset (&info, 0, sizeof info);
1040 err = gpgme_new (&ctx);
1043 err = gpgme_data_new (&sig);
1047 if (!getenv("GPG_AGENT_INFO")) {
1049 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
1051 gpgme_set_textmode (ctx, 1);
1052 gpgme_set_armor (ctx, 1);
1053 gpgme_signers_clear (ctx);
1054 for (p = key_list; p != NULL; p = p->next) {
1055 err = gpgme_signers_add (ctx, (GpgmeKey) p->data);
1059 for (p = key_list; p != NULL; p = p->next)
1060 gpgme_key_unref ((GpgmeKey) p->data);
1061 g_slist_free (key_list);
1067 clearsign ? GPGME_SIG_MODE_CLEAR : GPGME_SIG_MODE_DETACH);
1069 *r_siginfo = gpgme_get_op_info (ctx, 0);
1073 gpgmegtk_free_passphrase();
1074 debug_print ("signing failed: %s\n", gpgme_strerror (err));
1075 gpgme_data_release (sig);
1079 debug_print ("signing succeeded\n");
1082 gpgme_release (ctx);
1087 * Find TAG in XML and return a pointer into xml set just behind the
1088 * closing angle. Return NULL if not found.
1091 find_xml_tag (const char *xml, const char *tag)
1093 int taglen = strlen (tag);
1094 const char *s = xml;
1096 while ( (s = strchr (s, '<')) ) {
1098 if (!strncmp (s, tag, taglen)) {
1099 const char *s2 = s + taglen;
1100 if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
1102 while (*s2 && *s2 != '>') /* skip attributes */
1104 /* fixme: do need to handle angles inside attribute vallues? */
1105 return *s2? (s2+1):NULL;
1108 while (*s && *s != '>') /* skip to end of tag */
1116 * Extract the micalg from an GnupgOperationInfo XML container.
1119 extract_micalg (char *xml)
1123 s = find_xml_tag (xml, "GnupgOperationInfo");
1125 const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
1126 s = find_xml_tag (s, "signature");
1127 if (s && s_end && s < s_end) {
1128 const char *s_end2 = find_xml_tag (s, "/signature");
1129 if (s_end2 && s_end2 < s_end) {
1130 s = find_xml_tag (s, "micalg");
1131 if (s && s < s_end2) {
1132 s_end = strchr (s, '<');
1134 char *p = g_malloc (s_end - s + 1);
1135 memcpy (p, s, s_end - s);
1148 * Sign the file and replace its content with the signed one.
1151 rfc2015_sign (const char *file, GSList *key_list)
1155 int i, clineidx, saved_last;
1156 char *clines[3] = {NULL};
1158 GpgmeData header = NULL;
1159 GpgmeData plain = NULL;
1160 GpgmeData sigdata = NULL;
1162 int mime_version_seen = 0;
1163 char *boundary = create_boundary ();
1164 char *micalg = NULL;
1167 /* Open the source file */
1168 if ((fp = fopen(file, "rb")) == NULL) {
1169 FILE_OP_ERROR(file, "fopen");
1173 err = gpgme_data_new (&header);
1175 err = gpgme_data_new (&plain);
1177 debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
1181 /* get the content header lines from the source */
1184 while (!err && fgets(buf, sizeof(buf), fp)) {
1185 /* fixme: check for overlong lines */
1186 if (headerp (buf, content_names)) {
1187 if (clineidx >= DIM (clines)) {
1188 debug_print ("rfc2015_sign: too many content lines\n");
1191 clines[clineidx++] = g_strdup (buf);
1197 if (*buf == ' ' || *buf == '\t') {
1198 char *last = clines[clineidx - 1];
1199 clines[clineidx - 1] = g_strconcat (last, buf, NULL);
1205 if (headerp (buf, mime_version_name))
1206 mime_version_seen = 1;
1208 if (buf[0] == '\r' || buf[0] == '\n')
1210 err = gpgme_data_write (header, buf, strlen (buf));
1213 FILE_OP_ERROR (file, "fgets");
1217 /* write them to the temp data and add the rest of the message */
1218 for (i = 0; !err && i < clineidx; i++) {
1219 err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
1222 err = gpgme_data_write (plain, "\r\n", 2 );
1223 while (!err && fgets(buf, sizeof(buf), fp)) {
1224 err = gpgme_data_write (plain, buf, strlen (buf));
1227 FILE_OP_ERROR (file, "fgets");
1231 debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
1235 sigdata = pgp_sign (plain, key_list, FALSE, &siginfo);
1237 micalg = extract_micalg (siginfo);
1243 /* we have the signed message available in sigdata and now we are
1244 * going to rewrite the original file. To be sure that file has
1245 * been truncated we use an approach which should work everywhere:
1246 * close the file and then reopen it for writing. */
1248 FILE_OP_ERROR(file, "fclose");
1251 if ((fp = fopen(file, "wb")) == NULL) {
1252 FILE_OP_ERROR(file, "fopen");
1256 /* Write the rfc822 header and add new content lines */
1257 err = gpgme_data_rewind (header);
1259 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
1260 while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
1261 fwrite (buf, nread, 1, fp);
1263 if (err != GPGME_EOF) {
1264 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1268 FILE_OP_ERROR (file, "fwrite");
1271 gpgme_data_release (header);
1274 if (!mime_version_seen)
1275 fputs ("MIME-Version: 1.0\r\n", fp);
1276 fprintf (fp, "Content-Type: multipart/signed; "
1277 "protocol=\"application/pgp-signature\";\r\n");
1279 fprintf (fp, " micalg=\"%s\";", micalg);
1280 fprintf (fp, " boundary=\"%s\"\r\n", boundary);
1282 /* Part 1: signed material */
1286 err = gpgme_data_rewind (plain);
1288 debug_print ("gpgme_data_rewind on plain failed: %s\n",
1289 gpgme_strerror (err));
1292 while (!(err = gpgme_data_read (plain, buf, BUFFSIZE, &nread))) {
1293 fwrite (buf, nread, 1, fp);
1295 if (err != GPGME_EOF) {
1296 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1300 /* Part 2: signature */
1304 fputs ("Content-Type: application/pgp-signature\r\n"
1307 err = gpgme_data_rewind (sigdata);
1309 debug_print ("gpgme_data_rewind on sigdata failed: %s\n",
1310 gpgme_strerror (err));
1314 while (!(err = gpgme_data_read (sigdata, buf, BUFFSIZE, &nread))) {
1315 fwrite (buf, nread, 1, fp);
1317 if (err != GPGME_EOF) {
1318 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1322 /* Final boundary */
1328 FILE_OP_ERROR (file, "fwrite");
1332 gpgme_data_release (header);
1333 gpgme_data_release (plain);
1334 gpgme_data_release (sigdata);
1342 gpgme_data_release (header);
1343 gpgme_data_release (plain);
1344 gpgme_data_release (sigdata);
1347 return -1; /* error */
1352 * Sign the file with clear text and replace its content with the signed one.
1355 rfc2015_clearsign (const gchar *file, GSList *key_list)
1358 gchar buf[BUFFSIZE];
1360 GpgmeData text = NULL;
1361 GpgmeData sigdata = NULL;
1365 if ((fp = fopen(file, "rb")) == NULL) {
1366 FILE_OP_ERROR(file, "fopen");
1370 err = gpgme_data_new(&text);
1372 debug_print("gpgme_data_new failed: %s\n", gpgme_strerror(err));
1376 while (!err && fgets(buf, sizeof(buf), fp)) {
1377 err = gpgme_data_write(text, buf, strlen(buf));
1380 FILE_OP_ERROR(file, "fgets");
1384 debug_print("gpgme_data_write failed: %s\n", gpgme_strerror(err));
1388 sigdata = pgp_sign(text, key_list, TRUE, &siginfo);
1395 if (fclose(fp) == EOF) {
1396 FILE_OP_ERROR(file, "fclose");
1400 if ((fp = fopen(file, "wb")) == NULL) {
1401 FILE_OP_ERROR(file, "fopen");
1405 err = gpgme_data_rewind(sigdata);
1407 debug_print("gpgme_data_rewind on sigdata failed: %s\n",
1408 gpgme_strerror(err));
1412 while (!(err = gpgme_data_read(sigdata, buf, sizeof(buf), &nread))) {
1413 fwrite(buf, nread, 1, fp);
1415 if (err != GPGME_EOF) {
1416 debug_print("gpgme_data_read failed: %s\n", gpgme_strerror(err));
1420 if (fclose(fp) == EOF) {
1421 FILE_OP_ERROR(file, "fclose");
1425 gpgme_data_release(text);
1426 gpgme_data_release(sigdata);
1432 gpgme_data_release(text);
1433 gpgme_data_release(sigdata);
1439 * Create a new boundary in a way that it is very unlikely that this
1440 * will occur in the following text. It would be easy to ensure
1441 * uniqueness if everything is either quoted-printable or base64
1442 * encoded (note that conversion is allowed), but because MIME bodies
1443 * may be nested, it may happen that the same boundary has already
1444 * been used. We avoid scanning the message for conflicts and hope the
1447 * boundary := 0*69<bchars> bcharsnospace
1448 * bchars := bcharsnospace / " "
1449 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
1450 * "+" / "_" / "," / "-" / "." /
1451 * "/" / ":" / "=" / "?"
1455 create_boundary (void)
1457 static char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1458 "abcdefghijklmnopqrstuvwxyz"
1459 "1234567890'()+_,./:=?";
1466 /* We make the boundary depend on the pid, so that all running
1467 * processed generate different values even when they have been
1468 * started within the same second and srand48(time(NULL)) has been
1469 * used. I can't see whether this is really an advantage but it
1470 * doesn't do any harm.
1473 for(i = 0; i < sizeof(buf) - 1; i++) {
1474 buf[i] = tbl[(lrand48() ^ pid) % (sizeof(tbl) - 1)]; /* fill with random */
1475 if(buf[i] == '=' && equal == -1)
1480 /* now make sure that we do have the sequence "=." in it which cannot
1481 * be matched by quoted-printable or base64 encoding */
1482 if(equal != -1 && (equal+1) < i)
1489 return g_strdup(buf);
1492 #endif /* USE_GPGME */