LLSD.cs 24 KB

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