1
0

Util.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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. /// <summary>
  876. /// Is the given string a UUID?
  877. /// </summary>
  878. /// <param name="s"></param>
  879. /// <returns></returns>
  880. public static bool isUUID(string s)
  881. {
  882. return UUIDPattern.IsMatch(s);
  883. }
  884. public static string GetDisplayConnectionString(string connectionString)
  885. {
  886. int passPosition = 0;
  887. int passEndPosition = 0;
  888. string displayConnectionString = null;
  889. // hide the password in the connection string
  890. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  891. passPosition = connectionString.IndexOf("=", passPosition);
  892. if (passPosition < connectionString.Length)
  893. passPosition += 1;
  894. passEndPosition = connectionString.IndexOf(";", passPosition);
  895. displayConnectionString = connectionString.Substring(0, passPosition);
  896. displayConnectionString += "***";
  897. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  898. return displayConnectionString;
  899. }
  900. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  901. {
  902. Type settingsType = settingsClass.GetType();
  903. FieldInfo[] fieldInfos = settingsType.GetFields();
  904. foreach (FieldInfo fieldInfo in fieldInfos)
  905. {
  906. if (!fieldInfo.IsStatic)
  907. {
  908. if (fieldInfo.FieldType == typeof(System.String))
  909. {
  910. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  911. }
  912. else if (fieldInfo.FieldType == typeof(System.Boolean))
  913. {
  914. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  915. }
  916. else if (fieldInfo.FieldType == typeof(System.Int32))
  917. {
  918. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  919. }
  920. else if (fieldInfo.FieldType == typeof(System.Single))
  921. {
  922. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  923. }
  924. else if (fieldInfo.FieldType == typeof(System.UInt32))
  925. {
  926. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  927. }
  928. }
  929. }
  930. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  931. foreach (PropertyInfo propInfo in propertyInfos)
  932. {
  933. if ((propInfo.CanRead) && (propInfo.CanWrite))
  934. {
  935. if (propInfo.PropertyType == typeof(System.String))
  936. {
  937. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  938. }
  939. else if (propInfo.PropertyType == typeof(System.Boolean))
  940. {
  941. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  942. }
  943. else if (propInfo.PropertyType == typeof(System.Int32))
  944. {
  945. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  946. }
  947. else if (propInfo.PropertyType == typeof(System.Single))
  948. {
  949. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  950. }
  951. if (propInfo.PropertyType == typeof(System.UInt32))
  952. {
  953. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  954. }
  955. }
  956. }
  957. return settingsClass;
  958. }
  959. public static string Base64ToString(string str)
  960. {
  961. UTF8Encoding encoder = new UTF8Encoding();
  962. Decoder utf8Decode = encoder.GetDecoder();
  963. byte[] todecode_byte = Convert.FromBase64String(str);
  964. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  965. char[] decoded_char = new char[charCount];
  966. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  967. string result = new String(decoded_char);
  968. return result;
  969. }
  970. public static Guid GetHashGuid(string data, string salt)
  971. {
  972. byte[] hash = ComputeMD5Hash(data + salt);
  973. //string s = BitConverter.ToString(hash);
  974. Guid guid = new Guid(hash);
  975. return guid;
  976. }
  977. public static byte ConvertMaturityToAccessLevel(uint maturity)
  978. {
  979. byte retVal = 0;
  980. switch (maturity)
  981. {
  982. case 0: //PG
  983. retVal = 13;
  984. break;
  985. case 1: //Mature
  986. retVal = 21;
  987. break;
  988. case 2: // Adult
  989. retVal = 42;
  990. break;
  991. }
  992. return retVal;
  993. }
  994. /// <summary>
  995. /// Produces an OSDMap from its string representation on a stream
  996. /// </summary>
  997. /// <param name="data">The stream</param>
  998. /// <param name="length">The size of the data on the stream</param>
  999. /// <returns>The OSDMap or an exception</returns>
  1000. public static OSDMap GetOSDMap(Stream stream, int length)
  1001. {
  1002. byte[] data = new byte[length];
  1003. stream.Read(data, 0, length);
  1004. string strdata = Util.UTF8.GetString(data);
  1005. OSDMap args = null;
  1006. OSD buffer;
  1007. buffer = OSDParser.DeserializeJson(strdata);
  1008. if (buffer.Type == OSDType.Map)
  1009. {
  1010. args = (OSDMap)buffer;
  1011. return args;
  1012. }
  1013. return null;
  1014. }
  1015. public static string[] Glob(string path)
  1016. {
  1017. string vol=String.Empty;
  1018. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1019. {
  1020. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1021. if (vcomps.Length > 1)
  1022. {
  1023. path = vcomps[1];
  1024. vol = vcomps[0];
  1025. }
  1026. }
  1027. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1028. // Glob
  1029. path = vol;
  1030. if (vol != String.Empty)
  1031. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1032. else
  1033. path = new String(new char[] {Path.DirectorySeparatorChar});
  1034. List<string> paths = new List<string>();
  1035. List<string> found = new List<string>();
  1036. paths.Add(path);
  1037. int compIndex = -1;
  1038. foreach (string c in comps)
  1039. {
  1040. compIndex++;
  1041. List<string> addpaths = new List<string>();
  1042. foreach (string p in paths)
  1043. {
  1044. string[] dirs = Directory.GetDirectories(p, c);
  1045. if (dirs.Length != 0)
  1046. {
  1047. foreach (string dir in dirs)
  1048. addpaths.Add(Path.Combine(path, dir));
  1049. }
  1050. // Only add files if that is the last path component
  1051. if (compIndex == comps.Length - 1)
  1052. {
  1053. string[] files = Directory.GetFiles(p, c);
  1054. foreach (string f in files)
  1055. found.Add(f);
  1056. }
  1057. }
  1058. paths = addpaths;
  1059. }
  1060. return found.ToArray();
  1061. }
  1062. public static string ServerURI(string uri)
  1063. {
  1064. if (uri == string.Empty)
  1065. return string.Empty;
  1066. // Get rid of eventual slashes at the end
  1067. uri = uri.TrimEnd('/');
  1068. IPAddress ipaddr1 = null;
  1069. string port1 = "";
  1070. try
  1071. {
  1072. ipaddr1 = Util.GetHostFromURL(uri);
  1073. }
  1074. catch { }
  1075. try
  1076. {
  1077. port1 = uri.Split(new char[] { ':' })[2];
  1078. }
  1079. catch { }
  1080. // We tried our best to convert the domain names to IP addresses
  1081. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1082. }
  1083. public static byte[] StringToBytes256(string str)
  1084. {
  1085. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1086. if (str.Length > 254) str = str.Remove(254);
  1087. if (!str.EndsWith("\0")) { str += "\0"; }
  1088. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1089. // might have gotten an oversized array even after the string trim
  1090. byte[] data = UTF8.GetBytes(str);
  1091. if (data.Length > 256)
  1092. {
  1093. Array.Resize<byte>(ref data, 256);
  1094. data[255] = 0;
  1095. }
  1096. return data;
  1097. }
  1098. public static byte[] StringToBytes1024(string str)
  1099. {
  1100. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1101. if (str.Length > 1023) str = str.Remove(1023);
  1102. if (!str.EndsWith("\0")) { str += "\0"; }
  1103. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1104. // might have gotten an oversized array even after the string trim
  1105. byte[] data = UTF8.GetBytes(str);
  1106. if (data.Length > 1024)
  1107. {
  1108. Array.Resize<byte>(ref data, 1024);
  1109. data[1023] = 0;
  1110. }
  1111. return data;
  1112. }
  1113. #region FireAndForget Threading Pattern
  1114. /// <summary>
  1115. /// Created to work around a limitation in Mono with nested delegates
  1116. /// </summary>
  1117. private class FireAndForgetWrapper
  1118. {
  1119. public void FireAndForget(System.Threading.WaitCallback callback)
  1120. {
  1121. callback.BeginInvoke(null, EndFireAndForget, callback);
  1122. }
  1123. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1124. {
  1125. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1126. }
  1127. private static void EndFireAndForget(IAsyncResult ar)
  1128. {
  1129. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1130. try { callback.EndInvoke(ar); }
  1131. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1132. ar.AsyncWaitHandle.Close();
  1133. }
  1134. }
  1135. public static void FireAndForget(System.Threading.WaitCallback callback)
  1136. {
  1137. FireAndForget(callback, null);
  1138. }
  1139. public static void InitThreadPool(int maxThreads)
  1140. {
  1141. if (maxThreads < 2)
  1142. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1143. if (m_ThreadPool != null)
  1144. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1145. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1146. }
  1147. public static int FireAndForgetCount()
  1148. {
  1149. const int MAX_SYSTEM_THREADS = 200;
  1150. switch (FireAndForgetMethod)
  1151. {
  1152. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1153. case FireAndForgetMethod.QueueUserWorkItem:
  1154. case FireAndForgetMethod.BeginInvoke:
  1155. int workerThreads, iocpThreads;
  1156. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1157. return workerThreads;
  1158. case FireAndForgetMethod.SmartThreadPool:
  1159. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1160. case FireAndForgetMethod.Thread:
  1161. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1162. default:
  1163. throw new NotImplementedException();
  1164. }
  1165. }
  1166. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1167. {
  1168. switch (FireAndForgetMethod)
  1169. {
  1170. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1171. ThreadPool.UnsafeQueueUserWorkItem(callback, obj);
  1172. break;
  1173. case FireAndForgetMethod.QueueUserWorkItem:
  1174. ThreadPool.QueueUserWorkItem(callback, obj);
  1175. break;
  1176. case FireAndForgetMethod.BeginInvoke:
  1177. FireAndForgetWrapper wrapper = Singleton.GetInstance<FireAndForgetWrapper>();
  1178. wrapper.FireAndForget(callback, obj);
  1179. break;
  1180. case FireAndForgetMethod.SmartThreadPool:
  1181. if (m_ThreadPool == null)
  1182. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1183. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { callback, obj });
  1184. break;
  1185. case FireAndForgetMethod.Thread:
  1186. Thread thread = new Thread(delegate(object o) { callback(o); });
  1187. thread.Start(obj);
  1188. break;
  1189. default:
  1190. throw new NotImplementedException();
  1191. }
  1192. }
  1193. private static object SmartThreadPoolCallback(object o)
  1194. {
  1195. object[] array = (object[])o;
  1196. WaitCallback callback = (WaitCallback)array[0];
  1197. object obj = array[1];
  1198. callback(obj);
  1199. return null;
  1200. }
  1201. #endregion FireAndForget Threading Pattern
  1202. }
  1203. }