1
0

Util.cs 167 KB

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