Util.cs 83 KB

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