update_engine: Check XmlEncode() input strings.

XmlEncode() only supports valid UTF-8 string. Incomplete UTF-8 strings
would make it crash.

This patch limits the input string to ASCII-7 and falls back to a
default string value whenever an invalid one is found. Some of these
values come from the stateful partition, which would make the
update_engine fail forever.

BUG=chromium:471925
TEST=Added unittests.

Change-Id: I01c5da1b44462a0fe1eb703106a9d0dd3051100b
Reviewed-on: https://chromium-review.googlesource.com/263154
Reviewed-by: Alex Deymo <deymo@chromium.org>
Commit-Queue: Alex Deymo <deymo@chromium.org>
Tested-by: Alex Deymo <deymo@chromium.org>
diff --git a/omaha_request_action_unittest.cc b/omaha_request_action_unittest.cc
index 8a2090c..7ea513b 100644
--- a/omaha_request_action_unittest.cc
+++ b/omaha_request_action_unittest.cc
@@ -978,11 +978,27 @@
 }
 
 TEST_F(OmahaRequestActionTest, XmlEncodeTest) {
-  EXPECT_EQ("ab", XmlEncode("ab"));
-  EXPECT_EQ("a&lt;b", XmlEncode("a<b"));
-  EXPECT_EQ("&lt;&amp;&gt;", XmlEncode("<&>"));
-  EXPECT_EQ("&amp;lt;&amp;amp;&amp;gt;", XmlEncode("&lt;&amp;&gt;"));
+  string output;
+  EXPECT_TRUE(XmlEncode("ab", &output));
+  EXPECT_EQ("ab", output);
+  EXPECT_TRUE(XmlEncode("a<b", &output));
+  EXPECT_EQ("a&lt;b", output);
+  EXPECT_TRUE(XmlEncode("<&>", &output));
+  EXPECT_EQ("&lt;&amp;&gt;", output);
+  EXPECT_TRUE(XmlEncode("&lt;&amp;&gt;", &output));
+  EXPECT_EQ("&amp;lt;&amp;amp;&amp;gt;", output);
+  // g_markup_escape_text() would crash with unterminated UTF-8 strings.
+  EXPECT_FALSE(XmlEncode("\xc2", &output));
+  // Fail with invalid ASCII-7 chars.
+  EXPECT_FALSE(XmlEncode("This is an 'n' with a tilde: \xc3\xb1", &output));
+}
 
+TEST_F(OmahaRequestActionTest, XmlEncodeWithDefaultTest) {
+  EXPECT_EQ("&lt;&amp;&gt;", XmlEncodeWithDefault("<&>", "something else"));
+  EXPECT_EQ("<not escaped>", XmlEncodeWithDefault("\xc2", "<not escaped>"));
+}
+
+TEST_F(OmahaRequestActionTest, XmlEncodeIsUsedForParams) {
   chromeos::Blob post_data;
 
   // Make sure XML Encode is being called on the params