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);
415 partinfo->sig_unknown = (status == GPGME_SIG_STAT_NOKEY);
416 partinfo->sig_expired = (status == GPGME_SIG_STAT_GOOD_EXP);
417 partinfo->key_expired = (status == GPGME_SIG_STAT_GOOD_EXPKEY);
419 gpgme_data_release (sig);
420 gpgme_data_release (text);
422 if (prefs_common.gpg_signature_popup)
423 gpgmegtk_sig_status_destroy (statuswindow);
427 * Copy a gpgme data object to a temporary file and
428 * return this filename
432 copy_gpgmedata_to_temp (GpgmeData data, guint *length)
441 tmp = g_strdup_printf("%s%cgpgtmp.%08x",
442 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id );
444 if ((fp = fopen(tmp, "wb")) == NULL) {
445 FILE_OP_ERROR(tmp, "fopen");
450 err = gpgme_data_rewind ( data );
452 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
454 while (!(err = gpgme_data_read (data, buf, 100, &nread))) {
455 fwrite ( buf, nread, 1, fp );
458 if (err != GPGME_EOF)
459 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
469 pgp_decrypt (MimeInfo *partinfo, FILE *fp)
473 GpgmeData cipher = NULL, plain = NULL;
474 struct passphrase_cb_info_s info;
476 memset (&info, 0, sizeof info);
478 err = gpgme_new (&ctx);
480 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
484 err = gpgme_data_new_from_filepart (&cipher, NULL, fp,
485 partinfo->fpos, partinfo->size);
487 debug_print ("gpgme_data_new_from_filepart failed: %s\n",
488 gpgme_strerror (err));
492 err = gpgme_data_new (&plain);
494 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
498 if (!getenv("GPG_AGENT_INFO")) {
500 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
503 err = gpgme_op_decrypt (ctx, cipher, plain);
506 gpgme_data_release (cipher);
508 gpgmegtk_free_passphrase();
509 debug_print ("decryption failed: %s\n", gpgme_strerror (err));
510 gpgme_data_release (plain);
514 debug_print ("** decryption succeeded\n");
520 MimeInfo * rfc2015_find_signature (MimeInfo *mimeinfo)
527 if (g_strcasecmp (mimeinfo->content_type, "multipart/signed"))
530 debug_print ("** multipart/signed encountered\n");
532 /* check that we have at least 2 parts of the correct type */
533 for (partinfo = mimeinfo->children;
534 partinfo != NULL; partinfo = partinfo->next) {
535 if (++n > 1 && !g_strcasecmp (partinfo->content_type,
536 "application/pgp-signature"))
543 gboolean rfc2015_has_signature (MimeInfo *mimeinfo)
545 return rfc2015_find_signature (mimeinfo) != NULL;
548 void rfc2015_check_signature (MimeInfo *mimeinfo, FILE *fp)
552 partinfo = rfc2015_find_signature (mimeinfo);
557 g_message ("** yep, it is a pgp signature");
558 dump_mimeinfo ("gpg-signature", partinfo );
559 dump_part (partinfo, fp );
560 dump_mimeinfo ("signed text", mimeinfo->children );
561 dump_part (mimeinfo->children, fp);
564 check_signature (mimeinfo, partinfo, fp);
567 int rfc2015_is_encrypted (MimeInfo *mimeinfo)
569 if (!mimeinfo || mimeinfo->mime_type != MIME_MULTIPART)
571 if (g_strcasecmp (mimeinfo->content_type, "multipart/encrypted"))
573 /* fixme: we should check the protocol parameter */
577 gboolean rfc2015_msg_is_encrypted (const gchar *file)
583 if ((fp = fopen(file, "rb")) == NULL)
586 mimeinfo = procmime_scan_mime_header(fp);
592 ret = rfc2015_is_encrypted(mimeinfo);
593 procmime_mimeinfo_free_all(mimeinfo);
594 return ret != 0 ? TRUE : FALSE;
598 name_cmp(const char *a, const char *b)
600 for( ; *a && *b; a++, b++) {
602 && toupper(*(unsigned char *)a) != toupper(*(unsigned char *)b))
610 headerp(char *p, char **names)
619 if(p2[-1] == ' ' || p2[-1] == '\t') {
628 for(i = 0 ; names[i] != NULL; i++) {
629 if(!name_cmp (names[i], p))
634 return names[i] != NULL;
638 #define DECRYPTION_ABORT() \
640 procmime_mimeinfo_free_all(tmpinfo); \
641 msginfo->decryption_failed = 1; \
645 void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
648 MimeInfo *tmpinfo, *partinfo;
657 g_return_if_fail (msginfo != NULL);
658 g_return_if_fail (mimeinfo != NULL);
659 g_return_if_fail (fp != NULL);
660 g_return_if_fail (mimeinfo->mime_type == MIME_MULTIPART);
662 debug_print ("** decrypting multipart/encrypted message\n");
665 if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
667 tmpinfo = procmime_scan_mime_header(fp);
668 if (!tmpinfo || tmpinfo->mime_type != MIME_MULTIPART) {
672 procmime_scan_multipart_message(tmpinfo, fp);
674 /* check that we have the 2 parts */
675 partinfo = tmpinfo->children;
676 if (!partinfo || !partinfo->next) {
679 if (!g_strcasecmp (partinfo->content_type, "application/pgp-encrypted")) {
680 /* Fixme: check that the version is 1 */
683 partinfo = partinfo->next;
685 !g_strcasecmp (partinfo->content_type, "application/octet-stream")) {
687 g_warning ("oops: pgp_encrypted with more than 2 parts");
693 debug_print ("** yep, it is pgp encrypted\n");
695 plain = pgp_decrypt (partinfo, fp);
700 fname = g_strdup_printf("%s%cplaintext.%08x",
701 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
703 if ((dstfp = fopen(fname, "wb")) == NULL) {
704 FILE_OP_ERROR(fname, "fopen");
709 /* write the orginal header to the new file */
710 if (fseek(fp, tmpinfo->fpos, SEEK_SET) < 0)
713 while (fgets(buf, sizeof(buf), fp)) {
714 if (headerp (buf, content_names))
716 if (buf[0] == '\r' || buf[0] == '\n')
721 err = gpgme_data_rewind (plain);
723 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
725 while (!(err = gpgme_data_read (plain, buf, sizeof(buf), &nread))) {
726 fwrite (buf, nread, 1, dstfp);
729 if (err != GPGME_EOF) {
730 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
734 procmime_mimeinfo_free_all(tmpinfo);
736 msginfo->plaintext_file = fname;
737 msginfo->decryption_failed = 0;
740 #undef DECRYPTION_ABORT
744 * plain contains an entire mime object.
745 * Encrypt it and return an GpgmeData object with the encrypted version of
746 * the file or NULL in case of error.
749 pgp_encrypt ( GpgmeData plain, GpgmeRecipients rset )
753 GpgmeData cipher = NULL;
755 err = gpgme_new (&ctx);
757 err = gpgme_data_new (&cipher);
759 gpgme_set_armor (ctx, 1);
760 err = gpgme_op_encrypt (ctx, rset, plain, cipher);
764 debug_print ("encryption failed: %s\n", gpgme_strerror (err));
765 gpgme_data_release (cipher);
769 debug_print ("** encryption succeeded\n");
777 * Create and return a list of keys matching a key id
780 GSList *rfc2015_create_signers_list (const char *keyid)
782 GSList *key_list = NULL;
783 GpgmeCtx list_ctx = NULL;
788 err = gpgme_new (&list_ctx);
791 err = gpgme_op_keylist_start (list_ctx, keyid, 1);
794 while ( !(err = gpgme_op_keylist_next (list_ctx, &key)) ) {
795 key_list = g_slist_append (key_list, key);
797 if (err != GPGME_EOF)
800 if (key_list == NULL) {
801 debug_print ("no keys found for keyid \"%s\"\n", keyid);
806 debug_print ("rfc2015_create_signers_list failed: %s\n", gpgme_strerror (err));
807 for (p = key_list; p != NULL; p = p->next)
808 gpgme_key_unref ((GpgmeKey) p->data);
809 g_slist_free (key_list);
812 gpgme_release (list_ctx);
813 return err ? NULL : key_list;
817 * Encrypt the file by extracting all recipients and finding the
818 * encryption keys for all of them. The file content is then replaced
819 * by the encrypted one. */
821 rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
825 int i, clineidx, saved_last;
826 char *clines[3] = {NULL};
828 GpgmeData header = NULL;
829 GpgmeData plain = NULL;
830 GpgmeData cipher = NULL;
831 GpgmeRecipients rset = NULL;
833 int mime_version_seen = 0;
834 char *boundary = create_boundary ();
836 /* Create the list of recipients */
837 rset = gpgmegtk_recipient_selection (recp_list);
839 debug_print ("error creating recipient list\n" );
843 /* Open the source file */
844 if ((fp = fopen(file, "rb")) == NULL) {
845 FILE_OP_ERROR(file, "fopen");
849 err = gpgme_data_new (&header);
851 err = gpgme_data_new (&plain);
853 debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
857 /* get the content header lines from the source */
860 while (!err && fgets(buf, sizeof(buf), fp)) {
861 /* fixme: check for overlong lines */
862 if (headerp (buf, content_names)) {
863 if (clineidx >= DIM (clines)) {
864 debug_print ("rfc2015_encrypt: too many content lines\n");
867 clines[clineidx++] = g_strdup (buf);
873 if (*buf == ' ' || *buf == '\t') {
874 char *last = clines[clineidx-1];
875 clines[clineidx-1] = g_strconcat (last, buf, NULL);
881 if (headerp (buf, mime_version_name))
882 mime_version_seen = 1;
884 if (buf[0] == '\r' || buf[0] == '\n')
886 err = gpgme_data_write (header, buf, strlen (buf));
889 FILE_OP_ERROR (file, "fgets");
893 /* write them to the temp data and add the rest of the message */
894 for (i = 0; !err && i < clineidx; i++) {
895 debug_print ("%% %s:%d: cline=`%s'", __FILE__ ,__LINE__, clines[i]);
896 err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
899 err = gpgme_data_write (plain, "\r\n", 2);
900 while (!err && fgets(buf, sizeof(buf), fp)) {
901 err = gpgme_data_write (plain, buf, strlen (buf));
904 FILE_OP_ERROR (file, "fgets");
908 debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
912 cipher = pgp_encrypt (plain, rset);
913 gpgme_data_release (plain); plain = NULL;
914 gpgme_recipients_release (rset); rset = NULL;
918 /* we have the encrypted message available in cipher and now we
919 * are going to rewrite the source file. To be sure that file has
920 * been truncated we use an approach which should work everywhere:
921 * close the file and then reopen it for writing. It is important
922 * that this works, otherwise it may happen that parts of the
923 * plaintext are still in the file (The encrypted stuff is, due to
924 * compression, usually shorter than the plaintext).
926 * Yes, there is a race condition here, but everyone, who is so
927 * stupid to store the temp file with the plaintext in a public
928 * directory has to live with this anyway. */
930 FILE_OP_ERROR(file, "fclose");
933 if ((fp = fopen(file, "wb")) == NULL) {
934 FILE_OP_ERROR(file, "fopen");
938 /* Write the header, append new content lines, part 1 and part 2 header */
939 err = gpgme_data_rewind (header);
941 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
944 while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
945 fwrite (buf, nread, 1, fp);
947 if (err != GPGME_EOF) {
948 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
952 FILE_OP_ERROR (file, "fwrite");
955 gpgme_data_release (header); header = NULL;
957 if (!mime_version_seen)
958 fputs ("MIME-Version: 1\r\n", fp);
962 "Content-Type: text/plain; charset=US-ASCII\r\n"
963 "Content-Transfer-Encoding: 7bit\r\n"
967 "Content-Type: multipart/encrypted;"
968 " protocol=\"application/pgp-encrypted\";\r\n"
969 " boundary=\"%s\"\r\n"
972 "Content-Type: application/pgp-encrypted\r\n"
977 "Content-Type: application/octet-stream\r\n"
979 boundary, boundary, boundary);
982 /* append the encrypted stuff */
983 err = gpgme_data_rewind (cipher);
985 debug_print ("** gpgme_data_rewind on cipher failed: %s\n",
986 gpgme_strerror (err));
990 while (!(err = gpgme_data_read (cipher, buf, BUFFSIZE, &nread))) {
991 fwrite (buf, nread, 1, fp);
993 if (err != GPGME_EOF) {
994 debug_print ("** gpgme_data_read failed: %s\n", gpgme_strerror (err));
998 /* and the final boundary */
999 if (!ascii_armored) {
1007 FILE_OP_ERROR (file, "fwrite");
1011 gpgme_data_release (cipher);
1017 gpgme_data_release (header);
1018 gpgme_data_release (plain);
1019 gpgme_data_release (cipher);
1020 gpgme_recipients_release (rset);
1022 return -1; /* error */
1026 * plain contains an entire mime object. Sign it and return an
1027 * GpgmeData object with the signature of it or NULL in case of error.
1028 * r_siginfo returns an XML object with information about the signature.
1031 pgp_sign (GpgmeData plain, GSList *key_list, gboolean clearsign,
1035 GpgmeCtx ctx = NULL;
1037 GpgmeData sig = NULL;
1038 struct passphrase_cb_info_s info;
1041 memset (&info, 0, sizeof info);
1043 err = gpgme_new (&ctx);
1046 err = gpgme_data_new (&sig);
1050 if (!getenv("GPG_AGENT_INFO")) {
1052 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
1054 gpgme_set_textmode (ctx, 1);
1055 gpgme_set_armor (ctx, 1);
1056 gpgme_signers_clear (ctx);
1057 for (p = key_list; p != NULL; p = p->next) {
1058 err = gpgme_signers_add (ctx, (GpgmeKey) p->data);
1062 for (p = key_list; p != NULL; p = p->next)
1063 gpgme_key_unref ((GpgmeKey) p->data);
1064 g_slist_free (key_list);
1070 clearsign ? GPGME_SIG_MODE_CLEAR : GPGME_SIG_MODE_DETACH);
1072 *r_siginfo = gpgme_get_op_info (ctx, 0);
1076 gpgmegtk_free_passphrase();
1077 debug_print ("signing failed: %s\n", gpgme_strerror (err));
1078 gpgme_data_release (sig);
1082 debug_print ("signing succeeded\n");
1085 gpgme_release (ctx);
1090 * Find TAG in XML and return a pointer into xml set just behind the
1091 * closing angle. Return NULL if not found.
1094 find_xml_tag (const char *xml, const char *tag)
1096 int taglen = strlen (tag);
1097 const char *s = xml;
1099 while ( (s = strchr (s, '<')) ) {
1101 if (!strncmp (s, tag, taglen)) {
1102 const char *s2 = s + taglen;
1103 if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
1105 while (*s2 && *s2 != '>') /* skip attributes */
1107 /* fixme: do need to handle angles inside attribute vallues? */
1108 return *s2? (s2+1):NULL;
1111 while (*s && *s != '>') /* skip to end of tag */
1119 * Extract the micalg from an GnupgOperationInfo XML container.
1122 extract_micalg (char *xml)
1126 s = find_xml_tag (xml, "GnupgOperationInfo");
1128 const char *s_end = find_xml_tag (s, "/GnupgOperationInfo");
1129 s = find_xml_tag (s, "signature");
1130 if (s && s_end && s < s_end) {
1131 const char *s_end2 = find_xml_tag (s, "/signature");
1132 if (s_end2 && s_end2 < s_end) {
1133 s = find_xml_tag (s, "micalg");
1134 if (s && s < s_end2) {
1135 s_end = strchr (s, '<');
1137 char *p = g_malloc (s_end - s + 1);
1138 memcpy (p, s, s_end - s);
1151 * Sign the file and replace its content with the signed one.
1154 rfc2015_sign (const char *file, GSList *key_list)
1158 int i, clineidx, saved_last;
1159 char *clines[3] = {NULL};
1161 GpgmeData header = NULL;
1162 GpgmeData plain = NULL;
1163 GpgmeData sigdata = NULL;
1165 int mime_version_seen = 0;
1166 char *boundary = create_boundary ();
1167 char *micalg = NULL;
1170 /* Open the source file */
1171 if ((fp = fopen(file, "rb")) == NULL) {
1172 FILE_OP_ERROR(file, "fopen");
1176 err = gpgme_data_new (&header);
1178 err = gpgme_data_new (&plain);
1180 debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
1184 /* get the content header lines from the source */
1187 while (!err && fgets(buf, sizeof(buf), fp)) {
1188 /* fixme: check for overlong lines */
1189 if (headerp (buf, content_names)) {
1190 if (clineidx >= DIM (clines)) {
1191 debug_print ("rfc2015_sign: too many content lines\n");
1194 clines[clineidx++] = g_strdup (buf);
1200 if (*buf == ' ' || *buf == '\t') {
1201 char *last = clines[clineidx - 1];
1202 clines[clineidx - 1] = g_strconcat (last, buf, NULL);
1208 if (headerp (buf, mime_version_name))
1209 mime_version_seen = 1;
1211 if (buf[0] == '\r' || buf[0] == '\n')
1213 err = gpgme_data_write (header, buf, strlen (buf));
1216 FILE_OP_ERROR (file, "fgets");
1220 /* write them to the temp data and add the rest of the message */
1221 for (i = 0; !err && i < clineidx; i++) {
1222 err = gpgme_data_write (plain, clines[i], strlen (clines[i]));
1225 err = gpgme_data_write (plain, "\r\n", 2 );
1226 while (!err && fgets(buf, sizeof(buf), fp)) {
1227 err = gpgme_data_write (plain, buf, strlen (buf));
1230 FILE_OP_ERROR (file, "fgets");
1234 debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
1238 sigdata = pgp_sign (plain, key_list, FALSE, &siginfo);
1240 micalg = extract_micalg (siginfo);
1246 /* we have the signed message available in sigdata and now we are
1247 * going to rewrite the original file. To be sure that file has
1248 * been truncated we use an approach which should work everywhere:
1249 * close the file and then reopen it for writing. */
1251 FILE_OP_ERROR(file, "fclose");
1254 if ((fp = fopen(file, "wb")) == NULL) {
1255 FILE_OP_ERROR(file, "fopen");
1259 /* Write the rfc822 header and add new content lines */
1260 err = gpgme_data_rewind (header);
1262 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
1263 while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
1264 fwrite (buf, nread, 1, fp);
1266 if (err != GPGME_EOF) {
1267 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1271 FILE_OP_ERROR (file, "fwrite");
1274 gpgme_data_release (header);
1277 if (!mime_version_seen)
1278 fputs ("MIME-Version: 1.0\r\n", fp);
1279 fprintf (fp, "Content-Type: multipart/signed; "
1280 "protocol=\"application/pgp-signature\";\r\n");
1282 fprintf (fp, " micalg=\"%s\";", micalg);
1283 fprintf (fp, " boundary=\"%s\"\r\n", boundary);
1285 /* Part 1: signed material */
1289 err = gpgme_data_rewind (plain);
1291 debug_print ("gpgme_data_rewind on plain failed: %s\n",
1292 gpgme_strerror (err));
1295 while (!(err = gpgme_data_read (plain, buf, BUFFSIZE, &nread))) {
1296 fwrite (buf, nread, 1, fp);
1298 if (err != GPGME_EOF) {
1299 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1303 /* Part 2: signature */
1307 fputs ("Content-Type: application/pgp-signature\r\n"
1310 err = gpgme_data_rewind (sigdata);
1312 debug_print ("gpgme_data_rewind on sigdata failed: %s\n",
1313 gpgme_strerror (err));
1317 while (!(err = gpgme_data_read (sigdata, buf, BUFFSIZE, &nread))) {
1318 fwrite (buf, nread, 1, fp);
1320 if (err != GPGME_EOF) {
1321 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1325 /* Final boundary */
1331 FILE_OP_ERROR (file, "fwrite");
1335 gpgme_data_release (header);
1336 gpgme_data_release (plain);
1337 gpgme_data_release (sigdata);
1345 gpgme_data_release (header);
1346 gpgme_data_release (plain);
1347 gpgme_data_release (sigdata);
1350 return -1; /* error */
1355 * Sign the file with clear text and replace its content with the signed one.
1358 rfc2015_clearsign (const gchar *file, GSList *key_list)
1361 gchar buf[BUFFSIZE];
1363 GpgmeData text = NULL;
1364 GpgmeData sigdata = NULL;
1368 if ((fp = fopen(file, "rb")) == NULL) {
1369 FILE_OP_ERROR(file, "fopen");
1373 err = gpgme_data_new(&text);
1375 debug_print("gpgme_data_new failed: %s\n", gpgme_strerror(err));
1379 while (!err && fgets(buf, sizeof(buf), fp)) {
1380 err = gpgme_data_write(text, buf, strlen(buf));
1383 FILE_OP_ERROR(file, "fgets");
1387 debug_print("gpgme_data_write failed: %s\n", gpgme_strerror(err));
1391 sigdata = pgp_sign(text, key_list, TRUE, &siginfo);
1398 if (fclose(fp) == EOF) {
1399 FILE_OP_ERROR(file, "fclose");
1403 if ((fp = fopen(file, "wb")) == NULL) {
1404 FILE_OP_ERROR(file, "fopen");
1408 err = gpgme_data_rewind(sigdata);
1410 debug_print("gpgme_data_rewind on sigdata failed: %s\n",
1411 gpgme_strerror(err));
1415 while (!(err = gpgme_data_read(sigdata, buf, sizeof(buf), &nread))) {
1416 fwrite(buf, nread, 1, fp);
1418 if (err != GPGME_EOF) {
1419 debug_print("gpgme_data_read failed: %s\n", gpgme_strerror(err));
1423 if (fclose(fp) == EOF) {
1424 FILE_OP_ERROR(file, "fclose");
1428 gpgme_data_release(text);
1429 gpgme_data_release(sigdata);
1435 gpgme_data_release(text);
1436 gpgme_data_release(sigdata);
1442 * Create a new boundary in a way that it is very unlikely that this
1443 * will occur in the following text. It would be easy to ensure
1444 * uniqueness if everything is either quoted-printable or base64
1445 * encoded (note that conversion is allowed), but because MIME bodies
1446 * may be nested, it may happen that the same boundary has already
1447 * been used. We avoid scanning the message for conflicts and hope the
1450 * boundary := 0*69<bchars> bcharsnospace
1451 * bchars := bcharsnospace / " "
1452 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
1453 * "+" / "_" / "," / "-" / "." /
1454 * "/" / ":" / "=" / "?"
1458 create_boundary (void)
1460 static char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1461 "abcdefghijklmnopqrstuvwxyz"
1462 "1234567890'()+_,./:=?";
1469 /* We make the boundary depend on the pid, so that all running
1470 * processed generate different values even when they have been
1471 * started within the same second and srand48(time(NULL)) has been
1472 * used. I can't see whether this is really an advantage but it
1473 * doesn't do any harm.
1476 for(i = 0; i < sizeof(buf) - 1; i++) {
1477 buf[i] = tbl[(lrand48() ^ pid) % (sizeof(tbl) - 1)]; /* fill with random */
1478 if(buf[i] == '=' && equal == -1)
1483 /* now make sure that we do have the sequence "=." in it which cannot
1484 * be matched by quoted-printable or base64 encoding */
1485 if(equal != -1 && (equal+1) < i)
1492 return g_strdup(buf);
1495 #endif /* USE_GPGME */