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);
415 gpgme_data_release (sig);
416 gpgme_data_release (text);
418 if (prefs_common.gpg_signature_popup)
419 gpgmegtk_sig_status_destroy (statuswindow);
423 * Copy a gpgme data object to a temporary file and
424 * return this filename
428 copy_gpgmedata_to_temp (GpgmeData data, guint *length)
437 tmp = g_strdup_printf("%s%cgpgtmp.%08x",
438 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id );
440 if ((fp = fopen(tmp, "wb")) == NULL) {
441 FILE_OP_ERROR(tmp, "fopen");
446 err = gpgme_data_rewind ( data );
448 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
450 while (!(err = gpgme_data_read (data, buf, 100, &nread))) {
451 fwrite ( buf, nread, 1, fp );
454 if (err != GPGME_EOF)
455 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
465 pgp_decrypt (MimeInfo *partinfo, FILE *fp)
469 GpgmeData cipher = NULL, plain = NULL;
470 struct passphrase_cb_info_s info;
472 memset (&info, 0, sizeof info);
474 err = gpgme_new (&ctx);
476 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
480 err = gpgme_data_new_from_filepart (&cipher, NULL, fp,
481 partinfo->fpos, partinfo->size);
483 debug_print ("gpgme_data_new_from_filepart failed: %s\n",
484 gpgme_strerror (err));
488 err = gpgme_data_new (&plain);
490 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
494 if (!getenv("GPG_AGENT_INFO")) {
496 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
499 err = gpgme_op_decrypt (ctx, cipher, plain);
502 gpgme_data_release (cipher);
504 gpgmegtk_free_passphrase();
505 debug_print ("decryption failed: %s\n", gpgme_strerror (err));
506 gpgme_data_release (plain);
510 debug_print ("** decryption succeeded\n");
516 MimeInfo * rfc2015_find_signature (MimeInfo *mimeinfo)
523 if (g_strcasecmp (mimeinfo->content_type, "multipart/signed"))
526 debug_print ("** multipart/signed encountered\n");
528 /* check that we have at least 2 parts of the correct type */
529 for (partinfo = mimeinfo->children;
530 partinfo != NULL; partinfo = partinfo->next) {
531 if (++n > 1 && !g_strcasecmp (partinfo->content_type,
532 "application/pgp-signature"))
539 gboolean rfc2015_has_signature (MimeInfo *mimeinfo)
541 return rfc2015_find_signature (mimeinfo) != NULL;
544 void rfc2015_check_signature (MimeInfo *mimeinfo, FILE *fp)
548 partinfo = rfc2015_find_signature (mimeinfo);
553 g_message ("** yep, it is a pgp signature");
554 dump_mimeinfo ("gpg-signature", partinfo );
555 dump_part (partinfo, fp );
556 dump_mimeinfo ("signed text", mimeinfo->children );
557 dump_part (mimeinfo->children, fp);
560 check_signature (mimeinfo, partinfo, fp);
563 int rfc2015_is_encrypted (MimeInfo *mimeinfo)
567 if (g_strcasecmp (mimeinfo->content_type, "multipart/encrypted"))
569 /* fixme: we should check the protocol parameter */
573 gboolean rfc2015_msg_is_encrypted (const gchar *file)
579 if ((fp = fopen(file, "rb")) == NULL)
582 mimeinfo = procmime_scan_mime_header(fp);
588 ret = rfc2015_is_encrypted(mimeinfo);
589 procmime_mimeinfo_free_all(mimeinfo);
590 return ret != 0 ? TRUE : FALSE;
594 name_cmp(const char *a, const char *b)
596 for( ; *a && *b; a++, b++) {
598 && toupper(*(unsigned char *)a) != toupper(*(unsigned char *)b))
606 headerp(char *p, char **names)
615 if(p2[-1] == ' ' || p2[-1] == '\t') {
624 for(i = 0 ; names[i] != NULL; i++) {
625 if(!name_cmp (names[i], p))
630 return names[i] != NULL;
634 #define DECRYPTION_ABORT() \
636 procmime_mimeinfo_free_all(tmpinfo); \
637 msginfo->decryption_failed = 1; \
641 void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
644 MimeInfo *tmpinfo, *partinfo;
653 g_return_if_fail (msginfo != NULL);
654 g_return_if_fail (mimeinfo != NULL);
655 g_return_if_fail (fp != NULL);
656 g_return_if_fail (mimeinfo->mime_type == MIME_MULTIPART);
658 debug_print ("** decrypting multipart/encrypted message\n");
661 if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
663 tmpinfo = procmime_scan_mime_header(fp);
664 if (!tmpinfo || tmpinfo->mime_type != MIME_MULTIPART) {
668 procmime_scan_multipart_message(tmpinfo, fp);
670 /* check that we have the 2 parts */
671 partinfo = tmpinfo->children;
672 if (!partinfo || !partinfo->next) {
675 if (!g_strcasecmp (partinfo->content_type, "application/pgp-encrypted")) {
676 /* Fixme: check that the version is 1 */
679 partinfo = partinfo->next;
681 !g_strcasecmp (partinfo->content_type, "application/octet-stream")) {
683 g_warning ("oops: pgp_encrypted with more than 2 parts");
689 debug_print ("** yep, it is pgp encrypted\n");
691 plain = pgp_decrypt (partinfo, fp);
696 fname = g_strdup_printf("%s%cplaintext.%08x",
697 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
699 if ((dstfp = fopen(fname, "wb")) == NULL) {
700 FILE_OP_ERROR(fname, "fopen");
705 /* write the orginal header to the new file */
706 if (fseek(fp, tmpinfo->fpos, SEEK_SET) < 0)
709 while (fgets(buf, sizeof(buf), fp)) {
710 if (headerp (buf, content_names))
712 if (buf[0] == '\r' || buf[0] == '\n')
717 err = gpgme_data_rewind (plain);
719 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
721 while (!(err = gpgme_data_read (plain, buf, sizeof(buf), &nread))) {
722 fwrite (buf, nread, 1, dstfp);
725 if (err != GPGME_EOF) {
726 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
730 procmime_mimeinfo_free_all(tmpinfo);
732 msginfo->plaintext_file = fname;
733 msginfo->decryption_failed = 0;
736 #undef DECRYPTION_ABORT
740 * plain contains an entire mime object.
741 * Encrypt it and return an GpgmeData object with the encrypted version of
742 * the file or NULL in case of error.
745 pgp_encrypt ( GpgmeData plain, GpgmeRecipients rset )
749 GpgmeData cipher = NULL;
751 err = gpgme_new (&ctx);
753 err = gpgme_data_new (&cipher);
755 gpgme_set_armor (ctx, 1);
756 err = gpgme_op_encrypt (ctx, rset, plain, cipher);
760 debug_print ("encryption failed: %s\n", gpgme_strerror (err));
761 gpgme_data_release (cipher);
765 debug_print ("** encryption succeeded\n");
773 * Create and return a list of keys matching a key id
776 GSList *rfc2015_create_signers_list (const char *keyid)
778 GSList *key_list = NULL;
779 GpgmeCtx list_ctx = NULL;
784 err = gpgme_new (&list_ctx);
787 err = gpgme_op_keylist_start (list_ctx, keyid, 1);
790 while ( !(err = gpgme_op_keylist_next (list_ctx, &key)) ) {
791 key_list = g_slist_append (key_list, key);
793 if (err != GPGME_EOF)
796 if (key_list == NULL) {
797 debug_print ("no keys found for keyid \"%s\"\n", keyid);
802 debug_print ("rfc2015_create_signers_list failed: %s\n", gpgme_strerror (err));
803 for (p = key_list; p != NULL; p = p->next)
804 gpgme_key_unref ((GpgmeKey) p->data);
805 g_slist_free (key_list);
808 gpgme_release (list_ctx);
809 return err ? NULL : key_list;
813 * Encrypt the file by extracting all recipients and finding the
814 * encryption keys for all of them. The file content is then replaced
815 * by the encrypted one. */
817 rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
821 int i, clineidx, saved_last;
822 char *clines[3] = {NULL};
824 GpgmeData header = NULL;
825 GpgmeData plain = NULL;
826 GpgmeData cipher = NULL;
827 GpgmeRecipients rset = NULL;
829 int mime_version_seen = 0;
830 char *boundary = create_boundary ();
832 /* Create the list of recipients */
833 rset = gpgmegtk_recipient_selection (recp_list);
835 debug_print ("error creating recipient list\n" );
839 /* Open the source file */
840 if ((fp = fopen(file, "rb")) == NULL) {
841 FILE_OP_ERROR(file, "fopen");
845 err = gpgme_data_new (&header);
847 err = gpgme_data_new (&plain);
849 debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
853 /* get the content header lines from the source */
856 while (!err && fgets(buf, sizeof(buf), fp)) {
857 /* fixme: check for overlong lines */
858 if (headerp (buf, content_names)) {
859 if (clineidx >= DIM (clines)) {
860 debug_print ("rfc2015_encrypt: too many content lines\n");
863 clines[clineidx++] = g_strdup (buf);
869 if (*buf == ' ' || *buf == '\t') {
870 char *last = clines[clineidx-1];
871 clines[clineidx-1] = g_strconcat (last, buf, NULL);
877 if (headerp (buf, mime_version_name))
878 mime_version_seen = 1;
880 if (buf[0] == '\r' || buf[0] == '\n')
882 err = gpgme_data_write (header, buf, strlen (buf));
885 FILE_OP_ERROR (file, "fgets");
889 /* write them to the temp data and add the rest of the message */
890 for (i = 0; !err && i < clineidx; i++) {
891 debug_print ("%% %s:%d: cline=`%s'", __FILE__ ,__LINE__, clines[i]);
892 err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
895 err = gpgme_data_write (plain, "\r\n", 2);
896 while (!err && fgets(buf, sizeof(buf), fp)) {
897 err = gpgme_data_write (plain, buf, strlen (buf));
900 FILE_OP_ERROR (file, "fgets");
904 debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
908 cipher = pgp_encrypt (plain, rset);
909 gpgme_data_release (plain); plain = NULL;
910 gpgme_recipients_release (rset); rset = NULL;
914 /* we have the encrypted message available in cipher and now we
915 * are going to rewrite the source file. To be sure that file has
916 * been truncated we use an approach which should work everywhere:
917 * close the file and then reopen it for writing. It is important
918 * that this works, otherwise it may happen that parts of the
919 * plaintext are still in the file (The encrypted stuff is, due to
920 * compression, usually shorter than the plaintext).
922 * Yes, there is a race condition here, but everyone, who is so
923 * stupid to store the temp file with the plaintext in a public
924 * directory has to live with this anyway. */
926 FILE_OP_ERROR(file, "fclose");
929 if ((fp = fopen(file, "wb")) == NULL) {
930 FILE_OP_ERROR(file, "fopen");
934 /* Write the header, append new content lines, part 1 and part 2 header */
935 err = gpgme_data_rewind (header);
937 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
940 while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
941 fwrite (buf, nread, 1, fp);
943 if (err != GPGME_EOF) {
944 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
948 FILE_OP_ERROR (file, "fwrite");
951 gpgme_data_release (header); header = NULL;
953 if (!mime_version_seen)
954 fputs ("MIME-Version: 1\r\n", fp);
958 "Content-Type: text/plain; charset=US-ASCII\r\n"
959 "Content-Transfer-Encoding: 7bit\r\n"
963 "Content-Type: multipart/encrypted;"
964 " protocol=\"application/pgp-encrypted\";\r\n"
965 " boundary=\"%s\"\r\n"
968 "Content-Type: application/pgp-encrypted\r\n"
973 "Content-Type: application/octet-stream\r\n"
975 boundary, boundary, boundary);
978 /* append the encrypted stuff */
979 err = gpgme_data_rewind (cipher);
981 debug_print ("** gpgme_data_rewind on cipher failed: %s\n",
982 gpgme_strerror (err));
986 while (!(err = gpgme_data_read (cipher, buf, BUFFSIZE, &nread))) {
987 fwrite (buf, nread, 1, fp);
989 if (err != GPGME_EOF) {
990 debug_print ("** gpgme_data_read failed: %s\n", gpgme_strerror (err));
994 /* and the final boundary */
995 if (!ascii_armored) {
1003 FILE_OP_ERROR (file, "fwrite");
1007 gpgme_data_release (cipher);
1013 gpgme_data_release (header);
1014 gpgme_data_release (plain);
1015 gpgme_data_release (cipher);
1016 gpgme_recipients_release (rset);
1018 return -1; /* error */
1022 * plain contains an entire mime object. Sign it and return an
1023 * GpgmeData object with the signature of it or NULL in case of error.
1024 * r_siginfo returns an XML object with information about the signature.
1027 pgp_sign (GpgmeData plain, GSList *key_list, gboolean clearsign,
1031 GpgmeCtx ctx = NULL;
1033 GpgmeData sig = NULL;
1034 struct passphrase_cb_info_s info;
1037 memset (&info, 0, sizeof info);
1039 err = gpgme_new (&ctx);
1042 err = gpgme_data_new (&sig);
1046 if (!getenv("GPG_AGENT_INFO")) {
1048 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
1050 gpgme_set_textmode (ctx, 1);
1051 gpgme_set_armor (ctx, 1);
1052 gpgme_signers_clear (ctx);
1053 for (p = key_list; p != NULL; p = p->next) {
1054 err = gpgme_signers_add (ctx, (GpgmeKey) p->data);
1058 for (p = key_list; p != NULL; p = p->next)
1059 gpgme_key_unref ((GpgmeKey) p->data);
1060 g_slist_free (key_list);
1066 clearsign ? GPGME_SIG_MODE_CLEAR : GPGME_SIG_MODE_DETACH);
1068 *r_siginfo = gpgme_get_op_info (ctx, 0);
1072 gpgmegtk_free_passphrase();
1073 debug_print ("signing failed: %s\n", gpgme_strerror (err));
1074 gpgme_data_release (sig);
1078 debug_print ("signing succeeded\n");
1081 gpgme_release (ctx);
1086 * Find TAG in XML and return a pointer into xml set just behind the
1087 * closing angle. Return NULL if not found.
1090 find_xml_tag (const char *xml, const char *tag)
1092 int taglen = strlen (tag);
1093 const char *s = xml;
1095 while ( (s = strchr (s, '<')) ) {
1097 if (!strncmp (s, tag, taglen)) {
1098 const char *s2 = s + taglen;
1099 if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
1101 while (*s2 && *s2 != '>') /* skip attributes */
1103 /* fixme: do need to handle angles inside attribute vallues? */
1104 return *s2? (s2+1):NULL;
1107 while (*s && *s != '>') /* skip to end of tag */
1115 * Extract the micalg from an GnupgOperationInfo XML container.
1118 extract_micalg (char *xml)
1122 s = find_xml_tag (xml, "GnupgOperationInfo");
1124 const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
1125 s = find_xml_tag (s, "signature");
1126 if (s && s_end && s < s_end) {
1127 const char *s_end2 = find_xml_tag (s, "/signature");
1128 if (s_end2 && s_end2 < s_end) {
1129 s = find_xml_tag (s, "micalg");
1130 if (s && s < s_end2) {
1131 s_end = strchr (s, '<');
1133 char *p = g_malloc (s_end - s + 1);
1134 memcpy (p, s, s_end - s);
1147 * Sign the file and replace its content with the signed one.
1150 rfc2015_sign (const char *file, GSList *key_list)
1154 int i, clineidx, saved_last;
1155 char *clines[3] = {NULL};
1157 GpgmeData header = NULL;
1158 GpgmeData plain = NULL;
1159 GpgmeData sigdata = NULL;
1161 int mime_version_seen = 0;
1162 char *boundary = create_boundary ();
1163 char *micalg = NULL;
1166 /* Open the source file */
1167 if ((fp = fopen(file, "rb")) == NULL) {
1168 FILE_OP_ERROR(file, "fopen");
1172 err = gpgme_data_new (&header);
1174 err = gpgme_data_new (&plain);
1176 debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
1180 /* get the content header lines from the source */
1183 while (!err && fgets(buf, sizeof(buf), fp)) {
1184 /* fixme: check for overlong lines */
1185 if (headerp (buf, content_names)) {
1186 if (clineidx >= DIM (clines)) {
1187 debug_print ("rfc2015_sign: too many content lines\n");
1190 clines[clineidx++] = g_strdup (buf);
1196 if (*buf == ' ' || *buf == '\t') {
1197 char *last = clines[clineidx - 1];
1198 clines[clineidx - 1] = g_strconcat (last, buf, NULL);
1204 if (headerp (buf, mime_version_name))
1205 mime_version_seen = 1;
1207 if (buf[0] == '\r' || buf[0] == '\n')
1209 err = gpgme_data_write (header, buf, strlen (buf));
1212 FILE_OP_ERROR (file, "fgets");
1216 /* write them to the temp data and add the rest of the message */
1217 for (i = 0; !err && i < clineidx; i++) {
1218 err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
1221 err = gpgme_data_write (plain, "\r\n", 2 );
1222 while (!err && fgets(buf, sizeof(buf), fp)) {
1223 err = gpgme_data_write (plain, buf, strlen (buf));
1226 FILE_OP_ERROR (file, "fgets");
1230 debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
1234 sigdata = pgp_sign (plain, key_list, FALSE, &siginfo);
1236 micalg = extract_micalg (siginfo);
1242 /* we have the signed message available in sigdata and now we are
1243 * going to rewrite the original file. To be sure that file has
1244 * been truncated we use an approach which should work everywhere:
1245 * close the file and then reopen it for writing. */
1247 FILE_OP_ERROR(file, "fclose");
1250 if ((fp = fopen(file, "wb")) == NULL) {
1251 FILE_OP_ERROR(file, "fopen");
1255 /* Write the rfc822 header and add new content lines */
1256 err = gpgme_data_rewind (header);
1258 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
1259 while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
1260 fwrite (buf, nread, 1, fp);
1262 if (err != GPGME_EOF) {
1263 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1267 FILE_OP_ERROR (file, "fwrite");
1270 gpgme_data_release (header);
1273 if (!mime_version_seen)
1274 fputs ("MIME-Version: 1.0\r\n", fp);
1275 fprintf (fp, "Content-Type: multipart/signed; "
1276 "protocol=\"application/pgp-signature\";\r\n");
1278 fprintf (fp, " micalg=\"%s\";", micalg);
1279 fprintf (fp, " boundary=\"%s\"\r\n", boundary);
1281 /* Part 1: signed material */
1285 err = gpgme_data_rewind (plain);
1287 debug_print ("gpgme_data_rewind on plain failed: %s\n",
1288 gpgme_strerror (err));
1291 while (!(err = gpgme_data_read (plain, buf, BUFFSIZE, &nread))) {
1292 fwrite (buf, nread, 1, fp);
1294 if (err != GPGME_EOF) {
1295 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1299 /* Part 2: signature */
1303 fputs ("Content-Type: application/pgp-signature\r\n"
1306 err = gpgme_data_rewind (sigdata);
1308 debug_print ("gpgme_data_rewind on sigdata failed: %s\n",
1309 gpgme_strerror (err));
1313 while (!(err = gpgme_data_read (sigdata, buf, BUFFSIZE, &nread))) {
1314 fwrite (buf, nread, 1, fp);
1316 if (err != GPGME_EOF) {
1317 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1321 /* Final boundary */
1327 FILE_OP_ERROR (file, "fwrite");
1331 gpgme_data_release (header);
1332 gpgme_data_release (plain);
1333 gpgme_data_release (sigdata);
1341 gpgme_data_release (header);
1342 gpgme_data_release (plain);
1343 gpgme_data_release (sigdata);
1346 return -1; /* error */
1351 * Sign the file with clear text and replace its content with the signed one.
1354 rfc2015_clearsign (const gchar *file, GSList *key_list)
1357 gchar buf[BUFFSIZE];
1359 GpgmeData text = NULL;
1360 GpgmeData sigdata = NULL;
1364 if ((fp = fopen(file, "rb")) == NULL) {
1365 FILE_OP_ERROR(file, "fopen");
1369 err = gpgme_data_new(&text);
1371 debug_print("gpgme_data_new failed: %s\n", gpgme_strerror(err));
1375 while (!err && fgets(buf, sizeof(buf), fp)) {
1376 err = gpgme_data_write(text, buf, strlen(buf));
1379 FILE_OP_ERROR(file, "fgets");
1383 debug_print("gpgme_data_write failed: %s\n", gpgme_strerror(err));
1387 sigdata = pgp_sign(text, key_list, TRUE, &siginfo);
1394 if (fclose(fp) == EOF) {
1395 FILE_OP_ERROR(file, "fclose");
1399 if ((fp = fopen(file, "wb")) == NULL) {
1400 FILE_OP_ERROR(file, "fopen");
1404 err = gpgme_data_rewind(sigdata);
1406 debug_print("gpgme_data_rewind on sigdata failed: %s\n",
1407 gpgme_strerror(err));
1411 while (!(err = gpgme_data_read(sigdata, buf, sizeof(buf), &nread))) {
1412 fwrite(buf, nread, 1, fp);
1414 if (err != GPGME_EOF) {
1415 debug_print("gpgme_data_read failed: %s\n", gpgme_strerror(err));
1419 if (fclose(fp) == EOF) {
1420 FILE_OP_ERROR(file, "fclose");
1424 gpgme_data_release(text);
1425 gpgme_data_release(sigdata);
1431 gpgme_data_release(text);
1432 gpgme_data_release(sigdata);
1438 * Create a new boundary in a way that it is very unlikely that this
1439 * will occur in the following text. It would be easy to ensure
1440 * uniqueness if everything is either quoted-printable or base64
1441 * encoded (note that conversion is allowed), but because MIME bodies
1442 * may be nested, it may happen that the same boundary has already
1443 * been used. We avoid scanning the message for conflicts and hope the
1446 * boundary := 0*69<bchars> bcharsnospace
1447 * bchars := bcharsnospace / " "
1448 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
1449 * "+" / "_" / "," / "-" / "." /
1450 * "/" / ":" / "=" / "?"
1454 create_boundary (void)
1456 static char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1457 "abcdefghijklmnopqrstuvwxyz"
1458 "1234567890'()+_,./:=?";
1465 /* We make the boundary depend on the pid, so that all running
1466 * processed generate different values even when they have been
1467 * started within the same second and srand48(time(NULL)) has been
1468 * used. I can't see whether this is really an advantage but it
1469 * doesn't do any harm.
1472 for(i = 0; i < sizeof(buf) - 1; i++) {
1473 buf[i] = tbl[(lrand48() ^ pid) % (sizeof(tbl) - 1)]; /* fill with random */
1474 if(buf[i] == '=' && equal == -1)
1479 /* now make sure that we do have the sequence "=." in it which cannot
1480 * be matched by quoted-printable or base64 encoding */
1481 if(equal != -1 && (equal+1) < i)
1488 return g_strdup(buf);
1491 #endif /* USE_GPGME */