Util.cs 81 KB

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