Util.cs 57 KB

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