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);
67 static void dump_mimeinfo (const char *text, MimeInfo *x)
69 debug_print ("MimeInfo[%s] %p level=%d\n",
70 text, x, x? x->level:0 );
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,
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 );
89 static void dump_part ( MimeInfo *mimeinfo, FILE *fp )
91 unsigned int size = mimeinfo->size;
94 if (fseek (fp, mimeinfo->fpos, SEEK_SET)) {
95 debug_print ("dump_part: fseek error\n");
99 debug_print ("--- begin dump_part ----\n");
100 while (size-- && (c = getc (fp)) != EOF)
103 debug_print ("dump_part: read error\n");
104 debug_print ("--- end dump_part ----\n");
109 rfc2015_disable_all (void)
111 /* FIXME: set a flag, so that we don't bother the user with failed
117 rfc2015_secure_remove (const char *fname)
121 /* fixme: overwrite the file first */
127 sig_status_to_string (GpgmeSigStat status)
132 case GPGME_SIG_STAT_NONE:
133 result = _("Oops: Signature not verified");
135 case GPGME_SIG_STAT_NOSIG:
136 result = _("No signature found");
138 case GPGME_SIG_STAT_GOOD:
139 result = _("Good signature");
141 case GPGME_SIG_STAT_BAD:
142 result = _("BAD signature");
144 case GPGME_SIG_STAT_NOKEY:
145 result = _("No public key to verify the signature");
147 case GPGME_SIG_STAT_ERROR:
148 result = _("Error verifying the signature");
150 case GPGME_SIG_STAT_DIFF:
151 result = _("Different results for signatures");
154 result = _("Error: Unknown status");
162 sig_status_with_name (GpgmeSigStat status)
167 case GPGME_SIG_STAT_NONE:
168 result = _("Oops: Signature not verified");
170 case GPGME_SIG_STAT_NOSIG:
171 result = _("No signature found");
173 case GPGME_SIG_STAT_GOOD:
174 result = _("Good signature from \"%s\"");
176 case GPGME_SIG_STAT_BAD:
177 result = _("BAD signature from \"%s\"");
179 case GPGME_SIG_STAT_NOKEY:
180 result = _("No public key to verify the signature");
182 case GPGME_SIG_STAT_ERROR:
183 result = _("Error verifying the signature");
185 case GPGME_SIG_STAT_DIFF:
186 result = _("Different results for signatures");
189 result = _("Error: Unknown status");
197 sig_status_for_key(GString *str, GpgmeCtx ctx, GpgmeSigStat status,
198 GpgmeKey key, const gchar *fpr)
203 uid = gpgme_key_get_string_attr (key, GPGME_ATTR_USERID, NULL, idx);
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."));
212 g_string_sprintfa (str, sig_status_with_name (status), uid);
213 g_string_append (str, "\n");
216 uid = gpgme_key_get_string_attr (key, GPGME_ATTR_USERID,
220 g_string_sprintfa (str, _(" aka \"%s\"\n"),
226 sig_status_full (GpgmeCtx ctx)
235 struct tm *ctime_val;
239 str = g_string_new ("");
241 fpr = gpgme_get_sig_status (ctx, sig_idx, &status, &created);
242 while (fpr != NULL) {
244 ctime_val = localtime (&created);
245 strftime (ctime_str, sizeof (ctime_str), "%c",
247 g_string_sprintfa (str,
248 _("Signature made at %s\n"),
251 err = gpgme_get_sig_key (ctx, sig_idx, &key);
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"),
260 sig_status_for_key (str, ctx, status, key, fpr);
261 gpgme_key_unref (key);
263 g_string_append (str, "\n\n");
265 fpr = gpgme_get_sig_status (ctx, ++sig_idx, &status, &created);
269 g_string_free (str, FALSE);
273 static void check_signature (MimeInfo *mimeinfo, MimeInfo *partinfo, FILE *fp)
277 GpgmeData sig = NULL, text = NULL;
278 GpgmeSigStat status = GPGME_SIG_STAT_NONE;
279 GpgmegtkSigStatus statuswindow = NULL;
280 const char *result = NULL;
282 gint n_exclude_chars = 0;
284 if (prefs_common.gpg_signature_popup)
285 statuswindow = gpgmegtk_sig_status_create ();
287 err = gpgme_new (&ctx);
289 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
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,
301 if (fgetc(fp) == '\n') {
303 if (mimeinfo->children->size > 1) {
304 if (fseek(fp, mimeinfo->children->fpos + mimeinfo->children->size - 2,
309 if (fgetc(fp) == '\r')
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,
323 if (canonicalize_file_replace(tmp_file) < 0) {
329 err = gpgme_data_new_from_file(&text, tmp_file, 1);
335 err = gpgme_data_new_from_filepart (&sig, NULL, fp,
336 partinfo->fpos, partinfo->size);
338 debug_print ("gpgme_data_new_from_filepart failed: %s\n",
339 gpgme_strerror (err));
343 err = gpgme_op_verify (ctx, sig, text, &status);
345 debug_print ("gpgme_op_verify failed: %s\n", gpgme_strerror (err));
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);
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);
360 g_free (partinfo->sigstatus);
361 partinfo->sigstatus = g_strdup (result);
363 gpgme_data_release (sig);
364 gpgme_data_release (text);
366 if (prefs_common.gpg_signature_popup)
367 gpgmegtk_sig_status_destroy (statuswindow);
371 * Copy a gpgme data object to a temporary file and
372 * return this filename
376 copy_gpgmedata_to_temp (GpgmeData data, guint *length)
385 tmp = g_strdup_printf("%s%cgpgtmp.%08x",
386 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id );
388 if ((fp = fopen(tmp, "wb")) == NULL) {
389 FILE_OP_ERROR(tmp, "fopen");
394 err = gpgme_data_rewind ( data );
396 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
398 while (!(err = gpgme_data_read (data, buf, 100, &nread))) {
399 fwrite ( buf, nread, 1, fp );
402 if (err != GPGME_EOF)
403 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
413 pgp_decrypt (MimeInfo *partinfo, FILE *fp)
417 GpgmeData cipher = NULL, plain = NULL;
418 struct passphrase_cb_info_s info;
420 memset (&info, 0, sizeof info);
422 err = gpgme_new (&ctx);
424 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
428 err = gpgme_data_new_from_filepart (&cipher, NULL, fp,
429 partinfo->fpos, partinfo->size);
431 debug_print ("gpgme_data_new_from_filepart failed: %s\n",
432 gpgme_strerror (err));
436 err = gpgme_data_new (&plain);
438 debug_print ("gpgme_new failed: %s\n", gpgme_strerror (err));
442 if (!getenv("GPG_AGENT_INFO")) {
444 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
447 err = gpgme_op_decrypt (ctx, cipher, plain);
450 gpgme_data_release (cipher);
452 gpgmegtk_free_passphrase();
453 debug_print ("decryption failed: %s\n", gpgme_strerror (err));
454 gpgme_data_release (plain);
458 debug_print ("** decryption succeeded\n");
464 MimeInfo * rfc2015_find_signature (MimeInfo *mimeinfo)
471 if (g_strcasecmp (mimeinfo->content_type, "multipart/signed"))
474 debug_print ("** multipart/signed encountered\n");
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"))
487 gboolean rfc2015_has_signature (MimeInfo *mimeinfo)
489 return rfc2015_find_signature (mimeinfo) != NULL;
492 void rfc2015_check_signature (MimeInfo *mimeinfo, FILE *fp)
496 partinfo = rfc2015_find_signature (mimeinfo);
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);
508 check_signature (mimeinfo, partinfo, fp);
511 int rfc2015_is_encrypted (MimeInfo *mimeinfo)
515 if (g_strcasecmp (mimeinfo->content_type, "multipart/encrypted"))
517 /* fixme: we should check the protocol parameter */
521 gboolean rfc2015_msg_is_encrypted (const gchar *file)
527 if ((fp = fopen(file, "rb")) == NULL)
530 mimeinfo = procmime_scan_mime_header(fp);
536 ret = rfc2015_is_encrypted(mimeinfo);
537 procmime_mimeinfo_free_all(mimeinfo);
538 return ret != 0 ? TRUE : FALSE;
542 name_cmp(const char *a, const char *b)
544 for( ; *a && *b; a++, b++) {
546 && toupper(*(unsigned char *)a) != toupper(*(unsigned char *)b))
554 headerp(char *p, char **names)
563 if(p2[-1] == ' ' || p2[-1] == '\t') {
572 for(i = 0 ; names[i] != NULL; i++) {
573 if(!name_cmp (names[i], p))
578 return names[i] != NULL;
582 #define DECRYPTION_ABORT() \
584 procmime_mimeinfo_free_all(tmpinfo); \
585 msginfo->decryption_failed = 1; \
589 void rfc2015_decrypt_message (MsgInfo *msginfo, MimeInfo *mimeinfo, FILE *fp)
592 MimeInfo *tmpinfo, *partinfo;
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);
606 debug_print ("** decrypting multipart/encrypted message\n");
609 if (fseek(fp, mimeinfo->fpos, SEEK_SET) < 0)
611 tmpinfo = procmime_scan_mime_header(fp);
612 if (!tmpinfo || tmpinfo->mime_type != MIME_MULTIPART) {
616 procmime_scan_multipart_message(tmpinfo, fp);
618 /* check that we have the 2 parts */
619 partinfo = tmpinfo->children;
620 if (!partinfo || !partinfo->next) {
623 if (!g_strcasecmp (partinfo->content_type, "application/pgp-encrypted")) {
624 /* Fixme: check that the version is 1 */
627 partinfo = partinfo->next;
629 !g_strcasecmp (partinfo->content_type, "application/octet-stream")) {
631 g_warning ("oops: pgp_encrypted with more than 2 parts");
637 debug_print ("** yep, it is pgp encrypted\n");
639 plain = pgp_decrypt (partinfo, fp);
644 fname = g_strdup_printf("%s%cplaintext.%08x",
645 get_mime_tmp_dir(), G_DIR_SEPARATOR, ++id);
647 if ((dstfp = fopen(fname, "wb")) == NULL) {
648 FILE_OP_ERROR(fname, "fopen");
653 /* write the orginal header to the new file */
654 if (fseek(fp, tmpinfo->fpos, SEEK_SET) < 0)
657 while (fgets(buf, sizeof(buf), fp)) {
658 if (headerp (buf, content_names))
660 if (buf[0] == '\r' || buf[0] == '\n')
665 err = gpgme_data_rewind (plain);
667 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
669 while (!(err = gpgme_data_read (plain, buf, sizeof(buf), &nread))) {
670 fwrite (buf, nread, 1, dstfp);
673 if (err != GPGME_EOF) {
674 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
678 procmime_mimeinfo_free_all(tmpinfo);
680 msginfo->plaintext_file = fname;
681 msginfo->decryption_failed = 0;
684 #undef DECRYPTION_ABORT
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.
693 pgp_encrypt ( GpgmeData plain, GpgmeRecipients rset )
697 GpgmeData cipher = NULL;
699 err = gpgme_new (&ctx);
701 err = gpgme_data_new (&cipher);
703 gpgme_set_armor (ctx, 1);
704 err = gpgme_op_encrypt (ctx, rset, plain, cipher);
708 debug_print ("encryption failed: %s\n", gpgme_strerror (err));
709 gpgme_data_release (cipher);
713 debug_print ("** encryption succeeded\n");
721 * Create and return a list of keys matching a key id
724 GSList *rfc2015_create_signers_list (const char *keyid)
726 GSList *key_list = NULL;
727 GpgmeCtx list_ctx = NULL;
732 err = gpgme_new (&list_ctx);
735 err = gpgme_op_keylist_start (list_ctx, keyid, 1);
738 while ( !(err = gpgme_op_keylist_next (list_ctx, &key)) ) {
739 key_list = g_slist_append (key_list, key);
741 if (err != GPGME_EOF)
744 if (key_list == NULL) {
745 debug_print ("no keys found for keyid \"%s\"\n", keyid);
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);
756 gpgme_release (list_ctx);
757 return err ? NULL : key_list;
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. */
765 rfc2015_encrypt (const char *file, GSList *recp_list, gboolean ascii_armored)
769 int i, clineidx, saved_last;
770 char *clines[3] = {NULL};
772 GpgmeData header = NULL;
773 GpgmeData plain = NULL;
774 GpgmeData cipher = NULL;
775 GpgmeRecipients rset = NULL;
777 int mime_version_seen = 0;
778 char *boundary = create_boundary ();
780 /* Create the list of recipients */
781 rset = gpgmegtk_recipient_selection (recp_list);
783 debug_print ("error creating recipient list\n" );
787 /* Open the source file */
788 if ((fp = fopen(file, "rb")) == NULL) {
789 FILE_OP_ERROR(file, "fopen");
793 err = gpgme_data_new (&header);
795 err = gpgme_data_new (&plain);
797 debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
801 /* get the content header lines from the source */
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");
811 clines[clineidx++] = g_strdup (buf);
817 if (*buf == ' ' || *buf == '\t') {
818 char *last = clines[clineidx-1];
819 clines[clineidx-1] = g_strconcat (last, buf, NULL);
825 if (headerp (buf, mime_version_name))
826 mime_version_seen = 1;
828 if (buf[0] == '\r' || buf[0] == '\n')
830 err = gpgme_data_write (header, buf, strlen (buf));
833 FILE_OP_ERROR (file, "fgets");
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]));
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));
848 FILE_OP_ERROR (file, "fgets");
852 debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
856 cipher = pgp_encrypt (plain, rset);
857 gpgme_data_release (plain); plain = NULL;
858 gpgme_recipients_release (rset); rset = NULL;
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).
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. */
874 FILE_OP_ERROR(file, "fclose");
877 if ((fp = fopen(file, "wb")) == NULL) {
878 FILE_OP_ERROR(file, "fopen");
882 /* Write the header, append new content lines, part 1 and part 2 header */
883 err = gpgme_data_rewind (header);
885 debug_print ("gpgme_data_rewind failed: %s\n", gpgme_strerror (err));
888 while (!(err = gpgme_data_read (header, buf, BUFFSIZE, &nread))) {
889 fwrite (buf, nread, 1, fp);
891 if (err != GPGME_EOF) {
892 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
896 FILE_OP_ERROR (file, "fwrite");
899 gpgme_data_release (header); header = NULL;
901 if (!mime_version_seen)
902 fputs ("MIME-Version: 1\r\n", fp);
906 "Content-Type: text/plain; charset=US-ASCII\r\n"
907 "Content-Transfer-Encoding: 7bit\r\n"
911 "Content-Type: multipart/encrypted;"
912 " protocol=\"application/pgp-encrypted\";\r\n"
913 " boundary=\"%s\"\r\n"
916 "Content-Type: application/pgp-encrypted\r\n"
921 "Content-Type: application/octet-stream\r\n"
923 boundary, boundary, boundary);
926 /* append the encrypted stuff */
927 err = gpgme_data_rewind (cipher);
929 debug_print ("** gpgme_data_rewind on cipher failed: %s\n",
930 gpgme_strerror (err));
934 while (!(err = gpgme_data_read (cipher, buf, BUFFSIZE, &nread))) {
935 fwrite (buf, nread, 1, fp);
937 if (err != GPGME_EOF) {
938 debug_print ("** gpgme_data_read failed: %s\n", gpgme_strerror (err));
942 /* and the final boundary */
943 if (!ascii_armored) {
951 FILE_OP_ERROR (file, "fwrite");
955 gpgme_data_release (cipher);
961 gpgme_data_release (header);
962 gpgme_data_release (plain);
963 gpgme_data_release (cipher);
964 gpgme_recipients_release (rset);
966 return -1; /* error */
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.
975 pgp_sign (GpgmeData plain, GSList *key_list, gboolean clearsign,
981 GpgmeData sig = NULL;
982 struct passphrase_cb_info_s info;
985 memset (&info, 0, sizeof info);
987 err = gpgme_new (&ctx);
990 err = gpgme_data_new (&sig);
994 if (!getenv("GPG_AGENT_INFO")) {
996 gpgme_set_passphrase_cb (ctx, gpgmegtk_passphrase_cb, &info);
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);
1006 for (p = key_list; p != NULL; p = p->next)
1007 gpgme_key_unref ((GpgmeKey) p->data);
1008 g_slist_free (key_list);
1014 clearsign ? GPGME_SIG_MODE_CLEAR : GPGME_SIG_MODE_DETACH);
1016 *r_siginfo = gpgme_get_op_info (ctx, 0);
1020 gpgmegtk_free_passphrase();
1021 debug_print ("signing failed: %s\n", gpgme_strerror (err));
1022 gpgme_data_release (sig);
1026 debug_print ("signing succeeded\n");
1029 gpgme_release (ctx);
1034 * Find TAG in XML and return a pointer into xml set just behind the
1035 * closing angle. Return NULL if not found.
1038 find_xml_tag (const char *xml, const char *tag)
1040 int taglen = strlen (tag);
1041 const char *s = xml;
1043 while ( (s = strchr (s, '<')) ) {
1045 if (!strncmp (s, tag, taglen)) {
1046 const char *s2 = s + taglen;
1047 if (*s2 == '>' || isspace (*(const unsigned char*)s2) ) {
1049 while (*s2 && *s2 != '>') /* skip attributes */
1051 /* fixme: do need to handle angles inside attribute vallues? */
1052 return *s2? (s2+1):NULL;
1055 while (*s && *s != '>') /* skip to end of tag */
1063 * Extract the micalg from an GnupgOperationInfo XML container.
1066 extract_micalg (char *xml)
1070 s = find_xml_tag (xml, "GnupgOperationInfo");
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, '<');
1081 char *p = g_malloc (s_end - s + 1);
1082 memcpy (p, s, s_end - s);
1095 * Sign the file and replace its content with the signed one.
1098 rfc2015_sign (const char *file, GSList *key_list)
1102 int i, clineidx, saved_last;
1103 char *clines[3] = {NULL};
1105 GpgmeData header = NULL;
1106 GpgmeData plain = NULL;
1107 GpgmeData sigdata = NULL;
1109 int mime_version_seen = 0;
1110 char *boundary = create_boundary ();
1111 char *micalg = NULL;
1114 /* Open the source file */
1115 if ((fp = fopen(file, "rb")) == NULL) {
1116 FILE_OP_ERROR(file, "fopen");
1120 err = gpgme_data_new (&header);
1122 err = gpgme_data_new (&plain);
1124 debug_print ("gpgme_data_new failed: %s\n", gpgme_strerror (err));
1128 /* get the content header lines from the source */
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");
1138 clines[clineidx++] = g_strdup (buf);
1144 if (*buf == ' ' || *buf == '\t') {
1145 char *last = clines[clineidx - 1];
1146 clines[clineidx - 1] = g_strconcat (last, buf, NULL);
1152 if (headerp (buf, mime_version_name))
1153 mime_version_seen = 1;
1155 if (buf[0] == '\r' || buf[0] == '\n')
1157 err = gpgme_data_write (header, buf, strlen (buf));
1160 FILE_OP_ERROR (file, "fgets");
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]));
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));
1174 FILE_OP_ERROR (file, "fgets");
1178 debug_print ("gpgme_data_write failed: %s\n", gpgme_strerror (err));
1182 sigdata = pgp_sign (plain, key_list, FALSE, &siginfo);
1184 micalg = extract_micalg (siginfo);
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. */
1195 FILE_OP_ERROR(file, "fclose");
1198 if ((fp = fopen(file, "wb")) == NULL) {
1199 FILE_OP_ERROR(file, "fopen");
1203 /* Write the rfc822 header and add new content lines */
1204 err = gpgme_data_rewind (header);
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);
1210 if (err != GPGME_EOF) {
1211 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1215 FILE_OP_ERROR (file, "fwrite");
1218 gpgme_data_release (header);
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");
1226 fprintf (fp, " micalg=\"%s\";", micalg);
1227 fprintf (fp, " boundary=\"%s\"\r\n", boundary);
1229 /* Part 1: signed material */
1233 err = gpgme_data_rewind (plain);
1235 debug_print ("gpgme_data_rewind on plain failed: %s\n",
1236 gpgme_strerror (err));
1239 while (!(err = gpgme_data_read (plain, buf, BUFFSIZE, &nread))) {
1240 fwrite (buf, nread, 1, fp);
1242 if (err != GPGME_EOF) {
1243 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1247 /* Part 2: signature */
1251 fputs ("Content-Type: application/pgp-signature\r\n"
1254 err = gpgme_data_rewind (sigdata);
1256 debug_print ("gpgme_data_rewind on sigdata failed: %s\n",
1257 gpgme_strerror (err));
1261 while (!(err = gpgme_data_read (sigdata, buf, BUFFSIZE, &nread))) {
1262 fwrite (buf, nread, 1, fp);
1264 if (err != GPGME_EOF) {
1265 debug_print ("gpgme_data_read failed: %s\n", gpgme_strerror (err));
1269 /* Final boundary */
1275 FILE_OP_ERROR (file, "fwrite");
1279 gpgme_data_release (header);
1280 gpgme_data_release (plain);
1281 gpgme_data_release (sigdata);
1289 gpgme_data_release (header);
1290 gpgme_data_release (plain);
1291 gpgme_data_release (sigdata);
1294 return -1; /* error */
1299 * Sign the file with clear text and replace its content with the signed one.
1302 rfc2015_clearsign (const gchar *file, GSList *key_list)
1305 gchar buf[BUFFSIZE];
1307 GpgmeData text = NULL;
1308 GpgmeData sigdata = NULL;
1312 if ((fp = fopen(file, "rb")) == NULL) {
1313 FILE_OP_ERROR(file, "fopen");
1317 err = gpgme_data_new(&text);
1319 debug_print("gpgme_data_new failed: %s\n", gpgme_strerror(err));
1323 while (!err && fgets(buf, sizeof(buf), fp)) {
1324 err = gpgme_data_write(text, buf, strlen(buf));
1327 FILE_OP_ERROR(file, "fgets");
1331 debug_print("gpgme_data_write failed: %s\n", gpgme_strerror(err));
1335 sigdata = pgp_sign(text, key_list, TRUE, &siginfo);
1342 if (fclose(fp) == EOF) {
1343 FILE_OP_ERROR(file, "fclose");
1347 if ((fp = fopen(file, "wb")) == NULL) {
1348 FILE_OP_ERROR(file, "fopen");
1352 err = gpgme_data_rewind(sigdata);
1354 debug_print("gpgme_data_rewind on sigdata failed: %s\n",
1355 gpgme_strerror(err));
1359 while (!(err = gpgme_data_read(sigdata, buf, sizeof(buf), &nread))) {
1360 fwrite(buf, nread, 1, fp);
1362 if (err != GPGME_EOF) {
1363 debug_print("gpgme_data_read failed: %s\n", gpgme_strerror(err));
1367 if (fclose(fp) == EOF) {
1368 FILE_OP_ERROR(file, "fclose");
1372 gpgme_data_release(text);
1373 gpgme_data_release(sigdata);
1379 gpgme_data_release(text);
1380 gpgme_data_release(sigdata);
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
1394 * boundary := 0*69<bchars> bcharsnospace
1395 * bchars := bcharsnospace / " "
1396 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
1397 * "+" / "_" / "," / "-" / "." /
1398 * "/" / ":" / "=" / "?"
1402 create_boundary (void)
1404 static char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1405 "abcdefghijklmnopqrstuvwxyz"
1406 "1234567890'()+_,./:=?";
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.
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)
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)
1436 return g_strdup(buf);
1439 #endif /* USE_GPGME */