Util.cs 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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.Collections.Generic;
  30. using System.Data;
  31. using System.Globalization;
  32. using System.IO;
  33. using System.IO.Compression;
  34. using System.Net;
  35. using System.Net.Sockets;
  36. using System.Reflection;
  37. using System.Runtime.Serialization;
  38. using System.Runtime.Serialization.Formatters.Binary;
  39. using System.Security.Cryptography;
  40. using System.Text;
  41. using System.Text.RegularExpressions;
  42. using System.Xml;
  43. using System.Threading;
  44. using log4net;
  45. using Nini.Config;
  46. using Nwc.XmlRpc;
  47. using BclExtras;
  48. using OpenMetaverse;
  49. using OpenMetaverse.StructuredData;
  50. using Amib.Threading;
  51. namespace OpenSim.Framework
  52. {
  53. /// <summary>
  54. /// The method used by Util.FireAndForget for asynchronously firing events
  55. /// </summary>
  56. public enum FireAndForgetMethod
  57. {
  58. UnsafeQueueUserWorkItem,
  59. QueueUserWorkItem,
  60. BeginInvoke,
  61. SmartThreadPool,
  62. Thread,
  63. }
  64. /// <summary>
  65. /// Miscellaneous utility functions
  66. /// </summary>
  67. public class Util
  68. {
  69. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  70. private static uint nextXferID = 5000;
  71. private static Random randomClass = new Random();
  72. // Get a list of invalid file characters (OS dependent)
  73. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  74. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  75. private static object XferLock = new object();
  76. /// <summary>Thread pool used for Util.FireAndForget if
  77. /// FireAndForgetMethod.SmartThreadPool is used</summary>
  78. private static SmartThreadPool m_ThreadPool;
  79. // 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.
  80. private static readonly DateTime unixEpoch =
  81. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  82. public static readonly Regex UUIDPattern
  83. = 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}$");
  84. public static FireAndForgetMethod FireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
  85. /// <summary>
  86. /// Linear interpolates B<->C using percent A
  87. /// </summary>
  88. /// <param name="a"></param>
  89. /// <param name="b"></param>
  90. /// <param name="c"></param>
  91. /// <returns></returns>
  92. public static double lerp(double a, double b, double c)
  93. {
  94. return (b*a) + (c*(1 - a));
  95. }
  96. /// <summary>
  97. /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
  98. /// Layout:
  99. /// A B
  100. /// C D
  101. /// A<->C = Y
  102. /// C<->D = X
  103. /// </summary>
  104. /// <param name="x"></param>
  105. /// <param name="y"></param>
  106. /// <param name="a"></param>
  107. /// <param name="b"></param>
  108. /// <param name="c"></param>
  109. /// <param name="d"></param>
  110. /// <returns></returns>
  111. public static double lerp2D(double x, double y, double a, double b, double c, double d)
  112. {
  113. return lerp(y, lerp(x, a, b), lerp(x, c, d));
  114. }
  115. public static Encoding UTF8 = Encoding.UTF8;
  116. /// <value>
  117. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  118. /// </value>
  119. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  120. #region Vector Equations
  121. /// <summary>
  122. /// Get the distance between two 3d vectors
  123. /// </summary>
  124. /// <param name="a">A 3d vector</param>
  125. /// <param name="b">A 3d vector</param>
  126. /// <returns>The distance between the two vectors</returns>
  127. public static double GetDistanceTo(Vector3 a, Vector3 b)
  128. {
  129. float dx = a.X - b.X;
  130. float dy = a.Y - b.Y;
  131. float dz = a.Z - b.Z;
  132. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  133. }
  134. /// <summary>
  135. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  136. /// </summary>
  137. /// <param name="a"></param>
  138. /// <param name="b"></param>
  139. /// <param name="amount"></param>
  140. /// <returns></returns>
  141. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  142. {
  143. float dx = a.X - b.X;
  144. float dy = a.Y - b.Y;
  145. float dz = a.Z - b.Z;
  146. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  147. }
  148. /// <summary>
  149. /// Get the magnitude of a 3d vector
  150. /// </summary>
  151. /// <param name="a">A 3d vector</param>
  152. /// <returns>The magnitude of the vector</returns>
  153. public static double GetMagnitude(Vector3 a)
  154. {
  155. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  156. }
  157. /// <summary>
  158. /// Get a normalized form of a 3d vector
  159. /// </summary>
  160. /// <param name="a">A 3d vector</param>
  161. /// <returns>A new vector which is normalized form of the vector</returns>
  162. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  163. public static Vector3 GetNormalizedVector(Vector3 a)
  164. {
  165. if (IsZeroVector(a))
  166. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  167. float Mag = (float) GetMagnitude(a);
  168. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  169. }
  170. /// <summary>
  171. /// Returns if a vector is a zero vector (has all zero components)
  172. /// </summary>
  173. /// <returns></returns>
  174. public static bool IsZeroVector(Vector3 v)
  175. {
  176. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  177. {
  178. return true;
  179. }
  180. return false;
  181. }
  182. # endregion
  183. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  184. {
  185. float s;
  186. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  187. if (tr >= 1.0)
  188. {
  189. s = (float) (0.5 / Math.Sqrt(tr));
  190. return new Quaternion(
  191. (left.Z - up.Y) * s,
  192. (up.X - fwd.Z) * s,
  193. (fwd.Y - left.X) * s,
  194. (float) 0.25 / s);
  195. }
  196. else
  197. {
  198. float max = (left.Y > up.Z) ? left.Y : up.Z;
  199. if (max < fwd.X)
  200. {
  201. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  202. float x = (float) (s * 0.5);
  203. s = (float) (0.5 / s);
  204. return new Quaternion(
  205. x,
  206. (fwd.Y + left.X) * s,
  207. (up.X + fwd.Z) * s,
  208. (left.Z - up.Y) * s);
  209. }
  210. else if (max == left.Y)
  211. {
  212. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  213. float y = (float) (s * 0.5);
  214. s = (float) (0.5 / s);
  215. return new Quaternion(
  216. (fwd.Y + left.X) * s,
  217. y,
  218. (left.Z + up.Y) * s,
  219. (up.X - fwd.Z) * s);
  220. }
  221. else
  222. {
  223. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  224. float z = (float) (s * 0.5);
  225. s = (float) (0.5 / s);
  226. return new Quaternion(
  227. (up.X + fwd.Z) * s,
  228. (left.Z + up.Y) * s,
  229. z,
  230. (fwd.Y - left.X) * s);
  231. }
  232. }
  233. }
  234. public static Random RandomClass
  235. {
  236. get { return randomClass; }
  237. }
  238. public static ulong UIntsToLong(uint X, uint Y)
  239. {
  240. return Utils.UIntsToLong(X, Y);
  241. }
  242. public static T Clamp<T>(T x, T min, T max)
  243. where T : IComparable<T>
  244. {
  245. return x.CompareTo(max) > 0 ? max :
  246. x.CompareTo(min) < 0 ? min :
  247. x;
  248. }
  249. public static uint GetNextXferID()
  250. {
  251. uint id = 0;
  252. lock (XferLock)
  253. {
  254. id = nextXferID;
  255. nextXferID++;
  256. }
  257. return id;
  258. }
  259. public static string GetFileName(string file)
  260. {
  261. // Return just the filename on UNIX platforms
  262. // TODO: this should be customisable with a prefix, but that's something to do later.
  263. if (Environment.OSVersion.Platform == PlatformID.Unix)
  264. {
  265. return file;
  266. }
  267. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  268. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  269. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  270. {
  271. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  272. {
  273. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  274. }
  275. return "%APPDATA%\\OpenSim\\" + file;
  276. }
  277. // Catch all - covers older windows versions
  278. // (but those probably wont work anyway)
  279. return file;
  280. }
  281. /// <summary>
  282. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  283. ///
  284. /// Please don't delete me even if I appear currently unused!
  285. /// </summary>
  286. /// <param name="rawXml"></param>
  287. /// <returns></returns>
  288. public static string GetFormattedXml(string rawXml)
  289. {
  290. XmlDocument xd = new XmlDocument();
  291. xd.LoadXml(rawXml);
  292. StringBuilder sb = new StringBuilder();
  293. StringWriter sw = new StringWriter(sb);
  294. XmlTextWriter xtw = new XmlTextWriter(sw);
  295. xtw.Formatting = Formatting.Indented;
  296. try
  297. {
  298. xd.WriteTo(xtw);
  299. }
  300. finally
  301. {
  302. xtw.Close();
  303. }
  304. return sb.ToString();
  305. }
  306. public static bool IsEnvironmentSupported(ref string reason)
  307. {
  308. // Must have .NET 2.0 (Generics / libsl)
  309. if (Environment.Version.Major < 2)
  310. {
  311. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  312. return false;
  313. }
  314. // Windows 95/98/ME are unsupported
  315. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  316. Environment.OSVersion.Platform != PlatformID.Win32NT)
  317. {
  318. reason = "Windows 95/98/ME will not run OpenSim";
  319. return false;
  320. }
  321. // Windows 2000 / Pre-SP2 XP
  322. if (Environment.OSVersion.Version.Major == 5 &&
  323. Environment.OSVersion.Version.Minor == 0)
  324. {
  325. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  326. return false;
  327. }
  328. return true;
  329. }
  330. public static int UnixTimeSinceEpoch()
  331. {
  332. return ToUnixTime(DateTime.UtcNow);
  333. }
  334. public static int ToUnixTime(DateTime stamp)
  335. {
  336. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  337. return (int) t.TotalSeconds;
  338. }
  339. public static DateTime ToDateTime(ulong seconds)
  340. {
  341. DateTime epoch = unixEpoch;
  342. return epoch.AddSeconds(seconds);
  343. }
  344. public static DateTime ToDateTime(int seconds)
  345. {
  346. DateTime epoch = unixEpoch;
  347. return epoch.AddSeconds(seconds);
  348. }
  349. /// <summary>
  350. /// Return an md5 hash of the given string
  351. /// </summary>
  352. /// <param name="data"></param>
  353. /// <returns></returns>
  354. public static string Md5Hash(string data)
  355. {
  356. byte[] dataMd5 = ComputeMD5Hash(data);
  357. StringBuilder sb = new StringBuilder();
  358. for (int i = 0; i < dataMd5.Length; i++)
  359. sb.AppendFormat("{0:x2}", dataMd5[i]);
  360. return sb.ToString();
  361. }
  362. private static byte[] ComputeMD5Hash(string data)
  363. {
  364. MD5 md5 = MD5.Create();
  365. return md5.ComputeHash(Encoding.Default.GetBytes(data));
  366. }
  367. /// <summary>
  368. /// Return an SHA1 hash of the given string
  369. /// </summary>
  370. /// <param name="data"></param>
  371. /// <returns></returns>
  372. public static string SHA1Hash(string data)
  373. {
  374. byte[] hash = ComputeSHA1Hash(data);
  375. return BitConverter.ToString(hash).Replace("-", String.Empty);
  376. }
  377. private static byte[] ComputeSHA1Hash(string src)
  378. {
  379. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  380. return SHA1.ComputeHash(Encoding.Default.GetBytes(src));
  381. }
  382. public static int fast_distance2d(int x, int y)
  383. {
  384. x = Math.Abs(x);
  385. y = Math.Abs(y);
  386. int min = Math.Min(x, y);
  387. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  388. }
  389. public static bool IsOutsideView(uint oldx, uint newx, uint oldy, uint newy)
  390. {
  391. // Eventually this will be a function of the draw distance / camera position too.
  392. return (((int)Math.Abs((int)(oldx - newx)) > 1) || ((int)Math.Abs((int)(oldy - newy)) > 1));
  393. }
  394. public static string FieldToString(byte[] bytes)
  395. {
  396. return FieldToString(bytes, String.Empty);
  397. }
  398. /// <summary>
  399. /// Convert a variable length field (byte array) to a string, with a
  400. /// field name prepended to each line of the output
  401. /// </summary>
  402. /// <remarks>If the byte array has unprintable characters in it, a
  403. /// hex dump will be put in the string instead</remarks>
  404. /// <param name="bytes">The byte array to convert to a string</param>
  405. /// <param name="fieldName">A field name to prepend to each line of output</param>
  406. /// <returns>An ASCII string or a string containing a hex dump, minus
  407. /// the null terminator</returns>
  408. public static string FieldToString(byte[] bytes, string fieldName)
  409. {
  410. // Check for a common case
  411. if (bytes.Length == 0) return String.Empty;
  412. StringBuilder output = new StringBuilder();
  413. bool printable = true;
  414. for (int i = 0; i < bytes.Length; ++i)
  415. {
  416. // Check if there are any unprintable characters in the array
  417. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  418. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  419. {
  420. printable = false;
  421. break;
  422. }
  423. }
  424. if (printable)
  425. {
  426. if (fieldName.Length > 0)
  427. {
  428. output.Append(fieldName);
  429. output.Append(": ");
  430. }
  431. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  432. }
  433. else
  434. {
  435. for (int i = 0; i < bytes.Length; i += 16)
  436. {
  437. if (i != 0)
  438. output.Append(Environment.NewLine);
  439. if (fieldName.Length > 0)
  440. {
  441. output.Append(fieldName);
  442. output.Append(": ");
  443. }
  444. for (int j = 0; j < 16; j++)
  445. {
  446. if ((i + j) < bytes.Length)
  447. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  448. else
  449. output.Append(" ");
  450. }
  451. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  452. {
  453. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  454. output.Append((char) bytes[i + j]);
  455. else
  456. output.Append(".");
  457. }
  458. }
  459. }
  460. return output.ToString();
  461. }
  462. /// <summary>
  463. /// Converts a URL to a IPAddress
  464. /// </summary>
  465. /// <param name="url">URL Standard Format</param>
  466. /// <returns>A resolved IP Address</returns>
  467. public static IPAddress GetHostFromURL(string url)
  468. {
  469. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  470. }
  471. /// <summary>
  472. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  473. /// </summary>
  474. /// <param name="dnsAddress">DNS Hostname</param>
  475. /// <returns>An IP address, or null</returns>
  476. public static IPAddress GetHostFromDNS(string dnsAddress)
  477. {
  478. // Is it already a valid IP? No need to look it up.
  479. IPAddress ipa;
  480. if (IPAddress.TryParse(dnsAddress, out ipa))
  481. return ipa;
  482. IPAddress[] hosts = null;
  483. // Not an IP, lookup required
  484. try
  485. {
  486. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  487. }
  488. catch (Exception e)
  489. {
  490. m_log.ErrorFormat("[UTIL]: An error occurred while resolving {0}, {1}", dnsAddress, e);
  491. // Still going to throw the exception on for now, since this was what was happening in the first place
  492. throw e;
  493. }
  494. foreach (IPAddress host in hosts)
  495. {
  496. if (host.AddressFamily == AddressFamily.InterNetwork)
  497. {
  498. return host;
  499. }
  500. }
  501. if (hosts.Length > 0)
  502. return hosts[0];
  503. return null;
  504. }
  505. public static Uri GetURI(string protocol, string hostname, int port, string path)
  506. {
  507. return new UriBuilder(protocol, hostname, port, path).Uri;
  508. }
  509. /// <summary>
  510. /// Gets a list of all local system IP addresses
  511. /// </summary>
  512. /// <returns></returns>
  513. public static IPAddress[] GetLocalHosts()
  514. {
  515. return Dns.GetHostAddresses(Dns.GetHostName());
  516. }
  517. public static IPAddress GetLocalHost()
  518. {
  519. string dnsAddress = "localhost";
  520. IPAddress[] hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  521. foreach (IPAddress host in hosts)
  522. {
  523. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  524. {
  525. return host;
  526. }
  527. }
  528. if (hosts.Length > 0)
  529. {
  530. foreach (IPAddress host in hosts)
  531. {
  532. if (host.AddressFamily == AddressFamily.InterNetwork)
  533. return host;
  534. }
  535. // Well all else failed...
  536. return hosts[0];
  537. }
  538. return null;
  539. }
  540. /// <summary>
  541. /// Removes all invalid path chars (OS dependent)
  542. /// </summary>
  543. /// <param name="path">path</param>
  544. /// <returns>safe path</returns>
  545. public static string safePath(string path)
  546. {
  547. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  548. }
  549. /// <summary>
  550. /// Removes all invalid filename chars (OS dependent)
  551. /// </summary>
  552. /// <param name="path">filename</param>
  553. /// <returns>safe filename</returns>
  554. public static string safeFileName(string filename)
  555. {
  556. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  557. ;
  558. }
  559. //
  560. // directory locations
  561. //
  562. public static string homeDir()
  563. {
  564. string temp;
  565. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  566. // temp = Path.Combine(personal,".OpenSim");
  567. temp = ".";
  568. return temp;
  569. }
  570. public static string assetsDir()
  571. {
  572. return Path.Combine(configDir(), "assets");
  573. }
  574. public static string inventoryDir()
  575. {
  576. return Path.Combine(configDir(), "inventory");
  577. }
  578. public static string configDir()
  579. {
  580. return ".";
  581. }
  582. public static string dataDir()
  583. {
  584. return ".";
  585. }
  586. public static string logDir()
  587. {
  588. return ".";
  589. }
  590. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  591. public static string GetUniqueFilename(string FileName)
  592. {
  593. int count = 0;
  594. string Name;
  595. if (File.Exists(FileName))
  596. {
  597. FileInfo f = new FileInfo(FileName);
  598. if (!String.IsNullOrEmpty(f.Extension))
  599. {
  600. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  601. }
  602. else
  603. {
  604. Name = f.FullName;
  605. }
  606. while (File.Exists(FileName))
  607. {
  608. count++;
  609. FileName = Name + count + f.Extension;
  610. }
  611. }
  612. return FileName;
  613. }
  614. // Nini (config) related Methods
  615. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  616. {
  617. if (!File.Exists(fileName))
  618. {
  619. //create new file
  620. }
  621. XmlConfigSource config = new XmlConfigSource(fileName);
  622. AddDataRowToConfig(config, row);
  623. config.Save();
  624. return config;
  625. }
  626. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  627. {
  628. config.Configs.Add((string) row[0]);
  629. for (int i = 0; i < row.Table.Columns.Count; i++)
  630. {
  631. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  632. }
  633. }
  634. public static float Clip(float x, float min, float max)
  635. {
  636. return Math.Min(Math.Max(x, min), max);
  637. }
  638. public static int Clip(int x, int min, int max)
  639. {
  640. return Math.Min(Math.Max(x, min), max);
  641. }
  642. /// <summary>
  643. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  644. /// </summary>
  645. /// <param name="UUID"></param>
  646. /// <returns></returns>
  647. public static String ToRawUuidString(UUID UUID)
  648. {
  649. return UUID.Guid.ToString("n");
  650. }
  651. public static string CleanString(string input)
  652. {
  653. if (input.Length == 0)
  654. return input;
  655. int clip = input.Length;
  656. // Test for ++ string terminator
  657. int pos = input.IndexOf("\0");
  658. if (pos != -1 && pos < clip)
  659. clip = pos;
  660. // Test for CR
  661. pos = input.IndexOf("\r");
  662. if (pos != -1 && pos < clip)
  663. clip = pos;
  664. // Test for LF
  665. pos = input.IndexOf("\n");
  666. if (pos != -1 && pos < clip)
  667. clip = pos;
  668. // Truncate string before first end-of-line character found
  669. return input.Substring(0, clip);
  670. }
  671. /// <summary>
  672. /// returns the contents of /etc/issue on Unix Systems
  673. /// Use this for where it's absolutely necessary to implement platform specific stuff
  674. /// </summary>
  675. /// <returns></returns>
  676. public static string ReadEtcIssue()
  677. {
  678. try
  679. {
  680. StreamReader sr = new StreamReader("/etc/issue.net");
  681. string issue = sr.ReadToEnd();
  682. sr.Close();
  683. return issue;
  684. }
  685. catch (Exception)
  686. {
  687. return "";
  688. }
  689. }
  690. public static void SerializeToFile(string filename, Object obj)
  691. {
  692. IFormatter formatter = new BinaryFormatter();
  693. Stream stream = null;
  694. try
  695. {
  696. stream = new FileStream(
  697. filename, FileMode.Create,
  698. FileAccess.Write, FileShare.None);
  699. formatter.Serialize(stream, obj);
  700. }
  701. catch (Exception e)
  702. {
  703. m_log.Error(e.ToString());
  704. }
  705. finally
  706. {
  707. if (stream != null)
  708. {
  709. stream.Close();
  710. }
  711. }
  712. }
  713. public static Object DeserializeFromFile(string filename)
  714. {
  715. IFormatter formatter = new BinaryFormatter();
  716. Stream stream = null;
  717. Object ret = null;
  718. try
  719. {
  720. stream = new FileStream(
  721. filename, FileMode.Open,
  722. FileAccess.Read, FileShare.None);
  723. ret = formatter.Deserialize(stream);
  724. }
  725. catch (Exception e)
  726. {
  727. m_log.Error(e.ToString());
  728. }
  729. finally
  730. {
  731. if (stream != null)
  732. {
  733. stream.Close();
  734. }
  735. }
  736. return ret;
  737. }
  738. public static string Compress(string text)
  739. {
  740. byte[] buffer = Util.UTF8.GetBytes(text);
  741. MemoryStream memory = new MemoryStream();
  742. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  743. {
  744. compressor.Write(buffer, 0, buffer.Length);
  745. }
  746. memory.Position = 0;
  747. byte[] compressed = new byte[memory.Length];
  748. memory.Read(compressed, 0, compressed.Length);
  749. byte[] compressedBuffer = new byte[compressed.Length + 4];
  750. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  751. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  752. return Convert.ToBase64String(compressedBuffer);
  753. }
  754. public static string Decompress(string compressedText)
  755. {
  756. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  757. using (MemoryStream memory = new MemoryStream())
  758. {
  759. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  760. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  761. byte[] buffer = new byte[msgLength];
  762. memory.Position = 0;
  763. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  764. {
  765. decompressor.Read(buffer, 0, buffer.Length);
  766. }
  767. return Util.UTF8.GetString(buffer);
  768. }
  769. }
  770. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  771. {
  772. return SendXmlRpcCommand(url, methodName, args);
  773. }
  774. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  775. {
  776. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  777. return client.Send(url, 6000);
  778. }
  779. /// <summary>
  780. /// Returns an error message that the user could not be found in the database
  781. /// </summary>
  782. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  783. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  784. {
  785. XmlRpcResponse response = new XmlRpcResponse();
  786. Hashtable responseData = new Hashtable();
  787. responseData["error_type"] = "unknown_user";
  788. responseData["error_desc"] = "The user requested is not in the database";
  789. response.Value = responseData;
  790. return response;
  791. }
  792. /// <summary>
  793. /// Converts a byte array in big endian order into an ulong.
  794. /// </summary>
  795. /// <param name="bytes">
  796. /// The array of bytes
  797. /// </param>
  798. /// <returns>
  799. /// The extracted ulong
  800. /// </returns>
  801. public static ulong BytesToUInt64Big(byte[] bytes)
  802. {
  803. if (bytes.Length < 8) return 0;
  804. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  805. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  806. }
  807. // used for RemoteParcelRequest (for "About Landmark")
  808. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  809. {
  810. byte[] bytes =
  811. {
  812. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  813. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  814. (byte)x, (byte)(x >> 8), 0, 0,
  815. (byte)y, (byte)(y >> 8), 0, 0 };
  816. return new UUID(bytes, 0);
  817. }
  818. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  819. {
  820. byte[] bytes =
  821. {
  822. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  823. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  824. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  825. (byte)y, (byte)(y >> 8), 0, 0 };
  826. return new UUID(bytes, 0);
  827. }
  828. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  829. {
  830. byte[] bytes = parcelID.GetBytes();
  831. regionHandle = Utils.BytesToUInt64(bytes);
  832. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  833. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  834. }
  835. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  836. {
  837. byte[] bytes = parcelID.GetBytes();
  838. regionHandle = Utils.BytesToUInt64(bytes);
  839. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  840. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  841. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  842. }
  843. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  844. {
  845. ulong regionHandle;
  846. uint rx, ry;
  847. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  848. Utils.LongToUInts(regionHandle, out rx, out ry);
  849. x += rx;
  850. y += ry;
  851. }
  852. /// <summary>
  853. /// Get operating system information if available. Returns only the first 45 characters of information
  854. /// </summary>
  855. /// <returns>
  856. /// Operating system information. Returns an empty string if none was available.
  857. /// </returns>
  858. public static string GetOperatingSystemInformation()
  859. {
  860. string os = String.Empty;
  861. if (Environment.OSVersion.Platform != PlatformID.Unix)
  862. {
  863. os = Environment.OSVersion.ToString();
  864. }
  865. else
  866. {
  867. os = ReadEtcIssue();
  868. }
  869. if (os.Length > 45)
  870. {
  871. os = os.Substring(0, 45);
  872. }
  873. return os;
  874. }
  875. public static string GetRuntimeInformation()
  876. {
  877. string ru = String.Empty;
  878. if (Environment.OSVersion.Platform == PlatformID.Unix)
  879. ru = "Unix/Mono";
  880. else
  881. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  882. ru = "OSX/Mono";
  883. else
  884. {
  885. if (Type.GetType("Mono.Runtime") != null)
  886. ru = "Win/Mono";
  887. else
  888. ru = "Win/.NET";
  889. }
  890. return ru;
  891. }
  892. /// <summary>
  893. /// Is the given string a UUID?
  894. /// </summary>
  895. /// <param name="s"></param>
  896. /// <returns></returns>
  897. public static bool isUUID(string s)
  898. {
  899. return UUIDPattern.IsMatch(s);
  900. }
  901. public static string GetDisplayConnectionString(string connectionString)
  902. {
  903. int passPosition = 0;
  904. int passEndPosition = 0;
  905. string displayConnectionString = null;
  906. // hide the password in the connection string
  907. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  908. passPosition = connectionString.IndexOf("=", passPosition);
  909. if (passPosition < connectionString.Length)
  910. passPosition += 1;
  911. passEndPosition = connectionString.IndexOf(";", passPosition);
  912. displayConnectionString = connectionString.Substring(0, passPosition);
  913. displayConnectionString += "***";
  914. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  915. return displayConnectionString;
  916. }
  917. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  918. {
  919. Type settingsType = settingsClass.GetType();
  920. FieldInfo[] fieldInfos = settingsType.GetFields();
  921. foreach (FieldInfo fieldInfo in fieldInfos)
  922. {
  923. if (!fieldInfo.IsStatic)
  924. {
  925. if (fieldInfo.FieldType == typeof(System.String))
  926. {
  927. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  928. }
  929. else if (fieldInfo.FieldType == typeof(System.Boolean))
  930. {
  931. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  932. }
  933. else if (fieldInfo.FieldType == typeof(System.Int32))
  934. {
  935. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  936. }
  937. else if (fieldInfo.FieldType == typeof(System.Single))
  938. {
  939. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  940. }
  941. else if (fieldInfo.FieldType == typeof(System.UInt32))
  942. {
  943. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  944. }
  945. }
  946. }
  947. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  948. foreach (PropertyInfo propInfo in propertyInfos)
  949. {
  950. if ((propInfo.CanRead) && (propInfo.CanWrite))
  951. {
  952. if (propInfo.PropertyType == typeof(System.String))
  953. {
  954. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  955. }
  956. else if (propInfo.PropertyType == typeof(System.Boolean))
  957. {
  958. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  959. }
  960. else if (propInfo.PropertyType == typeof(System.Int32))
  961. {
  962. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  963. }
  964. else if (propInfo.PropertyType == typeof(System.Single))
  965. {
  966. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  967. }
  968. if (propInfo.PropertyType == typeof(System.UInt32))
  969. {
  970. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  971. }
  972. }
  973. }
  974. return settingsClass;
  975. }
  976. public static string Base64ToString(string str)
  977. {
  978. UTF8Encoding encoder = new UTF8Encoding();
  979. Decoder utf8Decode = encoder.GetDecoder();
  980. byte[] todecode_byte = Convert.FromBase64String(str);
  981. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  982. char[] decoded_char = new char[charCount];
  983. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  984. string result = new String(decoded_char);
  985. return result;
  986. }
  987. public static Guid GetHashGuid(string data, string salt)
  988. {
  989. byte[] hash = ComputeMD5Hash(data + salt);
  990. //string s = BitConverter.ToString(hash);
  991. Guid guid = new Guid(hash);
  992. return guid;
  993. }
  994. public static byte ConvertMaturityToAccessLevel(uint maturity)
  995. {
  996. byte retVal = 0;
  997. switch (maturity)
  998. {
  999. case 0: //PG
  1000. retVal = 13;
  1001. break;
  1002. case 1: //Mature
  1003. retVal = 21;
  1004. break;
  1005. case 2: // Adult
  1006. retVal = 42;
  1007. break;
  1008. }
  1009. return retVal;
  1010. }
  1011. /// <summary>
  1012. /// Produces an OSDMap from its string representation on a stream
  1013. /// </summary>
  1014. /// <param name="data">The stream</param>
  1015. /// <param name="length">The size of the data on the stream</param>
  1016. /// <returns>The OSDMap or an exception</returns>
  1017. public static OSDMap GetOSDMap(Stream stream, int length)
  1018. {
  1019. byte[] data = new byte[length];
  1020. stream.Read(data, 0, length);
  1021. string strdata = Util.UTF8.GetString(data);
  1022. OSDMap args = null;
  1023. OSD buffer;
  1024. buffer = OSDParser.DeserializeJson(strdata);
  1025. if (buffer.Type == OSDType.Map)
  1026. {
  1027. args = (OSDMap)buffer;
  1028. return args;
  1029. }
  1030. return null;
  1031. }
  1032. public static string[] Glob(string path)
  1033. {
  1034. string vol=String.Empty;
  1035. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1036. {
  1037. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1038. if (vcomps.Length > 1)
  1039. {
  1040. path = vcomps[1];
  1041. vol = vcomps[0];
  1042. }
  1043. }
  1044. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1045. // Glob
  1046. path = vol;
  1047. if (vol != String.Empty)
  1048. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1049. else
  1050. path = new String(new char[] {Path.DirectorySeparatorChar});
  1051. List<string> paths = new List<string>();
  1052. List<string> found = new List<string>();
  1053. paths.Add(path);
  1054. int compIndex = -1;
  1055. foreach (string c in comps)
  1056. {
  1057. compIndex++;
  1058. List<string> addpaths = new List<string>();
  1059. foreach (string p in paths)
  1060. {
  1061. string[] dirs = Directory.GetDirectories(p, c);
  1062. if (dirs.Length != 0)
  1063. {
  1064. foreach (string dir in dirs)
  1065. addpaths.Add(Path.Combine(path, dir));
  1066. }
  1067. // Only add files if that is the last path component
  1068. if (compIndex == comps.Length - 1)
  1069. {
  1070. string[] files = Directory.GetFiles(p, c);
  1071. foreach (string f in files)
  1072. found.Add(f);
  1073. }
  1074. }
  1075. paths = addpaths;
  1076. }
  1077. return found.ToArray();
  1078. }
  1079. public static string ServerURI(string uri)
  1080. {
  1081. if (uri == string.Empty)
  1082. return string.Empty;
  1083. // Get rid of eventual slashes at the end
  1084. uri = uri.TrimEnd('/');
  1085. IPAddress ipaddr1 = null;
  1086. string port1 = "";
  1087. try
  1088. {
  1089. ipaddr1 = Util.GetHostFromURL(uri);
  1090. }
  1091. catch { }
  1092. try
  1093. {
  1094. port1 = uri.Split(new char[] { ':' })[2];
  1095. }
  1096. catch { }
  1097. // We tried our best to convert the domain names to IP addresses
  1098. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1099. }
  1100. public static byte[] StringToBytes256(string str)
  1101. {
  1102. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1103. if (str.Length > 254) str = str.Remove(254);
  1104. if (!str.EndsWith("\0")) { str += "\0"; }
  1105. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1106. // might have gotten an oversized array even after the string trim
  1107. byte[] data = UTF8.GetBytes(str);
  1108. if (data.Length > 256)
  1109. {
  1110. Array.Resize<byte>(ref data, 256);
  1111. data[255] = 0;
  1112. }
  1113. return data;
  1114. }
  1115. public static byte[] StringToBytes1024(string str)
  1116. {
  1117. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1118. if (str.Length > 1023) str = str.Remove(1023);
  1119. if (!str.EndsWith("\0")) { str += "\0"; }
  1120. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1121. // might have gotten an oversized array even after the string trim
  1122. byte[] data = UTF8.GetBytes(str);
  1123. if (data.Length > 1024)
  1124. {
  1125. Array.Resize<byte>(ref data, 1024);
  1126. data[1023] = 0;
  1127. }
  1128. return data;
  1129. }
  1130. #region FireAndForget Threading Pattern
  1131. /// <summary>
  1132. /// Created to work around a limitation in Mono with nested delegates
  1133. /// </summary>
  1134. private class FireAndForgetWrapper
  1135. {
  1136. public void FireAndForget(System.Threading.WaitCallback callback)
  1137. {
  1138. callback.BeginInvoke(null, EndFireAndForget, callback);
  1139. }
  1140. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1141. {
  1142. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1143. }
  1144. private static void EndFireAndForget(IAsyncResult ar)
  1145. {
  1146. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1147. try { callback.EndInvoke(ar); }
  1148. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1149. ar.AsyncWaitHandle.Close();
  1150. }
  1151. }
  1152. public static void FireAndForget(System.Threading.WaitCallback callback)
  1153. {
  1154. FireAndForget(callback, null);
  1155. }
  1156. public static void InitThreadPool(int maxThreads)
  1157. {
  1158. if (maxThreads < 2)
  1159. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1160. if (m_ThreadPool != null)
  1161. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1162. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1163. }
  1164. public static int FireAndForgetCount()
  1165. {
  1166. const int MAX_SYSTEM_THREADS = 200;
  1167. switch (FireAndForgetMethod)
  1168. {
  1169. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1170. case FireAndForgetMethod.QueueUserWorkItem:
  1171. case FireAndForgetMethod.BeginInvoke:
  1172. int workerThreads, iocpThreads;
  1173. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1174. return workerThreads;
  1175. case FireAndForgetMethod.SmartThreadPool:
  1176. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1177. case FireAndForgetMethod.Thread:
  1178. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1179. default:
  1180. throw new NotImplementedException();
  1181. }
  1182. }
  1183. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1184. {
  1185. switch (FireAndForgetMethod)
  1186. {
  1187. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1188. ThreadPool.UnsafeQueueUserWorkItem(callback, obj);
  1189. break;
  1190. case FireAndForgetMethod.QueueUserWorkItem:
  1191. ThreadPool.QueueUserWorkItem(callback, obj);
  1192. break;
  1193. case FireAndForgetMethod.BeginInvoke:
  1194. FireAndForgetWrapper wrapper = Singleton.GetInstance<FireAndForgetWrapper>();
  1195. wrapper.FireAndForget(callback, obj);
  1196. break;
  1197. case FireAndForgetMethod.SmartThreadPool:
  1198. if (m_ThreadPool == null)
  1199. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1200. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { callback, obj });
  1201. break;
  1202. case FireAndForgetMethod.Thread:
  1203. Thread thread = new Thread(delegate(object o) { callback(o); });
  1204. thread.Start(obj);
  1205. break;
  1206. default:
  1207. throw new NotImplementedException();
  1208. }
  1209. }
  1210. private static object SmartThreadPoolCallback(object o)
  1211. {
  1212. object[] array = (object[])o;
  1213. WaitCallback callback = (WaitCallback)array[0];
  1214. object obj = array[1];
  1215. callback(obj);
  1216. return null;
  1217. }
  1218. #endregion FireAndForget Threading Pattern
  1219. /// <summary>
  1220. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1221. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1222. /// for the callers.
  1223. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1224. /// </summary>
  1225. /// <returns></returns>
  1226. public static Int32 EnvironmentTickCount()
  1227. {
  1228. return Environment.TickCount & EnvironmentTickCountMask;
  1229. }
  1230. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1231. /// <summary>
  1232. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1233. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1234. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1235. /// </summary>
  1236. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1237. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1238. {
  1239. Int32 diff = EnvironmentTickCount() - prevValue;
  1240. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1241. }
  1242. }
  1243. }