ExternalRepresentationUtils.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Collections.Frozen;
  30. using System.Diagnostics;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Text;
  34. using System.Xml;
  35. using log4net;
  36. using OpenMetaverse;
  37. using OpenSim.Services.Interfaces;
  38. namespace OpenSim.Framework.Serialization.External
  39. {
  40. /// <summary>
  41. /// Utilities for manipulating external representations of data structures in OpenSim
  42. /// </summary>
  43. public class ExternalRepresentationUtils
  44. {
  45. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  46. /// <summary>
  47. /// Populate a node with data read from xml using a dictinoary of processors
  48. /// </summary>
  49. /// <param name="nodeToFill"></param>
  50. /// <param name="processors"></param>
  51. /// <param name="xtr"></param>
  52. /// <returns>true on successful, false if there were any processing failures</returns>
  53. public static bool ExecuteReadProcessors<NodeType>(
  54. NodeType nodeToFill, FrozenDictionary<string, Action<NodeType, XmlReader>> processors, XmlReader xtr)
  55. {
  56. return ExecuteReadProcessors(
  57. nodeToFill,
  58. processors,
  59. xtr,
  60. (o, nodeName, e) => {
  61. m_log.Debug(string.Format("[ExternalRepresentationUtils]: Error while parsing element {0} ",
  62. nodeName), e);
  63. });
  64. }
  65. /// <summary>
  66. /// Populate a node with data read from xml using a dictinoary of processors
  67. /// </summary>
  68. /// <param name="nodeToFill"></param>
  69. /// <param name="processors"></param>
  70. /// <param name="xtr"></param>
  71. /// <param name="parseExceptionAction">
  72. /// Action to take if there is a parsing problem. This will usually just be to log the exception
  73. /// </param>
  74. /// <returns>true on successful, false if there were any processing failures</returns>
  75. public static bool ExecuteReadProcessors<NodeType>(
  76. NodeType nodeToFill,
  77. FrozenDictionary<string, Action<NodeType, XmlReader>> processors,
  78. XmlReader xtr,
  79. Action<NodeType, string, Exception> parseExceptionAction)
  80. {
  81. bool errors = false;
  82. int numErrors = 0;
  83. Stopwatch timer = new Stopwatch();
  84. timer.Start();
  85. string nodeName = string.Empty;
  86. while (xtr.NodeType != XmlNodeType.EndElement)
  87. {
  88. nodeName = xtr.Name;
  89. // m_log.DebugFormat("[ExternalRepresentationUtils]: Processing node: {0}", nodeName);
  90. Action<NodeType, XmlReader> p = null;
  91. if (processors.TryGetValue(xtr.Name, out p))
  92. {
  93. // m_log.DebugFormat("[ExternalRepresentationUtils]: Found processor for {0}", nodeName);
  94. try
  95. {
  96. p(nodeToFill, xtr);
  97. }
  98. catch (Exception e)
  99. {
  100. errors = true;
  101. parseExceptionAction(nodeToFill, nodeName, e);
  102. if (xtr.EOF)
  103. {
  104. m_log.Debug("[ExternalRepresentationUtils]: Aborting ExecuteReadProcessors due to unexpected end of XML");
  105. break;
  106. }
  107. if (++numErrors == 10)
  108. {
  109. m_log.Debug("[ExternalRepresentationUtils]: Aborting ExecuteReadProcessors due to too many parsing errors");
  110. break;
  111. }
  112. if (xtr.NodeType == XmlNodeType.EndElement)
  113. xtr.Read();
  114. }
  115. }
  116. else
  117. {
  118. // m_log.DebugFormat("[ExternalRepresentationUtils]: found unknown element \"{0}\"", nodeName);
  119. xtr.ReadOuterXml(); // ignore
  120. }
  121. if (timer.Elapsed.TotalSeconds >= 60)
  122. {
  123. m_log.Debug("[ExternalRepresentationUtils]: Aborting ExecuteReadProcessors due to timeout");
  124. errors = true;
  125. break;
  126. }
  127. }
  128. return errors;
  129. }
  130. /// <summary>
  131. /// Takes a XML representation of a SceneObjectPart and returns another XML representation
  132. /// with creator data added to it.
  133. /// </summary>
  134. /// <param name="xml">The SceneObjectPart represented in XML2</param>
  135. /// <param name="homeURL">The URL of the user agents service (home) for the creator</param>
  136. /// <param name="userService">The service for retrieving user account information</param>
  137. /// <param name="scopeID">The scope of the user account information (Grid ID)</param>
  138. /// <returns>The SceneObjectPart represented in XML2</returns>
  139. [Obsolete("This method is deprecated. Use RewriteSOP instead.")]
  140. public static string RewriteSOP_Old(string xml, string homeURL, IUserAccountService userService, UUID scopeID)
  141. {
  142. if (xml.Length == 0 || homeURL.Length == 0 || userService == null)
  143. return xml;
  144. XmlDocument doc = new XmlDocument();
  145. doc.LoadXml(xml);
  146. XmlNodeList sops = doc.GetElementsByTagName("SceneObjectPart");
  147. foreach (XmlNode sop in sops)
  148. {
  149. UserAccount creator = null;
  150. bool hasCreatorData = false;
  151. XmlNodeList nodes = sop.ChildNodes;
  152. foreach (XmlNode node in nodes)
  153. {
  154. if (node.Name == "CreatorID")
  155. {
  156. UUID uuid = UUID.Zero;
  157. UUID.TryParse(node.InnerText, out uuid);
  158. creator = userService.GetUserAccount(scopeID, uuid);
  159. }
  160. if (node.Name == "CreatorData" && node.InnerText != null && node.InnerText != string.Empty)
  161. hasCreatorData = true;
  162. //if (node.Name == "OwnerID")
  163. //{
  164. // UserAccount owner = GetUser(node.InnerText);
  165. // if (owner != null)
  166. // node.InnerText = m_ProfileServiceURL + "/" + node.InnerText + "/" + owner.FirstName + " " + owner.LastName;
  167. //}
  168. }
  169. if (!hasCreatorData && creator != null)
  170. {
  171. XmlElement creatorData = doc.CreateElement("CreatorData");
  172. creatorData.InnerText = CalcCreatorData(homeURL, creator.FirstName + " " + creator.LastName);
  173. sop.AppendChild(creatorData);
  174. }
  175. }
  176. using (StringWriter wr = new StringWriter())
  177. {
  178. doc.Save(wr);
  179. return wr.ToString();
  180. }
  181. }
  182. /// <summary>
  183. /// Takes a XML representation of a SceneObjectPart and returns another XML representation
  184. /// with creator data added to it.
  185. /// </summary>
  186. /// <param name="xml">The SceneObjectPart represented in XML2</param>
  187. /// <param name="sceneName">An identifier for the component that's calling this function</param>
  188. /// <param name="homeURL">The URL of the user agents service (home) for the creator</param>
  189. /// <param name="userService">The service for retrieving user account information</param>
  190. /// <param name="scopeID">The scope of the user account information (Grid ID)</param>
  191. /// <returns>The SceneObjectPart represented in XML2</returns>
  192. public static string RewriteSOP(string xmlData, string sceneName, string homeURL, IUserAccountService userService, UUID scopeID)
  193. {
  194. // Console.WriteLine("Input XML [{0}]", xmlData);
  195. if (xmlData.Length == 0 || homeURL.Length == 0 || userService == null)
  196. return xmlData;
  197. // Deal with bug introduced in Oct. 20 2014 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  198. // Fix bad assets before sending them elsewhere
  199. xmlData = SanitizeXml(xmlData);
  200. using (StringWriter sw = new StringWriter())
  201. using (XmlTextWriter writer = new XmlTextWriter(sw))
  202. using (XmlTextReader wrappedReader = new XmlTextReader(xmlData, XmlNodeType.Element, null))
  203. using (XmlReader reader = XmlReader.Create(wrappedReader, Util.SharedXmlReaderSettings))
  204. {
  205. TransformXml(reader, writer, sceneName, homeURL, userService, scopeID);
  206. // Console.WriteLine("Output: [{0}]", sw.ToString());
  207. return sw.ToString();
  208. }
  209. }
  210. protected static void TransformXml(XmlReader reader, XmlWriter writer, string sceneName, string homeURI, IUserAccountService userAccountService, UUID scopeID)
  211. {
  212. // m_log.DebugFormat("[HG ASSET MAPPER]: Transforming XML");
  213. int sopDepth = -1;
  214. UserAccount creator = null;
  215. bool hasCreatorData = false;
  216. while (reader.Read())
  217. {
  218. // Console.WriteLine("Depth: {0}, name {1}", reader.Depth, reader.Name);
  219. switch (reader.NodeType)
  220. {
  221. case XmlNodeType.Attribute:
  222. // Console.WriteLine("FOUND ATTRIBUTE {0}", reader.Name);
  223. writer.WriteAttributeString(reader.Name, reader.Value);
  224. break;
  225. case XmlNodeType.CDATA:
  226. writer.WriteCData(reader.Value);
  227. break;
  228. case XmlNodeType.Comment:
  229. writer.WriteComment(reader.Value);
  230. break;
  231. case XmlNodeType.DocumentType:
  232. writer.WriteDocType(reader.Name, reader.Value, null, null);
  233. break;
  234. case XmlNodeType.Element:
  235. // m_log.DebugFormat("Depth {0} at element {1}", reader.Depth, reader.Name);
  236. writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  237. if (reader.HasAttributes)
  238. {
  239. while (reader.MoveToNextAttribute())
  240. writer.WriteAttributeString(reader.Name, reader.Value);
  241. reader.MoveToElement();
  242. }
  243. if (reader.LocalName == "SceneObjectPart")
  244. {
  245. if (sopDepth < 0)
  246. {
  247. sopDepth = reader.Depth;
  248. // m_log.DebugFormat("[HG ASSET MAPPER]: Set sopDepth to {0}", sopDepth);
  249. }
  250. }
  251. else
  252. {
  253. if (sopDepth >= 0 && reader.Depth == sopDepth + 1)
  254. {
  255. if (reader.Name == "CreatorID")
  256. {
  257. reader.Read();
  258. if (reader.NodeType == XmlNodeType.Element && reader.Name == "Guid" || reader.Name == "UUID")
  259. {
  260. reader.Read();
  261. if (reader.NodeType == XmlNodeType.Text)
  262. {
  263. UUID uuid = UUID.Zero;
  264. UUID.TryParse(reader.Value, out uuid);
  265. creator = userAccountService.GetUserAccount(scopeID, uuid);
  266. writer.WriteElementString("UUID", reader.Value);
  267. reader.Read();
  268. }
  269. else
  270. {
  271. // If we unexpected run across mixed content in this node, still carry on
  272. // transforming the subtree (this replicates earlier behaviour).
  273. TransformXml(reader, writer, sceneName, homeURI, userAccountService, scopeID);
  274. }
  275. }
  276. else
  277. {
  278. // If we unexpected run across mixed content in this node, still carry on
  279. // transforming the subtree (this replicates earlier behaviour).
  280. TransformXml(reader, writer, sceneName, homeURI, userAccountService, scopeID);
  281. }
  282. }
  283. else if (reader.Name == "CreatorData")
  284. {
  285. reader.Read();
  286. if (reader.NodeType == XmlNodeType.Text)
  287. {
  288. hasCreatorData = true;
  289. writer.WriteString(reader.Value);
  290. }
  291. else
  292. {
  293. // If we unexpected run across mixed content in this node, still carry on
  294. // transforming the subtree (this replicates earlier behaviour).
  295. TransformXml(reader, writer, sceneName, homeURI, userAccountService, scopeID);
  296. }
  297. }
  298. }
  299. }
  300. if (reader.IsEmptyElement)
  301. {
  302. // m_log.DebugFormat("[HG ASSET MAPPER]: Writing end for empty element {0}", reader.Name);
  303. writer.WriteEndElement();
  304. }
  305. break;
  306. case XmlNodeType.EndElement:
  307. // m_log.DebugFormat("Depth {0} at EndElement", reader.Depth);
  308. if (sopDepth == reader.Depth)
  309. {
  310. if (!hasCreatorData && creator != null)
  311. writer.WriteElementString(reader.Prefix, "CreatorData", reader.NamespaceURI, string.Format("{0};{1} {2}", homeURI, creator.FirstName, creator.LastName));
  312. // m_log.DebugFormat("[HG ASSET MAPPER]: Reset sopDepth");
  313. sopDepth = -1;
  314. creator = null;
  315. hasCreatorData = false;
  316. }
  317. writer.WriteEndElement();
  318. break;
  319. case XmlNodeType.EntityReference:
  320. writer.WriteEntityRef(reader.Name);
  321. break;
  322. case XmlNodeType.ProcessingInstruction:
  323. writer.WriteProcessingInstruction(reader.Name, reader.Value);
  324. break;
  325. case XmlNodeType.Text:
  326. writer.WriteString(reader.Value);
  327. break;
  328. case XmlNodeType.XmlDeclaration:
  329. // For various reasons, not all serializations have xml declarations (or consistent ones)
  330. // and as it's embedded inside a byte stream we don't need it anyway, so ignore.
  331. break;
  332. default:
  333. m_log.WarnFormat(
  334. "[HG ASSET MAPPER]: Unrecognized node {0} in asset XML transform in {1}",
  335. reader.NodeType, sceneName);
  336. break;
  337. }
  338. }
  339. }
  340. public static string CalcCreatorData(string homeURL, string name)
  341. {
  342. return homeURL + ";" + name;
  343. }
  344. internal static string CalcCreatorData(string homeURL, UUID uuid, string name)
  345. {
  346. return homeURL + "/" + uuid + ";" + name;
  347. }
  348. /// <summary>
  349. /// Sanitation for bug introduced in Oct. 20 2014 (1eb3e6cc43e2a7b4053bc1185c7c88e22356c5e8)
  350. /// </summary>
  351. /// <param name="xmlData"></param>
  352. /// <returns></returns>
  353. public static string SanitizeXml(string xmlData)
  354. {
  355. if (!string.IsNullOrWhiteSpace(xmlData))
  356. {
  357. int indx = xmlData.IndexOf("xmlns:xmlns:");
  358. if(indx > 0)
  359. {
  360. int indx2 = indx + 12;
  361. while(xmlData[indx2 + 5] == ':')
  362. indx2 += 6;
  363. string bad = xmlData.Substring(indx, indx2 - indx);
  364. xmlData = xmlData.Replace(bad, "xmlns:");
  365. }
  366. }
  367. return xmlData;
  368. }
  369. }
  370. }