Util.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489
  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. /// <summary>
  1018. /// Produces an OSDMap from its string representation on a stream
  1019. /// </summary>
  1020. /// <param name="data">The stream</param>
  1021. /// <param name="length">The size of the data on the stream</param>
  1022. /// <returns>The OSDMap or an exception</returns>
  1023. public static OSDMap GetOSDMap(Stream stream, int length)
  1024. {
  1025. byte[] data = new byte[length];
  1026. stream.Read(data, 0, length);
  1027. string strdata = Util.UTF8.GetString(data);
  1028. OSDMap args = null;
  1029. OSD buffer;
  1030. buffer = OSDParser.DeserializeJson(strdata);
  1031. if (buffer.Type == OSDType.Map)
  1032. {
  1033. args = (OSDMap)buffer;
  1034. return args;
  1035. }
  1036. return null;
  1037. }
  1038. public static OSDMap GetOSDMap(string data)
  1039. {
  1040. OSDMap args = null;
  1041. try
  1042. {
  1043. OSD buffer;
  1044. // We should pay attention to the content-type, but let's assume we know it's Json
  1045. buffer = OSDParser.DeserializeJson(data);
  1046. if (buffer.Type == OSDType.Map)
  1047. {
  1048. args = (OSDMap)buffer;
  1049. return args;
  1050. }
  1051. else
  1052. {
  1053. // uh?
  1054. m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
  1055. return null;
  1056. }
  1057. }
  1058. catch (Exception ex)
  1059. {
  1060. m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
  1061. return null;
  1062. }
  1063. }
  1064. public static string[] Glob(string path)
  1065. {
  1066. string vol=String.Empty;
  1067. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1068. {
  1069. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1070. if (vcomps.Length > 1)
  1071. {
  1072. path = vcomps[1];
  1073. vol = vcomps[0];
  1074. }
  1075. }
  1076. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1077. // Glob
  1078. path = vol;
  1079. if (vol != String.Empty)
  1080. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1081. else
  1082. path = new String(new char[] {Path.DirectorySeparatorChar});
  1083. List<string> paths = new List<string>();
  1084. List<string> found = new List<string>();
  1085. paths.Add(path);
  1086. int compIndex = -1;
  1087. foreach (string c in comps)
  1088. {
  1089. compIndex++;
  1090. List<string> addpaths = new List<string>();
  1091. foreach (string p in paths)
  1092. {
  1093. string[] dirs = Directory.GetDirectories(p, c);
  1094. if (dirs.Length != 0)
  1095. {
  1096. foreach (string dir in dirs)
  1097. addpaths.Add(Path.Combine(path, dir));
  1098. }
  1099. // Only add files if that is the last path component
  1100. if (compIndex == comps.Length - 1)
  1101. {
  1102. string[] files = Directory.GetFiles(p, c);
  1103. foreach (string f in files)
  1104. found.Add(f);
  1105. }
  1106. }
  1107. paths = addpaths;
  1108. }
  1109. return found.ToArray();
  1110. }
  1111. public static string ServerURI(string uri)
  1112. {
  1113. if (uri == string.Empty)
  1114. return string.Empty;
  1115. // Get rid of eventual slashes at the end
  1116. uri = uri.TrimEnd('/');
  1117. IPAddress ipaddr1 = null;
  1118. string port1 = "";
  1119. try
  1120. {
  1121. ipaddr1 = Util.GetHostFromURL(uri);
  1122. }
  1123. catch { }
  1124. try
  1125. {
  1126. port1 = uri.Split(new char[] { ':' })[2];
  1127. }
  1128. catch { }
  1129. // We tried our best to convert the domain names to IP addresses
  1130. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1131. }
  1132. public static byte[] StringToBytes256(string str)
  1133. {
  1134. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1135. if (str.Length > 254) str = str.Remove(254);
  1136. if (!str.EndsWith("\0")) { str += "\0"; }
  1137. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1138. // might have gotten an oversized array even after the string trim
  1139. byte[] data = UTF8.GetBytes(str);
  1140. if (data.Length > 256)
  1141. {
  1142. Array.Resize<byte>(ref data, 256);
  1143. data[255] = 0;
  1144. }
  1145. return data;
  1146. }
  1147. public static byte[] StringToBytes1024(string str)
  1148. {
  1149. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1150. if (str.Length > 1023) str = str.Remove(1023);
  1151. if (!str.EndsWith("\0")) { str += "\0"; }
  1152. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1153. // might have gotten an oversized array even after the string trim
  1154. byte[] data = UTF8.GetBytes(str);
  1155. if (data.Length > 1024)
  1156. {
  1157. Array.Resize<byte>(ref data, 1024);
  1158. data[1023] = 0;
  1159. }
  1160. return data;
  1161. }
  1162. #region FireAndForget Threading Pattern
  1163. /// <summary>
  1164. /// Created to work around a limitation in Mono with nested delegates
  1165. /// </summary>
  1166. private class FireAndForgetWrapper
  1167. {
  1168. public void FireAndForget(System.Threading.WaitCallback callback)
  1169. {
  1170. callback.BeginInvoke(null, EndFireAndForget, callback);
  1171. }
  1172. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1173. {
  1174. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1175. }
  1176. private static void EndFireAndForget(IAsyncResult ar)
  1177. {
  1178. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1179. try { callback.EndInvoke(ar); }
  1180. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1181. ar.AsyncWaitHandle.Close();
  1182. }
  1183. }
  1184. public static void FireAndForget(System.Threading.WaitCallback callback)
  1185. {
  1186. FireAndForget(callback, null);
  1187. }
  1188. public static void InitThreadPool(int maxThreads)
  1189. {
  1190. if (maxThreads < 2)
  1191. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1192. if (m_ThreadPool != null)
  1193. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1194. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1195. }
  1196. public static int FireAndForgetCount()
  1197. {
  1198. const int MAX_SYSTEM_THREADS = 200;
  1199. switch (FireAndForgetMethod)
  1200. {
  1201. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1202. case FireAndForgetMethod.QueueUserWorkItem:
  1203. case FireAndForgetMethod.BeginInvoke:
  1204. int workerThreads, iocpThreads;
  1205. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1206. return workerThreads;
  1207. case FireAndForgetMethod.SmartThreadPool:
  1208. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1209. case FireAndForgetMethod.Thread:
  1210. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1211. default:
  1212. throw new NotImplementedException();
  1213. }
  1214. }
  1215. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1216. {
  1217. switch (FireAndForgetMethod)
  1218. {
  1219. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1220. ThreadPool.UnsafeQueueUserWorkItem(callback, obj);
  1221. break;
  1222. case FireAndForgetMethod.QueueUserWorkItem:
  1223. ThreadPool.QueueUserWorkItem(callback, obj);
  1224. break;
  1225. case FireAndForgetMethod.BeginInvoke:
  1226. FireAndForgetWrapper wrapper = Singleton.GetInstance<FireAndForgetWrapper>();
  1227. wrapper.FireAndForget(callback, obj);
  1228. break;
  1229. case FireAndForgetMethod.SmartThreadPool:
  1230. if (m_ThreadPool == null)
  1231. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1232. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { callback, obj });
  1233. break;
  1234. case FireAndForgetMethod.Thread:
  1235. Thread thread = new Thread(delegate(object o) { callback(o); });
  1236. thread.Start(obj);
  1237. break;
  1238. default:
  1239. throw new NotImplementedException();
  1240. }
  1241. }
  1242. private static object SmartThreadPoolCallback(object o)
  1243. {
  1244. object[] array = (object[])o;
  1245. WaitCallback callback = (WaitCallback)array[0];
  1246. object obj = array[1];
  1247. callback(obj);
  1248. return null;
  1249. }
  1250. #endregion FireAndForget Threading Pattern
  1251. /// <summary>
  1252. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1253. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1254. /// for the callers.
  1255. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1256. /// </summary>
  1257. /// <returns></returns>
  1258. public static Int32 EnvironmentTickCount()
  1259. {
  1260. return Environment.TickCount & EnvironmentTickCountMask;
  1261. }
  1262. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1263. /// <summary>
  1264. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1265. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1266. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1267. /// </summary>
  1268. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1269. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1270. {
  1271. Int32 diff = EnvironmentTickCount() - prevValue;
  1272. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1273. }
  1274. /// <summary>
  1275. /// Prints the call stack at any given point. Useful for debugging.
  1276. /// </summary>
  1277. public static void PrintCallStack()
  1278. {
  1279. StackTrace stackTrace = new StackTrace(); // get call stack
  1280. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  1281. // write call stack method names
  1282. foreach (StackFrame stackFrame in stackFrames)
  1283. {
  1284. m_log.Debug(stackFrame.GetMethod().DeclaringType + "." + stackFrame.GetMethod().Name); // write method name
  1285. }
  1286. }
  1287. }
  1288. }