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