LLSD.cs 24 KB

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