Util.cs 143 KB

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