Util.cs 143 KB

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