[PATCH] gpgme-tool: escape special characters in output XML data (<, >, and &).

W. Trevor King wking at tremily.us
Sat Oct 6 16:37:43 CEST 2012


src/gpgme-tool.c (result_xml_escape_replacement, result_xml_escape):
New.
(result_xml_tag_data): Use result_xml_escape() to escape data.
--

This is a general solution for generating valid XML, but the specific
output that inspired the change was from the KEYLIST command:

  <uid>William Trevor King <wking at tremily.us></uid>

Now the uids are properly escaped:

   <uid>William Trevor King &lt;wking at tremily.us&gt;</uid>

Signed-off-by: W. Trevor King <wking at tremily.us>
---
 src/gpgme-tool.c | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 66 insertions(+), 1 deletion(-)

diff --git a/src/gpgme-tool.c b/src/gpgme-tool.c
index d37088c..502b94e 100644
--- a/src/gpgme-tool.c
+++ b/src/gpgme-tool.c
@@ -657,12 +657,71 @@ result_xml_tag_start (struct result_xml_state *state, char *name, ...)
   return 0;
 }
 
+const char *
+result_xml_escape_replacement(char c)
+{
+  switch (c)
+    {
+    case '<':
+      return "&lt;";
+    case '>':
+      return "&gt;";
+    case '&':
+      return "&amp;";
+    default:
+      return NULL;
+    }
+}
+
+gpg_error_t
+result_xml_escape (const char *data, char **buf)
+{
+  int data_len, i, j = 1;
+  const char *r;
+	char *b;
+
+  data_len = strlen (data);
+  for (i = 0; i < data_len; i++)
+    {
+      r = result_xml_escape_replacement(data[i]);
+      if (r)
+        j += strlen (r);
+      else
+        j += 1;
+    }
+
+  b = (char *) malloc (j);
+  if (! b)
+		return gpg_error_from_syserror ();
+
+  j = 0;
+  for (i = 0; i < data_len; i++)
+    {
+      r = result_xml_escape_replacement(data[i]);
+      if (r)
+        {
+          strcpy (b + j, r);
+          j += strlen (r);
+        }
+      else
+        {
+          b[j] = data[i];
+          j += 1;
+        }
+    }
+  b[j] = 0;
+	*buf = b;
+
+  return 0;
+}
 
 gpg_error_t
 result_xml_tag_data (struct result_xml_state *state, const char *data)
 {
+  gpg_error_t err;
   result_xml_write_cb_t cb = state->cb;
   void *hook = state->hook;
+  char *buf = NULL;
 
   if (state->had_data[state->next_tag - 1])
     {
@@ -674,7 +733,13 @@ result_xml_tag_data (struct result_xml_state *state, const char *data)
     (*cb) (hook, ">", 1);
   state->had_data[state->next_tag - 1] = 2;
 
-  (*cb) (hook, data, strlen (data));
+  err = result_xml_escape(data, &buf);
+  if (err)
+    return err;
+
+  (*cb) (hook, buf, strlen (buf));
+
+  free (buf);
 
   return 0;
 }
-- 
1.7.12
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: </pipermail/attachments/20121006/088d03fd/attachment.pgp>


More information about the Gnupg-devel mailing list