1
0

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