Util.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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. IPAddress[] iplist = GetLocalHosts();
  520. if (iplist.Length == 0) // No accessible external interfaces
  521. {
  522. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  523. IPAddress localhost = loopback[0];
  524. return localhost;
  525. }
  526. foreach (IPAddress host in iplist)
  527. {
  528. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  529. {
  530. return host;
  531. }
  532. }
  533. if (iplist.Length > 0)
  534. {
  535. foreach (IPAddress host in iplist)
  536. {
  537. if (host.AddressFamily == AddressFamily.InterNetwork)
  538. return host;
  539. }
  540. // Well all else failed...
  541. return iplist[0];
  542. }
  543. return null;
  544. }
  545. /// <summary>
  546. /// Removes all invalid path chars (OS dependent)
  547. /// </summary>
  548. /// <param name="path">path</param>
  549. /// <returns>safe path</returns>
  550. public static string safePath(string path)
  551. {
  552. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  553. }
  554. /// <summary>
  555. /// Removes all invalid filename chars (OS dependent)
  556. /// </summary>
  557. /// <param name="path">filename</param>
  558. /// <returns>safe filename</returns>
  559. public static string safeFileName(string filename)
  560. {
  561. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  562. ;
  563. }
  564. //
  565. // directory locations
  566. //
  567. public static string homeDir()
  568. {
  569. string temp;
  570. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  571. // temp = Path.Combine(personal,".OpenSim");
  572. temp = ".";
  573. return temp;
  574. }
  575. public static string assetsDir()
  576. {
  577. return Path.Combine(configDir(), "assets");
  578. }
  579. public static string inventoryDir()
  580. {
  581. return Path.Combine(configDir(), "inventory");
  582. }
  583. public static string configDir()
  584. {
  585. return ".";
  586. }
  587. public static string dataDir()
  588. {
  589. return ".";
  590. }
  591. public static string logDir()
  592. {
  593. return ".";
  594. }
  595. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  596. public static string GetUniqueFilename(string FileName)
  597. {
  598. int count = 0;
  599. string Name;
  600. if (File.Exists(FileName))
  601. {
  602. FileInfo f = new FileInfo(FileName);
  603. if (!String.IsNullOrEmpty(f.Extension))
  604. {
  605. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  606. }
  607. else
  608. {
  609. Name = f.FullName;
  610. }
  611. while (File.Exists(FileName))
  612. {
  613. count++;
  614. FileName = Name + count + f.Extension;
  615. }
  616. }
  617. return FileName;
  618. }
  619. // Nini (config) related Methods
  620. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  621. {
  622. if (!File.Exists(fileName))
  623. {
  624. //create new file
  625. }
  626. XmlConfigSource config = new XmlConfigSource(fileName);
  627. AddDataRowToConfig(config, row);
  628. config.Save();
  629. return config;
  630. }
  631. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  632. {
  633. config.Configs.Add((string) row[0]);
  634. for (int i = 0; i < row.Table.Columns.Count; i++)
  635. {
  636. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  637. }
  638. }
  639. public static float Clip(float x, float min, float max)
  640. {
  641. return Math.Min(Math.Max(x, min), max);
  642. }
  643. public static int Clip(int x, int min, int max)
  644. {
  645. return Math.Min(Math.Max(x, min), max);
  646. }
  647. /// <summary>
  648. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  649. /// </summary>
  650. /// <param name="UUID"></param>
  651. /// <returns></returns>
  652. public static String ToRawUuidString(UUID UUID)
  653. {
  654. return UUID.Guid.ToString("n");
  655. }
  656. public static string CleanString(string input)
  657. {
  658. if (input.Length == 0)
  659. return input;
  660. int clip = input.Length;
  661. // Test for ++ string terminator
  662. int pos = input.IndexOf("\0");
  663. if (pos != -1 && pos < clip)
  664. clip = pos;
  665. // Test for CR
  666. pos = input.IndexOf("\r");
  667. if (pos != -1 && pos < clip)
  668. clip = pos;
  669. // Test for LF
  670. pos = input.IndexOf("\n");
  671. if (pos != -1 && pos < clip)
  672. clip = pos;
  673. // Truncate string before first end-of-line character found
  674. return input.Substring(0, clip);
  675. }
  676. /// <summary>
  677. /// returns the contents of /etc/issue on Unix Systems
  678. /// Use this for where it's absolutely necessary to implement platform specific stuff
  679. /// </summary>
  680. /// <returns></returns>
  681. public static string ReadEtcIssue()
  682. {
  683. try
  684. {
  685. StreamReader sr = new StreamReader("/etc/issue.net");
  686. string issue = sr.ReadToEnd();
  687. sr.Close();
  688. return issue;
  689. }
  690. catch (Exception)
  691. {
  692. return "";
  693. }
  694. }
  695. public static void SerializeToFile(string filename, Object obj)
  696. {
  697. IFormatter formatter = new BinaryFormatter();
  698. Stream stream = null;
  699. try
  700. {
  701. stream = new FileStream(
  702. filename, FileMode.Create,
  703. FileAccess.Write, FileShare.None);
  704. formatter.Serialize(stream, obj);
  705. }
  706. catch (Exception e)
  707. {
  708. m_log.Error(e.ToString());
  709. }
  710. finally
  711. {
  712. if (stream != null)
  713. {
  714. stream.Close();
  715. }
  716. }
  717. }
  718. public static Object DeserializeFromFile(string filename)
  719. {
  720. IFormatter formatter = new BinaryFormatter();
  721. Stream stream = null;
  722. Object ret = null;
  723. try
  724. {
  725. stream = new FileStream(
  726. filename, FileMode.Open,
  727. FileAccess.Read, FileShare.None);
  728. ret = formatter.Deserialize(stream);
  729. }
  730. catch (Exception e)
  731. {
  732. m_log.Error(e.ToString());
  733. }
  734. finally
  735. {
  736. if (stream != null)
  737. {
  738. stream.Close();
  739. }
  740. }
  741. return ret;
  742. }
  743. public static string Compress(string text)
  744. {
  745. byte[] buffer = Util.UTF8.GetBytes(text);
  746. MemoryStream memory = new MemoryStream();
  747. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  748. {
  749. compressor.Write(buffer, 0, buffer.Length);
  750. }
  751. memory.Position = 0;
  752. byte[] compressed = new byte[memory.Length];
  753. memory.Read(compressed, 0, compressed.Length);
  754. byte[] compressedBuffer = new byte[compressed.Length + 4];
  755. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  756. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  757. return Convert.ToBase64String(compressedBuffer);
  758. }
  759. public static string Decompress(string compressedText)
  760. {
  761. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  762. using (MemoryStream memory = new MemoryStream())
  763. {
  764. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  765. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  766. byte[] buffer = new byte[msgLength];
  767. memory.Position = 0;
  768. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  769. {
  770. decompressor.Read(buffer, 0, buffer.Length);
  771. }
  772. return Util.UTF8.GetString(buffer);
  773. }
  774. }
  775. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  776. {
  777. return SendXmlRpcCommand(url, methodName, args);
  778. }
  779. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  780. {
  781. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  782. return client.Send(url, 6000);
  783. }
  784. /// <summary>
  785. /// Returns an error message that the user could not be found in the database
  786. /// </summary>
  787. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  788. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  789. {
  790. XmlRpcResponse response = new XmlRpcResponse();
  791. Hashtable responseData = new Hashtable();
  792. responseData["error_type"] = "unknown_user";
  793. responseData["error_desc"] = "The user requested is not in the database";
  794. response.Value = responseData;
  795. return response;
  796. }
  797. /// <summary>
  798. /// Converts a byte array in big endian order into an ulong.
  799. /// </summary>
  800. /// <param name="bytes">
  801. /// The array of bytes
  802. /// </param>
  803. /// <returns>
  804. /// The extracted ulong
  805. /// </returns>
  806. public static ulong BytesToUInt64Big(byte[] bytes)
  807. {
  808. if (bytes.Length < 8) return 0;
  809. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  810. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  811. }
  812. // used for RemoteParcelRequest (for "About Landmark")
  813. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  814. {
  815. byte[] bytes =
  816. {
  817. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  818. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  819. (byte)x, (byte)(x >> 8), 0, 0,
  820. (byte)y, (byte)(y >> 8), 0, 0 };
  821. return new UUID(bytes, 0);
  822. }
  823. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  824. {
  825. byte[] bytes =
  826. {
  827. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  828. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  829. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  830. (byte)y, (byte)(y >> 8), 0, 0 };
  831. return new UUID(bytes, 0);
  832. }
  833. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  834. {
  835. byte[] bytes = parcelID.GetBytes();
  836. regionHandle = Utils.BytesToUInt64(bytes);
  837. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  838. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  839. }
  840. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  841. {
  842. byte[] bytes = parcelID.GetBytes();
  843. regionHandle = Utils.BytesToUInt64(bytes);
  844. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  845. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  846. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  847. }
  848. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  849. {
  850. ulong regionHandle;
  851. uint rx, ry;
  852. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  853. Utils.LongToUInts(regionHandle, out rx, out ry);
  854. x += rx;
  855. y += ry;
  856. }
  857. /// <summary>
  858. /// Get operating system information if available. Returns only the first 45 characters of information
  859. /// </summary>
  860. /// <returns>
  861. /// Operating system information. Returns an empty string if none was available.
  862. /// </returns>
  863. public static string GetOperatingSystemInformation()
  864. {
  865. string os = String.Empty;
  866. if (Environment.OSVersion.Platform != PlatformID.Unix)
  867. {
  868. os = Environment.OSVersion.ToString();
  869. }
  870. else
  871. {
  872. os = ReadEtcIssue();
  873. }
  874. if (os.Length > 45)
  875. {
  876. os = os.Substring(0, 45);
  877. }
  878. return os;
  879. }
  880. public static string GetRuntimeInformation()
  881. {
  882. string ru = String.Empty;
  883. if (Environment.OSVersion.Platform == PlatformID.Unix)
  884. ru = "Unix/Mono";
  885. else
  886. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  887. ru = "OSX/Mono";
  888. else
  889. {
  890. if (Type.GetType("Mono.Runtime") != null)
  891. ru = "Win/Mono";
  892. else
  893. ru = "Win/.NET";
  894. }
  895. return ru;
  896. }
  897. /// <summary>
  898. /// Is the given string a UUID?
  899. /// </summary>
  900. /// <param name="s"></param>
  901. /// <returns></returns>
  902. public static bool isUUID(string s)
  903. {
  904. return UUIDPattern.IsMatch(s);
  905. }
  906. public static string GetDisplayConnectionString(string connectionString)
  907. {
  908. int passPosition = 0;
  909. int passEndPosition = 0;
  910. string displayConnectionString = null;
  911. // hide the password in the connection string
  912. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  913. passPosition = connectionString.IndexOf("=", passPosition);
  914. if (passPosition < connectionString.Length)
  915. passPosition += 1;
  916. passEndPosition = connectionString.IndexOf(";", passPosition);
  917. displayConnectionString = connectionString.Substring(0, passPosition);
  918. displayConnectionString += "***";
  919. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  920. return displayConnectionString;
  921. }
  922. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  923. {
  924. Type settingsType = settingsClass.GetType();
  925. FieldInfo[] fieldInfos = settingsType.GetFields();
  926. foreach (FieldInfo fieldInfo in fieldInfos)
  927. {
  928. if (!fieldInfo.IsStatic)
  929. {
  930. if (fieldInfo.FieldType == typeof(System.String))
  931. {
  932. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  933. }
  934. else if (fieldInfo.FieldType == typeof(System.Boolean))
  935. {
  936. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  937. }
  938. else if (fieldInfo.FieldType == typeof(System.Int32))
  939. {
  940. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  941. }
  942. else if (fieldInfo.FieldType == typeof(System.Single))
  943. {
  944. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  945. }
  946. else if (fieldInfo.FieldType == typeof(System.UInt32))
  947. {
  948. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  949. }
  950. }
  951. }
  952. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  953. foreach (PropertyInfo propInfo in propertyInfos)
  954. {
  955. if ((propInfo.CanRead) && (propInfo.CanWrite))
  956. {
  957. if (propInfo.PropertyType == typeof(System.String))
  958. {
  959. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  960. }
  961. else if (propInfo.PropertyType == typeof(System.Boolean))
  962. {
  963. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  964. }
  965. else if (propInfo.PropertyType == typeof(System.Int32))
  966. {
  967. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  968. }
  969. else if (propInfo.PropertyType == typeof(System.Single))
  970. {
  971. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  972. }
  973. if (propInfo.PropertyType == typeof(System.UInt32))
  974. {
  975. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  976. }
  977. }
  978. }
  979. return settingsClass;
  980. }
  981. public static string Base64ToString(string str)
  982. {
  983. UTF8Encoding encoder = new UTF8Encoding();
  984. Decoder utf8Decode = encoder.GetDecoder();
  985. byte[] todecode_byte = Convert.FromBase64String(str);
  986. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  987. char[] decoded_char = new char[charCount];
  988. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  989. string result = new String(decoded_char);
  990. return result;
  991. }
  992. public static Guid GetHashGuid(string data, string salt)
  993. {
  994. byte[] hash = ComputeMD5Hash(data + salt);
  995. //string s = BitConverter.ToString(hash);
  996. Guid guid = new Guid(hash);
  997. return guid;
  998. }
  999. public static byte ConvertMaturityToAccessLevel(uint maturity)
  1000. {
  1001. byte retVal = 0;
  1002. switch (maturity)
  1003. {
  1004. case 0: //PG
  1005. retVal = 13;
  1006. break;
  1007. case 1: //Mature
  1008. retVal = 21;
  1009. break;
  1010. case 2: // Adult
  1011. retVal = 42;
  1012. break;
  1013. }
  1014. return retVal;
  1015. }
  1016. public static uint ConvertAccessLevelToMaturity(byte maturity)
  1017. {
  1018. if (maturity <= 13)
  1019. return 0;
  1020. else if (maturity <= 21)
  1021. return 1;
  1022. else
  1023. return 2;
  1024. }
  1025. /// <summary>
  1026. /// Produces an OSDMap from its string representation on a stream
  1027. /// </summary>
  1028. /// <param name="data">The stream</param>
  1029. /// <param name="length">The size of the data on the stream</param>
  1030. /// <returns>The OSDMap or an exception</returns>
  1031. public static OSDMap GetOSDMap(Stream stream, int length)
  1032. {
  1033. byte[] data = new byte[length];
  1034. stream.Read(data, 0, length);
  1035. string strdata = Util.UTF8.GetString(data);
  1036. OSDMap args = null;
  1037. OSD buffer;
  1038. buffer = OSDParser.DeserializeJson(strdata);
  1039. if (buffer.Type == OSDType.Map)
  1040. {
  1041. args = (OSDMap)buffer;
  1042. return args;
  1043. }
  1044. return null;
  1045. }
  1046. public static string[] Glob(string path)
  1047. {
  1048. string vol=String.Empty;
  1049. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1050. {
  1051. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1052. if (vcomps.Length > 1)
  1053. {
  1054. path = vcomps[1];
  1055. vol = vcomps[0];
  1056. }
  1057. }
  1058. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1059. // Glob
  1060. path = vol;
  1061. if (vol != String.Empty)
  1062. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1063. else
  1064. path = new String(new char[] {Path.DirectorySeparatorChar});
  1065. List<string> paths = new List<string>();
  1066. List<string> found = new List<string>();
  1067. paths.Add(path);
  1068. int compIndex = -1;
  1069. foreach (string c in comps)
  1070. {
  1071. compIndex++;
  1072. List<string> addpaths = new List<string>();
  1073. foreach (string p in paths)
  1074. {
  1075. string[] dirs = Directory.GetDirectories(p, c);
  1076. if (dirs.Length != 0)
  1077. {
  1078. foreach (string dir in dirs)
  1079. addpaths.Add(Path.Combine(path, dir));
  1080. }
  1081. // Only add files if that is the last path component
  1082. if (compIndex == comps.Length - 1)
  1083. {
  1084. string[] files = Directory.GetFiles(p, c);
  1085. foreach (string f in files)
  1086. found.Add(f);
  1087. }
  1088. }
  1089. paths = addpaths;
  1090. }
  1091. return found.ToArray();
  1092. }
  1093. public static string ServerURI(string uri)
  1094. {
  1095. if (uri == string.Empty)
  1096. return string.Empty;
  1097. // Get rid of eventual slashes at the end
  1098. uri = uri.TrimEnd('/');
  1099. IPAddress ipaddr1 = null;
  1100. string port1 = "";
  1101. try
  1102. {
  1103. ipaddr1 = Util.GetHostFromURL(uri);
  1104. }
  1105. catch { }
  1106. try
  1107. {
  1108. port1 = uri.Split(new char[] { ':' })[2];
  1109. }
  1110. catch { }
  1111. // We tried our best to convert the domain names to IP addresses
  1112. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1113. }
  1114. public static byte[] StringToBytes256(string str)
  1115. {
  1116. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1117. if (str.Length > 254) str = str.Remove(254);
  1118. if (!str.EndsWith("\0")) { str += "\0"; }
  1119. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1120. // might have gotten an oversized array even after the string trim
  1121. byte[] data = UTF8.GetBytes(str);
  1122. if (data.Length > 256)
  1123. {
  1124. Array.Resize<byte>(ref data, 256);
  1125. data[255] = 0;
  1126. }
  1127. return data;
  1128. }
  1129. public static byte[] StringToBytes1024(string str)
  1130. {
  1131. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1132. if (str.Length > 1023) str = str.Remove(1023);
  1133. if (!str.EndsWith("\0")) { str += "\0"; }
  1134. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1135. // might have gotten an oversized array even after the string trim
  1136. byte[] data = UTF8.GetBytes(str);
  1137. if (data.Length > 1024)
  1138. {
  1139. Array.Resize<byte>(ref data, 1024);
  1140. data[1023] = 0;
  1141. }
  1142. return data;
  1143. }
  1144. #region FireAndForget Threading Pattern
  1145. /// <summary>
  1146. /// Created to work around a limitation in Mono with nested delegates
  1147. /// </summary>
  1148. private class FireAndForgetWrapper
  1149. {
  1150. public void FireAndForget(System.Threading.WaitCallback callback)
  1151. {
  1152. callback.BeginInvoke(null, EndFireAndForget, callback);
  1153. }
  1154. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1155. {
  1156. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1157. }
  1158. private static void EndFireAndForget(IAsyncResult ar)
  1159. {
  1160. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1161. try { callback.EndInvoke(ar); }
  1162. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1163. ar.AsyncWaitHandle.Close();
  1164. }
  1165. }
  1166. public static void FireAndForget(System.Threading.WaitCallback callback)
  1167. {
  1168. FireAndForget(callback, null);
  1169. }
  1170. public static void InitThreadPool(int maxThreads)
  1171. {
  1172. if (maxThreads < 2)
  1173. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1174. if (m_ThreadPool != null)
  1175. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1176. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1177. }
  1178. public static int FireAndForgetCount()
  1179. {
  1180. const int MAX_SYSTEM_THREADS = 200;
  1181. switch (FireAndForgetMethod)
  1182. {
  1183. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1184. case FireAndForgetMethod.QueueUserWorkItem:
  1185. case FireAndForgetMethod.BeginInvoke:
  1186. int workerThreads, iocpThreads;
  1187. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1188. return workerThreads;
  1189. case FireAndForgetMethod.SmartThreadPool:
  1190. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1191. case FireAndForgetMethod.Thread:
  1192. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1193. default:
  1194. throw new NotImplementedException();
  1195. }
  1196. }
  1197. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1198. {
  1199. switch (FireAndForgetMethod)
  1200. {
  1201. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1202. ThreadPool.UnsafeQueueUserWorkItem(callback, obj);
  1203. break;
  1204. case FireAndForgetMethod.QueueUserWorkItem:
  1205. ThreadPool.QueueUserWorkItem(callback, obj);
  1206. break;
  1207. case FireAndForgetMethod.BeginInvoke:
  1208. FireAndForgetWrapper wrapper = Singleton.GetInstance<FireAndForgetWrapper>();
  1209. wrapper.FireAndForget(callback, obj);
  1210. break;
  1211. case FireAndForgetMethod.SmartThreadPool:
  1212. if (m_ThreadPool == null)
  1213. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1214. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { callback, obj });
  1215. break;
  1216. case FireAndForgetMethod.Thread:
  1217. Thread thread = new Thread(delegate(object o) { callback(o); });
  1218. thread.Start(obj);
  1219. break;
  1220. default:
  1221. throw new NotImplementedException();
  1222. }
  1223. }
  1224. private static object SmartThreadPoolCallback(object o)
  1225. {
  1226. object[] array = (object[])o;
  1227. WaitCallback callback = (WaitCallback)array[0];
  1228. object obj = array[1];
  1229. callback(obj);
  1230. return null;
  1231. }
  1232. #endregion FireAndForget Threading Pattern
  1233. /// <summary>
  1234. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1235. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1236. /// for the callers.
  1237. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1238. /// </summary>
  1239. /// <returns></returns>
  1240. public static Int32 EnvironmentTickCount()
  1241. {
  1242. return Environment.TickCount & EnvironmentTickCountMask;
  1243. }
  1244. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1245. /// <summary>
  1246. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1247. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1248. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1249. /// </summary>
  1250. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1251. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1252. {
  1253. Int32 diff = EnvironmentTickCount() - prevValue;
  1254. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1255. }
  1256. }
  1257. }