Util.cs 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289
  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. using System.Collections.Concurrent;
  54. using System.Collections.Specialized;
  55. using System.Web;
  56. namespace OpenSim.Framework
  57. {
  58. [Flags]
  59. public enum PermissionMask : uint
  60. {
  61. None = 0,
  62. // folded perms
  63. foldedTransfer = 1,
  64. foldedModify = 1 << 1,
  65. foldedCopy = 1 << 2,
  66. foldedMask = 0x07,
  67. //
  68. Transfer = 1 << 13,
  69. Modify = 1 << 14,
  70. Copy = 1 << 15,
  71. Export = 1 << 16,
  72. Move = 1 << 19,
  73. Damage = 1 << 20,
  74. // All does not contain Export, which is special and must be
  75. // explicitly given
  76. All = (1 << 13) | (1 << 14) | (1 << 15) | (1 << 19)
  77. }
  78. /// <summary>
  79. /// The method used by Util.FireAndForget for asynchronously firing events
  80. /// </summary>
  81. /// <remarks>
  82. /// None is used to execute the method in the same thread that made the call. It should only be used by regression
  83. /// test code that relies on predictable event ordering.
  84. /// RegressionTest is used by regression tests. It fires the call synchronously and does not catch any exceptions.
  85. /// </remarks>
  86. public enum FireAndForgetMethod
  87. {
  88. None,
  89. RegressionTest,
  90. UnsafeQueueUserWorkItem,
  91. QueueUserWorkItem,
  92. BeginInvoke,
  93. SmartThreadPool,
  94. Thread,
  95. }
  96. /// <summary>
  97. /// Class for delivering SmartThreadPool statistical information
  98. /// </summary>
  99. /// <remarks>
  100. /// We do it this way so that we do not directly expose STP.
  101. /// </remarks>
  102. public class STPInfo
  103. {
  104. public string Name { get; set; }
  105. public STPStartInfo STPStartInfo { get; set; }
  106. public WIGStartInfo WIGStartInfo { get; set; }
  107. public bool IsIdle { get; set; }
  108. public bool IsShuttingDown { get; set; }
  109. public int MaxThreads { get; set; }
  110. public int MinThreads { get; set; }
  111. public int InUseThreads { get; set; }
  112. public int ActiveThreads { get; set; }
  113. public int WaitingCallbacks { get; set; }
  114. public int MaxConcurrentWorkItems { get; set; }
  115. }
  116. /// <summary>
  117. /// Miscellaneous utility functions
  118. /// </summary>
  119. public static class Util
  120. {
  121. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  122. /// <summary>
  123. /// Log-level for the thread pool:
  124. /// 0 = no logging
  125. /// 1 = only first line of stack trace; don't log common threads
  126. /// 2 = full stack trace; don't log common threads
  127. /// 3 = full stack trace, including common threads
  128. /// </summary>
  129. public static int LogThreadPool { get; set; }
  130. public static bool LogOverloads { get; set; }
  131. public static readonly int MAX_THREADPOOL_LEVEL = 3;
  132. public static double TimeStampClockPeriodMS;
  133. static Util()
  134. {
  135. LogThreadPool = 0;
  136. LogOverloads = true;
  137. TimeStampClockPeriodMS = 1000.0D / (double)Stopwatch.Frequency;
  138. m_log.InfoFormat("[UTIL] TimeStamp clock with period of {0}ms", Math.Round(TimeStampClockPeriodMS,6,MidpointRounding.AwayFromZero));
  139. }
  140. private static uint nextXferID = 5000;
  141. private static Random randomClass = new ThreadSafeRandom();
  142. // Get a list of invalid file characters (OS dependent)
  143. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  144. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  145. private static object XferLock = new object();
  146. /// <summary>
  147. /// Thread pool used for Util.FireAndForget if FireAndForgetMethod.SmartThreadPool is used
  148. /// </summary>
  149. private static SmartThreadPool m_ThreadPool;
  150. // Watchdog timer that aborts threads that have timed-out
  151. private static Timer m_threadPoolWatchdog;
  152. // 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.
  153. public static readonly DateTime UnixEpoch =
  154. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  155. private static readonly string rawUUIDPattern
  156. = "[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}";
  157. public static readonly Regex PermissiveUUIDPattern = new Regex(rawUUIDPattern);
  158. public static readonly Regex UUIDPattern = new Regex(string.Format("^{0}$", rawUUIDPattern));
  159. public static FireAndForgetMethod DefaultFireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
  160. public static FireAndForgetMethod FireAndForgetMethod = DefaultFireAndForgetMethod;
  161. public static bool IsPlatformMono
  162. {
  163. get { return Type.GetType("Mono.Runtime") != null; }
  164. }
  165. /// <summary>
  166. /// Gets the name of the directory where the current running executable
  167. /// is located
  168. /// </summary>
  169. /// <returns>Filesystem path to the directory containing the current
  170. /// executable</returns>
  171. public static string ExecutingDirectory()
  172. {
  173. return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  174. }
  175. /// <summary>
  176. /// Linear interpolates B<->C using percent A
  177. /// </summary>
  178. /// <param name="a"></param>
  179. /// <param name="b"></param>
  180. /// <param name="c"></param>
  181. /// <returns></returns>
  182. public static double lerp(double a, double b, double c)
  183. {
  184. return (b*a) + (c*(1 - a));
  185. }
  186. /// <summary>
  187. /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
  188. /// Layout:
  189. /// A B
  190. /// C D
  191. /// A<->C = Y
  192. /// C<->D = X
  193. /// </summary>
  194. /// <param name="x"></param>
  195. /// <param name="y"></param>
  196. /// <param name="a"></param>
  197. /// <param name="b"></param>
  198. /// <param name="c"></param>
  199. /// <param name="d"></param>
  200. /// <returns></returns>
  201. public static double lerp2D(double x, double y, double a, double b, double c, double d)
  202. {
  203. return lerp(y, lerp(x, a, b), lerp(x, c, d));
  204. }
  205. public static Encoding UTF8 = Encoding.UTF8;
  206. public static Encoding UTF8NoBomEncoding = new UTF8Encoding(false);
  207. /// <value>
  208. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  209. /// </value>
  210. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  211. #region Vector Equations
  212. /// <summary>
  213. /// Get the distance between two 3d vectors
  214. /// </summary>
  215. /// <param name="a">A 3d vector</param>
  216. /// <param name="b">A 3d vector</param>
  217. /// <returns>The distance between the two vectors</returns>
  218. public static double GetDistanceTo(Vector3 a, Vector3 b)
  219. {
  220. float dx = a.X - b.X;
  221. float dy = a.Y - b.Y;
  222. float dz = a.Z - b.Z;
  223. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  224. }
  225. /// <summary>
  226. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  227. /// </summary>
  228. /// <param name="a"></param>
  229. /// <param name="b"></param>
  230. /// <param name="amount"></param>
  231. /// <returns></returns>
  232. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  233. {
  234. float dx = a.X - b.X;
  235. float dy = a.Y - b.Y;
  236. float dz = a.Z - b.Z;
  237. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  238. }
  239. /// <summary>
  240. /// Get the magnitude of a 3d vector
  241. /// </summary>
  242. /// <param name="a">A 3d vector</param>
  243. /// <returns>The magnitude of the vector</returns>
  244. public static double GetMagnitude(Vector3 a)
  245. {
  246. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  247. }
  248. /// <summary>
  249. /// Get a normalized form of a 3d vector
  250. /// </summary>
  251. /// <param name="a">A 3d vector</param>
  252. /// <returns>A new vector which is normalized form of the vector</returns>
  253. public static Vector3 GetNormalizedVector(Vector3 a)
  254. {
  255. Vector3 v = new Vector3(a.X, a.Y, a.Z);
  256. v.Normalize();
  257. return v;
  258. }
  259. /// <summary>
  260. /// Returns if a vector is a zero vector (has all zero components)
  261. /// </summary>
  262. /// <returns></returns>
  263. public static bool IsZeroVector(Vector3 v)
  264. {
  265. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  266. {
  267. return true;
  268. }
  269. return false;
  270. }
  271. # endregion
  272. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  273. {
  274. float s;
  275. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  276. if (tr >= 1.0)
  277. {
  278. s = (float) (0.5 / Math.Sqrt(tr));
  279. return new Quaternion(
  280. (left.Z - up.Y) * s,
  281. (up.X - fwd.Z) * s,
  282. (fwd.Y - left.X) * s,
  283. (float) 0.25 / s);
  284. }
  285. else
  286. {
  287. float max = (left.Y > up.Z) ? left.Y : up.Z;
  288. if (max < fwd.X)
  289. {
  290. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  291. float x = (float) (s * 0.5);
  292. s = (float) (0.5 / s);
  293. return new Quaternion(
  294. x,
  295. (fwd.Y + left.X) * s,
  296. (up.X + fwd.Z) * s,
  297. (left.Z - up.Y) * s);
  298. }
  299. else if (max == left.Y)
  300. {
  301. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  302. float y = (float) (s * 0.5);
  303. s = (float) (0.5 / s);
  304. return new Quaternion(
  305. (fwd.Y + left.X) * s,
  306. y,
  307. (left.Z + up.Y) * s,
  308. (up.X - fwd.Z) * s);
  309. }
  310. else
  311. {
  312. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  313. float z = (float) (s * 0.5);
  314. s = (float) (0.5 / s);
  315. return new Quaternion(
  316. (up.X + fwd.Z) * s,
  317. (left.Z + up.Y) * s,
  318. z,
  319. (fwd.Y - left.X) * s);
  320. }
  321. }
  322. }
  323. public static Random RandomClass
  324. {
  325. get { return randomClass; }
  326. }
  327. public static ulong UIntsToLong(uint X, uint Y)
  328. {
  329. return Utils.UIntsToLong(X, Y);
  330. }
  331. // Regions are identified with a 'handle' made up of its region coordinates packed into a ulong.
  332. // Several places rely on the ability to extract a region's location from its handle.
  333. // Note the location is in 'world coordinates' (see below).
  334. // Region handles are based on the lowest coordinate of the region so trim the passed x,y to be the regions 0,0.
  335. public static ulong RegionWorldLocToHandle(uint X, uint Y)
  336. {
  337. return Utils.UIntsToLong(X, Y);
  338. }
  339. public static ulong RegionLocToHandle(uint X, uint Y)
  340. {
  341. return Utils.UIntsToLong(Util.RegionToWorldLoc(X), Util.RegionToWorldLoc(Y));
  342. }
  343. public static void RegionHandleToWorldLoc(ulong handle, out uint X, out uint Y)
  344. {
  345. X = (uint)(handle >> 32);
  346. Y = (uint)(handle & (ulong)uint.MaxValue);
  347. }
  348. public static void RegionHandleToRegionLoc(ulong handle, out uint X, out uint Y)
  349. {
  350. uint worldX, worldY;
  351. RegionHandleToWorldLoc(handle, out worldX, out worldY);
  352. X = WorldToRegionLoc(worldX);
  353. Y = WorldToRegionLoc(worldY);
  354. }
  355. // A region location can be 'world coordinates' (meters from zero) or 'region coordinates'
  356. // (number of regions from zero). This measurement of regions relies on the legacy 256 region size.
  357. // These routines exist to make what is being converted explicit so the next person knows what was meant.
  358. // Convert a region's 'world coordinate' to its 'region coordinate'.
  359. public static uint WorldToRegionLoc(uint worldCoord)
  360. {
  361. return worldCoord / Constants.RegionSize;
  362. }
  363. // Convert a region's 'region coordinate' to its 'world coordinate'.
  364. public static uint RegionToWorldLoc(uint regionCoord)
  365. {
  366. return regionCoord * Constants.RegionSize;
  367. }
  368. public static T Clamp<T>(T x, T min, T max)
  369. where T : IComparable<T>
  370. {
  371. return x.CompareTo(max) > 0 ? max :
  372. x.CompareTo(min) < 0 ? min :
  373. x;
  374. }
  375. // Clamp the maximum magnitude of a vector
  376. public static Vector3 ClampV(Vector3 x, float max)
  377. {
  378. float lenSq = x.LengthSquared();
  379. if (lenSq > (max * max))
  380. {
  381. x = x / x.Length() * max;
  382. }
  383. return x;
  384. }
  385. /// <summary>
  386. /// Check if any of the values in a Vector3 are NaN or Infinity
  387. /// </summary>
  388. /// <param name="v">Vector3 to check</param>
  389. /// <returns></returns>
  390. public static bool IsNanOrInfinity(Vector3 v)
  391. {
  392. if (float.IsNaN(v.X) || float.IsNaN(v.Y) || float.IsNaN(v.Z))
  393. return true;
  394. if (float.IsInfinity(v.X) || float.IsInfinity(v.Y) || float.IsNaN(v.Z))
  395. return true;
  396. return false;
  397. }
  398. // Inclusive, within range test (true if equal to the endpoints)
  399. public static bool InRange<T>(T x, T min, T max)
  400. where T : IComparable<T>
  401. {
  402. return x.CompareTo(max) <= 0 && x.CompareTo(min) >= 0;
  403. }
  404. public static uint GetNextXferID()
  405. {
  406. uint id = 0;
  407. lock (XferLock)
  408. {
  409. id = nextXferID;
  410. nextXferID++;
  411. }
  412. return id;
  413. }
  414. public static string GetFileName(string file)
  415. {
  416. // Return just the filename on UNIX platforms
  417. // TODO: this should be customisable with a prefix, but that's something to do later.
  418. if (Environment.OSVersion.Platform == PlatformID.Unix)
  419. {
  420. return file;
  421. }
  422. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  423. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  424. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  425. {
  426. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  427. {
  428. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  429. }
  430. return "%APPDATA%\\OpenSim\\" + file;
  431. }
  432. // Catch all - covers older windows versions
  433. // (but those probably wont work anyway)
  434. return file;
  435. }
  436. /// <summary>
  437. /// Debug utility function to convert OSD into formatted XML for debugging purposes.
  438. /// </summary>
  439. /// <param name="osd">
  440. /// A <see cref="OSD"/>
  441. /// </param>
  442. /// <returns>
  443. /// A <see cref="System.String"/>
  444. /// </returns>
  445. public static string GetFormattedXml(OSD osd)
  446. {
  447. return GetFormattedXml(OSDParser.SerializeLLSDXmlString(osd));
  448. }
  449. /// <summary>
  450. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  451. /// </summary>
  452. /// <remarks>
  453. /// Please don't delete me even if I appear currently unused!
  454. /// </remarks>
  455. /// <param name="rawXml"></param>
  456. /// <returns></returns>
  457. public static string GetFormattedXml(string rawXml)
  458. {
  459. XmlDocument xd = new XmlDocument();
  460. xd.LoadXml(rawXml);
  461. StringBuilder sb = new StringBuilder();
  462. StringWriter sw = new StringWriter(sb);
  463. XmlTextWriter xtw = new XmlTextWriter(sw);
  464. xtw.Formatting = Formatting.Indented;
  465. try
  466. {
  467. xd.WriteTo(xtw);
  468. }
  469. finally
  470. {
  471. xtw.Close();
  472. }
  473. return sb.ToString();
  474. }
  475. public static byte[] DocToBytes(XmlDocument doc)
  476. {
  477. using (MemoryStream ms = new MemoryStream())
  478. using (XmlTextWriter xw = new XmlTextWriter(ms, null))
  479. {
  480. xw.Formatting = Formatting.Indented;
  481. doc.WriteTo(xw);
  482. xw.Flush();
  483. return ms.ToArray();
  484. }
  485. }
  486. /// <summary>
  487. /// Is the platform Windows?
  488. /// </summary>
  489. /// <returns>true if so, false otherwise</returns>
  490. public static bool IsWindows()
  491. {
  492. PlatformID platformId = Environment.OSVersion.Platform;
  493. return (platformId == PlatformID.Win32NT
  494. || platformId == PlatformID.Win32S
  495. || platformId == PlatformID.Win32Windows
  496. || platformId == PlatformID.WinCE);
  497. }
  498. public static bool LoadArchSpecificWindowsDll(string libraryName)
  499. {
  500. return LoadArchSpecificWindowsDll(libraryName, string.Empty);
  501. }
  502. public static bool LoadArchSpecificWindowsDll(string libraryName, string path)
  503. {
  504. // We do this so that OpenSimulator on Windows loads the correct native library depending on whether
  505. // it's running as a 32-bit process or a 64-bit one. By invoking LoadLibary here, later DLLImports
  506. // will find it already loaded later on.
  507. //
  508. // This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
  509. // controlled in config files.
  510. string nativeLibraryPath;
  511. if (Util.Is64BitProcess())
  512. nativeLibraryPath = Path.Combine(Path.Combine(path, "lib64"), libraryName);
  513. else
  514. nativeLibraryPath = Path.Combine(Path.Combine(path, "lib32"), libraryName);
  515. m_log.DebugFormat("[UTIL]: Loading native Windows library at {0}", nativeLibraryPath);
  516. if (Util.LoadLibrary(nativeLibraryPath) == IntPtr.Zero)
  517. {
  518. m_log.ErrorFormat(
  519. "[UTIL]: Couldn't find native Windows library at {0}", nativeLibraryPath);
  520. return false;
  521. }
  522. else
  523. {
  524. return true;
  525. }
  526. }
  527. public static bool IsEnvironmentSupported(ref string reason)
  528. {
  529. // Must have .NET 2.0 (Generics / libsl)
  530. if (Environment.Version.Major < 2)
  531. {
  532. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  533. return false;
  534. }
  535. // Windows 95/98/ME are unsupported
  536. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  537. Environment.OSVersion.Platform != PlatformID.Win32NT)
  538. {
  539. reason = "Windows 95/98/ME will not run OpenSim";
  540. return false;
  541. }
  542. // Windows 2000 / Pre-SP2 XP
  543. if (Environment.OSVersion.Version.Major == 5 &&
  544. Environment.OSVersion.Version.Minor == 0)
  545. {
  546. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  547. return false;
  548. }
  549. return true;
  550. }
  551. public static int UnixTimeSinceEpoch()
  552. {
  553. return ToUnixTime(DateTime.UtcNow);
  554. }
  555. public static int ToUnixTime(DateTime stamp)
  556. {
  557. TimeSpan t = stamp.ToUniversalTime() - UnixEpoch;
  558. return (int)t.TotalSeconds;
  559. }
  560. public static DateTime ToDateTime(ulong seconds)
  561. {
  562. return UnixEpoch.AddSeconds(seconds);
  563. }
  564. public static DateTime ToDateTime(int seconds)
  565. {
  566. return UnixEpoch.AddSeconds(seconds);
  567. }
  568. /// <summary>
  569. /// Return an md5 hash of the given string
  570. /// </summary>
  571. /// <param name="data"></param>
  572. /// <returns></returns>
  573. public static string Md5Hash(string data)
  574. {
  575. return Md5Hash(data, Encoding.Default);
  576. }
  577. public static string Md5Hash(string data, Encoding encoding)
  578. {
  579. byte[] dataMd5 = ComputeMD5Hash(data, encoding);
  580. StringBuilder sb = new StringBuilder();
  581. for (int i = 0; i < dataMd5.Length; i++)
  582. sb.AppendFormat("{0:x2}", dataMd5[i]);
  583. return sb.ToString();
  584. }
  585. private static byte[] ComputeMD5Hash(string data, Encoding encoding)
  586. {
  587. MD5 md5 = MD5.Create();
  588. return md5.ComputeHash(encoding.GetBytes(data));
  589. }
  590. /// <summary>
  591. /// Return an SHA1 hash
  592. /// </summary>
  593. /// <param name="data"></param>
  594. /// <returns></returns>
  595. public static string SHA1Hash(string data, Encoding enc)
  596. {
  597. return SHA1Hash(enc.GetBytes(data));
  598. }
  599. public static string SHA1Hash(string data)
  600. {
  601. return SHA1Hash(Encoding.Default.GetBytes(data));
  602. }
  603. /// <summary>
  604. /// Return an SHA1 hash
  605. /// </summary>
  606. /// <param name="data"></param>
  607. /// <returns></returns>
  608. public static string SHA1Hash(byte[] data)
  609. {
  610. byte[] hash = ComputeSHA1Hash(data);
  611. return BitConverter.ToString(hash).Replace("-", String.Empty);
  612. }
  613. private static byte[] ComputeSHA1Hash(byte[] src)
  614. {
  615. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  616. return SHA1.ComputeHash(src);
  617. }
  618. public static int fast_distance2d(int x, int y)
  619. {
  620. x = Math.Abs(x);
  621. y = Math.Abs(y);
  622. int min = Math.Min(x, y);
  623. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  624. }
  625. /// <summary>
  626. /// Determines whether a point is inside a bounding box.
  627. /// </summary>
  628. /// <param name='v'></param>
  629. /// <param name='min'></param>
  630. /// <param name='max'></param>
  631. /// <returns></returns>
  632. public static bool IsInsideBox(Vector3 v, Vector3 min, Vector3 max)
  633. {
  634. return v.X >= min.X & v.Y >= min.Y && v.Z >= min.Z
  635. && v.X <= max.X && v.Y <= max.Y && v.Z <= max.Z;
  636. }
  637. /// <summary>
  638. /// Are the co-ordinates of the new region visible from the old region?
  639. /// </summary>
  640. /// <param name="oldx">Old region x-coord</param>
  641. /// <param name="newx">New region x-coord</param>
  642. /// <param name="oldy">Old region y-coord</param>
  643. /// <param name="newy">New region y-coord</param>
  644. /// <returns></returns>
  645. public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy,
  646. int oldsizex, int oldsizey, int newsizex, int newsizey)
  647. {
  648. // we still need to make sure we see new region 1stNeighbors
  649. oldx *= Constants.RegionSize;
  650. newx *= Constants.RegionSize;
  651. if (oldx + oldsizex + drawdist < newx)
  652. return true;
  653. if (newx + newsizex + drawdist < oldx)
  654. return true;
  655. oldy *= Constants.RegionSize;
  656. newy *= Constants.RegionSize;
  657. if (oldy + oldsizey + drawdist < newy)
  658. return true;
  659. if (newy + newsizey + drawdist< oldy)
  660. return true;
  661. return false;
  662. }
  663. public static string FieldToString(byte[] bytes)
  664. {
  665. return FieldToString(bytes, String.Empty);
  666. }
  667. /// <summary>
  668. /// Convert a variable length field (byte array) to a string, with a
  669. /// field name prepended to each line of the output
  670. /// </summary>
  671. /// <remarks>If the byte array has unprintable characters in it, a
  672. /// hex dump will be put in the string instead</remarks>
  673. /// <param name="bytes">The byte array to convert to a string</param>
  674. /// <param name="fieldName">A field name to prepend to each line of output</param>
  675. /// <returns>An ASCII string or a string containing a hex dump, minus
  676. /// the null terminator</returns>
  677. public static string FieldToString(byte[] bytes, string fieldName)
  678. {
  679. // Check for a common case
  680. if (bytes.Length == 0) return String.Empty;
  681. StringBuilder output = new StringBuilder();
  682. bool printable = true;
  683. for (int i = 0; i < bytes.Length; ++i)
  684. {
  685. // Check if there are any unprintable characters in the array
  686. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  687. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  688. {
  689. printable = false;
  690. break;
  691. }
  692. }
  693. if (printable)
  694. {
  695. if (fieldName.Length > 0)
  696. {
  697. output.Append(fieldName);
  698. output.Append(": ");
  699. }
  700. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  701. }
  702. else
  703. {
  704. for (int i = 0; i < bytes.Length; i += 16)
  705. {
  706. if (i != 0)
  707. output.Append(Environment.NewLine);
  708. if (fieldName.Length > 0)
  709. {
  710. output.Append(fieldName);
  711. output.Append(": ");
  712. }
  713. for (int j = 0; j < 16; j++)
  714. {
  715. if ((i + j) < bytes.Length)
  716. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  717. else
  718. output.Append(" ");
  719. }
  720. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  721. {
  722. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  723. output.Append((char) bytes[i + j]);
  724. else
  725. output.Append(".");
  726. }
  727. }
  728. }
  729. return output.ToString();
  730. }
  731. /// <summary>
  732. /// Converts a URL to a IPAddress
  733. /// </summary>
  734. /// <param name="url">URL Standard Format</param>
  735. /// <returns>A resolved IP Address</returns>
  736. public static IPAddress GetHostFromURL(string url)
  737. {
  738. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  739. }
  740. /// <summary>
  741. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  742. /// </summary>
  743. /// <param name="dnsAddress">DNS Hostname</param>
  744. /// <returns>An IP address, or null</returns>
  745. public static IPAddress GetHostFromDNS(string dnsAddress)
  746. {
  747. // Is it already a valid IP? No need to look it up.
  748. IPAddress ipa;
  749. if (IPAddress.TryParse(dnsAddress, out ipa))
  750. return ipa;
  751. IPAddress[] hosts = null;
  752. // Not an IP, lookup required
  753. try
  754. {
  755. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  756. }
  757. catch (Exception e)
  758. {
  759. m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);
  760. // Still going to throw the exception on for now, since this was what was happening in the first place
  761. throw e;
  762. }
  763. foreach (IPAddress host in hosts)
  764. {
  765. if (host.AddressFamily == AddressFamily.InterNetwork)
  766. {
  767. return host;
  768. }
  769. }
  770. if (hosts.Length > 0)
  771. return hosts[0];
  772. return null;
  773. }
  774. public static Uri GetURI(string protocol, string hostname, int port, string path)
  775. {
  776. return new UriBuilder(protocol, hostname, port, path).Uri;
  777. }
  778. /// <summary>
  779. /// Gets a list of all local system IP addresses
  780. /// </summary>
  781. /// <returns></returns>
  782. public static IPAddress[] GetLocalHosts()
  783. {
  784. return Dns.GetHostAddresses(Dns.GetHostName());
  785. }
  786. public static IPAddress GetLocalHost()
  787. {
  788. IPAddress[] iplist = GetLocalHosts();
  789. if (iplist.Length == 0) // No accessible external interfaces
  790. {
  791. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  792. IPAddress localhost = loopback[0];
  793. return localhost;
  794. }
  795. foreach (IPAddress host in iplist)
  796. {
  797. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  798. {
  799. return host;
  800. }
  801. }
  802. if (iplist.Length > 0)
  803. {
  804. foreach (IPAddress host in iplist)
  805. {
  806. if (host.AddressFamily == AddressFamily.InterNetwork)
  807. return host;
  808. }
  809. // Well all else failed...
  810. return iplist[0];
  811. }
  812. return null;
  813. }
  814. /// <summary>
  815. /// Parses a foreign asset ID.
  816. /// </summary>
  817. /// <param name="id">A possibly-foreign asset ID: http://grid.example.com:8002/00000000-0000-0000-0000-000000000000 </param>
  818. /// <param name="url">The URL: http://grid.example.com:8002</param>
  819. /// <param name="assetID">The asset ID: 00000000-0000-0000-0000-000000000000. Returned even if 'id' isn't foreign.</param>
  820. /// <returns>True: this is a foreign asset ID; False: it isn't</returns>
  821. public static bool ParseForeignAssetID(string id, out string url, out string assetID)
  822. {
  823. url = String.Empty;
  824. assetID = String.Empty;
  825. UUID uuid;
  826. if (UUID.TryParse(id, out uuid))
  827. {
  828. assetID = uuid.ToString();
  829. return false;
  830. }
  831. if ((id.Length == 0) || (id[0] != 'h' && id[0] != 'H'))
  832. return false;
  833. Uri assetUri;
  834. if (!Uri.TryCreate(id, UriKind.Absolute, out assetUri) || assetUri.Scheme != Uri.UriSchemeHttp)
  835. return false;
  836. // Simian
  837. if (assetUri.Query != string.Empty)
  838. {
  839. NameValueCollection qscoll = HttpUtility.ParseQueryString(assetUri.Query);
  840. assetID = qscoll["id"];
  841. if (assetID != null)
  842. url = id.Replace(assetID, ""); // Malformed again, as simian expects
  843. else
  844. url = id; // !!! best effort
  845. }
  846. else // robust
  847. {
  848. url = "http://" + assetUri.Authority;
  849. assetID = assetUri.LocalPath.Trim(new char[] { '/' });
  850. }
  851. if (!UUID.TryParse(assetID, out uuid))
  852. return false;
  853. return true;
  854. }
  855. /// <summary>
  856. /// Removes all invalid path chars (OS dependent)
  857. /// </summary>
  858. /// <param name="path">path</param>
  859. /// <returns>safe path</returns>
  860. public static string safePath(string path)
  861. {
  862. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  863. }
  864. /// <summary>
  865. /// Removes all invalid filename chars (OS dependent)
  866. /// </summary>
  867. /// <param name="path">filename</param>
  868. /// <returns>safe filename</returns>
  869. public static string safeFileName(string filename)
  870. {
  871. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  872. ;
  873. }
  874. //
  875. // directory locations
  876. //
  877. public static string homeDir()
  878. {
  879. string temp;
  880. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  881. // temp = Path.Combine(personal,".OpenSim");
  882. temp = ".";
  883. return temp;
  884. }
  885. public static string assetsDir()
  886. {
  887. return Path.Combine(configDir(), "assets");
  888. }
  889. public static string inventoryDir()
  890. {
  891. return Path.Combine(configDir(), "inventory");
  892. }
  893. public static string configDir()
  894. {
  895. return ".";
  896. }
  897. public static string dataDir()
  898. {
  899. return ".";
  900. }
  901. public static string logFile()
  902. {
  903. foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
  904. {
  905. if (appender is FileAppender)
  906. {
  907. return ((FileAppender)appender).File;
  908. }
  909. }
  910. return "./OpenSim.log";
  911. }
  912. public static string logDir()
  913. {
  914. return Path.GetDirectoryName(logFile());
  915. }
  916. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  917. public static string GetUniqueFilename(string FileName)
  918. {
  919. int count = 0;
  920. string Name;
  921. if (File.Exists(FileName))
  922. {
  923. FileInfo f = new FileInfo(FileName);
  924. if (!String.IsNullOrEmpty(f.Extension))
  925. {
  926. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  927. }
  928. else
  929. {
  930. Name = f.FullName;
  931. }
  932. while (File.Exists(FileName))
  933. {
  934. count++;
  935. FileName = Name + count + f.Extension;
  936. }
  937. }
  938. return FileName;
  939. }
  940. #region Nini (config) related Methods
  941. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  942. {
  943. if (!File.Exists(fileName))
  944. {
  945. // create new file
  946. }
  947. XmlConfigSource config = new XmlConfigSource(fileName);
  948. AddDataRowToConfig(config, row);
  949. config.Save();
  950. return config;
  951. }
  952. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  953. {
  954. config.Configs.Add((string) row[0]);
  955. for (int i = 0; i < row.Table.Columns.Count; i++)
  956. {
  957. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  958. }
  959. }
  960. public static string GetConfigVarWithDefaultSection(IConfigSource config, string varname, string section)
  961. {
  962. // First, check the Startup section, the default section
  963. IConfig cnf = config.Configs["Startup"];
  964. if (cnf == null)
  965. return string.Empty;
  966. string val = cnf.GetString(varname, string.Empty);
  967. // Then check for an overwrite of the default in the given section
  968. if (!string.IsNullOrEmpty(section))
  969. {
  970. cnf = config.Configs[section];
  971. if (cnf != null)
  972. val = cnf.GetString(varname, val);
  973. }
  974. return val;
  975. }
  976. /// <summary>
  977. /// Gets the value of a configuration variable by looking into
  978. /// multiple sections in order. The latter sections overwrite
  979. /// any values previously found.
  980. /// </summary>
  981. /// <typeparam name="T">Type of the variable</typeparam>
  982. /// <param name="config">The configuration object</param>
  983. /// <param name="varname">The configuration variable</param>
  984. /// <param name="sections">Ordered sequence of sections to look at</param>
  985. /// <returns></returns>
  986. public static T GetConfigVarFromSections<T>(IConfigSource config, string varname, string[] sections)
  987. {
  988. return GetConfigVarFromSections<T>(config, varname, sections, default(T));
  989. }
  990. /// <summary>
  991. /// Gets the value of a configuration variable by looking into
  992. /// multiple sections in order. The latter sections overwrite
  993. /// any values previously found.
  994. /// </summary>
  995. /// <remarks>
  996. /// If no value is found then the given default value is returned
  997. /// </remarks>
  998. /// <typeparam name="T">Type of the variable</typeparam>
  999. /// <param name="config">The configuration object</param>
  1000. /// <param name="varname">The configuration variable</param>
  1001. /// <param name="sections">Ordered sequence of sections to look at</param>
  1002. /// <param name="val">Default value</param>
  1003. /// <returns></returns>
  1004. public static T GetConfigVarFromSections<T>(IConfigSource config, string varname, string[] sections, object val)
  1005. {
  1006. foreach (string section in sections)
  1007. {
  1008. IConfig cnf = config.Configs[section];
  1009. if (cnf == null)
  1010. continue;
  1011. if (typeof(T) == typeof(String))
  1012. val = cnf.GetString(varname, (string)val);
  1013. else if (typeof(T) == typeof(Boolean))
  1014. val = cnf.GetBoolean(varname, (bool)val);
  1015. else if (typeof(T) == typeof(Int32))
  1016. val = cnf.GetInt(varname, (int)val);
  1017. else if (typeof(T) == typeof(float))
  1018. val = cnf.GetFloat(varname, (float)val);
  1019. else
  1020. m_log.ErrorFormat("[UTIL]: Unhandled type {0}", typeof(T));
  1021. }
  1022. return (T)val;
  1023. }
  1024. public static void MergeEnvironmentToConfig(IConfigSource ConfigSource)
  1025. {
  1026. IConfig enVars = ConfigSource.Configs["Environment"];
  1027. // if section does not exist then user isn't expecting them, so don't bother.
  1028. if( enVars != null )
  1029. {
  1030. // load the values from the environment
  1031. EnvConfigSource envConfigSource = new EnvConfigSource();
  1032. // add the requested keys
  1033. string[] env_keys = enVars.GetKeys();
  1034. foreach ( string key in env_keys )
  1035. {
  1036. envConfigSource.AddEnv(key, string.Empty);
  1037. }
  1038. // load the values from environment
  1039. envConfigSource.LoadEnv();
  1040. // add them in to the master
  1041. ConfigSource.Merge(envConfigSource);
  1042. ConfigSource.ExpandKeyValues();
  1043. }
  1044. }
  1045. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  1046. {
  1047. Type settingsType = settingsClass.GetType();
  1048. FieldInfo[] fieldInfos = settingsType.GetFields();
  1049. foreach (FieldInfo fieldInfo in fieldInfos)
  1050. {
  1051. if (!fieldInfo.IsStatic)
  1052. {
  1053. if (fieldInfo.FieldType == typeof(System.String))
  1054. {
  1055. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  1056. }
  1057. else if (fieldInfo.FieldType == typeof(System.Boolean))
  1058. {
  1059. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  1060. }
  1061. else if (fieldInfo.FieldType == typeof(System.Int32))
  1062. {
  1063. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  1064. }
  1065. else if (fieldInfo.FieldType == typeof(System.Single))
  1066. {
  1067. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  1068. }
  1069. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1070. {
  1071. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1072. }
  1073. }
  1074. }
  1075. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1076. foreach (PropertyInfo propInfo in propertyInfos)
  1077. {
  1078. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1079. {
  1080. if (propInfo.PropertyType == typeof(System.String))
  1081. {
  1082. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1083. }
  1084. else if (propInfo.PropertyType == typeof(System.Boolean))
  1085. {
  1086. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1087. }
  1088. else if (propInfo.PropertyType == typeof(System.Int32))
  1089. {
  1090. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1091. }
  1092. else if (propInfo.PropertyType == typeof(System.Single))
  1093. {
  1094. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1095. }
  1096. if (propInfo.PropertyType == typeof(System.UInt32))
  1097. {
  1098. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1099. }
  1100. }
  1101. }
  1102. return settingsClass;
  1103. }
  1104. /// <summary>
  1105. /// Reads a configuration file, configFile, merging it with the main configuration, config.
  1106. /// If the file doesn't exist, it copies a given exampleConfigFile onto configFile, and then
  1107. /// merges it.
  1108. /// </summary>
  1109. /// <param name="config">The main configuration data</param>
  1110. /// <param name="configFileName">The name of a configuration file in ConfigDirectory variable, no path</param>
  1111. /// <param name="exampleConfigFile">Full path to an example configuration file</param>
  1112. /// <param name="configFilePath">Full path ConfigDirectory/configFileName</param>
  1113. /// <param name="created">True if the file was created in ConfigDirectory, false if it existed</param>
  1114. /// <returns>True if success</returns>
  1115. public static bool MergeConfigurationFile(IConfigSource config, string configFileName, string exampleConfigFile, out string configFilePath, out bool created)
  1116. {
  1117. created = false;
  1118. configFilePath = string.Empty;
  1119. IConfig cnf = config.Configs["Startup"];
  1120. if (cnf == null)
  1121. {
  1122. m_log.WarnFormat("[UTILS]: Startup section doesn't exist");
  1123. return false;
  1124. }
  1125. string configDirectory = cnf.GetString("ConfigDirectory", ".");
  1126. string configFile = Path.Combine(configDirectory, configFileName);
  1127. if (!File.Exists(configFile) && !string.IsNullOrEmpty(exampleConfigFile))
  1128. {
  1129. // We need to copy the example onto it
  1130. if (!Directory.Exists(configDirectory))
  1131. Directory.CreateDirectory(configDirectory);
  1132. try
  1133. {
  1134. File.Copy(exampleConfigFile, configFile);
  1135. created = true;
  1136. }
  1137. catch (Exception e)
  1138. {
  1139. m_log.WarnFormat("[UTILS]: Exception copying configuration file {0} to {1}: {2}", configFile, exampleConfigFile, e.Message);
  1140. return false;
  1141. }
  1142. }
  1143. if (File.Exists(configFile))
  1144. {
  1145. // Merge
  1146. config.Merge(new IniConfigSource(configFile));
  1147. config.ExpandKeyValues();
  1148. configFilePath = configFile;
  1149. return true;
  1150. }
  1151. else
  1152. return false;
  1153. }
  1154. #endregion
  1155. public static float Clip(float x, float min, float max)
  1156. {
  1157. return Math.Min(Math.Max(x, min), max);
  1158. }
  1159. public static int Clip(int x, int min, int max)
  1160. {
  1161. return Math.Min(Math.Max(x, min), max);
  1162. }
  1163. public static Vector3 Clip(Vector3 vec, float min, float max)
  1164. {
  1165. return new Vector3(Clip(vec.X, min, max), Clip(vec.Y, min, max),
  1166. Clip(vec.Z, min, max));
  1167. }
  1168. /// <summary>
  1169. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  1170. /// </summary>
  1171. /// <param name="UUID"></param>
  1172. /// <returns></returns>
  1173. public static String ToRawUuidString(UUID UUID)
  1174. {
  1175. return UUID.Guid.ToString("n");
  1176. }
  1177. public static string CleanString(string input)
  1178. {
  1179. if (input.Length == 0)
  1180. return input;
  1181. int clip = input.Length;
  1182. // Test for ++ string terminator
  1183. int pos = input.IndexOf("\0");
  1184. if (pos != -1 && pos < clip)
  1185. clip = pos;
  1186. // Test for CR
  1187. pos = input.IndexOf("\r");
  1188. if (pos != -1 && pos < clip)
  1189. clip = pos;
  1190. // Test for LF
  1191. pos = input.IndexOf("\n");
  1192. if (pos != -1 && pos < clip)
  1193. clip = pos;
  1194. // Truncate string before first end-of-line character found
  1195. return input.Substring(0, clip);
  1196. }
  1197. /// <summary>
  1198. /// returns the contents of /etc/issue on Unix Systems
  1199. /// Use this for where it's absolutely necessary to implement platform specific stuff
  1200. /// </summary>
  1201. /// <returns></returns>
  1202. public static string ReadEtcIssue()
  1203. {
  1204. try
  1205. {
  1206. StreamReader sr = new StreamReader("/etc/issue.net");
  1207. string issue = sr.ReadToEnd();
  1208. sr.Close();
  1209. return issue;
  1210. }
  1211. catch (Exception)
  1212. {
  1213. return "";
  1214. }
  1215. }
  1216. public static void SerializeToFile(string filename, Object obj)
  1217. {
  1218. IFormatter formatter = new BinaryFormatter();
  1219. Stream stream = null;
  1220. try
  1221. {
  1222. stream = new FileStream(
  1223. filename, FileMode.Create,
  1224. FileAccess.Write, FileShare.None);
  1225. formatter.Serialize(stream, obj);
  1226. }
  1227. catch (Exception e)
  1228. {
  1229. m_log.Error(e.ToString());
  1230. }
  1231. finally
  1232. {
  1233. if (stream != null)
  1234. {
  1235. stream.Close();
  1236. }
  1237. }
  1238. }
  1239. public static Object DeserializeFromFile(string filename)
  1240. {
  1241. IFormatter formatter = new BinaryFormatter();
  1242. Stream stream = null;
  1243. Object ret = null;
  1244. try
  1245. {
  1246. stream = new FileStream(
  1247. filename, FileMode.Open,
  1248. FileAccess.Read, FileShare.None);
  1249. ret = formatter.Deserialize(stream);
  1250. }
  1251. catch (Exception e)
  1252. {
  1253. m_log.Error(e.ToString());
  1254. }
  1255. finally
  1256. {
  1257. if (stream != null)
  1258. {
  1259. stream.Close();
  1260. }
  1261. }
  1262. return ret;
  1263. }
  1264. public static string Compress(string text)
  1265. {
  1266. byte[] buffer = Util.UTF8.GetBytes(text);
  1267. MemoryStream memory = new MemoryStream();
  1268. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  1269. {
  1270. compressor.Write(buffer, 0, buffer.Length);
  1271. }
  1272. memory.Position = 0;
  1273. byte[] compressed = new byte[memory.Length];
  1274. memory.Read(compressed, 0, compressed.Length);
  1275. byte[] compressedBuffer = new byte[compressed.Length + 4];
  1276. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  1277. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  1278. return Convert.ToBase64String(compressedBuffer);
  1279. }
  1280. public static string Decompress(string compressedText)
  1281. {
  1282. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  1283. using (MemoryStream memory = new MemoryStream())
  1284. {
  1285. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  1286. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  1287. byte[] buffer = new byte[msgLength];
  1288. memory.Position = 0;
  1289. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  1290. {
  1291. decompressor.Read(buffer, 0, buffer.Length);
  1292. }
  1293. return Util.UTF8.GetString(buffer);
  1294. }
  1295. }
  1296. /// <summary>
  1297. /// Copy data from one stream to another, leaving the read position of both streams at the beginning.
  1298. /// </summary>
  1299. /// <param name='inputStream'>
  1300. /// Input stream. Must be seekable.
  1301. /// </param>
  1302. /// <exception cref='ArgumentException'>
  1303. /// Thrown if the input stream is not seekable.
  1304. /// </exception>
  1305. public static Stream Copy(Stream inputStream)
  1306. {
  1307. if (!inputStream.CanSeek)
  1308. throw new ArgumentException("Util.Copy(Stream inputStream) must receive an inputStream that can seek");
  1309. const int readSize = 256;
  1310. byte[] buffer = new byte[readSize];
  1311. MemoryStream ms = new MemoryStream();
  1312. int count = inputStream.Read(buffer, 0, readSize);
  1313. while (count > 0)
  1314. {
  1315. ms.Write(buffer, 0, count);
  1316. count = inputStream.Read(buffer, 0, readSize);
  1317. }
  1318. ms.Position = 0;
  1319. inputStream.Position = 0;
  1320. return ms;
  1321. }
  1322. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  1323. {
  1324. return SendXmlRpcCommand(url, methodName, args);
  1325. }
  1326. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  1327. {
  1328. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  1329. return client.Send(url, 6000);
  1330. }
  1331. /// <summary>
  1332. /// Returns an error message that the user could not be found in the database
  1333. /// </summary>
  1334. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  1335. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  1336. {
  1337. XmlRpcResponse response = new XmlRpcResponse();
  1338. Hashtable responseData = new Hashtable();
  1339. responseData["error_type"] = "unknown_user";
  1340. responseData["error_desc"] = "The user requested is not in the database";
  1341. response.Value = responseData;
  1342. return response;
  1343. }
  1344. /// <summary>
  1345. /// Converts a byte array in big endian order into an ulong.
  1346. /// </summary>
  1347. /// <param name="bytes">
  1348. /// The array of bytes
  1349. /// </param>
  1350. /// <returns>
  1351. /// The extracted ulong
  1352. /// </returns>
  1353. public static ulong BytesToUInt64Big(byte[] bytes)
  1354. {
  1355. if (bytes.Length < 8) return 0;
  1356. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  1357. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  1358. }
  1359. // used for RemoteParcelRequest (for "About Landmark")
  1360. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  1361. {
  1362. byte[] bytes =
  1363. {
  1364. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  1365. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
  1366. (byte)x, (byte)(x >> 8), 0, 0,
  1367. (byte)y, (byte)(y >> 8), 0, 0 };
  1368. return new UUID(bytes, 0);
  1369. }
  1370. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  1371. {
  1372. byte[] bytes =
  1373. {
  1374. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  1375. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
  1376. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  1377. (byte)y, (byte)(y >> 8), 0, 0 };
  1378. return new UUID(bytes, 0);
  1379. }
  1380. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  1381. {
  1382. byte[] bytes = parcelID.GetBytes();
  1383. regionHandle = Utils.BytesToUInt64(bytes);
  1384. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  1385. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  1386. }
  1387. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  1388. {
  1389. byte[] bytes = parcelID.GetBytes();
  1390. regionHandle = Utils.BytesToUInt64(bytes);
  1391. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  1392. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  1393. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  1394. }
  1395. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  1396. {
  1397. ulong regionHandle;
  1398. uint rx, ry;
  1399. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  1400. Utils.LongToUInts(regionHandle, out rx, out ry);
  1401. x += rx;
  1402. y += ry;
  1403. }
  1404. /// <summary>
  1405. /// Get operating system information if available. Returns only the first 45 characters of information
  1406. /// </summary>
  1407. /// <returns>
  1408. /// Operating system information. Returns an empty string if none was available.
  1409. /// </returns>
  1410. public static string GetOperatingSystemInformation()
  1411. {
  1412. string os = String.Empty;
  1413. // if (Environment.OSVersion.Platform != PlatformID.Unix)
  1414. // {
  1415. // os = Environment.OSVersion.ToString();
  1416. // }
  1417. // else
  1418. // {
  1419. // os = ReadEtcIssue();
  1420. // }
  1421. //
  1422. // if (os.Length > 45)
  1423. // {
  1424. // os = os.Substring(0, 45);
  1425. // }
  1426. return os;
  1427. }
  1428. public static string GetRuntimeInformation()
  1429. {
  1430. string ru = String.Empty;
  1431. if (Environment.OSVersion.Platform == PlatformID.Unix)
  1432. ru = "Unix/Mono";
  1433. else
  1434. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  1435. ru = "OSX/Mono";
  1436. else
  1437. {
  1438. if (IsPlatformMono)
  1439. ru = "Win/Mono";
  1440. else
  1441. ru = "Win/.NET";
  1442. }
  1443. return ru;
  1444. }
  1445. /// <summary>
  1446. /// Is the given string a UUID?
  1447. /// </summary>
  1448. /// <param name="s"></param>
  1449. /// <returns></returns>
  1450. public static bool isUUID(string s)
  1451. {
  1452. return UUIDPattern.IsMatch(s);
  1453. }
  1454. public static string GetDisplayConnectionString(string connectionString)
  1455. {
  1456. int passPosition = 0;
  1457. int passEndPosition = 0;
  1458. string displayConnectionString = null;
  1459. // hide the password in the connection string
  1460. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  1461. passPosition = connectionString.IndexOf("=", passPosition);
  1462. if (passPosition < connectionString.Length)
  1463. passPosition += 1;
  1464. passEndPosition = connectionString.IndexOf(";", passPosition);
  1465. displayConnectionString = connectionString.Substring(0, passPosition);
  1466. displayConnectionString += "***";
  1467. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  1468. return displayConnectionString;
  1469. }
  1470. public static string Base64ToString(string str)
  1471. {
  1472. Decoder utf8Decode = Encoding.UTF8.GetDecoder();
  1473. byte[] todecode_byte = Convert.FromBase64String(str);
  1474. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  1475. char[] decoded_char = new char[charCount];
  1476. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  1477. string result = new String(decoded_char);
  1478. return result;
  1479. }
  1480. public static void BinaryToASCII(char[] chars)
  1481. {
  1482. for (int i = 0; i < chars.Length; i++)
  1483. {
  1484. char ch = chars[i];
  1485. if (ch < 32 || ch > 127)
  1486. chars[i] = '.';
  1487. }
  1488. }
  1489. public static string BinaryToASCII(string src)
  1490. {
  1491. char[] chars = src.ToCharArray();
  1492. BinaryToASCII(chars);
  1493. return new String(chars);
  1494. }
  1495. /// <summary>
  1496. /// Reads a known number of bytes from a stream.
  1497. /// Throws EndOfStreamException if the stream doesn't contain enough data.
  1498. /// </summary>
  1499. /// <param name="stream">The stream to read data from</param>
  1500. /// <param name="data">The array to write bytes into. The array
  1501. /// will be completely filled from the stream, so an appropriate
  1502. /// size must be given.</param>
  1503. public static void ReadStream(Stream stream, byte[] data)
  1504. {
  1505. int offset = 0;
  1506. int remaining = data.Length;
  1507. while (remaining > 0)
  1508. {
  1509. int read = stream.Read(data, offset, remaining);
  1510. if (read <= 0)
  1511. throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining));
  1512. remaining -= read;
  1513. offset += read;
  1514. }
  1515. }
  1516. public static Guid GetHashGuid(string data, string salt)
  1517. {
  1518. byte[] hash = ComputeMD5Hash(data + salt, Encoding.Default);
  1519. //string s = BitConverter.ToString(hash);
  1520. Guid guid = new Guid(hash);
  1521. return guid;
  1522. }
  1523. public static byte ConvertMaturityToAccessLevel(uint maturity)
  1524. {
  1525. byte retVal = 0;
  1526. switch (maturity)
  1527. {
  1528. case 0: //PG
  1529. retVal = 13;
  1530. break;
  1531. case 1: //Mature
  1532. retVal = 21;
  1533. break;
  1534. case 2: // Adult
  1535. retVal = 42;
  1536. break;
  1537. }
  1538. return retVal;
  1539. }
  1540. public static uint ConvertAccessLevelToMaturity(byte maturity)
  1541. {
  1542. if (maturity <= 13)
  1543. return 0;
  1544. else if (maturity <= 21)
  1545. return 1;
  1546. else
  1547. return 2;
  1548. }
  1549. /// <summary>
  1550. /// Produces an OSDMap from its string representation on a stream
  1551. /// </summary>
  1552. /// <param name="data">The stream</param>
  1553. /// <param name="length">The size of the data on the stream</param>
  1554. /// <returns>The OSDMap or an exception</returns>
  1555. public static OSDMap GetOSDMap(Stream stream, int length)
  1556. {
  1557. byte[] data = new byte[length];
  1558. stream.Read(data, 0, length);
  1559. string strdata = Util.UTF8.GetString(data);
  1560. OSDMap args = null;
  1561. OSD buffer;
  1562. buffer = OSDParser.DeserializeJson(strdata);
  1563. if (buffer.Type == OSDType.Map)
  1564. {
  1565. args = (OSDMap)buffer;
  1566. return args;
  1567. }
  1568. return null;
  1569. }
  1570. public static OSDMap GetOSDMap(string data)
  1571. {
  1572. OSDMap args = null;
  1573. try
  1574. {
  1575. OSD buffer;
  1576. // We should pay attention to the content-type, but let's assume we know it's Json
  1577. buffer = OSDParser.DeserializeJson(data);
  1578. if (buffer.Type == OSDType.Map)
  1579. {
  1580. args = (OSDMap)buffer;
  1581. return args;
  1582. }
  1583. else
  1584. {
  1585. // uh?
  1586. m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
  1587. return null;
  1588. }
  1589. }
  1590. catch (Exception ex)
  1591. {
  1592. m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
  1593. return null;
  1594. }
  1595. }
  1596. public static string[] Glob(string path)
  1597. {
  1598. string vol=String.Empty;
  1599. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1600. {
  1601. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1602. if (vcomps.Length > 1)
  1603. {
  1604. path = vcomps[1];
  1605. vol = vcomps[0];
  1606. }
  1607. }
  1608. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1609. // Glob
  1610. path = vol;
  1611. if (vol != String.Empty)
  1612. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1613. else
  1614. path = new String(new char[] {Path.DirectorySeparatorChar});
  1615. List<string> paths = new List<string>();
  1616. List<string> found = new List<string>();
  1617. paths.Add(path);
  1618. int compIndex = -1;
  1619. foreach (string c in comps)
  1620. {
  1621. compIndex++;
  1622. List<string> addpaths = new List<string>();
  1623. foreach (string p in paths)
  1624. {
  1625. string[] dirs = Directory.GetDirectories(p, c);
  1626. if (dirs.Length != 0)
  1627. {
  1628. foreach (string dir in dirs)
  1629. addpaths.Add(Path.Combine(path, dir));
  1630. }
  1631. // Only add files if that is the last path component
  1632. if (compIndex == comps.Length - 1)
  1633. {
  1634. string[] files = Directory.GetFiles(p, c);
  1635. foreach (string f in files)
  1636. found.Add(f);
  1637. }
  1638. }
  1639. paths = addpaths;
  1640. }
  1641. return found.ToArray();
  1642. }
  1643. public static string ServerURI(string uri)
  1644. {
  1645. if (uri == string.Empty)
  1646. return string.Empty;
  1647. // Get rid of eventual slashes at the end
  1648. uri = uri.TrimEnd('/');
  1649. IPAddress ipaddr1 = null;
  1650. string port1 = "";
  1651. try
  1652. {
  1653. ipaddr1 = Util.GetHostFromURL(uri);
  1654. }
  1655. catch { }
  1656. try
  1657. {
  1658. port1 = uri.Split(new char[] { ':' })[2];
  1659. }
  1660. catch { }
  1661. // We tried our best to convert the domain names to IP addresses
  1662. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1663. }
  1664. /// <summary>
  1665. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1666. /// </summary>
  1667. /// <param name="str">
  1668. /// If null or empty, then an bytes[0] is returned.
  1669. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1670. /// </param>
  1671. /// <param name="args">
  1672. /// Arguments to substitute into the string via the {} mechanism.
  1673. /// </param>
  1674. /// <returns></returns>
  1675. public static byte[] StringToBytes256(string str, params object[] args)
  1676. {
  1677. return StringToBytes256(string.Format(str, args));
  1678. }
  1679. /// <summary>
  1680. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1681. /// </summary>
  1682. /// <param name="str">
  1683. /// If null or empty, then an bytes[0] is returned.
  1684. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1685. /// </param>
  1686. /// <returns></returns>
  1687. public static byte[] StringToBytes256(string str)
  1688. {
  1689. if (String.IsNullOrEmpty(str))
  1690. return Utils.EmptyBytes;
  1691. if (!str.EndsWith("\0"))
  1692. str += "\0";
  1693. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1694. // might have gotten an oversized array even after the string trim
  1695. byte[] data = UTF8.GetBytes(str);
  1696. if (data.Length > 256)
  1697. {
  1698. int cut = 255;
  1699. if((data[cut] & 0x80 ) != 0 )
  1700. {
  1701. while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
  1702. cut--;
  1703. }
  1704. Array.Resize<byte>(ref data, cut + 1);
  1705. data[cut] = 0;
  1706. }
  1707. return data;
  1708. }
  1709. /// <summary>
  1710. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1711. /// </summary>
  1712. /// <param name="str">
  1713. /// If null or empty, then an bytes[0] is returned.
  1714. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1715. /// </param>
  1716. /// <param name="args">
  1717. /// Arguments to substitute into the string via the {} mechanism.
  1718. /// </param>
  1719. /// <returns></returns>
  1720. public static byte[] StringToBytes1024(string str, params object[] args)
  1721. {
  1722. return StringToBytes1024(string.Format(str, args));
  1723. }
  1724. /// <summary>
  1725. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1726. /// </summary>
  1727. /// <param name="str">
  1728. /// If null or empty, then an bytes[0] is returned.
  1729. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1730. /// </param>
  1731. /// <returns></returns>
  1732. public static byte[] StringToBytes1024(string str)
  1733. {
  1734. if (String.IsNullOrEmpty(str))
  1735. return Utils.EmptyBytes;
  1736. if (!str.EndsWith("\0"))
  1737. str += "\0";
  1738. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1739. // might have gotten an oversized array even after the string trim
  1740. byte[] data = UTF8.GetBytes(str);
  1741. if (data.Length > 1024)
  1742. {
  1743. int cut = 1023;
  1744. if((data[cut] & 0x80 ) != 0 )
  1745. {
  1746. while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
  1747. cut--;
  1748. }
  1749. Array.Resize<byte>(ref data, cut + 1);
  1750. data[cut] = 0;
  1751. }
  1752. return data;
  1753. }
  1754. /// <summary>
  1755. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to MaxLength bytes if necessary.
  1756. /// </summary>
  1757. /// <param name="str">
  1758. /// If null or empty, then an bytes[0] is returned.
  1759. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1760. /// </param>
  1761. /// <param name="args">
  1762. /// Arguments to substitute into the string via the {} mechanism.
  1763. /// </param>
  1764. /// <returns></returns>
  1765. public static byte[] StringToBytes(string str, int MaxLength, params object[] args)
  1766. {
  1767. return StringToBytes1024(string.Format(str, args), MaxLength);
  1768. }
  1769. /// <summary>
  1770. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to MaxLength bytes if necessary.
  1771. /// </summary>
  1772. /// <param name="str">
  1773. /// If null or empty, then an bytes[0] is returned.
  1774. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1775. /// </param>
  1776. /// <returns></returns>
  1777. public static byte[] StringToBytes(string str, int MaxLength)
  1778. {
  1779. if (String.IsNullOrEmpty(str))
  1780. return Utils.EmptyBytes;
  1781. if (!str.EndsWith("\0"))
  1782. str += "\0";
  1783. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1784. // might have gotten an oversized array even after the string trim
  1785. byte[] data = UTF8.GetBytes(str);
  1786. if (data.Length > MaxLength)
  1787. {
  1788. int cut = MaxLength -1 ;
  1789. if((data[cut] & 0x80 ) != 0 )
  1790. {
  1791. while(cut > 0 && (data[cut] & 0xc0) != 0xc0)
  1792. cut--;
  1793. }
  1794. Array.Resize<byte>(ref data, cut + 1);
  1795. data[cut] = 0;
  1796. }
  1797. return data;
  1798. }
  1799. /// <summary>
  1800. /// Pretty format the hashtable contents to a single line.
  1801. /// </summary>
  1802. /// <remarks>
  1803. /// Used for debugging output.
  1804. /// </remarks>
  1805. /// <param name='ht'></param>
  1806. public static string PrettyFormatToSingleLine(Hashtable ht)
  1807. {
  1808. StringBuilder sb = new StringBuilder();
  1809. int i = 0;
  1810. foreach (string key in ht.Keys)
  1811. {
  1812. sb.AppendFormat("{0}:{1}", key, ht[key]);
  1813. if (++i < ht.Count)
  1814. sb.AppendFormat(", ");
  1815. }
  1816. return sb.ToString();
  1817. }
  1818. /// <summary>
  1819. /// Used to trigger an early library load on Windows systems.
  1820. /// </summary>
  1821. /// <remarks>
  1822. /// Required to get 32-bit and 64-bit processes to automatically use the
  1823. /// appropriate native library.
  1824. /// </remarks>
  1825. /// <param name="dllToLoad"></param>
  1826. /// <returns></returns>
  1827. [DllImport("kernel32.dll")]
  1828. public static extern IntPtr LoadLibrary(string dllToLoad);
  1829. /// <summary>
  1830. /// Determine whether the current process is 64 bit
  1831. /// </summary>
  1832. /// <returns>true if so, false if not</returns>
  1833. public static bool Is64BitProcess()
  1834. {
  1835. return IntPtr.Size == 8;
  1836. }
  1837. #region FireAndForget Threading Pattern
  1838. /// <summary>
  1839. /// Created to work around a limitation in Mono with nested delegates
  1840. /// </summary>
  1841. private sealed class FireAndForgetWrapper
  1842. {
  1843. private static volatile FireAndForgetWrapper instance;
  1844. private static object syncRoot = new Object();
  1845. public static FireAndForgetWrapper Instance {
  1846. get {
  1847. if (instance == null)
  1848. {
  1849. lock (syncRoot)
  1850. {
  1851. if (instance == null)
  1852. {
  1853. instance = new FireAndForgetWrapper();
  1854. }
  1855. }
  1856. }
  1857. return instance;
  1858. }
  1859. }
  1860. public void FireAndForget(System.Threading.WaitCallback callback)
  1861. {
  1862. callback.BeginInvoke(null, EndFireAndForget, callback);
  1863. }
  1864. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1865. {
  1866. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1867. }
  1868. private static void EndFireAndForget(IAsyncResult ar)
  1869. {
  1870. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1871. try { callback.EndInvoke(ar); }
  1872. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1873. ar.AsyncWaitHandle.Close();
  1874. }
  1875. }
  1876. public static void InitThreadPool(int minThreads, int maxThreads)
  1877. {
  1878. if (maxThreads < 2)
  1879. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1880. if (minThreads > maxThreads || minThreads < 2)
  1881. throw new ArgumentOutOfRangeException("minThreads", "minThreads must be greater than 2 and less than or equal to maxThreads");
  1882. if (m_ThreadPool != null)
  1883. {
  1884. m_log.Warn("SmartThreadPool is already initialized. Ignoring request.");
  1885. return;
  1886. }
  1887. STPStartInfo startInfo = new STPStartInfo();
  1888. startInfo.ThreadPoolName = "Util";
  1889. startInfo.IdleTimeout = 20000;
  1890. startInfo.MaxWorkerThreads = maxThreads;
  1891. startInfo.MinWorkerThreads = minThreads;
  1892. m_ThreadPool = new SmartThreadPool(startInfo);
  1893. m_threadPoolWatchdog = new Timer(ThreadPoolWatchdog, null, 0, 1000);
  1894. }
  1895. public static int FireAndForgetCount()
  1896. {
  1897. const int MAX_SYSTEM_THREADS = 200;
  1898. switch (FireAndForgetMethod)
  1899. {
  1900. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1901. case FireAndForgetMethod.QueueUserWorkItem:
  1902. case FireAndForgetMethod.BeginInvoke:
  1903. int workerThreads, iocpThreads;
  1904. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1905. return workerThreads;
  1906. case FireAndForgetMethod.SmartThreadPool:
  1907. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1908. case FireAndForgetMethod.Thread:
  1909. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1910. default:
  1911. throw new NotImplementedException();
  1912. }
  1913. }
  1914. /// <summary>
  1915. /// Additional information about threads in the main thread pool. Used to time how long the
  1916. /// thread has been running, and abort it if it has timed-out.
  1917. /// </summary>
  1918. private class ThreadInfo
  1919. {
  1920. public long ThreadFuncNum { get; set; }
  1921. public string StackTrace { get; set; }
  1922. private string context;
  1923. public bool LogThread { get; set; }
  1924. public IWorkItemResult WorkItem { get; set; }
  1925. public Thread Thread { get; set; }
  1926. public bool Running { get; set; }
  1927. public bool Aborted { get; set; }
  1928. private int started;
  1929. public ThreadInfo(long threadFuncNum, string context)
  1930. {
  1931. ThreadFuncNum = threadFuncNum;
  1932. this.context = context;
  1933. LogThread = false;
  1934. Thread = null;
  1935. Running = false;
  1936. Aborted = false;
  1937. }
  1938. public void Started()
  1939. {
  1940. Thread = Thread.CurrentThread;
  1941. started = EnvironmentTickCount();
  1942. Running = true;
  1943. }
  1944. public void Ended()
  1945. {
  1946. Running = false;
  1947. }
  1948. public int Elapsed()
  1949. {
  1950. return EnvironmentTickCountSubtract(started);
  1951. }
  1952. public void Abort()
  1953. {
  1954. Aborted = true;
  1955. WorkItem.Cancel(true);
  1956. }
  1957. /// <summary>
  1958. /// Returns the thread's stack trace.
  1959. /// </summary>
  1960. /// <remarks>
  1961. /// May return one of two stack traces. First, tries to get the thread's active stack
  1962. /// trace. But this can fail, so as a fallback this method will return the stack
  1963. /// trace that was active when the task was queued.
  1964. /// </remarks>
  1965. public string GetStackTrace()
  1966. {
  1967. string ret = (context == null) ? "" : ("(" + context + ") ");
  1968. StackTrace activeStackTrace = Util.GetStackTrace(Thread);
  1969. if (activeStackTrace != null)
  1970. ret += activeStackTrace.ToString();
  1971. else if (StackTrace != null)
  1972. ret += "(Stack trace when queued) " + StackTrace;
  1973. // else, no stack trace available
  1974. return ret;
  1975. }
  1976. }
  1977. private static long nextThreadFuncNum = 0;
  1978. private static long numQueuedThreadFuncs = 0;
  1979. private static long numRunningThreadFuncs = 0;
  1980. private static long numTotalThreadFuncsCalled = 0;
  1981. private static Int32 threadFuncOverloadMode = 0;
  1982. public static long TotalQueuedFireAndForgetCalls { get { return numQueuedThreadFuncs; } }
  1983. public static long TotalRunningFireAndForgetCalls { get { return numRunningThreadFuncs; } }
  1984. // Maps (ThreadFunc number -> Thread)
  1985. private static ConcurrentDictionary<long, ThreadInfo> activeThreads = new ConcurrentDictionary<long, ThreadInfo>();
  1986. private static readonly int THREAD_TIMEOUT = 10 * 60 * 1000; // 10 minutes
  1987. /// <summary>
  1988. /// Finds threads in the main thread pool that have timed-out, and aborts them.
  1989. /// </summary>
  1990. private static void ThreadPoolWatchdog(object state)
  1991. {
  1992. foreach (KeyValuePair<long, ThreadInfo> entry in activeThreads)
  1993. {
  1994. ThreadInfo t = entry.Value;
  1995. if (t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT))
  1996. {
  1997. m_log.WarnFormat("Timeout in threadfunc {0} ({1}) {2}", t.ThreadFuncNum, t.Thread.Name, t.GetStackTrace());
  1998. t.Abort();
  1999. ThreadInfo dummy;
  2000. activeThreads.TryRemove(entry.Key, out dummy);
  2001. // It's possible that the thread won't abort. To make sure the thread pool isn't
  2002. // depleted, increase the pool size.
  2003. m_ThreadPool.MaxThreads++;
  2004. }
  2005. }
  2006. }
  2007. public static long TotalFireAndForgetCallsMade { get { return numTotalThreadFuncsCalled; } }
  2008. public static Dictionary<string, int> GetFireAndForgetCallsMade()
  2009. {
  2010. return new Dictionary<string, int>(m_fireAndForgetCallsMade);
  2011. }
  2012. private static Dictionary<string, int> m_fireAndForgetCallsMade = new Dictionary<string, int>();
  2013. public static Dictionary<string, int> GetFireAndForgetCallsInProgress()
  2014. {
  2015. return new Dictionary<string, int>(m_fireAndForgetCallsInProgress);
  2016. }
  2017. private static Dictionary<string, int> m_fireAndForgetCallsInProgress = new Dictionary<string, int>();
  2018. public static void FireAndForget(System.Threading.WaitCallback callback)
  2019. {
  2020. FireAndForget(callback, null, null);
  2021. }
  2022. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  2023. {
  2024. FireAndForget(callback, obj, null);
  2025. }
  2026. public static void FireAndForget(System.Threading.WaitCallback callback, object obj, string context)
  2027. {
  2028. Interlocked.Increment(ref numTotalThreadFuncsCalled);
  2029. if (context != null)
  2030. {
  2031. if (!m_fireAndForgetCallsMade.ContainsKey(context))
  2032. m_fireAndForgetCallsMade[context] = 1;
  2033. else
  2034. m_fireAndForgetCallsMade[context]++;
  2035. if (!m_fireAndForgetCallsInProgress.ContainsKey(context))
  2036. m_fireAndForgetCallsInProgress[context] = 1;
  2037. else
  2038. m_fireAndForgetCallsInProgress[context]++;
  2039. }
  2040. WaitCallback realCallback;
  2041. bool loggingEnabled = LogThreadPool > 0;
  2042. long threadFuncNum = Interlocked.Increment(ref nextThreadFuncNum);
  2043. ThreadInfo threadInfo = new ThreadInfo(threadFuncNum, context);
  2044. if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
  2045. {
  2046. // If we're running regression tests, then we want any exceptions to rise up to the test code.
  2047. realCallback =
  2048. o =>
  2049. {
  2050. Culture.SetCurrentCulture();
  2051. callback(o);
  2052. if (context != null)
  2053. m_fireAndForgetCallsInProgress[context]--;
  2054. };
  2055. }
  2056. else
  2057. {
  2058. // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
  2059. // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
  2060. // for decimals places but is read by a culture that treats commas as number seperators.
  2061. realCallback = o =>
  2062. {
  2063. long numQueued1 = Interlocked.Decrement(ref numQueuedThreadFuncs);
  2064. long numRunning1 = Interlocked.Increment(ref numRunningThreadFuncs);
  2065. threadInfo.Started();
  2066. activeThreads[threadFuncNum] = threadInfo;
  2067. try
  2068. {
  2069. if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread)
  2070. m_log.DebugFormat("Run threadfunc {0} (Queued {1}, Running {2})", threadFuncNum, numQueued1, numRunning1);
  2071. Culture.SetCurrentCulture();
  2072. callback(o);
  2073. }
  2074. catch (ThreadAbortException e)
  2075. {
  2076. m_log.Error(string.Format("Aborted threadfunc {0} ", threadFuncNum), e);
  2077. }
  2078. catch (Exception e)
  2079. {
  2080. m_log.Error(string.Format("[UTIL]: Util STP threadfunc {0} terminated with error ", threadFuncNum), e);
  2081. }
  2082. finally
  2083. {
  2084. Interlocked.Decrement(ref numRunningThreadFuncs);
  2085. threadInfo.Ended();
  2086. ThreadInfo dummy;
  2087. activeThreads.TryRemove(threadFuncNum, out dummy);
  2088. if ((loggingEnabled || (threadFuncOverloadMode == 1)) && threadInfo.LogThread)
  2089. m_log.DebugFormat("Exit threadfunc {0} ({1})", threadFuncNum, FormatDuration(threadInfo.Elapsed()));
  2090. if (context != null)
  2091. m_fireAndForgetCallsInProgress[context]--;
  2092. }
  2093. };
  2094. }
  2095. long numQueued = Interlocked.Increment(ref numQueuedThreadFuncs);
  2096. try
  2097. {
  2098. long numRunning = numRunningThreadFuncs;
  2099. if (m_ThreadPool != null && LogOverloads)
  2100. {
  2101. if ((threadFuncOverloadMode == 0) && (numRunning >= m_ThreadPool.MaxThreads))
  2102. {
  2103. if (Interlocked.CompareExchange(ref threadFuncOverloadMode, 1, 0) == 0)
  2104. m_log.DebugFormat("Threadfunc: enable overload mode (Queued {0}, Running {1})", numQueued, numRunning);
  2105. }
  2106. else if ((threadFuncOverloadMode == 1) && (numRunning <= (m_ThreadPool.MaxThreads * 2) / 3))
  2107. {
  2108. if (Interlocked.CompareExchange(ref threadFuncOverloadMode, 0, 1) == 1)
  2109. m_log.DebugFormat("Threadfunc: disable overload mode (Queued {0}, Running {1})", numQueued, numRunning);
  2110. }
  2111. }
  2112. if (loggingEnabled || (threadFuncOverloadMode == 1))
  2113. {
  2114. string full, partial;
  2115. GetFireAndForgetStackTrace(out full, out partial);
  2116. threadInfo.StackTrace = full;
  2117. threadInfo.LogThread = ShouldLogThread(partial);
  2118. if (threadInfo.LogThread)
  2119. {
  2120. m_log.DebugFormat("Queue threadfunc {0} (Queued {1}, Running {2}) {3}{4}",
  2121. threadFuncNum, numQueued, numRunningThreadFuncs,
  2122. (context == null) ? "" : ("(" + context + ") "),
  2123. (LogThreadPool >= 2) ? full : partial);
  2124. }
  2125. }
  2126. else
  2127. {
  2128. // Since we didn't log "Queue threadfunc", don't log "Run threadfunc" or "End threadfunc" either.
  2129. // Those log lines aren't useful when we don't know which function is running in the thread.
  2130. threadInfo.LogThread = false;
  2131. }
  2132. switch (FireAndForgetMethod)
  2133. {
  2134. case FireAndForgetMethod.RegressionTest:
  2135. case FireAndForgetMethod.None:
  2136. realCallback.Invoke(obj);
  2137. break;
  2138. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  2139. ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
  2140. break;
  2141. case FireAndForgetMethod.QueueUserWorkItem:
  2142. ThreadPool.QueueUserWorkItem(realCallback, obj);
  2143. break;
  2144. case FireAndForgetMethod.BeginInvoke:
  2145. FireAndForgetWrapper wrapper = FireAndForgetWrapper.Instance;
  2146. wrapper.FireAndForget(realCallback, obj);
  2147. break;
  2148. case FireAndForgetMethod.SmartThreadPool:
  2149. if (m_ThreadPool == null)
  2150. InitThreadPool(2, 15);
  2151. threadInfo.WorkItem = m_ThreadPool.QueueWorkItem((cb, o) => cb(o), realCallback, obj);
  2152. break;
  2153. case FireAndForgetMethod.Thread:
  2154. Thread thread = new Thread(delegate(object o) { realCallback(o); });
  2155. thread.Start(obj);
  2156. break;
  2157. default:
  2158. throw new NotImplementedException();
  2159. }
  2160. }
  2161. catch (Exception)
  2162. {
  2163. Interlocked.Decrement(ref numQueuedThreadFuncs);
  2164. ThreadInfo dummy;
  2165. activeThreads.TryRemove(threadFuncNum, out dummy);
  2166. throw;
  2167. }
  2168. }
  2169. /// <summary>
  2170. /// Returns whether the thread should be logged. Some very common threads aren't logged,
  2171. /// to avoid filling up the log.
  2172. /// </summary>
  2173. /// <param name="stackTrace">A partial stack trace of where the thread was queued</param>
  2174. /// <returns>Whether to log this thread</returns>
  2175. private static bool ShouldLogThread(string stackTrace)
  2176. {
  2177. if (LogThreadPool < 3)
  2178. {
  2179. if (stackTrace.Contains("BeginFireQueueEmpty"))
  2180. return false;
  2181. }
  2182. return true;
  2183. }
  2184. /// <summary>
  2185. /// Returns a stack trace for a thread added using FireAndForget().
  2186. /// </summary>
  2187. /// <param name="full">Will contain the full stack trace</param>
  2188. /// <param name="partial">Will contain only the first frame of the stack trace</param>
  2189. private static void GetFireAndForgetStackTrace(out string full, out string partial)
  2190. {
  2191. string src = Environment.StackTrace;
  2192. string[] lines = src.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
  2193. StringBuilder dest = new StringBuilder(src.Length);
  2194. bool started = false;
  2195. bool first = true;
  2196. partial = "";
  2197. for (int i = 0; i < lines.Length; i++)
  2198. {
  2199. string line = lines[i];
  2200. if (!started)
  2201. {
  2202. // Skip the initial stack frames, because they're of no interest for debugging
  2203. if (line.Contains("StackTrace") || line.Contains("FireAndForget"))
  2204. continue;
  2205. started = true;
  2206. }
  2207. if (first)
  2208. {
  2209. line = line.TrimStart();
  2210. first = false;
  2211. partial = line;
  2212. }
  2213. bool last = (i == lines.Length - 1);
  2214. if (last)
  2215. dest.Append(line);
  2216. else
  2217. dest.AppendLine(line);
  2218. }
  2219. full = dest.ToString();
  2220. }
  2221. #pragma warning disable 0618
  2222. /// <summary>
  2223. /// Return the stack trace of a different thread.
  2224. /// </summary>
  2225. /// <remarks>
  2226. /// This is complicated because the thread needs to be paused in order to get its stack
  2227. /// trace. And pausing another thread can cause a deadlock. This method attempts to
  2228. /// avoid deadlock by using a short timeout (200ms), after which it gives up and
  2229. /// returns 'null' instead of the stack trace.
  2230. ///
  2231. /// Take from: http://stackoverflow.com/a/14935378
  2232. ///
  2233. /// WARNING: this doesn't work in Mono. See https://bugzilla.novell.com/show_bug.cgi?id=571691
  2234. ///
  2235. /// </remarks>
  2236. /// <returns>The stack trace, or null if failed to get it</returns>
  2237. private static StackTrace GetStackTrace(Thread targetThread)
  2238. {
  2239. if (IsPlatformMono)
  2240. {
  2241. // This doesn't work in Mono
  2242. return null;
  2243. }
  2244. ManualResetEventSlim fallbackThreadReady = new ManualResetEventSlim();
  2245. ManualResetEventSlim exitedSafely = new ManualResetEventSlim();
  2246. try
  2247. {
  2248. new Thread(delegate()
  2249. {
  2250. fallbackThreadReady.Set();
  2251. while (!exitedSafely.Wait(200))
  2252. {
  2253. try
  2254. {
  2255. targetThread.Resume();
  2256. }
  2257. catch (Exception)
  2258. {
  2259. // Whatever happens, do never stop to resume the main-thread regularly until the main-thread has exited safely.
  2260. }
  2261. }
  2262. }).Start();
  2263. fallbackThreadReady.Wait();
  2264. // From here, you have about 200ms to get the stack-trace
  2265. targetThread.Suspend();
  2266. StackTrace trace = null;
  2267. try
  2268. {
  2269. trace = new StackTrace(targetThread, true);
  2270. }
  2271. catch (ThreadStateException)
  2272. {
  2273. //failed to get stack trace, since the fallback-thread resumed the thread
  2274. //possible reasons:
  2275. //1.) This thread was just too slow
  2276. //2.) A deadlock ocurred
  2277. //Automatic retry seems too risky here, so just return null.
  2278. }
  2279. try
  2280. {
  2281. targetThread.Resume();
  2282. }
  2283. catch (ThreadStateException)
  2284. {
  2285. // Thread is running again already
  2286. }
  2287. return trace;
  2288. }
  2289. finally
  2290. {
  2291. // Signal the fallack-thread to stop
  2292. exitedSafely.Set();
  2293. }
  2294. }
  2295. #pragma warning restore 0618
  2296. /// <summary>
  2297. /// Get information about the current state of the smart thread pool.
  2298. /// </summary>
  2299. /// <returns>
  2300. /// null if this isn't the pool being used for non-scriptengine threads.
  2301. /// </returns>
  2302. public static STPInfo GetSmartThreadPoolInfo()
  2303. {
  2304. if (m_ThreadPool == null)
  2305. return null;
  2306. STPInfo stpi = new STPInfo();
  2307. stpi.Name = m_ThreadPool.Name;
  2308. stpi.STPStartInfo = m_ThreadPool.STPStartInfo;
  2309. stpi.IsIdle = m_ThreadPool.IsIdle;
  2310. stpi.IsShuttingDown = m_ThreadPool.IsShuttingdown;
  2311. stpi.MaxThreads = m_ThreadPool.MaxThreads;
  2312. stpi.MinThreads = m_ThreadPool.MinThreads;
  2313. stpi.InUseThreads = m_ThreadPool.InUseThreads;
  2314. stpi.ActiveThreads = m_ThreadPool.ActiveThreads;
  2315. stpi.WaitingCallbacks = m_ThreadPool.WaitingCallbacks;
  2316. stpi.MaxConcurrentWorkItems = m_ThreadPool.Concurrency;
  2317. return stpi;
  2318. }
  2319. #endregion FireAndForget Threading Pattern
  2320. /// <summary>
  2321. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  2322. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  2323. /// for the callers.
  2324. /// This trims it to a 12 day interval so don't let your frame time get too long.
  2325. /// </summary>
  2326. /// <returns></returns>
  2327. public static Int32 EnvironmentTickCount()
  2328. {
  2329. return Environment.TickCount & EnvironmentTickCountMask;
  2330. }
  2331. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  2332. /// <summary>
  2333. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  2334. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  2335. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  2336. /// </summary>
  2337. /// <param name="newValue"></param>
  2338. /// <param name="prevValue"></param>
  2339. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  2340. public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  2341. {
  2342. Int32 diff = newValue - prevValue;
  2343. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  2344. }
  2345. /// <summary>
  2346. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  2347. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  2348. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  2349. /// </summary>
  2350. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  2351. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  2352. {
  2353. return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
  2354. }
  2355. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  2356. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  2357. // A positive return value indicates A occured later than B
  2358. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  2359. {
  2360. // A, B and TC are all between 0 and 0x3fffffff
  2361. int tc = EnvironmentTickCount();
  2362. if (tc - tcA >= 0)
  2363. tcA += EnvironmentTickCountMask + 1;
  2364. if (tc - tcB >= 0)
  2365. tcB += EnvironmentTickCountMask + 1;
  2366. return tcA - tcB;
  2367. }
  2368. // returns a timestamp in ms as double
  2369. // using the time resolution avaiable to StopWatch
  2370. public static double GetTimeStampMS()
  2371. {
  2372. return (double)Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
  2373. }
  2374. /// <summary>
  2375. /// Formats a duration (given in milliseconds).
  2376. /// </summary>
  2377. public static string FormatDuration(int ms)
  2378. {
  2379. TimeSpan span = new TimeSpan(ms * TimeSpan.TicksPerMillisecond);
  2380. string str = "";
  2381. string suffix = null;
  2382. int hours = (int)span.TotalHours;
  2383. if (hours > 0)
  2384. {
  2385. str += hours.ToString(str.Length == 0 ? "0" : "00");
  2386. suffix = "hours";
  2387. }
  2388. if ((hours > 0) || (span.Minutes > 0))
  2389. {
  2390. if (str.Length > 0)
  2391. str += ":";
  2392. str += span.Minutes.ToString(str.Length == 0 ? "0" : "00");
  2393. if (suffix == null)
  2394. suffix = "min";
  2395. }
  2396. if ((hours > 0) || (span.Minutes > 0) || (span.Seconds > 0))
  2397. {
  2398. if (str.Length > 0)
  2399. str += ":";
  2400. str += span.Seconds.ToString(str.Length == 0 ? "0" : "00");
  2401. if (suffix == null)
  2402. suffix = "sec";
  2403. }
  2404. if (suffix == null)
  2405. suffix = "ms";
  2406. if (span.TotalMinutes < 1)
  2407. {
  2408. int ms1 = span.Milliseconds;
  2409. if (str.Length > 0)
  2410. {
  2411. ms1 /= 100;
  2412. str += ".";
  2413. }
  2414. str += ms1.ToString("0");
  2415. }
  2416. str += " " + suffix;
  2417. return str;
  2418. }
  2419. /// <summary>
  2420. /// Prints the call stack at any given point. Useful for debugging.
  2421. /// </summary>
  2422. public static void PrintCallStack()
  2423. {
  2424. PrintCallStack(m_log.DebugFormat);
  2425. }
  2426. public delegate void DebugPrinter(string msg, params Object[] parm);
  2427. public static void PrintCallStack(DebugPrinter printer)
  2428. {
  2429. StackTrace stackTrace = new StackTrace(true); // get call stack
  2430. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  2431. // write call stack method names
  2432. foreach (StackFrame stackFrame in stackFrames)
  2433. {
  2434. MethodBase mb = stackFrame.GetMethod();
  2435. printer("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
  2436. }
  2437. }
  2438. /// <summary>
  2439. /// Gets the client IP address
  2440. /// </summary>
  2441. /// <param name="xff"></param>
  2442. /// <returns></returns>
  2443. public static IPEndPoint GetClientIPFromXFF(string xff)
  2444. {
  2445. if (xff == string.Empty)
  2446. return null;
  2447. string[] parts = xff.Split(new char[] { ',' });
  2448. if (parts.Length > 0)
  2449. {
  2450. try
  2451. {
  2452. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  2453. }
  2454. catch (Exception e)
  2455. {
  2456. m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
  2457. }
  2458. }
  2459. return null;
  2460. }
  2461. public static string GetCallerIP(Hashtable req)
  2462. {
  2463. if (req.ContainsKey("headers"))
  2464. {
  2465. try
  2466. {
  2467. Hashtable headers = (Hashtable)req["headers"];
  2468. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  2469. return headers["remote_addr"].ToString();
  2470. }
  2471. catch (Exception e)
  2472. {
  2473. m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
  2474. }
  2475. }
  2476. return string.Empty;
  2477. }
  2478. #region Xml Serialization Utilities
  2479. public static bool ReadBoolean(XmlReader reader)
  2480. {
  2481. // AuroraSim uses "int" for some fields that are boolean in OpenSim, e.g. "PassCollisions". Don't fail because of this.
  2482. reader.ReadStartElement();
  2483. string val = reader.ReadContentAsString().ToLower();
  2484. bool result = val.Equals("true") || val.Equals("1");
  2485. reader.ReadEndElement();
  2486. return result;
  2487. }
  2488. public static UUID ReadUUID(XmlReader reader, string name)
  2489. {
  2490. UUID id;
  2491. string idStr;
  2492. reader.ReadStartElement(name);
  2493. if (reader.Name == "Guid")
  2494. idStr = reader.ReadElementString("Guid");
  2495. else if (reader.Name == "UUID")
  2496. idStr = reader.ReadElementString("UUID");
  2497. else // no leading tag
  2498. idStr = reader.ReadContentAsString();
  2499. UUID.TryParse(idStr, out id);
  2500. reader.ReadEndElement();
  2501. return id;
  2502. }
  2503. public static Vector3 ReadVector(XmlReader reader, string name)
  2504. {
  2505. Vector3 vec;
  2506. reader.ReadStartElement(name);
  2507. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  2508. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  2509. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  2510. reader.ReadEndElement();
  2511. return vec;
  2512. }
  2513. public static Quaternion ReadQuaternion(XmlReader reader, string name)
  2514. {
  2515. Quaternion quat = new Quaternion();
  2516. reader.ReadStartElement(name);
  2517. while (reader.NodeType != XmlNodeType.EndElement)
  2518. {
  2519. switch (reader.Name.ToLower())
  2520. {
  2521. case "x":
  2522. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  2523. break;
  2524. case "y":
  2525. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  2526. break;
  2527. case "z":
  2528. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  2529. break;
  2530. case "w":
  2531. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  2532. break;
  2533. }
  2534. }
  2535. reader.ReadEndElement();
  2536. return quat;
  2537. }
  2538. public static T ReadEnum<T>(XmlReader reader, string name)
  2539. {
  2540. string value = reader.ReadElementContentAsString(name, String.Empty);
  2541. // !!!!! to deal with flags without commas
  2542. if (value.Contains(" ") && !value.Contains(","))
  2543. value = value.Replace(" ", ", ");
  2544. return (T)Enum.Parse(typeof(T), value); ;
  2545. }
  2546. #endregion
  2547. #region Universal User Identifiers
  2548. /// <summary>
  2549. /// Attempts to parse a UUI into its components: UUID, name and URL.
  2550. /// </summary>
  2551. /// <param name="value">uuid[;endpoint[;first last[;secret]]]</param>
  2552. /// <param name="uuid">the uuid part</param>
  2553. /// <param name="url">the endpoint part (e.g. http://foo.com)</param>
  2554. /// <param name="firstname">the first name part (e.g. Test)</param>
  2555. /// <param name="lastname">the last name part (e.g User)</param>
  2556. /// <param name="secret">the secret part</param>
  2557. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  2558. {
  2559. uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "UserUPUUI"; secret = string.Empty;
  2560. string[] parts = value.Split(';');
  2561. if (parts.Length >= 1)
  2562. if (!UUID.TryParse(parts[0], out uuid))
  2563. return false;
  2564. if (parts.Length >= 2)
  2565. url = parts[1];
  2566. if (parts.Length >= 3)
  2567. {
  2568. string[] name = parts[2].Split();
  2569. if (name.Length == 2)
  2570. {
  2571. firstname = name[0];
  2572. lastname = name[1];
  2573. }
  2574. }
  2575. if (parts.Length >= 4)
  2576. secret = parts[3];
  2577. return true;
  2578. }
  2579. /// <summary>
  2580. /// For foreign avatars, extracts their original name and Server URL from their First Name and Last Name.
  2581. /// </summary>
  2582. public static bool ParseForeignAvatarName(string firstname, string lastname,
  2583. out string realFirstName, out string realLastName, out string serverURI)
  2584. {
  2585. realFirstName = realLastName = serverURI = string.Empty;
  2586. if (!lastname.Contains("@"))
  2587. return false;
  2588. if (!firstname.Contains("."))
  2589. return false;
  2590. realFirstName = firstname.Split('.')[0];
  2591. realLastName = firstname.Split('.')[1];
  2592. serverURI = new Uri("http://" + lastname.Replace("@", "")).ToString();
  2593. return true;
  2594. }
  2595. /// <summary>
  2596. /// Produces a universal (HG) system-facing identifier given the information
  2597. /// </summary>
  2598. /// <param name="acircuit"></param>
  2599. /// <returns>uuid[;homeURI[;first last]]</returns>
  2600. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  2601. {
  2602. if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
  2603. return UniversalIdentifier(acircuit.AgentID, acircuit.firstname, acircuit.lastname, acircuit.ServiceURLs["HomeURI"].ToString());
  2604. else
  2605. return acircuit.AgentID.ToString();
  2606. }
  2607. /// <summary>
  2608. /// Produces a universal (HG) system-facing identifier given the information
  2609. /// </summary>
  2610. /// <param name="id">UUID of the user</param>
  2611. /// <param name="firstName">first name (e.g Test)</param>
  2612. /// <param name="lastName">last name (e.g. User)</param>
  2613. /// <param name="homeURI">homeURI (e.g. http://foo.com)</param>
  2614. /// <returns>a string of the form uuid[;homeURI[;first last]]</returns>
  2615. public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
  2616. {
  2617. string agentsURI = homeURI;
  2618. if (!agentsURI.EndsWith("/"))
  2619. agentsURI += "/";
  2620. // This is ugly, but there's no other way, given that the name is changed
  2621. // in the agent circuit data for foreigners
  2622. if (lastName.Contains("@"))
  2623. {
  2624. string[] parts = firstName.Split(new char[] { '.' });
  2625. if (parts.Length == 2)
  2626. return CalcUniversalIdentifier(id, agentsURI, parts[0] + " " + parts[1]);
  2627. }
  2628. return CalcUniversalIdentifier(id, agentsURI, firstName + " " + lastName);
  2629. }
  2630. private static string CalcUniversalIdentifier(UUID id, string agentsURI, string name)
  2631. {
  2632. return id.ToString() + ";" + agentsURI + ";" + name;
  2633. }
  2634. /// <summary>
  2635. /// Produces a universal (HG) user-facing name given the information
  2636. /// </summary>
  2637. /// <param name="firstName"></param>
  2638. /// <param name="lastName"></param>
  2639. /// <param name="homeURI"></param>
  2640. /// <returns>string of the form first.last @foo.com or first last</returns>
  2641. public static string UniversalName(String firstName, String lastName, String homeURI)
  2642. {
  2643. Uri uri = null;
  2644. try
  2645. {
  2646. uri = new Uri(homeURI);
  2647. }
  2648. catch (UriFormatException)
  2649. {
  2650. return firstName + " " + lastName;
  2651. }
  2652. return firstName + "." + lastName + " " + "@" + uri.Authority;
  2653. }
  2654. #endregion
  2655. /// <summary>
  2656. /// Escapes the special characters used in "LIKE".
  2657. /// </summary>
  2658. /// <remarks>
  2659. /// For example: EscapeForLike("foo_bar%baz") = "foo\_bar\%baz"
  2660. /// </remarks>
  2661. public static string EscapeForLike(string str)
  2662. {
  2663. return str.Replace("_", "\\_").Replace("%", "\\%");
  2664. }
  2665. /// <summary>
  2666. /// Returns the name of the user's viewer.
  2667. /// </summary>
  2668. /// <remarks>
  2669. /// This method handles two ways that viewers specify their name:
  2670. /// 1. Viewer = "Firestorm-Release 4.4.2.34167", Channel = "(don't care)" -> "Firestorm-Release 4.4.2.34167"
  2671. /// 2. Viewer = "4.5.1.38838", Channel = "Firestorm-Beta" -> "Firestorm-Beta 4.5.1.38838"
  2672. /// </remarks>
  2673. public static string GetViewerName(AgentCircuitData agent)
  2674. {
  2675. string name = agent.Viewer;
  2676. if (name == null)
  2677. name = "";
  2678. else
  2679. name = name.Trim();
  2680. // Check if 'Viewer' is just a version number. If it's *not*, then we
  2681. // assume that it contains the real viewer name, and we return it.
  2682. foreach (char c in name)
  2683. {
  2684. if (Char.IsLetter(c))
  2685. return name;
  2686. }
  2687. // The 'Viewer' string contains just a version number. If there's anything in
  2688. // 'Channel' then assume that it's the viewer name.
  2689. if ((agent.Channel != null) && (agent.Channel.Length > 0))
  2690. name = agent.Channel.Trim() + " " + name;
  2691. return name;
  2692. }
  2693. public static void LogFailedXML(string message, string xml)
  2694. {
  2695. int length = xml.Length;
  2696. if (length > 2000)
  2697. xml = xml.Substring(0, 2000) + "...";
  2698. m_log.ErrorFormat("{0} Failed XML ({1} bytes) = {2}", message, length, xml);
  2699. }
  2700. }
  2701. public class DoubleQueue<T> where T:class
  2702. {
  2703. private Queue<T> m_lowQueue = new Queue<T>();
  2704. private Queue<T> m_highQueue = new Queue<T>();
  2705. private object m_syncRoot = new object();
  2706. private Semaphore m_s = new Semaphore(0, 1);
  2707. public DoubleQueue()
  2708. {
  2709. }
  2710. public virtual int Count
  2711. {
  2712. get
  2713. {
  2714. lock (m_syncRoot)
  2715. return m_highQueue.Count + m_lowQueue.Count;
  2716. }
  2717. }
  2718. public virtual void Enqueue(T data)
  2719. {
  2720. Enqueue(m_lowQueue, data);
  2721. }
  2722. public virtual void EnqueueLow(T data)
  2723. {
  2724. Enqueue(m_lowQueue, data);
  2725. }
  2726. public virtual void EnqueueHigh(T data)
  2727. {
  2728. Enqueue(m_highQueue, data);
  2729. }
  2730. private void Enqueue(Queue<T> q, T data)
  2731. {
  2732. lock (m_syncRoot)
  2733. {
  2734. q.Enqueue(data);
  2735. m_s.WaitOne(0);
  2736. m_s.Release();
  2737. }
  2738. }
  2739. public virtual T Dequeue()
  2740. {
  2741. return Dequeue(Timeout.Infinite);
  2742. }
  2743. public virtual T Dequeue(int tmo)
  2744. {
  2745. return Dequeue(TimeSpan.FromMilliseconds(tmo));
  2746. }
  2747. public virtual T Dequeue(TimeSpan wait)
  2748. {
  2749. T res = null;
  2750. if (!Dequeue(wait, ref res))
  2751. return null;
  2752. return res;
  2753. }
  2754. public bool Dequeue(int timeout, ref T res)
  2755. {
  2756. return Dequeue(TimeSpan.FromMilliseconds(timeout), ref res);
  2757. }
  2758. public bool Dequeue(TimeSpan wait, ref T res)
  2759. {
  2760. if (!m_s.WaitOne(wait))
  2761. return false;
  2762. lock (m_syncRoot)
  2763. {
  2764. if (m_highQueue.Count > 0)
  2765. res = m_highQueue.Dequeue();
  2766. else if (m_lowQueue.Count > 0)
  2767. res = m_lowQueue.Dequeue();
  2768. if (m_highQueue.Count == 0 && m_lowQueue.Count == 0)
  2769. return true;
  2770. try
  2771. {
  2772. m_s.Release();
  2773. }
  2774. catch
  2775. {
  2776. }
  2777. return true;
  2778. }
  2779. }
  2780. public virtual void Clear()
  2781. {
  2782. lock (m_syncRoot)
  2783. {
  2784. // Make sure sem count is 0
  2785. m_s.WaitOne(0);
  2786. m_lowQueue.Clear();
  2787. m_highQueue.Clear();
  2788. }
  2789. }
  2790. }
  2791. public class BetterRandom
  2792. {
  2793. private const int BufferSize = 1024; // must be a multiple of 4
  2794. private byte[] RandomBuffer;
  2795. private int BufferOffset;
  2796. private RNGCryptoServiceProvider rng;
  2797. public BetterRandom()
  2798. {
  2799. RandomBuffer = new byte[BufferSize];
  2800. rng = new RNGCryptoServiceProvider();
  2801. BufferOffset = RandomBuffer.Length;
  2802. }
  2803. private void FillBuffer()
  2804. {
  2805. rng.GetBytes(RandomBuffer);
  2806. BufferOffset = 0;
  2807. }
  2808. public int Next()
  2809. {
  2810. if (BufferOffset >= RandomBuffer.Length)
  2811. {
  2812. FillBuffer();
  2813. }
  2814. int val = BitConverter.ToInt32(RandomBuffer, BufferOffset) & 0x7fffffff;
  2815. BufferOffset += sizeof(int);
  2816. return val;
  2817. }
  2818. public int Next(int maxValue)
  2819. {
  2820. return Next() % maxValue;
  2821. }
  2822. public int Next(int minValue, int maxValue)
  2823. {
  2824. if (maxValue < minValue)
  2825. {
  2826. throw new ArgumentOutOfRangeException("maxValue must be greater than or equal to minValue");
  2827. }
  2828. int range = maxValue - minValue;
  2829. return minValue + Next(range);
  2830. }
  2831. public double NextDouble()
  2832. {
  2833. int val = Next();
  2834. return (double)val / int.MaxValue;
  2835. }
  2836. public void GetBytes(byte[] buff)
  2837. {
  2838. rng.GetBytes(buff);
  2839. }
  2840. }
  2841. }