Util.cs 52 KB

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