1
0

LLSD.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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;
  29. using System.Globalization;
  30. using System.IO;
  31. using System.Security.Cryptography;
  32. using System.Text;
  33. using System.Xml;
  34. using OpenMetaverse;
  35. namespace OpenSim.Framework.Capabilities
  36. {
  37. /// <summary>
  38. /// Borrowed from (a older version of) libsl for now, as their new llsd code doesn't work we our decoding code.
  39. /// </summary>
  40. public static class LLSD
  41. {
  42. /// <summary>
  43. ///
  44. /// </summary>
  45. public class LLSDParseException : Exception
  46. {
  47. public LLSDParseException(string message) : base(message)
  48. {
  49. }
  50. }
  51. /// <summary>
  52. ///
  53. /// </summary>
  54. public class LLSDSerializeException : Exception
  55. {
  56. public LLSDSerializeException(string message) : base(message)
  57. {
  58. }
  59. }
  60. /// <summary>
  61. ///
  62. /// </summary>
  63. /// <param name="b"></param>
  64. /// <returns></returns>
  65. public static object LLSDDeserialize(byte[] b)
  66. {
  67. using (MemoryStream ms = new MemoryStream(b, false))
  68. {
  69. return LLSDDeserialize(ms);
  70. }
  71. }
  72. /// <summary>
  73. ///
  74. /// </summary>
  75. /// <param name="st"></param>
  76. /// <returns></returns>
  77. public static object LLSDDeserialize(Stream st)
  78. {
  79. using (XmlTextReader reader = new XmlTextReader(st))
  80. {
  81. reader.ProhibitDtd = true;
  82. reader.Read();
  83. SkipWS(reader);
  84. if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "llsd")
  85. throw new LLSDParseException("Expected <llsd>");
  86. reader.Read();
  87. object ret = LLSDParseOne(reader);
  88. SkipWS(reader);
  89. if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "llsd")
  90. throw new LLSDParseException("Expected </llsd>");
  91. return ret;
  92. }
  93. }
  94. /// <summary>
  95. ///
  96. /// </summary>
  97. /// <param name="obj"></param>
  98. /// <returns></returns>
  99. public static byte[] LLSDSerialize(object obj)
  100. {
  101. StringWriter sw = new StringWriter();
  102. XmlTextWriter writer = new XmlTextWriter(sw);
  103. writer.Formatting = Formatting.None;
  104. writer.WriteStartElement(String.Empty, "llsd", String.Empty);
  105. LLSDWriteOne(writer, obj);
  106. writer.WriteEndElement();
  107. writer.Close();
  108. return Util.UTF8.GetBytes(sw.ToString());
  109. }
  110. /// <summary>
  111. ///
  112. /// </summary>
  113. /// <param name="writer"></param>
  114. /// <param name="obj"></param>
  115. public static void LLSDWriteOne(XmlTextWriter writer, object obj)
  116. {
  117. if (obj == null)
  118. {
  119. writer.WriteStartElement(String.Empty, "undef", String.Empty);
  120. writer.WriteEndElement();
  121. return;
  122. }
  123. if (obj is string)
  124. {
  125. writer.WriteStartElement(String.Empty, "string", String.Empty);
  126. writer.WriteString((string) obj);
  127. writer.WriteEndElement();
  128. }
  129. else if (obj is int)
  130. {
  131. writer.WriteStartElement(String.Empty, "integer", String.Empty);
  132. writer.WriteString(obj.ToString());
  133. writer.WriteEndElement();
  134. }
  135. else if (obj is double)
  136. {
  137. writer.WriteStartElement(String.Empty, "real", String.Empty);
  138. writer.WriteString(obj.ToString());
  139. writer.WriteEndElement();
  140. }
  141. else if (obj is bool)
  142. {
  143. bool b = (bool) obj;
  144. writer.WriteStartElement(String.Empty, "boolean", String.Empty);
  145. writer.WriteString(b ? "1" : "0");
  146. writer.WriteEndElement();
  147. }
  148. else if (obj is ulong)
  149. {
  150. throw new Exception("ulong in LLSD is currently not implemented, fix me!");
  151. }
  152. else if (obj is UUID)
  153. {
  154. UUID u = (UUID) obj;
  155. writer.WriteStartElement(String.Empty, "uuid", String.Empty);
  156. writer.WriteString(u.ToString());
  157. writer.WriteEndElement();
  158. }
  159. else if (obj is Hashtable)
  160. {
  161. Hashtable h = obj as Hashtable;
  162. writer.WriteStartElement(String.Empty, "map", String.Empty);
  163. foreach (string key in h.Keys)
  164. {
  165. writer.WriteStartElement(String.Empty, "key", String.Empty);
  166. writer.WriteString(key);
  167. writer.WriteEndElement();
  168. LLSDWriteOne(writer, h[key]);
  169. }
  170. writer.WriteEndElement();
  171. }
  172. else if (obj is ArrayList)
  173. {
  174. ArrayList a = obj as ArrayList;
  175. writer.WriteStartElement(String.Empty, "array", String.Empty);
  176. foreach (object item in a)
  177. {
  178. LLSDWriteOne(writer, item);
  179. }
  180. writer.WriteEndElement();
  181. }
  182. else if (obj is byte[])
  183. {
  184. byte[] b = obj as byte[];
  185. writer.WriteStartElement(String.Empty, "binary", String.Empty);
  186. writer.WriteStartAttribute(String.Empty, "encoding", String.Empty);
  187. writer.WriteString("base64");
  188. writer.WriteEndAttribute();
  189. //// Calculate the length of the base64 output
  190. //long length = (long)(4.0d * b.Length / 3.0d);
  191. //if (length % 4 != 0) length += 4 - (length % 4);
  192. //// Create the char[] for base64 output and fill it
  193. //char[] tmp = new char[length];
  194. //int i = Convert.ToBase64CharArray(b, 0, b.Length, tmp, 0);
  195. //writer.WriteString(new String(tmp));
  196. writer.WriteString(Convert.ToBase64String(b));
  197. writer.WriteEndElement();
  198. }
  199. else
  200. {
  201. throw new LLSDSerializeException("Unknown type " + obj.GetType().Name);
  202. }
  203. }
  204. /// <summary>
  205. ///
  206. /// </summary>
  207. /// <param name="reader"></param>
  208. /// <returns></returns>
  209. public static object LLSDParseOne(XmlTextReader reader)
  210. {
  211. SkipWS(reader);
  212. if (reader.NodeType != XmlNodeType.Element)
  213. throw new LLSDParseException("Expected an element");
  214. string dtype = reader.LocalName;
  215. object ret = null;
  216. switch (dtype)
  217. {
  218. case "undef":
  219. {
  220. if (reader.IsEmptyElement)
  221. {
  222. reader.Read();
  223. return null;
  224. }
  225. reader.Read();
  226. SkipWS(reader);
  227. ret = null;
  228. break;
  229. }
  230. case "boolean":
  231. {
  232. if (reader.IsEmptyElement)
  233. {
  234. reader.Read();
  235. return false;
  236. }
  237. reader.Read();
  238. string s = reader.ReadString().Trim();
  239. if (s == String.Empty || s == "false" || s == "0")
  240. ret = false;
  241. else if (s == "true" || s == "1")
  242. ret = true;
  243. else
  244. throw new LLSDParseException("Bad boolean value " + s);
  245. break;
  246. }
  247. case "integer":
  248. {
  249. if (reader.IsEmptyElement)
  250. {
  251. reader.Read();
  252. return 0;
  253. }
  254. reader.Read();
  255. ret = Convert.ToInt32(reader.ReadString().Trim());
  256. break;
  257. }
  258. case "real":
  259. {
  260. if (reader.IsEmptyElement)
  261. {
  262. reader.Read();
  263. return 0.0f;
  264. }
  265. reader.Read();
  266. ret = Convert.ToDouble(reader.ReadString().Trim());
  267. break;
  268. }
  269. case "uuid":
  270. {
  271. if (reader.IsEmptyElement)
  272. {
  273. reader.Read();
  274. return UUID.Zero;
  275. }
  276. reader.Read();
  277. ret = new UUID(reader.ReadString().Trim());
  278. break;
  279. }
  280. case "string":
  281. {
  282. if (reader.IsEmptyElement)
  283. {
  284. reader.Read();
  285. return String.Empty;
  286. }
  287. reader.Read();
  288. ret = reader.ReadString();
  289. break;
  290. }
  291. case "binary":
  292. {
  293. if (reader.IsEmptyElement)
  294. {
  295. reader.Read();
  296. return new byte[0];
  297. }
  298. if (reader.GetAttribute("encoding") != null &&
  299. reader.GetAttribute("encoding") != "base64")
  300. {
  301. throw new LLSDParseException("Unknown encoding: " + reader.GetAttribute("encoding"));
  302. }
  303. reader.Read();
  304. FromBase64Transform b64 = new FromBase64Transform(FromBase64TransformMode.IgnoreWhiteSpaces);
  305. byte[] inp = Util.UTF8.GetBytes(reader.ReadString());
  306. ret = b64.TransformFinalBlock(inp, 0, inp.Length);
  307. break;
  308. }
  309. case "date":
  310. {
  311. reader.Read();
  312. throw new Exception("LLSD TODO: date");
  313. }
  314. case "map":
  315. {
  316. return LLSDParseMap(reader);
  317. }
  318. case "array":
  319. {
  320. return LLSDParseArray(reader);
  321. }
  322. default:
  323. throw new LLSDParseException("Unknown element <" + dtype + ">");
  324. }
  325. if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != dtype)
  326. {
  327. throw new LLSDParseException("Expected </" + dtype + ">");
  328. }
  329. reader.Read();
  330. return ret;
  331. }
  332. /// <summary>
  333. ///
  334. /// </summary>
  335. /// <param name="reader"></param>
  336. /// <returns></returns>
  337. public static Hashtable LLSDParseMap(XmlTextReader reader)
  338. {
  339. Hashtable ret = new Hashtable();
  340. if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map")
  341. throw new LLSDParseException("Expected <map>");
  342. if (reader.IsEmptyElement)
  343. {
  344. reader.Read();
  345. return ret;
  346. }
  347. reader.Read();
  348. while (true)
  349. {
  350. SkipWS(reader);
  351. if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map")
  352. {
  353. reader.Read();
  354. break;
  355. }
  356. if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key")
  357. throw new LLSDParseException("Expected <key>");
  358. string key = reader.ReadString();
  359. if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key")
  360. throw new LLSDParseException("Expected </key>");
  361. reader.Read();
  362. object val = LLSDParseOne(reader);
  363. ret[key] = val;
  364. }
  365. return ret; // TODO
  366. }
  367. /// <summary>
  368. ///
  369. /// </summary>
  370. /// <param name="reader"></param>
  371. /// <returns></returns>
  372. public static ArrayList LLSDParseArray(XmlTextReader reader)
  373. {
  374. ArrayList ret = new ArrayList();
  375. if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array")
  376. throw new LLSDParseException("Expected <array>");
  377. if (reader.IsEmptyElement)
  378. {
  379. reader.Read();
  380. return ret;
  381. }
  382. reader.Read();
  383. while (true)
  384. {
  385. SkipWS(reader);
  386. if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array")
  387. {
  388. reader.Read();
  389. break;
  390. }
  391. ret.Insert(ret.Count, LLSDParseOne(reader));
  392. }
  393. return ret; // TODO
  394. }
  395. /// <summary>
  396. ///
  397. /// </summary>
  398. /// <param name="count"></param>
  399. /// <returns></returns>
  400. private static string GetSpaces(int count)
  401. {
  402. StringBuilder b = new StringBuilder();
  403. for (int i = 0; i < count; i++) b.Append(" ");
  404. return b.ToString();
  405. }
  406. /// <summary>
  407. ///
  408. /// </summary>
  409. /// <param name="obj"></param>
  410. /// <param name="indent"></param>
  411. /// <returns></returns>
  412. public static String LLSDDump(object obj, int indent)
  413. {
  414. if (obj == null)
  415. {
  416. return GetSpaces(indent) + "- undef\n";
  417. }
  418. else if (obj is string)
  419. {
  420. return GetSpaces(indent) + "- string \"" + (string) obj + "\"\n";
  421. }
  422. else if (obj is int)
  423. {
  424. return GetSpaces(indent) + "- integer " + obj.ToString() + "\n";
  425. }
  426. else if (obj is double)
  427. {
  428. return GetSpaces(indent) + "- float " + obj.ToString() + "\n";
  429. }
  430. else if (obj is UUID)
  431. {
  432. return GetSpaces(indent) + "- uuid " + ((UUID) obj).ToString() + Environment.NewLine;
  433. }
  434. else if (obj is Hashtable)
  435. {
  436. StringBuilder ret = new StringBuilder();
  437. ret.Append(GetSpaces(indent) + "- map" + Environment.NewLine);
  438. Hashtable map = (Hashtable) obj;
  439. foreach (string key in map.Keys)
  440. {
  441. ret.Append(GetSpaces(indent + 2) + "- key \"" + key + "\"" + Environment.NewLine);
  442. ret.Append(LLSDDump(map[key], indent + 3));
  443. }
  444. return ret.ToString();
  445. }
  446. else if (obj is ArrayList)
  447. {
  448. StringBuilder ret = new StringBuilder();
  449. ret.Append(GetSpaces(indent) + "- array\n");
  450. ArrayList list = (ArrayList) obj;
  451. foreach (object item in list)
  452. {
  453. ret.Append(LLSDDump(item, indent + 2));
  454. }
  455. return ret.ToString();
  456. }
  457. else if (obj is byte[])
  458. {
  459. return GetSpaces(indent) + "- binary\n" + Utils.BytesToHexString((byte[]) obj, GetSpaces(indent)) +
  460. Environment.NewLine;
  461. }
  462. else
  463. {
  464. return GetSpaces(indent) + "- unknown type " + obj.GetType().Name + Environment.NewLine;
  465. }
  466. }
  467. public static object ParseTerseLLSD(string llsd)
  468. {
  469. int notused;
  470. return ParseTerseLLSD(llsd, out notused);
  471. }
  472. public static object ParseTerseLLSD(string llsd, out int endPos)
  473. {
  474. if (llsd.Length == 0)
  475. {
  476. endPos = 0;
  477. return null;
  478. }
  479. // Identify what type of object this is
  480. switch (llsd[0])
  481. {
  482. case '!':
  483. throw new LLSDParseException("Undefined value type encountered");
  484. case '1':
  485. endPos = 1;
  486. return true;
  487. case '0':
  488. endPos = 1;
  489. return false;
  490. case 'i':
  491. {
  492. if (llsd.Length < 2) throw new LLSDParseException("Integer value type with no value");
  493. int value;
  494. endPos = FindEnd(llsd, 1);
  495. if (Int32.TryParse(llsd.Substring(1, endPos - 1), out value))
  496. return value;
  497. else
  498. throw new LLSDParseException("Failed to parse integer value type");
  499. }
  500. case 'r':
  501. {
  502. if (llsd.Length < 2) throw new LLSDParseException("Real value type with no value");
  503. double value;
  504. endPos = FindEnd(llsd, 1);
  505. if (Double.TryParse(llsd.Substring(1, endPos - 1), NumberStyles.Float,
  506. Culture.NumberFormatInfo, out value))
  507. return value;
  508. else
  509. throw new LLSDParseException("Failed to parse double value type");
  510. }
  511. case 'u':
  512. {
  513. if (llsd.Length < 17) throw new LLSDParseException("UUID value type with no value");
  514. UUID value;
  515. endPos = FindEnd(llsd, 1);
  516. if (UUID.TryParse(llsd.Substring(1, endPos - 1), out value))
  517. return value;
  518. else
  519. throw new LLSDParseException("Failed to parse UUID value type");
  520. }
  521. case 'b':
  522. //byte[] value = new byte[llsd.Length - 1];
  523. // This isn't the actual binary LLSD format, just the terse format sent
  524. // at login so I don't even know if there is a binary type
  525. throw new LLSDParseException("Binary value type is unimplemented");
  526. case 's':
  527. case 'l':
  528. if (llsd.Length < 2) throw new LLSDParseException("String value type with no value");
  529. endPos = FindEnd(llsd, 1);
  530. return llsd.Substring(1, endPos - 1);
  531. case 'd':
  532. // Never seen one before, don't know what the format is
  533. throw new LLSDParseException("Date value type is unimplemented");
  534. case '[':
  535. {
  536. if (llsd.IndexOf(']') == -1) throw new LLSDParseException("Invalid array");
  537. int pos = 0;
  538. ArrayList array = new ArrayList();
  539. while (llsd[pos] != ']')
  540. {
  541. ++pos;
  542. // Advance past comma if need be
  543. if (llsd[pos] == ',') ++pos;
  544. // Allow a single whitespace character
  545. if (pos < llsd.Length && llsd[pos] == ' ') ++pos;
  546. int end;
  547. array.Add(ParseTerseLLSD(llsd.Substring(pos), out end));
  548. pos += end;
  549. }
  550. endPos = pos + 1;
  551. return array;
  552. }
  553. case '{':
  554. {
  555. if (llsd.IndexOf('}') == -1) throw new LLSDParseException("Invalid map");
  556. int pos = 0;
  557. Hashtable hashtable = new Hashtable();
  558. while (llsd[pos] != '}')
  559. {
  560. ++pos;
  561. // Advance past comma if need be
  562. if (llsd[pos] == ',') ++pos;
  563. // Allow a single whitespace character
  564. if (pos < llsd.Length && llsd[pos] == ' ') ++pos;
  565. if (llsd[pos] != '\'') throw new LLSDParseException("Expected a map key");
  566. int endquote = llsd.IndexOf('\'', pos + 1);
  567. if (endquote == -1 || (endquote + 1) >= llsd.Length || llsd[endquote + 1] != ':')
  568. throw new LLSDParseException("Invalid map format");
  569. string key = llsd.Substring(pos, endquote - pos);
  570. key = key.Replace("'", String.Empty);
  571. pos += (endquote - pos) + 2;
  572. int end;
  573. hashtable.Add(key, ParseTerseLLSD(llsd.Substring(pos), out end));
  574. pos += end;
  575. }
  576. endPos = pos + 1;
  577. return hashtable;
  578. }
  579. default:
  580. throw new Exception("Unknown value type");
  581. }
  582. }
  583. private static int FindEnd(string llsd, int start)
  584. {
  585. int end = llsd.IndexOfAny(new char[] {',', ']', '}'});
  586. if (end == -1) end = llsd.Length - 1;
  587. return end;
  588. }
  589. /// <summary>
  590. ///
  591. /// </summary>
  592. /// <param name="reader"></param>
  593. private static void SkipWS(XmlTextReader reader)
  594. {
  595. while (
  596. reader.NodeType == XmlNodeType.Comment ||
  597. reader.NodeType == XmlNodeType.Whitespace ||
  598. reader.NodeType == XmlNodeType.SignificantWhitespace ||
  599. reader.NodeType == XmlNodeType.XmlDeclaration)
  600. {
  601. reader.Read();
  602. }
  603. }
  604. }
  605. }