Util.cs 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123
  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.InteropServices;
  39. using System.Runtime.Serialization;
  40. using System.Runtime.Serialization.Formatters.Binary;
  41. using System.Security.Cryptography;
  42. using System.Text;
  43. using System.Text.RegularExpressions;
  44. using System.Xml;
  45. using System.Threading;
  46. using log4net;
  47. using Nini.Config;
  48. using Nwc.XmlRpc;
  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. /// <remarks>
  58. /// None is used to execute the method in the same thread that made the call. It should only be used by regression
  59. /// test code that relies on predictable event ordering.
  60. /// RegressionTest is used by regression tests. It fires the call synchronously and does not catch any exceptions.
  61. /// </remarks>
  62. public enum FireAndForgetMethod
  63. {
  64. None,
  65. RegressionTest,
  66. UnsafeQueueUserWorkItem,
  67. QueueUserWorkItem,
  68. BeginInvoke,
  69. SmartThreadPool,
  70. Thread,
  71. }
  72. /// <summary>
  73. /// Miscellaneous utility functions
  74. /// </summary>
  75. public class Util
  76. {
  77. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  78. private static uint nextXferID = 5000;
  79. private static Random randomClass = new Random();
  80. // Get a list of invalid file characters (OS dependent)
  81. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  82. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  83. private static object XferLock = new object();
  84. /// <summary>
  85. /// Thread pool used for Util.FireAndForget if FireAndForgetMethod.SmartThreadPool is used
  86. /// </summary>
  87. private static SmartThreadPool m_ThreadPool;
  88. // 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.
  89. private static readonly DateTime unixEpoch =
  90. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  91. private static readonly string rawUUIDPattern
  92. = "[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}";
  93. public static readonly Regex PermissiveUUIDPattern = new Regex(rawUUIDPattern);
  94. public static readonly Regex UUIDPattern = new Regex(string.Format("^{0}$", rawUUIDPattern));
  95. public static FireAndForgetMethod DefaultFireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
  96. public static FireAndForgetMethod FireAndForgetMethod = DefaultFireAndForgetMethod;
  97. /// <summary>
  98. /// Gets the name of the directory where the current running executable
  99. /// is located
  100. /// </summary>
  101. /// <returns>Filesystem path to the directory containing the current
  102. /// executable</returns>
  103. public static string ExecutingDirectory()
  104. {
  105. return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  106. }
  107. /// <summary>
  108. /// Linear interpolates B<->C using percent A
  109. /// </summary>
  110. /// <param name="a"></param>
  111. /// <param name="b"></param>
  112. /// <param name="c"></param>
  113. /// <returns></returns>
  114. public static double lerp(double a, double b, double c)
  115. {
  116. return (b*a) + (c*(1 - a));
  117. }
  118. /// <summary>
  119. /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
  120. /// Layout:
  121. /// A B
  122. /// C D
  123. /// A<->C = Y
  124. /// C<->D = X
  125. /// </summary>
  126. /// <param name="x"></param>
  127. /// <param name="y"></param>
  128. /// <param name="a"></param>
  129. /// <param name="b"></param>
  130. /// <param name="c"></param>
  131. /// <param name="d"></param>
  132. /// <returns></returns>
  133. public static double lerp2D(double x, double y, double a, double b, double c, double d)
  134. {
  135. return lerp(y, lerp(x, a, b), lerp(x, c, d));
  136. }
  137. public static Encoding UTF8 = Encoding.UTF8;
  138. public static Encoding UTF8NoBomEncoding = new UTF8Encoding(false);
  139. /// <value>
  140. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  141. /// </value>
  142. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  143. #region Vector Equations
  144. /// <summary>
  145. /// Get the distance between two 3d vectors
  146. /// </summary>
  147. /// <param name="a">A 3d vector</param>
  148. /// <param name="b">A 3d vector</param>
  149. /// <returns>The distance between the two vectors</returns>
  150. public static double GetDistanceTo(Vector3 a, Vector3 b)
  151. {
  152. float dx = a.X - b.X;
  153. float dy = a.Y - b.Y;
  154. float dz = a.Z - b.Z;
  155. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  156. }
  157. /// <summary>
  158. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  159. /// </summary>
  160. /// <param name="a"></param>
  161. /// <param name="b"></param>
  162. /// <param name="amount"></param>
  163. /// <returns></returns>
  164. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  165. {
  166. float dx = a.X - b.X;
  167. float dy = a.Y - b.Y;
  168. float dz = a.Z - b.Z;
  169. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  170. }
  171. /// <summary>
  172. /// Get the magnitude of a 3d vector
  173. /// </summary>
  174. /// <param name="a">A 3d vector</param>
  175. /// <returns>The magnitude of the vector</returns>
  176. public static double GetMagnitude(Vector3 a)
  177. {
  178. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  179. }
  180. /// <summary>
  181. /// Get a normalized form of a 3d vector
  182. /// </summary>
  183. /// <param name="a">A 3d vector</param>
  184. /// <returns>A new vector which is normalized form of the vector</returns>
  185. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  186. public static Vector3 GetNormalizedVector(Vector3 a)
  187. {
  188. if (IsZeroVector(a))
  189. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  190. float Mag = (float) GetMagnitude(a);
  191. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  192. }
  193. /// <summary>
  194. /// Returns if a vector is a zero vector (has all zero components)
  195. /// </summary>
  196. /// <returns></returns>
  197. public static bool IsZeroVector(Vector3 v)
  198. {
  199. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  200. {
  201. return true;
  202. }
  203. return false;
  204. }
  205. # endregion
  206. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  207. {
  208. float s;
  209. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  210. if (tr >= 1.0)
  211. {
  212. s = (float) (0.5 / Math.Sqrt(tr));
  213. return new Quaternion(
  214. (left.Z - up.Y) * s,
  215. (up.X - fwd.Z) * s,
  216. (fwd.Y - left.X) * s,
  217. (float) 0.25 / s);
  218. }
  219. else
  220. {
  221. float max = (left.Y > up.Z) ? left.Y : up.Z;
  222. if (max < fwd.X)
  223. {
  224. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  225. float x = (float) (s * 0.5);
  226. s = (float) (0.5 / s);
  227. return new Quaternion(
  228. x,
  229. (fwd.Y + left.X) * s,
  230. (up.X + fwd.Z) * s,
  231. (left.Z - up.Y) * s);
  232. }
  233. else if (max == left.Y)
  234. {
  235. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  236. float y = (float) (s * 0.5);
  237. s = (float) (0.5 / s);
  238. return new Quaternion(
  239. (fwd.Y + left.X) * s,
  240. y,
  241. (left.Z + up.Y) * s,
  242. (up.X - fwd.Z) * s);
  243. }
  244. else
  245. {
  246. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  247. float z = (float) (s * 0.5);
  248. s = (float) (0.5 / s);
  249. return new Quaternion(
  250. (up.X + fwd.Z) * s,
  251. (left.Z + up.Y) * s,
  252. z,
  253. (fwd.Y - left.X) * s);
  254. }
  255. }
  256. }
  257. public static Random RandomClass
  258. {
  259. get { return randomClass; }
  260. }
  261. public static ulong UIntsToLong(uint X, uint Y)
  262. {
  263. return Utils.UIntsToLong(X, Y);
  264. }
  265. public static T Clamp<T>(T x, T min, T max)
  266. where T : IComparable<T>
  267. {
  268. return x.CompareTo(max) > 0 ? max :
  269. x.CompareTo(min) < 0 ? min :
  270. x;
  271. }
  272. // Clamp the maximum magnitude of a vector
  273. public static Vector3 ClampV(Vector3 x, float max)
  274. {
  275. Vector3 ret = x;
  276. float lenSq = x.LengthSquared();
  277. if (lenSq > (max * max))
  278. {
  279. x = x / x.Length() * max;
  280. }
  281. return x;
  282. }
  283. // Inclusive, within range test (true if equal to the endpoints)
  284. public static bool InRange<T>(T x, T min, T max)
  285. where T : IComparable<T>
  286. {
  287. return x.CompareTo(max) <= 0 && x.CompareTo(min) >= 0;
  288. }
  289. public static uint GetNextXferID()
  290. {
  291. uint id = 0;
  292. lock (XferLock)
  293. {
  294. id = nextXferID;
  295. nextXferID++;
  296. }
  297. return id;
  298. }
  299. public static string GetFileName(string file)
  300. {
  301. // Return just the filename on UNIX platforms
  302. // TODO: this should be customisable with a prefix, but that's something to do later.
  303. if (Environment.OSVersion.Platform == PlatformID.Unix)
  304. {
  305. return file;
  306. }
  307. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  308. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  309. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  310. {
  311. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  312. {
  313. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  314. }
  315. return "%APPDATA%\\OpenSim\\" + file;
  316. }
  317. // Catch all - covers older windows versions
  318. // (but those probably wont work anyway)
  319. return file;
  320. }
  321. /// <summary>
  322. /// Debug utility function to convert OSD into formatted XML for debugging purposes.
  323. /// </summary>
  324. /// <param name="osd">
  325. /// A <see cref="OSD"/>
  326. /// </param>
  327. /// <returns>
  328. /// A <see cref="System.String"/>
  329. /// </returns>
  330. public static string GetFormattedXml(OSD osd)
  331. {
  332. return GetFormattedXml(OSDParser.SerializeLLSDXmlString(osd));
  333. }
  334. /// <summary>
  335. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  336. /// </summary>
  337. /// <remarks>
  338. /// Please don't delete me even if I appear currently unused!
  339. /// </remarks>
  340. /// <param name="rawXml"></param>
  341. /// <returns></returns>
  342. public static string GetFormattedXml(string rawXml)
  343. {
  344. XmlDocument xd = new XmlDocument();
  345. xd.LoadXml(rawXml);
  346. StringBuilder sb = new StringBuilder();
  347. StringWriter sw = new StringWriter(sb);
  348. XmlTextWriter xtw = new XmlTextWriter(sw);
  349. xtw.Formatting = Formatting.Indented;
  350. try
  351. {
  352. xd.WriteTo(xtw);
  353. }
  354. finally
  355. {
  356. xtw.Close();
  357. }
  358. return sb.ToString();
  359. }
  360. /// <summary>
  361. /// Is the platform Windows?
  362. /// </summary>
  363. /// <returns>true if so, false otherwise</returns>
  364. public static bool IsWindows()
  365. {
  366. PlatformID platformId = Environment.OSVersion.Platform;
  367. return (platformId == PlatformID.Win32NT
  368. || platformId == PlatformID.Win32S
  369. || platformId == PlatformID.Win32Windows
  370. || platformId == PlatformID.WinCE);
  371. }
  372. public static bool LoadArchSpecificWindowsDll(string libraryName)
  373. {
  374. // We do this so that OpenSimulator on Windows loads the correct native library depending on whether
  375. // it's running as a 32-bit process or a 64-bit one. By invoking LoadLibary here, later DLLImports
  376. // will find it already loaded later on.
  377. //
  378. // This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
  379. // controlled in config files.
  380. string nativeLibraryPath;
  381. if (Util.Is64BitProcess())
  382. nativeLibraryPath = "lib64/" + libraryName;
  383. else
  384. nativeLibraryPath = "lib32/" + libraryName;
  385. m_log.DebugFormat("[UTIL]: Loading native Windows library at {0}", nativeLibraryPath);
  386. if (Util.LoadLibrary(nativeLibraryPath) == IntPtr.Zero)
  387. {
  388. m_log.ErrorFormat(
  389. "[UTIL]: Couldn't find native Windows library at {0}", nativeLibraryPath);
  390. return false;
  391. }
  392. else
  393. {
  394. return true;
  395. }
  396. }
  397. public static bool IsEnvironmentSupported(ref string reason)
  398. {
  399. // Must have .NET 2.0 (Generics / libsl)
  400. if (Environment.Version.Major < 2)
  401. {
  402. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  403. return false;
  404. }
  405. // Windows 95/98/ME are unsupported
  406. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  407. Environment.OSVersion.Platform != PlatformID.Win32NT)
  408. {
  409. reason = "Windows 95/98/ME will not run OpenSim";
  410. return false;
  411. }
  412. // Windows 2000 / Pre-SP2 XP
  413. if (Environment.OSVersion.Version.Major == 5 &&
  414. Environment.OSVersion.Version.Minor == 0)
  415. {
  416. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  417. return false;
  418. }
  419. return true;
  420. }
  421. public static int UnixTimeSinceEpoch()
  422. {
  423. return ToUnixTime(DateTime.UtcNow);
  424. }
  425. public static int ToUnixTime(DateTime stamp)
  426. {
  427. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  428. return (int) t.TotalSeconds;
  429. }
  430. public static DateTime ToDateTime(ulong seconds)
  431. {
  432. DateTime epoch = unixEpoch;
  433. return epoch.AddSeconds(seconds);
  434. }
  435. public static DateTime ToDateTime(int seconds)
  436. {
  437. DateTime epoch = unixEpoch;
  438. return epoch.AddSeconds(seconds);
  439. }
  440. /// <summary>
  441. /// Return an md5 hash of the given string
  442. /// </summary>
  443. /// <param name="data"></param>
  444. /// <returns></returns>
  445. public static string Md5Hash(string data)
  446. {
  447. byte[] dataMd5 = ComputeMD5Hash(data);
  448. StringBuilder sb = new StringBuilder();
  449. for (int i = 0; i < dataMd5.Length; i++)
  450. sb.AppendFormat("{0:x2}", dataMd5[i]);
  451. return sb.ToString();
  452. }
  453. private static byte[] ComputeMD5Hash(string data)
  454. {
  455. MD5 md5 = MD5.Create();
  456. return md5.ComputeHash(Encoding.Default.GetBytes(data));
  457. }
  458. /// <summary>
  459. /// Return an SHA1 hash
  460. /// </summary>
  461. /// <param name="data"></param>
  462. /// <returns></returns>
  463. public static string SHA1Hash(string data)
  464. {
  465. return SHA1Hash(Encoding.Default.GetBytes(data));
  466. }
  467. /// <summary>
  468. /// Return an SHA1 hash
  469. /// </summary>
  470. /// <param name="data"></param>
  471. /// <returns></returns>
  472. public static string SHA1Hash(byte[] data)
  473. {
  474. byte[] hash = ComputeSHA1Hash(data);
  475. return BitConverter.ToString(hash).Replace("-", String.Empty);
  476. }
  477. private static byte[] ComputeSHA1Hash(byte[] src)
  478. {
  479. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  480. return SHA1.ComputeHash(src);
  481. }
  482. public static int fast_distance2d(int x, int y)
  483. {
  484. x = Math.Abs(x);
  485. y = Math.Abs(y);
  486. int min = Math.Min(x, y);
  487. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  488. }
  489. /// <summary>
  490. /// Determines whether a point is inside a bounding box.
  491. /// </summary>
  492. /// <param name='v'></param>
  493. /// <param name='min'></param>
  494. /// <param name='max'></param>
  495. /// <returns></returns>
  496. public static bool IsInsideBox(Vector3 v, Vector3 min, Vector3 max)
  497. {
  498. return v.X >= min.X & v.Y >= min.Y && v.Z >= min.Z
  499. && v.X <= max.X && v.Y <= max.Y && v.Z <= max.Z;
  500. }
  501. /// <summary>
  502. /// Are the co-ordinates of the new region visible from the old region?
  503. /// </summary>
  504. /// <param name="oldx">Old region x-coord</param>
  505. /// <param name="newx">New region x-coord</param>
  506. /// <param name="oldy">Old region y-coord</param>
  507. /// <param name="newy">New region y-coord</param>
  508. /// <returns></returns>
  509. public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy)
  510. {
  511. int dd = (int)((drawdist + Constants.RegionSize - 1) / Constants.RegionSize);
  512. int startX = (int)oldx - dd;
  513. int startY = (int)oldy - dd;
  514. int endX = (int)oldx + dd;
  515. int endY = (int)oldy + dd;
  516. return (newx < startX || endX < newx || newy < startY || endY < newy);
  517. }
  518. public static string FieldToString(byte[] bytes)
  519. {
  520. return FieldToString(bytes, String.Empty);
  521. }
  522. /// <summary>
  523. /// Convert a variable length field (byte array) to a string, with a
  524. /// field name prepended to each line of the output
  525. /// </summary>
  526. /// <remarks>If the byte array has unprintable characters in it, a
  527. /// hex dump will be put in the string instead</remarks>
  528. /// <param name="bytes">The byte array to convert to a string</param>
  529. /// <param name="fieldName">A field name to prepend to each line of output</param>
  530. /// <returns>An ASCII string or a string containing a hex dump, minus
  531. /// the null terminator</returns>
  532. public static string FieldToString(byte[] bytes, string fieldName)
  533. {
  534. // Check for a common case
  535. if (bytes.Length == 0) return String.Empty;
  536. StringBuilder output = new StringBuilder();
  537. bool printable = true;
  538. for (int i = 0; i < bytes.Length; ++i)
  539. {
  540. // Check if there are any unprintable characters in the array
  541. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  542. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  543. {
  544. printable = false;
  545. break;
  546. }
  547. }
  548. if (printable)
  549. {
  550. if (fieldName.Length > 0)
  551. {
  552. output.Append(fieldName);
  553. output.Append(": ");
  554. }
  555. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  556. }
  557. else
  558. {
  559. for (int i = 0; i < bytes.Length; i += 16)
  560. {
  561. if (i != 0)
  562. output.Append(Environment.NewLine);
  563. if (fieldName.Length > 0)
  564. {
  565. output.Append(fieldName);
  566. output.Append(": ");
  567. }
  568. for (int j = 0; j < 16; j++)
  569. {
  570. if ((i + j) < bytes.Length)
  571. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  572. else
  573. output.Append(" ");
  574. }
  575. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  576. {
  577. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  578. output.Append((char) bytes[i + j]);
  579. else
  580. output.Append(".");
  581. }
  582. }
  583. }
  584. return output.ToString();
  585. }
  586. /// <summary>
  587. /// Converts a URL to a IPAddress
  588. /// </summary>
  589. /// <param name="url">URL Standard Format</param>
  590. /// <returns>A resolved IP Address</returns>
  591. public static IPAddress GetHostFromURL(string url)
  592. {
  593. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  594. }
  595. /// <summary>
  596. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  597. /// </summary>
  598. /// <param name="dnsAddress">DNS Hostname</param>
  599. /// <returns>An IP address, or null</returns>
  600. public static IPAddress GetHostFromDNS(string dnsAddress)
  601. {
  602. // Is it already a valid IP? No need to look it up.
  603. IPAddress ipa;
  604. if (IPAddress.TryParse(dnsAddress, out ipa))
  605. return ipa;
  606. IPAddress[] hosts = null;
  607. // Not an IP, lookup required
  608. try
  609. {
  610. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  611. }
  612. catch (Exception e)
  613. {
  614. m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);
  615. // Still going to throw the exception on for now, since this was what was happening in the first place
  616. throw e;
  617. }
  618. foreach (IPAddress host in hosts)
  619. {
  620. if (host.AddressFamily == AddressFamily.InterNetwork)
  621. {
  622. return host;
  623. }
  624. }
  625. if (hosts.Length > 0)
  626. return hosts[0];
  627. return null;
  628. }
  629. public static Uri GetURI(string protocol, string hostname, int port, string path)
  630. {
  631. return new UriBuilder(protocol, hostname, port, path).Uri;
  632. }
  633. /// <summary>
  634. /// Gets a list of all local system IP addresses
  635. /// </summary>
  636. /// <returns></returns>
  637. public static IPAddress[] GetLocalHosts()
  638. {
  639. return Dns.GetHostAddresses(Dns.GetHostName());
  640. }
  641. public static IPAddress GetLocalHost()
  642. {
  643. IPAddress[] iplist = GetLocalHosts();
  644. if (iplist.Length == 0) // No accessible external interfaces
  645. {
  646. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  647. IPAddress localhost = loopback[0];
  648. return localhost;
  649. }
  650. foreach (IPAddress host in iplist)
  651. {
  652. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  653. {
  654. return host;
  655. }
  656. }
  657. if (iplist.Length > 0)
  658. {
  659. foreach (IPAddress host in iplist)
  660. {
  661. if (host.AddressFamily == AddressFamily.InterNetwork)
  662. return host;
  663. }
  664. // Well all else failed...
  665. return iplist[0];
  666. }
  667. return null;
  668. }
  669. /// <summary>
  670. /// Removes all invalid path chars (OS dependent)
  671. /// </summary>
  672. /// <param name="path">path</param>
  673. /// <returns>safe path</returns>
  674. public static string safePath(string path)
  675. {
  676. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  677. }
  678. /// <summary>
  679. /// Removes all invalid filename chars (OS dependent)
  680. /// </summary>
  681. /// <param name="path">filename</param>
  682. /// <returns>safe filename</returns>
  683. public static string safeFileName(string filename)
  684. {
  685. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  686. ;
  687. }
  688. //
  689. // directory locations
  690. //
  691. public static string homeDir()
  692. {
  693. string temp;
  694. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  695. // temp = Path.Combine(personal,".OpenSim");
  696. temp = ".";
  697. return temp;
  698. }
  699. public static string assetsDir()
  700. {
  701. return Path.Combine(configDir(), "assets");
  702. }
  703. public static string inventoryDir()
  704. {
  705. return Path.Combine(configDir(), "inventory");
  706. }
  707. public static string configDir()
  708. {
  709. return ".";
  710. }
  711. public static string dataDir()
  712. {
  713. return ".";
  714. }
  715. public static string logDir()
  716. {
  717. return ".";
  718. }
  719. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  720. public static string GetUniqueFilename(string FileName)
  721. {
  722. int count = 0;
  723. string Name;
  724. if (File.Exists(FileName))
  725. {
  726. FileInfo f = new FileInfo(FileName);
  727. if (!String.IsNullOrEmpty(f.Extension))
  728. {
  729. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  730. }
  731. else
  732. {
  733. Name = f.FullName;
  734. }
  735. while (File.Exists(FileName))
  736. {
  737. count++;
  738. FileName = Name + count + f.Extension;
  739. }
  740. }
  741. return FileName;
  742. }
  743. // Nini (config) related Methods
  744. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  745. {
  746. if (!File.Exists(fileName))
  747. {
  748. //create new file
  749. }
  750. XmlConfigSource config = new XmlConfigSource(fileName);
  751. AddDataRowToConfig(config, row);
  752. config.Save();
  753. return config;
  754. }
  755. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  756. {
  757. config.Configs.Add((string) row[0]);
  758. for (int i = 0; i < row.Table.Columns.Count; i++)
  759. {
  760. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  761. }
  762. }
  763. public static float Clip(float x, float min, float max)
  764. {
  765. return Math.Min(Math.Max(x, min), max);
  766. }
  767. public static int Clip(int x, int min, int max)
  768. {
  769. return Math.Min(Math.Max(x, min), max);
  770. }
  771. public static Vector3 Clip(Vector3 vec, float min, float max)
  772. {
  773. return new Vector3(Clip(vec.X, min, max), Clip(vec.Y, min, max),
  774. Clip(vec.Z, min, max));
  775. }
  776. /// <summary>
  777. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  778. /// </summary>
  779. /// <param name="UUID"></param>
  780. /// <returns></returns>
  781. public static String ToRawUuidString(UUID UUID)
  782. {
  783. return UUID.Guid.ToString("n");
  784. }
  785. public static string CleanString(string input)
  786. {
  787. if (input.Length == 0)
  788. return input;
  789. int clip = input.Length;
  790. // Test for ++ string terminator
  791. int pos = input.IndexOf("\0");
  792. if (pos != -1 && pos < clip)
  793. clip = pos;
  794. // Test for CR
  795. pos = input.IndexOf("\r");
  796. if (pos != -1 && pos < clip)
  797. clip = pos;
  798. // Test for LF
  799. pos = input.IndexOf("\n");
  800. if (pos != -1 && pos < clip)
  801. clip = pos;
  802. // Truncate string before first end-of-line character found
  803. return input.Substring(0, clip);
  804. }
  805. /// <summary>
  806. /// returns the contents of /etc/issue on Unix Systems
  807. /// Use this for where it's absolutely necessary to implement platform specific stuff
  808. /// </summary>
  809. /// <returns></returns>
  810. public static string ReadEtcIssue()
  811. {
  812. try
  813. {
  814. StreamReader sr = new StreamReader("/etc/issue.net");
  815. string issue = sr.ReadToEnd();
  816. sr.Close();
  817. return issue;
  818. }
  819. catch (Exception)
  820. {
  821. return "";
  822. }
  823. }
  824. public static void SerializeToFile(string filename, Object obj)
  825. {
  826. IFormatter formatter = new BinaryFormatter();
  827. Stream stream = null;
  828. try
  829. {
  830. stream = new FileStream(
  831. filename, FileMode.Create,
  832. FileAccess.Write, FileShare.None);
  833. formatter.Serialize(stream, obj);
  834. }
  835. catch (Exception e)
  836. {
  837. m_log.Error(e.ToString());
  838. }
  839. finally
  840. {
  841. if (stream != null)
  842. {
  843. stream.Close();
  844. }
  845. }
  846. }
  847. public static Object DeserializeFromFile(string filename)
  848. {
  849. IFormatter formatter = new BinaryFormatter();
  850. Stream stream = null;
  851. Object ret = null;
  852. try
  853. {
  854. stream = new FileStream(
  855. filename, FileMode.Open,
  856. FileAccess.Read, FileShare.None);
  857. ret = formatter.Deserialize(stream);
  858. }
  859. catch (Exception e)
  860. {
  861. m_log.Error(e.ToString());
  862. }
  863. finally
  864. {
  865. if (stream != null)
  866. {
  867. stream.Close();
  868. }
  869. }
  870. return ret;
  871. }
  872. public static string Compress(string text)
  873. {
  874. byte[] buffer = Util.UTF8.GetBytes(text);
  875. MemoryStream memory = new MemoryStream();
  876. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  877. {
  878. compressor.Write(buffer, 0, buffer.Length);
  879. }
  880. memory.Position = 0;
  881. byte[] compressed = new byte[memory.Length];
  882. memory.Read(compressed, 0, compressed.Length);
  883. byte[] compressedBuffer = new byte[compressed.Length + 4];
  884. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  885. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  886. return Convert.ToBase64String(compressedBuffer);
  887. }
  888. public static string Decompress(string compressedText)
  889. {
  890. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  891. using (MemoryStream memory = new MemoryStream())
  892. {
  893. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  894. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  895. byte[] buffer = new byte[msgLength];
  896. memory.Position = 0;
  897. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  898. {
  899. decompressor.Read(buffer, 0, buffer.Length);
  900. }
  901. return Util.UTF8.GetString(buffer);
  902. }
  903. }
  904. /// <summary>
  905. /// Copy data from one stream to another, leaving the read position of both streams at the beginning.
  906. /// </summary>
  907. /// <param name='inputStream'>
  908. /// Input stream. Must be seekable.
  909. /// </param>
  910. /// <exception cref='ArgumentException'>
  911. /// Thrown if the input stream is not seekable.
  912. /// </exception>
  913. public static Stream Copy(Stream inputStream)
  914. {
  915. if (!inputStream.CanSeek)
  916. throw new ArgumentException("Util.Copy(Stream inputStream) must receive an inputStream that can seek");
  917. const int readSize = 256;
  918. byte[] buffer = new byte[readSize];
  919. MemoryStream ms = new MemoryStream();
  920. int count = inputStream.Read(buffer, 0, readSize);
  921. while (count > 0)
  922. {
  923. ms.Write(buffer, 0, count);
  924. count = inputStream.Read(buffer, 0, readSize);
  925. }
  926. ms.Position = 0;
  927. inputStream.Position = 0;
  928. return ms;
  929. }
  930. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  931. {
  932. return SendXmlRpcCommand(url, methodName, args);
  933. }
  934. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  935. {
  936. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  937. return client.Send(url, 6000);
  938. }
  939. /// <summary>
  940. /// Returns an error message that the user could not be found in the database
  941. /// </summary>
  942. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  943. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  944. {
  945. XmlRpcResponse response = new XmlRpcResponse();
  946. Hashtable responseData = new Hashtable();
  947. responseData["error_type"] = "unknown_user";
  948. responseData["error_desc"] = "The user requested is not in the database";
  949. response.Value = responseData;
  950. return response;
  951. }
  952. /// <summary>
  953. /// Converts a byte array in big endian order into an ulong.
  954. /// </summary>
  955. /// <param name="bytes">
  956. /// The array of bytes
  957. /// </param>
  958. /// <returns>
  959. /// The extracted ulong
  960. /// </returns>
  961. public static ulong BytesToUInt64Big(byte[] bytes)
  962. {
  963. if (bytes.Length < 8) return 0;
  964. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  965. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  966. }
  967. // used for RemoteParcelRequest (for "About Landmark")
  968. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  969. {
  970. byte[] bytes =
  971. {
  972. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  973. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  974. (byte)x, (byte)(x >> 8), 0, 0,
  975. (byte)y, (byte)(y >> 8), 0, 0 };
  976. return new UUID(bytes, 0);
  977. }
  978. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  979. {
  980. byte[] bytes =
  981. {
  982. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  983. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  984. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  985. (byte)y, (byte)(y >> 8), 0, 0 };
  986. return new UUID(bytes, 0);
  987. }
  988. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  989. {
  990. byte[] bytes = parcelID.GetBytes();
  991. regionHandle = Utils.BytesToUInt64(bytes);
  992. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  993. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  994. }
  995. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  996. {
  997. byte[] bytes = parcelID.GetBytes();
  998. regionHandle = Utils.BytesToUInt64(bytes);
  999. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  1000. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  1001. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  1002. }
  1003. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  1004. {
  1005. ulong regionHandle;
  1006. uint rx, ry;
  1007. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  1008. Utils.LongToUInts(regionHandle, out rx, out ry);
  1009. x += rx;
  1010. y += ry;
  1011. }
  1012. /// <summary>
  1013. /// Get operating system information if available. Returns only the first 45 characters of information
  1014. /// </summary>
  1015. /// <returns>
  1016. /// Operating system information. Returns an empty string if none was available.
  1017. /// </returns>
  1018. public static string GetOperatingSystemInformation()
  1019. {
  1020. string os = String.Empty;
  1021. if (Environment.OSVersion.Platform != PlatformID.Unix)
  1022. {
  1023. os = Environment.OSVersion.ToString();
  1024. }
  1025. else
  1026. {
  1027. os = ReadEtcIssue();
  1028. }
  1029. if (os.Length > 45)
  1030. {
  1031. os = os.Substring(0, 45);
  1032. }
  1033. return os;
  1034. }
  1035. public static string GetRuntimeInformation()
  1036. {
  1037. string ru = String.Empty;
  1038. if (Environment.OSVersion.Platform == PlatformID.Unix)
  1039. ru = "Unix/Mono";
  1040. else
  1041. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  1042. ru = "OSX/Mono";
  1043. else
  1044. {
  1045. if (Type.GetType("Mono.Runtime") != null)
  1046. ru = "Win/Mono";
  1047. else
  1048. ru = "Win/.NET";
  1049. }
  1050. return ru;
  1051. }
  1052. /// <summary>
  1053. /// Is the given string a UUID?
  1054. /// </summary>
  1055. /// <param name="s"></param>
  1056. /// <returns></returns>
  1057. public static bool isUUID(string s)
  1058. {
  1059. return UUIDPattern.IsMatch(s);
  1060. }
  1061. public static string GetDisplayConnectionString(string connectionString)
  1062. {
  1063. int passPosition = 0;
  1064. int passEndPosition = 0;
  1065. string displayConnectionString = null;
  1066. // hide the password in the connection string
  1067. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  1068. passPosition = connectionString.IndexOf("=", passPosition);
  1069. if (passPosition < connectionString.Length)
  1070. passPosition += 1;
  1071. passEndPosition = connectionString.IndexOf(";", passPosition);
  1072. displayConnectionString = connectionString.Substring(0, passPosition);
  1073. displayConnectionString += "***";
  1074. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  1075. return displayConnectionString;
  1076. }
  1077. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  1078. {
  1079. Type settingsType = settingsClass.GetType();
  1080. FieldInfo[] fieldInfos = settingsType.GetFields();
  1081. foreach (FieldInfo fieldInfo in fieldInfos)
  1082. {
  1083. if (!fieldInfo.IsStatic)
  1084. {
  1085. if (fieldInfo.FieldType == typeof(System.String))
  1086. {
  1087. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  1088. }
  1089. else if (fieldInfo.FieldType == typeof(System.Boolean))
  1090. {
  1091. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  1092. }
  1093. else if (fieldInfo.FieldType == typeof(System.Int32))
  1094. {
  1095. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  1096. }
  1097. else if (fieldInfo.FieldType == typeof(System.Single))
  1098. {
  1099. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  1100. }
  1101. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1102. {
  1103. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1104. }
  1105. }
  1106. }
  1107. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1108. foreach (PropertyInfo propInfo in propertyInfos)
  1109. {
  1110. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1111. {
  1112. if (propInfo.PropertyType == typeof(System.String))
  1113. {
  1114. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1115. }
  1116. else if (propInfo.PropertyType == typeof(System.Boolean))
  1117. {
  1118. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1119. }
  1120. else if (propInfo.PropertyType == typeof(System.Int32))
  1121. {
  1122. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1123. }
  1124. else if (propInfo.PropertyType == typeof(System.Single))
  1125. {
  1126. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1127. }
  1128. if (propInfo.PropertyType == typeof(System.UInt32))
  1129. {
  1130. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1131. }
  1132. }
  1133. }
  1134. return settingsClass;
  1135. }
  1136. public static string Base64ToString(string str)
  1137. {
  1138. Decoder utf8Decode = Encoding.UTF8.GetDecoder();
  1139. byte[] todecode_byte = Convert.FromBase64String(str);
  1140. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  1141. char[] decoded_char = new char[charCount];
  1142. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  1143. string result = new String(decoded_char);
  1144. return result;
  1145. }
  1146. public static Guid GetHashGuid(string data, string salt)
  1147. {
  1148. byte[] hash = ComputeMD5Hash(data + salt);
  1149. //string s = BitConverter.ToString(hash);
  1150. Guid guid = new Guid(hash);
  1151. return guid;
  1152. }
  1153. public static byte ConvertMaturityToAccessLevel(uint maturity)
  1154. {
  1155. byte retVal = 0;
  1156. switch (maturity)
  1157. {
  1158. case 0: //PG
  1159. retVal = 13;
  1160. break;
  1161. case 1: //Mature
  1162. retVal = 21;
  1163. break;
  1164. case 2: // Adult
  1165. retVal = 42;
  1166. break;
  1167. }
  1168. return retVal;
  1169. }
  1170. public static uint ConvertAccessLevelToMaturity(byte maturity)
  1171. {
  1172. if (maturity <= 13)
  1173. return 0;
  1174. else if (maturity <= 21)
  1175. return 1;
  1176. else
  1177. return 2;
  1178. }
  1179. /// <summary>
  1180. /// Produces an OSDMap from its string representation on a stream
  1181. /// </summary>
  1182. /// <param name="data">The stream</param>
  1183. /// <param name="length">The size of the data on the stream</param>
  1184. /// <returns>The OSDMap or an exception</returns>
  1185. public static OSDMap GetOSDMap(Stream stream, int length)
  1186. {
  1187. byte[] data = new byte[length];
  1188. stream.Read(data, 0, length);
  1189. string strdata = Util.UTF8.GetString(data);
  1190. OSDMap args = null;
  1191. OSD buffer;
  1192. buffer = OSDParser.DeserializeJson(strdata);
  1193. if (buffer.Type == OSDType.Map)
  1194. {
  1195. args = (OSDMap)buffer;
  1196. return args;
  1197. }
  1198. return null;
  1199. }
  1200. public static OSDMap GetOSDMap(string data)
  1201. {
  1202. OSDMap args = null;
  1203. try
  1204. {
  1205. OSD buffer;
  1206. // We should pay attention to the content-type, but let's assume we know it's Json
  1207. buffer = OSDParser.DeserializeJson(data);
  1208. if (buffer.Type == OSDType.Map)
  1209. {
  1210. args = (OSDMap)buffer;
  1211. return args;
  1212. }
  1213. else
  1214. {
  1215. // uh?
  1216. m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
  1217. return null;
  1218. }
  1219. }
  1220. catch (Exception ex)
  1221. {
  1222. m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
  1223. return null;
  1224. }
  1225. }
  1226. public static string[] Glob(string path)
  1227. {
  1228. string vol=String.Empty;
  1229. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1230. {
  1231. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1232. if (vcomps.Length > 1)
  1233. {
  1234. path = vcomps[1];
  1235. vol = vcomps[0];
  1236. }
  1237. }
  1238. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1239. // Glob
  1240. path = vol;
  1241. if (vol != String.Empty)
  1242. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1243. else
  1244. path = new String(new char[] {Path.DirectorySeparatorChar});
  1245. List<string> paths = new List<string>();
  1246. List<string> found = new List<string>();
  1247. paths.Add(path);
  1248. int compIndex = -1;
  1249. foreach (string c in comps)
  1250. {
  1251. compIndex++;
  1252. List<string> addpaths = new List<string>();
  1253. foreach (string p in paths)
  1254. {
  1255. string[] dirs = Directory.GetDirectories(p, c);
  1256. if (dirs.Length != 0)
  1257. {
  1258. foreach (string dir in dirs)
  1259. addpaths.Add(Path.Combine(path, dir));
  1260. }
  1261. // Only add files if that is the last path component
  1262. if (compIndex == comps.Length - 1)
  1263. {
  1264. string[] files = Directory.GetFiles(p, c);
  1265. foreach (string f in files)
  1266. found.Add(f);
  1267. }
  1268. }
  1269. paths = addpaths;
  1270. }
  1271. return found.ToArray();
  1272. }
  1273. public static string ServerURI(string uri)
  1274. {
  1275. if (uri == string.Empty)
  1276. return string.Empty;
  1277. // Get rid of eventual slashes at the end
  1278. uri = uri.TrimEnd('/');
  1279. IPAddress ipaddr1 = null;
  1280. string port1 = "";
  1281. try
  1282. {
  1283. ipaddr1 = Util.GetHostFromURL(uri);
  1284. }
  1285. catch { }
  1286. try
  1287. {
  1288. port1 = uri.Split(new char[] { ':' })[2];
  1289. }
  1290. catch { }
  1291. // We tried our best to convert the domain names to IP addresses
  1292. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1293. }
  1294. /// <summary>
  1295. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1296. /// </summary>
  1297. /// <param name="str">
  1298. /// If null or empty, then an bytes[0] is returned.
  1299. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1300. /// </param>
  1301. /// <param name="args">
  1302. /// Arguments to substitute into the string via the {} mechanism.
  1303. /// </param>
  1304. /// <returns></returns>
  1305. public static byte[] StringToBytes256(string str, params object[] args)
  1306. {
  1307. return StringToBytes256(string.Format(str, args));
  1308. }
  1309. /// <summary>
  1310. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1311. /// </summary>
  1312. /// <param name="str">
  1313. /// If null or empty, then an bytes[0] is returned.
  1314. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1315. /// </param>
  1316. /// <returns></returns>
  1317. public static byte[] StringToBytes256(string str)
  1318. {
  1319. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1320. if (str.Length > 254) str = str.Remove(254);
  1321. if (!str.EndsWith("\0")) { str += "\0"; }
  1322. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1323. // might have gotten an oversized array even after the string trim
  1324. byte[] data = UTF8.GetBytes(str);
  1325. if (data.Length > 256)
  1326. {
  1327. Array.Resize<byte>(ref data, 256);
  1328. data[255] = 0;
  1329. }
  1330. return data;
  1331. }
  1332. /// <summary>
  1333. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1334. /// </summary>
  1335. /// <param name="str">
  1336. /// If null or empty, then an bytes[0] is returned.
  1337. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1338. /// </param>
  1339. /// <param name="args">
  1340. /// Arguments to substitute into the string via the {} mechanism.
  1341. /// </param>
  1342. /// <returns></returns>
  1343. public static byte[] StringToBytes1024(string str, params object[] args)
  1344. {
  1345. return StringToBytes1024(string.Format(str, args));
  1346. }
  1347. /// <summary>
  1348. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1349. /// </summary>
  1350. /// <param name="str">
  1351. /// If null or empty, then an bytes[0] is returned.
  1352. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1353. /// </param>
  1354. /// <returns></returns>
  1355. public static byte[] StringToBytes1024(string str)
  1356. {
  1357. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1358. if (str.Length > 1023) str = str.Remove(1023);
  1359. if (!str.EndsWith("\0")) { str += "\0"; }
  1360. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1361. // might have gotten an oversized array even after the string trim
  1362. byte[] data = UTF8.GetBytes(str);
  1363. if (data.Length > 1024)
  1364. {
  1365. Array.Resize<byte>(ref data, 1024);
  1366. data[1023] = 0;
  1367. }
  1368. return data;
  1369. }
  1370. /// <summary>
  1371. /// Used to trigger an early library load on Windows systems.
  1372. /// </summary>
  1373. /// <remarks>
  1374. /// Required to get 32-bit and 64-bit processes to automatically use the
  1375. /// appropriate native library.
  1376. /// </remarks>
  1377. /// <param name="dllToLoad"></param>
  1378. /// <returns></returns>
  1379. [DllImport("kernel32.dll")]
  1380. public static extern IntPtr LoadLibrary(string dllToLoad);
  1381. /// <summary>
  1382. /// Determine whether the current process is 64 bit
  1383. /// </summary>
  1384. /// <returns>true if so, false if not</returns>
  1385. public static bool Is64BitProcess()
  1386. {
  1387. return IntPtr.Size == 8;
  1388. }
  1389. #region FireAndForget Threading Pattern
  1390. /// <summary>
  1391. /// Created to work around a limitation in Mono with nested delegates
  1392. /// </summary>
  1393. private sealed class FireAndForgetWrapper
  1394. {
  1395. private static volatile FireAndForgetWrapper instance;
  1396. private static object syncRoot = new Object();
  1397. public static FireAndForgetWrapper Instance {
  1398. get {
  1399. if (instance == null)
  1400. {
  1401. lock (syncRoot)
  1402. {
  1403. if (instance == null)
  1404. {
  1405. instance = new FireAndForgetWrapper();
  1406. }
  1407. }
  1408. }
  1409. return instance;
  1410. }
  1411. }
  1412. public void FireAndForget(System.Threading.WaitCallback callback)
  1413. {
  1414. callback.BeginInvoke(null, EndFireAndForget, callback);
  1415. }
  1416. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1417. {
  1418. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1419. }
  1420. private static void EndFireAndForget(IAsyncResult ar)
  1421. {
  1422. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1423. try { callback.EndInvoke(ar); }
  1424. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1425. ar.AsyncWaitHandle.Close();
  1426. }
  1427. }
  1428. public static void FireAndForget(System.Threading.WaitCallback callback)
  1429. {
  1430. FireAndForget(callback, null);
  1431. }
  1432. public static void InitThreadPool(int maxThreads)
  1433. {
  1434. if (maxThreads < 2)
  1435. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1436. if (m_ThreadPool != null)
  1437. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1438. STPStartInfo startInfo = new STPStartInfo();
  1439. startInfo.ThreadPoolName = "Util";
  1440. startInfo.IdleTimeout = 2000;
  1441. startInfo.MaxWorkerThreads = maxThreads;
  1442. startInfo.MinWorkerThreads = 2;
  1443. m_ThreadPool = new SmartThreadPool(startInfo);
  1444. }
  1445. public static int FireAndForgetCount()
  1446. {
  1447. const int MAX_SYSTEM_THREADS = 200;
  1448. switch (FireAndForgetMethod)
  1449. {
  1450. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1451. case FireAndForgetMethod.QueueUserWorkItem:
  1452. case FireAndForgetMethod.BeginInvoke:
  1453. int workerThreads, iocpThreads;
  1454. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1455. return workerThreads;
  1456. case FireAndForgetMethod.SmartThreadPool:
  1457. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1458. case FireAndForgetMethod.Thread:
  1459. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1460. default:
  1461. throw new NotImplementedException();
  1462. }
  1463. }
  1464. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1465. {
  1466. WaitCallback realCallback;
  1467. if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
  1468. {
  1469. // If we're running regression tests, then we want any exceptions to rise up to the test code.
  1470. realCallback = o => { Culture.SetCurrentCulture(); callback(o); };
  1471. }
  1472. else
  1473. {
  1474. // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
  1475. // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
  1476. // for decimals places but is read by a culture that treats commas as number seperators.
  1477. realCallback = o =>
  1478. {
  1479. Culture.SetCurrentCulture();
  1480. try
  1481. {
  1482. callback(o);
  1483. }
  1484. catch (Exception e)
  1485. {
  1486. m_log.ErrorFormat(
  1487. "[UTIL]: Continuing after async_call_method thread terminated with exception {0}{1}",
  1488. e.Message, e.StackTrace);
  1489. }
  1490. };
  1491. }
  1492. switch (FireAndForgetMethod)
  1493. {
  1494. case FireAndForgetMethod.RegressionTest:
  1495. case FireAndForgetMethod.None:
  1496. realCallback.Invoke(obj);
  1497. break;
  1498. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1499. ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
  1500. break;
  1501. case FireAndForgetMethod.QueueUserWorkItem:
  1502. ThreadPool.QueueUserWorkItem(realCallback, obj);
  1503. break;
  1504. case FireAndForgetMethod.BeginInvoke:
  1505. FireAndForgetWrapper wrapper = FireAndForgetWrapper.Instance;
  1506. wrapper.FireAndForget(realCallback, obj);
  1507. break;
  1508. case FireAndForgetMethod.SmartThreadPool:
  1509. if (m_ThreadPool == null)
  1510. InitThreadPool(15);
  1511. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { realCallback, obj });
  1512. break;
  1513. case FireAndForgetMethod.Thread:
  1514. Thread thread = new Thread(delegate(object o) { realCallback(o); });
  1515. thread.Start(obj);
  1516. break;
  1517. default:
  1518. throw new NotImplementedException();
  1519. }
  1520. }
  1521. /// <summary>
  1522. /// Get a thread pool report.
  1523. /// </summary>
  1524. /// <returns></returns>
  1525. public static string GetThreadPoolReport()
  1526. {
  1527. string threadPoolUsed = null;
  1528. int maxThreads = 0;
  1529. int minThreads = 0;
  1530. int allocatedThreads = 0;
  1531. int inUseThreads = 0;
  1532. int waitingCallbacks = 0;
  1533. int completionPortThreads = 0;
  1534. StringBuilder sb = new StringBuilder();
  1535. if (FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  1536. {
  1537. // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
  1538. if (m_ThreadPool != null)
  1539. {
  1540. threadPoolUsed = "SmartThreadPool";
  1541. maxThreads = m_ThreadPool.MaxThreads;
  1542. minThreads = m_ThreadPool.MinThreads;
  1543. inUseThreads = m_ThreadPool.InUseThreads;
  1544. allocatedThreads = m_ThreadPool.ActiveThreads;
  1545. waitingCallbacks = m_ThreadPool.WaitingCallbacks;
  1546. }
  1547. }
  1548. else if (
  1549. FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem
  1550. || FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
  1551. {
  1552. threadPoolUsed = "BuiltInThreadPool";
  1553. ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
  1554. ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
  1555. int availableThreads;
  1556. ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
  1557. inUseThreads = maxThreads - availableThreads;
  1558. allocatedThreads = -1;
  1559. waitingCallbacks = -1;
  1560. }
  1561. if (threadPoolUsed != null)
  1562. {
  1563. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  1564. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  1565. sb.AppendFormat("Min threads : {0}\n", minThreads);
  1566. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  1567. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  1568. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  1569. }
  1570. else
  1571. {
  1572. sb.AppendFormat("Thread pool not used\n");
  1573. }
  1574. return sb.ToString();
  1575. }
  1576. private static object SmartThreadPoolCallback(object o)
  1577. {
  1578. object[] array = (object[])o;
  1579. WaitCallback callback = (WaitCallback)array[0];
  1580. object obj = array[1];
  1581. callback(obj);
  1582. return null;
  1583. }
  1584. #endregion FireAndForget Threading Pattern
  1585. /// <summary>
  1586. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1587. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1588. /// for the callers.
  1589. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1590. /// </summary>
  1591. /// <returns></returns>
  1592. public static Int32 EnvironmentTickCount()
  1593. {
  1594. return Environment.TickCount & EnvironmentTickCountMask;
  1595. }
  1596. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1597. /// <summary>
  1598. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1599. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1600. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1601. /// </summary>
  1602. /// <param name="newValue"></param>
  1603. /// <param name="prevValue"></param>
  1604. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1605. public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  1606. {
  1607. Int32 diff = newValue - prevValue;
  1608. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1609. }
  1610. /// <summary>
  1611. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1612. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1613. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1614. /// </summary>
  1615. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1616. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1617. {
  1618. return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
  1619. }
  1620. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  1621. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  1622. // A positive return value indicates A occured later than B
  1623. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  1624. {
  1625. // A, B and TC are all between 0 and 0x3fffffff
  1626. int tc = EnvironmentTickCount();
  1627. if (tc - tcA >= 0)
  1628. tcA += EnvironmentTickCountMask + 1;
  1629. if (tc - tcB >= 0)
  1630. tcB += EnvironmentTickCountMask + 1;
  1631. return tcA - tcB;
  1632. }
  1633. /// <summary>
  1634. /// Prints the call stack at any given point. Useful for debugging.
  1635. /// </summary>
  1636. public static void PrintCallStack()
  1637. {
  1638. PrintCallStack(m_log.DebugFormat);
  1639. }
  1640. public delegate void DebugPrinter(string msg, params Object[] parm);
  1641. public static void PrintCallStack(DebugPrinter printer)
  1642. {
  1643. StackTrace stackTrace = new StackTrace(true); // get call stack
  1644. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  1645. // write call stack method names
  1646. foreach (StackFrame stackFrame in stackFrames)
  1647. {
  1648. MethodBase mb = stackFrame.GetMethod();
  1649. printer("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
  1650. }
  1651. }
  1652. /// <summary>
  1653. /// Gets the client IP address
  1654. /// </summary>
  1655. /// <param name="xff"></param>
  1656. /// <returns></returns>
  1657. public static IPEndPoint GetClientIPFromXFF(string xff)
  1658. {
  1659. if (xff == string.Empty)
  1660. return null;
  1661. string[] parts = xff.Split(new char[] { ',' });
  1662. if (parts.Length > 0)
  1663. {
  1664. try
  1665. {
  1666. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  1667. }
  1668. catch (Exception e)
  1669. {
  1670. m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
  1671. }
  1672. }
  1673. return null;
  1674. }
  1675. public static string GetCallerIP(Hashtable req)
  1676. {
  1677. if (req.ContainsKey("headers"))
  1678. {
  1679. try
  1680. {
  1681. Hashtable headers = (Hashtable)req["headers"];
  1682. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  1683. return headers["remote_addr"].ToString();
  1684. }
  1685. catch (Exception e)
  1686. {
  1687. m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
  1688. }
  1689. }
  1690. return string.Empty;
  1691. }
  1692. #region Xml Serialization Utilities
  1693. public static bool ReadBoolean(XmlTextReader reader)
  1694. {
  1695. reader.ReadStartElement();
  1696. bool result = Boolean.Parse(reader.ReadContentAsString().ToLower());
  1697. reader.ReadEndElement();
  1698. return result;
  1699. }
  1700. public static UUID ReadUUID(XmlTextReader reader, string name)
  1701. {
  1702. UUID id;
  1703. string idStr;
  1704. reader.ReadStartElement(name);
  1705. if (reader.Name == "Guid")
  1706. idStr = reader.ReadElementString("Guid");
  1707. else if (reader.Name == "UUID")
  1708. idStr = reader.ReadElementString("UUID");
  1709. else // no leading tag
  1710. idStr = reader.ReadContentAsString();
  1711. UUID.TryParse(idStr, out id);
  1712. reader.ReadEndElement();
  1713. return id;
  1714. }
  1715. public static Vector3 ReadVector(XmlTextReader reader, string name)
  1716. {
  1717. Vector3 vec;
  1718. reader.ReadStartElement(name);
  1719. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  1720. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  1721. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  1722. reader.ReadEndElement();
  1723. return vec;
  1724. }
  1725. public static Quaternion ReadQuaternion(XmlTextReader reader, string name)
  1726. {
  1727. Quaternion quat = new Quaternion();
  1728. reader.ReadStartElement(name);
  1729. while (reader.NodeType != XmlNodeType.EndElement)
  1730. {
  1731. switch (reader.Name.ToLower())
  1732. {
  1733. case "x":
  1734. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1735. break;
  1736. case "y":
  1737. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1738. break;
  1739. case "z":
  1740. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1741. break;
  1742. case "w":
  1743. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1744. break;
  1745. }
  1746. }
  1747. reader.ReadEndElement();
  1748. return quat;
  1749. }
  1750. public static T ReadEnum<T>(XmlTextReader reader, string name)
  1751. {
  1752. string value = reader.ReadElementContentAsString(name, String.Empty);
  1753. // !!!!! to deal with flags without commas
  1754. if (value.Contains(" ") && !value.Contains(","))
  1755. value = value.Replace(" ", ", ");
  1756. return (T)Enum.Parse(typeof(T), value); ;
  1757. }
  1758. #endregion
  1759. #region Universal User Identifiers
  1760. /// <summary>
  1761. /// </summary>
  1762. /// <param name="value">uuid[;endpoint[;first last[;secret]]]</param>
  1763. /// <param name="uuid">the uuid part</param>
  1764. /// <param name="url">the endpoint part (e.g. http://foo.com)</param>
  1765. /// <param name="firstname">the first name part (e.g. Test)</param>
  1766. /// <param name="lastname">the last name part (e.g User)</param>
  1767. /// <param name="secret">the secret part</param>
  1768. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  1769. {
  1770. uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "User"; secret = string.Empty;
  1771. string[] parts = value.Split(';');
  1772. if (parts.Length >= 1)
  1773. if (!UUID.TryParse(parts[0], out uuid))
  1774. return false;
  1775. if (parts.Length >= 2)
  1776. url = parts[1];
  1777. if (parts.Length >= 3)
  1778. {
  1779. string[] name = parts[2].Split();
  1780. if (name.Length == 2)
  1781. {
  1782. firstname = name[0];
  1783. lastname = name[1];
  1784. }
  1785. }
  1786. if (parts.Length >= 4)
  1787. secret = parts[3];
  1788. return true;
  1789. }
  1790. /// <summary>
  1791. /// Produces a universal (HG) system-facing identifier given the information
  1792. /// </summary>
  1793. /// <param name="acircuit"></param>
  1794. /// <returns>uuid[;homeURI[;first last]]</returns>
  1795. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  1796. {
  1797. if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
  1798. return UniversalIdentifier(acircuit.AgentID, acircuit.firstname, acircuit.lastname, acircuit.ServiceURLs["HomeURI"].ToString());
  1799. else
  1800. return acircuit.AgentID.ToString();
  1801. }
  1802. /// <summary>
  1803. /// Produces a universal (HG) system-facing identifier given the information
  1804. /// </summary>
  1805. /// <param name="id">UUID of the user</param>
  1806. /// <param name="firstName">first name (e.g Test)</param>
  1807. /// <param name="lastName">last name (e.g. User)</param>
  1808. /// <param name="homeURI">homeURI (e.g. http://foo.com)</param>
  1809. /// <returns>a string of the form uuid[;homeURI[;first last]]</returns>
  1810. public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
  1811. {
  1812. string agentsURI = homeURI;
  1813. if (!agentsURI.EndsWith("/"))
  1814. agentsURI += "/";
  1815. // This is ugly, but there's no other way, given that the name is changed
  1816. // in the agent circuit data for foreigners
  1817. if (lastName.Contains("@"))
  1818. {
  1819. string[] parts = firstName.Split(new char[] { '.' });
  1820. if (parts.Length == 2)
  1821. return id.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
  1822. }
  1823. return id.ToString() + ";" + agentsURI + ";" + firstName + " " + lastName;
  1824. }
  1825. /// <summary>
  1826. /// Produces a universal (HG) user-facing name given the information
  1827. /// </summary>
  1828. /// <param name="firstName"></param>
  1829. /// <param name="lastName"></param>
  1830. /// <param name="homeURI"></param>
  1831. /// <returns>string of the form first.last @foo.com or first last</returns>
  1832. public static string UniversalName(String firstName, String lastName, String homeURI)
  1833. {
  1834. Uri uri = null;
  1835. try
  1836. {
  1837. uri = new Uri(homeURI);
  1838. }
  1839. catch (UriFormatException)
  1840. {
  1841. return firstName + " " + lastName;
  1842. }
  1843. return firstName + "." + lastName + " " + "@" + uri.Authority;
  1844. }
  1845. #endregion
  1846. }
  1847. }