Util.cs 30 KB

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