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. 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. // AuroraSim uses "int" for some fields that are boolean in OpenSim, e.g. "PassCollisions". Don't fail because of this.
  1770. reader.ReadStartElement();
  1771. string val = reader.ReadContentAsString().ToLower();
  1772. bool result = val.Equals("true") || val.Equals("1");
  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. }