Util.cs 139 KB

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