Util.cs 138 KB

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