Util.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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.Data;
  29. using System.Globalization;
  30. using System.IO;
  31. using System.IO.Compression;
  32. using System.Net;
  33. using System.Net.Sockets;
  34. using System.Reflection;
  35. using System.Runtime.Serialization;
  36. using System.Runtime.Serialization.Formatters.Binary;
  37. using System.Security.Cryptography;
  38. using System.Text;
  39. using System.Text.RegularExpressions;
  40. using System.Xml;
  41. using log4net;
  42. using Nini.Config;
  43. using Nwc.XmlRpc;
  44. using OpenMetaverse;
  45. namespace OpenSim.Framework
  46. {
  47. /// <summary>
  48. /// Miscellaneous utility functions
  49. /// </summary>
  50. public class Util
  51. {
  52. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  53. private static uint nextXferID = 5000;
  54. private static Random randomClass = new Random();
  55. // Get a list of invalid file characters (OS dependent)
  56. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  57. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  58. private static object XferLock = new object();
  59. // Unix-epoch starts at January 1st 1970, 00:00:00 UTC. And all our times in the server are (or at least should be) in UTC.
  60. private static readonly DateTime unixEpoch =
  61. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  62. public static readonly Regex UUIDPattern
  63. = new Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
  64. #region Vector Equations
  65. /// <summary>
  66. /// Get the distance between two 3d vectors
  67. /// </summary>
  68. /// <param name="a">A 3d vector</param>
  69. /// <param name="b">A 3d vector</param>
  70. /// <returns>The distance between the two vectors</returns>
  71. public static double GetDistanceTo(Vector3 a, Vector3 b)
  72. {
  73. float dx = a.X - b.X;
  74. float dy = a.Y - b.Y;
  75. float dz = a.Z - b.Z;
  76. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  77. }
  78. /// <summary>
  79. /// Get the magnitude of a 3d vector
  80. /// </summary>
  81. /// <param name="a">A 3d vector</param>
  82. /// <returns>The magnitude of the vector</returns>
  83. public static double GetMagnitude(Vector3 a)
  84. {
  85. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  86. }
  87. /// <summary>
  88. /// Get a normalized form of a 3d vector
  89. /// </summary>
  90. /// <param name="a">A 3d vector</param>
  91. /// <returns>A new vector which is normalized form of the vector</returns>
  92. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  93. public static Vector3 GetNormalizedVector(Vector3 a)
  94. {
  95. if (IsZeroVector(a))
  96. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  97. float Mag = (float) GetMagnitude(a);
  98. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  99. }
  100. /// <summary>
  101. /// Returns if a vector is a zero vector (has all zero components)
  102. /// </summary>
  103. /// <returns></returns>
  104. public static bool IsZeroVector(Vector3 v)
  105. {
  106. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  107. {
  108. return true;
  109. }
  110. return false;
  111. }
  112. # endregion
  113. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  114. {
  115. float s;
  116. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  117. if (tr >= 1.0)
  118. {
  119. s = (float) (0.5 / Math.Sqrt(tr));
  120. return new Quaternion(
  121. (left.Z - up.Y) * s,
  122. (up.X - fwd.Z) * s,
  123. (fwd.Y - left.X) * s,
  124. (float) 0.25 / s);
  125. }
  126. else
  127. {
  128. float max = (left.Y > up.Z) ? left.Y : up.Z;
  129. if (max < fwd.X)
  130. {
  131. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  132. float x = (float) (s * 0.5);
  133. s = (float) (0.5 / s);
  134. return new Quaternion(
  135. x,
  136. (fwd.Y + left.X) * s,
  137. (up.X + fwd.Z) * s,
  138. (left.Z - up.Y) * s);
  139. }
  140. else if (max == left.Y)
  141. {
  142. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  143. float y = (float) (s * 0.5);
  144. s = (float) (0.5 / s);
  145. return new Quaternion(
  146. (fwd.Y + left.X) * s,
  147. y,
  148. (left.Z + up.Y) * s,
  149. (up.X - fwd.Z) * s);
  150. }
  151. else
  152. {
  153. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  154. float z = (float) (s * 0.5);
  155. s = (float) (0.5 / s);
  156. return new Quaternion(
  157. (up.X + fwd.Z) * s,
  158. (left.Z + up.Y) * s,
  159. z,
  160. (fwd.Y - left.X) * s);
  161. }
  162. }
  163. }
  164. public static Random RandomClass
  165. {
  166. get { return randomClass; }
  167. }
  168. public static ulong UIntsToLong(uint X, uint Y)
  169. {
  170. return Utils.UIntsToLong(X, Y);
  171. }
  172. public static T Clamp<T>(T x, T min, T max)
  173. where T : System.IComparable<T>
  174. {
  175. return x.CompareTo(max) > 0 ? max :
  176. x.CompareTo(min) < 0 ? min :
  177. x;
  178. }
  179. public static uint GetNextXferID()
  180. {
  181. uint id = 0;
  182. lock (XferLock)
  183. {
  184. id = nextXferID;
  185. nextXferID++;
  186. }
  187. return id;
  188. }
  189. public static string GetFileName(string file)
  190. {
  191. // Return just the filename on UNIX platforms
  192. // TODO: this should be customisable with a prefix, but that's something to do later.
  193. if (Environment.OSVersion.Platform == PlatformID.Unix)
  194. {
  195. return file;
  196. }
  197. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  198. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  199. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  200. {
  201. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  202. {
  203. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  204. }
  205. return "%APPDATA%\\OpenSim\\" + file;
  206. }
  207. // Catch all - covers older windows versions
  208. // (but those probably wont work anyway)
  209. return file;
  210. }
  211. /// <summary>
  212. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  213. ///
  214. /// Please don't delete me even if I appear currently unused!
  215. /// </summary>
  216. /// <param name="rawXml"></param>
  217. /// <returns></returns>
  218. public static string GetFormattedXml(string rawXml)
  219. {
  220. XmlDocument xd = new XmlDocument();
  221. xd.LoadXml(rawXml);
  222. StringBuilder sb = new StringBuilder();
  223. StringWriter sw = new StringWriter(sb);
  224. XmlTextWriter xtw = new XmlTextWriter(sw);
  225. xtw.Formatting = Formatting.Indented;
  226. try
  227. {
  228. xd.WriteTo(xtw);
  229. }
  230. finally
  231. {
  232. xtw.Close();
  233. }
  234. return sb.ToString();
  235. }
  236. public static bool IsEnvironmentSupported(ref string reason)
  237. {
  238. // Must have .NET 2.0 (Generics / libsl)
  239. if (Environment.Version.Major < 2)
  240. {
  241. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  242. return false;
  243. }
  244. // Windows 95/98/ME are unsupported
  245. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  246. Environment.OSVersion.Platform != PlatformID.Win32NT)
  247. {
  248. reason = "Windows 95/98/ME will not run OpenSim";
  249. return false;
  250. }
  251. // Windows 2000 / Pre-SP2 XP
  252. if (Environment.OSVersion.Version.Major == 5 &&
  253. Environment.OSVersion.Version.Minor == 0)
  254. {
  255. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  256. return false;
  257. }
  258. return true;
  259. }
  260. public static int UnixTimeSinceEpoch()
  261. {
  262. return ToUnixTime(DateTime.UtcNow);
  263. }
  264. public static int ToUnixTime(DateTime stamp)
  265. {
  266. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  267. return (int) t.TotalSeconds;
  268. }
  269. public static DateTime ToDateTime(ulong seconds)
  270. {
  271. DateTime epoch = unixEpoch;
  272. return epoch.AddSeconds(seconds);
  273. }
  274. public static DateTime ToDateTime(int seconds)
  275. {
  276. DateTime epoch = unixEpoch;
  277. return epoch.AddSeconds(seconds);
  278. }
  279. /// <summary>
  280. /// Return an md5 hash of the given string
  281. /// </summary>
  282. /// <param name="pass"></param>
  283. /// <returns></returns>
  284. public static string Md5Hash(string pass)
  285. {
  286. MD5 md5 = MD5CryptoServiceProvider.Create();
  287. byte[] dataMd5 = md5.ComputeHash(Encoding.Default.GetBytes(pass));
  288. StringBuilder sb = new StringBuilder();
  289. for (int i = 0; i < dataMd5.Length; i++)
  290. sb.AppendFormat("{0:x2}", dataMd5[i]);
  291. return sb.ToString();
  292. }
  293. public static string GetRandomCapsPath()
  294. {
  295. UUID caps = UUID.Random();
  296. string capsPath = caps.ToString();
  297. capsPath = capsPath.Remove(capsPath.Length - 4, 4);
  298. return capsPath;
  299. }
  300. public static int fast_distance2d(int x, int y)
  301. {
  302. x = Math.Abs(x);
  303. y = Math.Abs(y);
  304. int min = Math.Min(x, y);
  305. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  306. }
  307. public static bool IsOutsideView(uint oldx, uint newx, uint oldy, uint newy)
  308. {
  309. // Eventually this will be a function of the draw distance / camera position too.
  310. return (((int)Math.Abs((int)(oldx - newx)) > 1) || ((int)Math.Abs((int)(oldy - newy)) > 1));
  311. }
  312. public static string FieldToString(byte[] bytes)
  313. {
  314. return FieldToString(bytes, String.Empty);
  315. }
  316. /// <summary>
  317. /// Convert a variable length field (byte array) to a string, with a
  318. /// field name prepended to each line of the output
  319. /// </summary>
  320. /// <remarks>If the byte array has unprintable characters in it, a
  321. /// hex dump will be put in the string instead</remarks>
  322. /// <param name="bytes">The byte array to convert to a string</param>
  323. /// <param name="fieldName">A field name to prepend to each line of output</param>
  324. /// <returns>An ASCII string or a string containing a hex dump, minus
  325. /// the null terminator</returns>
  326. public static string FieldToString(byte[] bytes, string fieldName)
  327. {
  328. // Check for a common case
  329. if (bytes.Length == 0) return String.Empty;
  330. StringBuilder output = new StringBuilder();
  331. bool printable = true;
  332. for (int i = 0; i < bytes.Length; ++i)
  333. {
  334. // Check if there are any unprintable characters in the array
  335. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  336. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  337. {
  338. printable = false;
  339. break;
  340. }
  341. }
  342. if (printable)
  343. {
  344. if (fieldName.Length > 0)
  345. {
  346. output.Append(fieldName);
  347. output.Append(": ");
  348. }
  349. output.Append(CleanString(UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  350. }
  351. else
  352. {
  353. for (int i = 0; i < bytes.Length; i += 16)
  354. {
  355. if (i != 0)
  356. output.Append(Environment.NewLine);
  357. if (fieldName.Length > 0)
  358. {
  359. output.Append(fieldName);
  360. output.Append(": ");
  361. }
  362. for (int j = 0; j < 16; j++)
  363. {
  364. if ((i + j) < bytes.Length)
  365. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  366. else
  367. output.Append(" ");
  368. }
  369. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  370. {
  371. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  372. output.Append((char) bytes[i + j]);
  373. else
  374. output.Append(".");
  375. }
  376. }
  377. }
  378. return output.ToString();
  379. }
  380. /// <summary>
  381. /// Converts a URL to a IPAddress
  382. /// </summary>
  383. /// <param name="url">URL Standard Format</param>
  384. /// <returns>A resolved IP Address</returns>
  385. public static IPAddress GetHostFromURL(string url)
  386. {
  387. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  388. }
  389. /// <summary>
  390. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  391. /// </summary>
  392. /// <param name="dnsAddress">DNS Hostname</param>
  393. /// <returns>An IP address, or null</returns>
  394. public static IPAddress GetHostFromDNS(string dnsAddress)
  395. {
  396. // Is it already a valid IP? No need to look it up.
  397. IPAddress ipa;
  398. if (IPAddress.TryParse(dnsAddress, out ipa))
  399. return ipa;
  400. IPAddress[] hosts = null;
  401. // Not an IP, lookup required
  402. try
  403. {
  404. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  405. }
  406. catch (Exception e)
  407. {
  408. m_log.ErrorFormat("[UTIL]: An error occurred while resolving {0}, {1}", dnsAddress, e);
  409. // Still going to throw the exception on for now, since this was what was happening in the first place
  410. throw e;
  411. }
  412. foreach (IPAddress host in hosts)
  413. {
  414. if (host.AddressFamily == AddressFamily.InterNetwork)
  415. {
  416. return host;
  417. }
  418. }
  419. if (hosts.Length > 0)
  420. return hosts[0];
  421. return null;
  422. }
  423. public static IPAddress GetLocalHost()
  424. {
  425. string dnsAddress = "localhost";
  426. IPAddress[] hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  427. foreach (IPAddress host in hosts)
  428. {
  429. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  430. {
  431. return host;
  432. }
  433. }
  434. if (hosts.Length > 0)
  435. return hosts[0];
  436. return null;
  437. }
  438. /// <summary>
  439. /// Removes all invalid path chars (OS dependent)
  440. /// </summary>
  441. /// <param name="path">path</param>
  442. /// <returns>safe path</returns>
  443. public static string safePath(string path)
  444. {
  445. return Regex.Replace(path, @regexInvalidPathChars, string.Empty);
  446. }
  447. /// <summary>
  448. /// Removes all invalid filename chars (OS dependent)
  449. /// </summary>
  450. /// <param name="path">filename</param>
  451. /// <returns>safe filename</returns>
  452. public static string safeFileName(string filename)
  453. {
  454. return Regex.Replace(filename, @regexInvalidFileChars, string.Empty);
  455. ;
  456. }
  457. //
  458. // directory locations
  459. //
  460. public static string homeDir()
  461. {
  462. string temp;
  463. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  464. // temp = Path.Combine(personal,".OpenSim");
  465. temp = ".";
  466. return temp;
  467. }
  468. public static string assetsDir()
  469. {
  470. return Path.Combine(configDir(), "assets");
  471. }
  472. public static string inventoryDir()
  473. {
  474. return Path.Combine(configDir(), "inventory");
  475. }
  476. public static string configDir()
  477. {
  478. return ".";
  479. }
  480. public static string dataDir()
  481. {
  482. return ".";
  483. }
  484. public static string logDir()
  485. {
  486. return ".";
  487. }
  488. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  489. public static string GetUniqueFilename(string FileName)
  490. {
  491. int count = 0;
  492. string Name;
  493. if (File.Exists(FileName))
  494. {
  495. FileInfo f = new FileInfo(FileName);
  496. if (!string.IsNullOrEmpty(f.Extension))
  497. {
  498. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  499. }
  500. else
  501. {
  502. Name = f.FullName;
  503. }
  504. while (File.Exists(FileName))
  505. {
  506. count++;
  507. FileName = Name + count + f.Extension;
  508. }
  509. }
  510. return FileName;
  511. }
  512. // Nini (config) related Methods
  513. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  514. {
  515. if (!File.Exists(fileName))
  516. {
  517. //create new file
  518. }
  519. XmlConfigSource config = new XmlConfigSource(fileName);
  520. AddDataRowToConfig(config, row);
  521. config.Save();
  522. return config;
  523. }
  524. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  525. {
  526. config.Configs.Add((string) row[0]);
  527. for (int i = 0; i < row.Table.Columns.Count; i++)
  528. {
  529. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  530. }
  531. }
  532. public static float Clip(float x, float min, float max)
  533. {
  534. return Math.Min(Math.Max(x, min), max);
  535. }
  536. public static int Clip(int x, int min, int max)
  537. {
  538. return Math.Min(Math.Max(x, min), max);
  539. }
  540. /// <summary>
  541. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  542. /// </summary>
  543. /// <param name="UUID"></param>
  544. /// <returns></returns>
  545. public static String ToRawUuidString(UUID UUID)
  546. {
  547. return UUID.Guid.ToString("n");
  548. }
  549. public static string CleanString(string input)
  550. {
  551. if (input.Length == 0)
  552. return input;
  553. int clip = input.Length;
  554. // Test for ++ string terminator
  555. int pos = input.IndexOf("\0");
  556. if (pos != -1 && pos < clip)
  557. clip = pos;
  558. // Test for CR
  559. pos = input.IndexOf("\r");
  560. if (pos != -1 && pos < clip)
  561. clip = pos;
  562. // Test for LF
  563. pos = input.IndexOf("\n");
  564. if (pos != -1 && pos < clip)
  565. clip = pos;
  566. // Truncate string before first end-of-line character found
  567. return input.Substring(0, clip);
  568. }
  569. /// <summary>
  570. /// returns the contents of /etc/issue on Unix Systems
  571. /// Use this for where it's absolutely necessary to implement platform specific stuff
  572. /// </summary>
  573. /// <returns></returns>
  574. public static string ReadEtcIssue()
  575. {
  576. try
  577. {
  578. StreamReader sr = new StreamReader("/etc/issue.net");
  579. string issue = sr.ReadToEnd();
  580. sr.Close();
  581. return issue;
  582. }
  583. catch (Exception)
  584. {
  585. return "";
  586. }
  587. }
  588. public static void SerializeToFile(string filename, Object obj)
  589. {
  590. IFormatter formatter = new BinaryFormatter();
  591. Stream stream = null;
  592. try
  593. {
  594. stream = new FileStream(
  595. filename, FileMode.Create,
  596. FileAccess.Write, FileShare.None);
  597. formatter.Serialize(stream, obj);
  598. }
  599. catch (Exception e)
  600. {
  601. System.Console.WriteLine(e.Message);
  602. System.Console.WriteLine(e.StackTrace);
  603. }
  604. finally
  605. {
  606. if (stream != null)
  607. {
  608. stream.Close();
  609. }
  610. }
  611. }
  612. public static Object DeserializeFromFile(string filename)
  613. {
  614. IFormatter formatter = new BinaryFormatter();
  615. Stream stream = null;
  616. Object ret = null;
  617. try
  618. {
  619. stream = new FileStream(
  620. filename, FileMode.Open,
  621. FileAccess.Read, FileShare.None);
  622. ret = formatter.Deserialize(stream);
  623. }
  624. catch (Exception e)
  625. {
  626. System.Console.WriteLine(e.Message);
  627. System.Console.WriteLine(e.StackTrace);
  628. }
  629. finally
  630. {
  631. if (stream != null)
  632. {
  633. stream.Close();
  634. }
  635. }
  636. return ret;
  637. }
  638. public static string Compress(string text)
  639. {
  640. byte[] buffer = Encoding.UTF8.GetBytes(text);
  641. MemoryStream memory = new MemoryStream();
  642. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  643. {
  644. compressor.Write(buffer, 0, buffer.Length);
  645. }
  646. memory.Position = 0;
  647. // MemoryStream outStream = new MemoryStream();
  648. byte[] compressed = new byte[memory.Length];
  649. memory.Read(compressed, 0, compressed.Length);
  650. byte[] compressedBuffer = new byte[compressed.Length + 4];
  651. System.Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  652. System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  653. return Convert.ToBase64String(compressedBuffer);
  654. }
  655. public static string Decompress(string compressedText)
  656. {
  657. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  658. using (MemoryStream memory = new MemoryStream())
  659. {
  660. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  661. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  662. byte[] buffer = new byte[msgLength];
  663. memory.Position = 0;
  664. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  665. {
  666. decompressor.Read(buffer, 0, buffer.Length);
  667. }
  668. return Encoding.UTF8.GetString(buffer);
  669. }
  670. }
  671. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  672. {
  673. return SendXmlRpcCommand(url, methodName, args);
  674. }
  675. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  676. {
  677. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  678. return client.Send(url, 6000);
  679. }
  680. /// <summary>
  681. /// Converts a byte array in big endian order into an ulong.
  682. /// </summary>
  683. /// <param name="bytes">
  684. /// The array of bytes
  685. /// </param>
  686. /// <returns>
  687. /// The extracted ulong
  688. /// </returns>
  689. public static ulong BytesToUInt64Big(byte[] bytes)
  690. {
  691. if (bytes.Length < 8) return 0;
  692. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  693. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  694. }
  695. // used for RemoteParcelRequest (for "About Landmark")
  696. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  697. {
  698. byte[] bytes =
  699. {
  700. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  701. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  702. (byte)x, (byte)(x >> 8), (byte)(x >> 16), (byte)(x >> 24),
  703. (byte)y, (byte)(y >> 8), (byte)(y >> 16), (byte)(y >> 24) };
  704. return new UUID(bytes, 0);
  705. }
  706. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  707. {
  708. byte[] bytes = parcelID.GetBytes();
  709. regionHandle = Utils.BytesToUInt64(bytes);
  710. x = Utils.BytesToUInt(bytes, 8);
  711. y = Utils.BytesToUInt(bytes, 12);
  712. }
  713. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  714. {
  715. ulong regionHandle;
  716. uint rx, ry;
  717. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  718. Utils.LongToUInts(regionHandle, out rx, out ry);
  719. x += rx;
  720. y += ry;
  721. }
  722. /// <summary>
  723. /// Get operating system information if available. Returns only the first 45 characters of information
  724. /// </summary>
  725. /// <returns>
  726. /// Operating system information. Returns an empty string if none was available.
  727. /// </returns>
  728. public static string GetOperatingSystemInformation()
  729. {
  730. string os = String.Empty;
  731. if (System.Environment.OSVersion.Platform != PlatformID.Unix)
  732. {
  733. os = System.Environment.OSVersion.ToString();
  734. }
  735. else
  736. {
  737. os = ReadEtcIssue();
  738. }
  739. if (os.Length > 45)
  740. {
  741. os = os.Substring(0, 45);
  742. }
  743. return os;
  744. }
  745. /// <summary>
  746. /// Is the given string a UUID?
  747. /// </summary>
  748. /// <param name="s"></param>
  749. /// <returns></returns>
  750. public static bool isUUID(string s)
  751. {
  752. return UUIDPattern.IsMatch(s);
  753. }
  754. }
  755. }