1
0

Util.cs 81 KB

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