1
0

Util.cs 165 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705
  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. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1303. public static void CreateOrUpdateSelfsignedCert(string certFileName, string certHostName, string certHostIp, string certPassword)
  1304. {
  1305. CreateOrUpdateSelfsignedCertificate(certFileName, certHostName, certHostIp, certPassword);
  1306. }
  1307. /// <summary>
  1308. /// Create or renew an SSL selfsigned certificate using the parameters set in the startup section of OpenSim.ini
  1309. /// </summary>
  1310. /// <param name="certFileName">The certificate file name.</param>
  1311. /// <param name="certHostName">The certificate host DNS name (CN).</param>
  1312. /// <param name="certHostIp">The certificate host IP address.</param>
  1313. /// <param name="certPassword">The certificate password.</param>
  1314. private static void CreateOrUpdateSelfsignedCertificate(string certFileName, string certHostName, string certHostIp, string certPassword)
  1315. {
  1316. SubjectAlternativeNameBuilder san = new();
  1317. san.AddDnsName(certHostName);
  1318. san.AddIpAddress(IPAddress.Parse(certHostIp));
  1319. // What OpenSim check (CN).
  1320. X500DistinguishedName dn = new($"CN={certHostName}");
  1321. using (RSA rsa = RSA.Create(2048))
  1322. {
  1323. CertificateRequest request = new(dn, rsa, HashAlgorithmName.SHA256,RSASignaturePadding.Pkcs1);
  1324. // (Optional)...
  1325. request.CertificateExtensions.Add(
  1326. new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature , false));
  1327. // (Optional) SSL Server Authentication...
  1328. request.CertificateExtensions.Add(
  1329. new X509EnhancedKeyUsageExtension(
  1330. new OidCollection { 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("SSL\\src\\"))
  1336. Directory.CreateDirectory("SSL\\src\\");
  1337. if (!Directory.Exists("SSL\\ssl\\"))
  1338. Directory.CreateDirectory("SSL\\ssl\\");
  1339. // Store the RSA key in SSL\src\
  1340. File.WriteAllText($"SSL\\src\\{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. byte[] pfxCertBytes = string.IsNullOrEmpty(certPassword)
  1344. ? certificate.Export(X509ContentType.Pfx)
  1345. : certificate.Export(X509ContentType.Pfx, certPassword);
  1346. File.WriteAllBytes($"SSL\\ssl\\{certFileName}.pfx", pfxCertBytes);
  1347. byte[] p12CertBytes = string.IsNullOrEmpty(certPassword)
  1348. ? certificate.Export(X509ContentType.Pkcs12)
  1349. : certificate.Export(X509ContentType.Pkcs12, certPassword);
  1350. File.WriteAllBytes($"SSL\\ssl\\{certFileName}.p12", p12CertBytes);
  1351. }
  1352. }
  1353. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1354. public static void ConvertPemToPKCS12(string certFileName, string fullChainPath, string privateKeyPath)
  1355. {
  1356. ConvertPemToPKCS12Certificate(certFileName, fullChainPath, privateKeyPath, null);
  1357. }
  1358. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1359. public static void ConvertPemToPKCS12(string certFileName, string fullChainPath, string privateKeyPath, string outputPassword)
  1360. {
  1361. ConvertPemToPKCS12Certificate(certFileName, fullChainPath, privateKeyPath, outputPassword);
  1362. }
  1363. /// <summary>
  1364. /// Convert or renew .pem certificate to PKCS12 .pfx and .p12 usable by OpenSim.
  1365. /// the parameters are set in the startup section of OpenSim.ini
  1366. /// </summary>
  1367. /// <param name="certFileName">The output certificate file name.</param>
  1368. /// <param name="certPath">The path of fullchain.pem. If your CA don't provide
  1369. /// the fullchain file, you can set the cert.pem instead.</param>
  1370. /// <param name="keyPath">The path of the private key (privkey.pem).</param>
  1371. /// <param name="outputPassword">The output certificates password.</param>
  1372. private static void ConvertPemToPKCS12Certificate(string certFileName, string certPath, string keyPath, string outputPassword)
  1373. {
  1374. if(string.IsNullOrEmpty(certPath) || string.IsNullOrEmpty(keyPath)){
  1375. m_log.Error($"[UTIL PemToPKCS12]: Missing fullchain.pem or privkey.pem path!.");
  1376. return;
  1377. }
  1378. // Convert .pem (like Let's Encrypt files) to X509Certificate2 certificate.
  1379. X509Certificate2 certificate;
  1380. try
  1381. {
  1382. certificate = X509Certificate2.CreateFromPemFile(certPath, keyPath);
  1383. }
  1384. catch(CryptographicException e)
  1385. {
  1386. m_log.Error($"[UTIL PemToPKCS12]: {e.Message}" );
  1387. return;
  1388. }
  1389. // Create the SSL folder and ssl sub folder if not exists.
  1390. if (!Directory.Exists("SSL\\ssl\\"))
  1391. Directory.CreateDirectory("SSL\\ssl\\");
  1392. // Export and store the .pfx and .p12 certificates in SSL\ssl\.
  1393. byte[] pfxCertBytes = string.IsNullOrEmpty(outputPassword)
  1394. ? certificate.Export(X509ContentType.Pfx)
  1395. : certificate.Export(X509ContentType.Pfx, outputPassword);
  1396. File.WriteAllBytes($"SSL\\ssl\\{certFileName}.pfx", pfxCertBytes);
  1397. byte[] p12CertBytes = string.IsNullOrEmpty(outputPassword)
  1398. ? certificate.Export(X509ContentType.Pkcs12)
  1399. : certificate.Export(X509ContentType.Pkcs12, outputPassword);
  1400. File.WriteAllBytes($"SSL\\ssl\\{certFileName}.p12", p12CertBytes);
  1401. }
  1402. public static int fast_distance2d(int x, int y)
  1403. {
  1404. x = Math.Abs(x);
  1405. y = Math.Abs(y);
  1406. int min = Math.Min(x, y);
  1407. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  1408. }
  1409. /// <summary>
  1410. /// Determines whether a point is inside a bounding box.
  1411. /// </summary>
  1412. /// <param name='v'></param>
  1413. /// <param name='min'></param>
  1414. /// <param name='max'></param>
  1415. /// <returns></returns>
  1416. public static bool IsInsideBox(Vector3 v, Vector3 min, Vector3 max)
  1417. {
  1418. return v.X >= min.X && v.Y >= min.Y && v.Z >= min.Z
  1419. && v.X <= max.X && v.Y <= max.Y && v.Z <= max.Z;
  1420. }
  1421. /// <summary>
  1422. /// Are the co-ordinates of the new region visible from the old region?
  1423. /// </summary>
  1424. /// <param name="oldx">Old region x-coord</param>
  1425. /// <param name="newx">New region x-coord</param>
  1426. /// <param name="oldy">Old region y-coord</param>
  1427. /// <param name="newy">New region y-coord</param>
  1428. /// <returns></returns>
  1429. public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy,
  1430. int oldsizex, int oldsizey, int newsizex, int newsizey)
  1431. {
  1432. // we still need to make sure we see new region 1stNeighbors
  1433. drawdist--;
  1434. oldx *= Constants.RegionSize;
  1435. newx *= Constants.RegionSize;
  1436. if (oldx + oldsizex + drawdist < newx)
  1437. return true;
  1438. if (newx + newsizex + drawdist < oldx)
  1439. return true;
  1440. oldy *= Constants.RegionSize;
  1441. newy *= Constants.RegionSize;
  1442. if (oldy + oldsizey + drawdist < newy)
  1443. return true;
  1444. if (newy + newsizey + drawdist < oldy)
  1445. return true;
  1446. return false;
  1447. }
  1448. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1449. public static string FieldToString(byte[] bytes)
  1450. {
  1451. return FieldToString(bytes, String.Empty);
  1452. }
  1453. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1454. public static string FieldToASCIIString(byte[] bytes, int limit)
  1455. {
  1456. return CleanString(Encoding.ASCII.GetString(bytes, 0, limit < bytes.Length ? limit : bytes.Length));
  1457. }
  1458. /// <summary>
  1459. /// Convert a variable length field (byte array) to a string, with a
  1460. /// field name prepended to each line of the output
  1461. /// </summary>
  1462. /// <remarks>If the byte array has unprintable characters in it, a
  1463. /// hex dump will be put in the string instead</remarks>
  1464. /// <param name="bytes">The byte array to convert to a string</param>
  1465. /// <param name="fieldName">A field name to prepend to each line of output</param>
  1466. /// <returns>An ASCII string or a string containing a hex dump, minus
  1467. /// the null terminator</returns>
  1468. public static string FieldToString(byte[] bytes, string fieldName)
  1469. {
  1470. // Check for a common case
  1471. if (bytes.Length == 0) return String.Empty;
  1472. StringBuilder output = new();
  1473. bool printable = true;
  1474. for (int i = 0; i < bytes.Length; ++i)
  1475. {
  1476. // Check if there are any unprintable characters in the array
  1477. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  1478. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  1479. {
  1480. printable = false;
  1481. break;
  1482. }
  1483. }
  1484. if (printable)
  1485. {
  1486. if (fieldName.Length > 0)
  1487. {
  1488. output.Append(fieldName);
  1489. output.Append(": ");
  1490. }
  1491. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  1492. }
  1493. else
  1494. {
  1495. for (int i = 0; i < bytes.Length; i += 16)
  1496. {
  1497. if (i != 0)
  1498. output.Append(Environment.NewLine);
  1499. if (fieldName.Length > 0)
  1500. {
  1501. output.Append(fieldName);
  1502. output.Append(": ");
  1503. }
  1504. for (int j = 0; j < 16; j++)
  1505. {
  1506. if ((i + j) < bytes.Length)
  1507. output.Append($"{bytes[i + j]:X2} ");
  1508. else
  1509. output.Append(" ");
  1510. }
  1511. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  1512. {
  1513. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  1514. output.Append((char)bytes[i + j]);
  1515. else
  1516. output.Append('.');
  1517. }
  1518. }
  1519. }
  1520. return output.ToString();
  1521. }
  1522. private static readonly IPEndPoint dummyIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
  1523. private static readonly ExpiringCacheOS<string, IPAddress> dnscache = new(30000);
  1524. private static readonly ExpiringCacheOS<SocketAddress, EndPoint> EndpointsCache = new(300000);
  1525. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1526. public static EndPoint GetEndPoint(SocketAddress sckaddr)
  1527. {
  1528. if (!EndpointsCache.TryGetValue(sckaddr, 300000, out EndPoint ep))
  1529. {
  1530. ep = dummyIPEndPoint.Create(sckaddr);
  1531. EndpointsCache.AddOrUpdate(sckaddr, ep, 300);
  1532. }
  1533. return ep;
  1534. }
  1535. /// <summary>
  1536. /// Converts a URL to a IPAddress
  1537. /// </summary>
  1538. /// <param name="url">URL Standard Format</param>
  1539. /// <returns>A resolved IP Address</returns>
  1540. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1541. public static IPAddress GetHostFromURL(string url)
  1542. {
  1543. return GetHostFromDNS(url.Split(SplitSlashColonArray)[3]);
  1544. }
  1545. /// <summary>
  1546. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  1547. /// </summary>
  1548. /// <param name="dnsAddress">DNS Hostname</param>
  1549. /// <returns>An IP address, or null</returns>
  1550. public static IPAddress GetHostFromDNS(string dnsAddress)
  1551. {
  1552. if (String.IsNullOrWhiteSpace(dnsAddress))
  1553. return null;
  1554. if (dnscache.TryGetValue(dnsAddress, 300000, out IPAddress ia) && ia != null)
  1555. return ia;
  1556. // If it is already an IP, don't let GetHostEntry see it
  1557. if (IPAddress.TryParse(dnsAddress, out ia) && ia != null)
  1558. {
  1559. if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
  1560. return null;
  1561. dnscache.AddOrUpdate(dnsAddress, ia, 300);
  1562. return ia;
  1563. }
  1564. IPHostEntry IPH;
  1565. try
  1566. {
  1567. IPH = Dns.GetHostEntry(dnsAddress);
  1568. }
  1569. catch // (SocketException e)
  1570. {
  1571. return null;
  1572. }
  1573. if (IPH == null || IPH.AddressList.Length == 0)
  1574. return null;
  1575. ia = null;
  1576. foreach (IPAddress Adr in IPH.AddressList)
  1577. {
  1578. ia ??= Adr;
  1579. if (Adr.AddressFamily == AddressFamily.InterNetwork)
  1580. {
  1581. ia = Adr;
  1582. break;
  1583. }
  1584. }
  1585. if (ia != null)
  1586. dnscache.AddOrUpdate(dnsAddress, ia, 300);
  1587. return ia;
  1588. }
  1589. public static IPEndPoint getEndPoint(IPAddress ia, int port)
  1590. {
  1591. if (ia == null)
  1592. return null;
  1593. try
  1594. {
  1595. return new IPEndPoint(ia, port);
  1596. }
  1597. catch
  1598. {
  1599. return null;
  1600. }
  1601. }
  1602. public static IPEndPoint getEndPoint(string hostname, int port)
  1603. {
  1604. if (String.IsNullOrWhiteSpace(hostname))
  1605. return null;
  1606. if (dnscache.TryGetValue(hostname, 300000, out IPAddress ia) && ia != null)
  1607. return getEndPoint(ia, port);
  1608. // If it is already an IP, don't let GetHostEntry see it
  1609. if (IPAddress.TryParse(hostname, out ia) && ia != null)
  1610. {
  1611. if (ia.Equals(IPAddress.Any) || ia.Equals(IPAddress.IPv6Any))
  1612. return null;
  1613. dnscache.AddOrUpdate(hostname, ia, 300);
  1614. return getEndPoint(ia, port);
  1615. }
  1616. IPHostEntry IPH;
  1617. try
  1618. {
  1619. IPH = Dns.GetHostEntry(hostname);
  1620. }
  1621. catch // (SocketException e)
  1622. {
  1623. return null;
  1624. }
  1625. if (IPH == null || IPH.AddressList.Length == 0)
  1626. return null;
  1627. ia = null;
  1628. foreach (IPAddress Adr in IPH.AddressList)
  1629. {
  1630. ia ??= Adr;
  1631. if (Adr.AddressFamily == AddressFamily.InterNetwork)
  1632. {
  1633. ia = Adr;
  1634. break;
  1635. }
  1636. }
  1637. if (ia != null)
  1638. dnscache.AddOrUpdate(hostname, ia, 300);
  1639. return getEndPoint(ia, port);
  1640. }
  1641. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1642. public static Uri GetURI(string protocol, string hostname, int port, string path)
  1643. {
  1644. return new UriBuilder(protocol, hostname, port, path).Uri;
  1645. }
  1646. /// <summary>
  1647. /// Gets a list of all local system IP addresses
  1648. /// </summary>
  1649. /// <returns></returns>
  1650. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1651. public static IPAddress[] GetLocalHosts()
  1652. {
  1653. return Dns.GetHostAddresses(Dns.GetHostName());
  1654. }
  1655. public static IPAddress GetLocalHost()
  1656. {
  1657. IPAddress[] iplist = GetLocalHosts();
  1658. if (iplist.Length == 0) // No accessible external interfaces
  1659. {
  1660. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  1661. IPAddress localhost = loopback[0];
  1662. return localhost;
  1663. }
  1664. foreach (IPAddress host in iplist)
  1665. {
  1666. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  1667. {
  1668. return host;
  1669. }
  1670. }
  1671. if (iplist.Length > 0)
  1672. {
  1673. foreach (IPAddress host in iplist)
  1674. {
  1675. if (host.AddressFamily == AddressFamily.InterNetwork)
  1676. return host;
  1677. }
  1678. // Well all else failed...
  1679. return iplist[0];
  1680. }
  1681. return null;
  1682. }
  1683. /// <summary>
  1684. /// Parses a foreign asset ID.
  1685. /// </summary>
  1686. /// <param name="id">A possibly-foreign asset ID: http://grid.example.com:8002/00000000-0000-0000-0000-000000000000 </param>
  1687. /// <param name="url">The URL: http://grid.example.com:8002</param>
  1688. /// <param name="assetID">The asset ID: 00000000-0000-0000-0000-000000000000. Returned even if 'id' isn't foreign.</param>
  1689. /// <returns>True: this is a foreign asset ID; False: it isn't</returns>
  1690. public static int ParseForeignAssetID(string id, out string url, out string assetID)
  1691. {
  1692. url = string.Empty;
  1693. assetID = string.Empty;
  1694. if (id.Length == 0)
  1695. return -1;
  1696. if (id[0] != 'h' && id[0] != 'H')
  1697. {
  1698. if (UUID.TryParse(id, out _))
  1699. {
  1700. assetID = id;
  1701. return 0;
  1702. }
  1703. return -1;
  1704. }
  1705. OSHTTPURI uri = new(id, true);
  1706. if (uri.IsResolvedHost)
  1707. {
  1708. url = uri.URL;
  1709. string tmp = uri.Path;
  1710. if (tmp.Length < 36)
  1711. return -3;
  1712. if (tmp[0] == '/')
  1713. tmp = tmp[1..];
  1714. if (UUID.TryParse(tmp, out _))
  1715. {
  1716. assetID = tmp;
  1717. return 1;
  1718. }
  1719. return -1;
  1720. }
  1721. return -2;
  1722. }
  1723. /// <summary>
  1724. /// Removes all invalid path chars (OS dependent)
  1725. /// </summary>
  1726. /// <param name="path">path</param>
  1727. /// <returns>safe path</returns>
  1728. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1729. public static string SafePath(string path)
  1730. {
  1731. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  1732. }
  1733. /// <summary>
  1734. /// Removes all invalid filename chars (OS dependent)
  1735. /// </summary>
  1736. /// <param name="path">filename</param>
  1737. /// <returns>safe filename</returns>
  1738. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1739. public static string SafeFileName(string filename)
  1740. {
  1741. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  1742. }
  1743. //
  1744. // directory locations
  1745. //
  1746. public static string homeDir()
  1747. {
  1748. string temp;
  1749. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  1750. // temp = Path.Combine(personal,".OpenSim");
  1751. temp = ".";
  1752. return temp;
  1753. }
  1754. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1755. public static string assetsDir()
  1756. {
  1757. return Path.Combine(configDir(), "assets");
  1758. }
  1759. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1760. public static string inventoryDir()
  1761. {
  1762. return Path.Combine(configDir(), "inventory");
  1763. }
  1764. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1765. public static string configDir()
  1766. {
  1767. return ".";
  1768. }
  1769. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1770. public static string dataDir()
  1771. {
  1772. return ".";
  1773. }
  1774. public static string logFile()
  1775. {
  1776. foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
  1777. {
  1778. if (appender is FileAppender appender1 && appender1.Name == "LogFileAppender")
  1779. {
  1780. return appender1.File;
  1781. }
  1782. }
  1783. return "./OpenSim.log";
  1784. }
  1785. public static string StatsLogFile()
  1786. {
  1787. foreach (IAppender appender in LogManager.GetRepository().GetAppenders())
  1788. {
  1789. if (appender is FileAppender appender1 && appender1.Name == "StatsLogFileAppender")
  1790. {
  1791. return appender1.File;
  1792. }
  1793. }
  1794. return "./OpenSimStats.log";
  1795. }
  1796. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1797. public static string logDir()
  1798. {
  1799. return Path.GetDirectoryName(logFile());
  1800. }
  1801. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  1802. public static string GetUniqueFilename(string FileName)
  1803. {
  1804. int count = 0;
  1805. string Name;
  1806. if (File.Exists(FileName))
  1807. {
  1808. FileInfo f = new(FileName);
  1809. if (!String.IsNullOrEmpty(f.Extension))
  1810. {
  1811. Name = f.FullName[..f.FullName.LastIndexOf('.')];
  1812. }
  1813. else
  1814. {
  1815. Name = f.FullName;
  1816. }
  1817. while (File.Exists(FileName))
  1818. {
  1819. count++;
  1820. FileName = Name + count + f.Extension;
  1821. }
  1822. }
  1823. return FileName;
  1824. }
  1825. #region Nini (config) related Methods
  1826. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  1827. {
  1828. if (!File.Exists(fileName))
  1829. {
  1830. // create new file
  1831. }
  1832. XmlConfigSource config = new(fileName);
  1833. AddDataRowToConfig(config, row);
  1834. config.Save();
  1835. return config;
  1836. }
  1837. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  1838. {
  1839. config.Configs.Add((string)row[0]);
  1840. for (int i = 0; i < row.Table.Columns.Count; i++)
  1841. {
  1842. config.Configs[(string)row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  1843. }
  1844. }
  1845. public static string GetConfigVarWithDefaultSection(IConfigSource config, string varname, string section)
  1846. {
  1847. // First, check the Startup section, the default section
  1848. IConfig cnf = config.Configs["Startup"];
  1849. if (cnf == null)
  1850. return string.Empty;
  1851. string val = cnf.GetString(varname, string.Empty);
  1852. // Then check for an overwrite of the default in the given section
  1853. if (!string.IsNullOrEmpty(section))
  1854. {
  1855. cnf = config.Configs[section];
  1856. if (cnf != null)
  1857. val = cnf.GetString(varname, val);
  1858. }
  1859. return val;
  1860. }
  1861. /// <summary>
  1862. /// Gets the value of a configuration variable by looking into
  1863. /// multiple sections in order. The latter sections overwrite
  1864. /// any values previously found.
  1865. /// </summary>
  1866. /// <typeparam name="T">Type of the variable</typeparam>
  1867. /// <param name="config">The configuration object</param>
  1868. /// <param name="varname">The configuration variable</param>
  1869. /// <param name="sections">Ordered sequence of sections to look at</param>
  1870. /// <returns></returns>
  1871. public static T GetConfigVarFromSections<T>(IConfigSource config, string varname, string[] sections)
  1872. {
  1873. return GetConfigVarFromSections<T>(config, varname, sections, default(T));
  1874. }
  1875. /// <summary>
  1876. /// Gets the value of a configuration variable by looking into
  1877. /// multiple sections in order. The latter sections overwrite
  1878. /// any values previously found.
  1879. /// </summary>
  1880. /// <remarks>
  1881. /// If no value is found then the given default value is returned
  1882. /// </remarks>
  1883. /// <typeparam name="T">Type of the variable</typeparam>
  1884. /// <param name="config">The configuration object</param>
  1885. /// <param name="varname">The configuration variable</param>
  1886. /// <param name="sections">Ordered sequence of sections to look at</param>
  1887. /// <param name="val">Default value</param>
  1888. /// <returns></returns>
  1889. public static T GetConfigVarFromSections<T>(IConfigSource config, string varname, string[] sections, object val)
  1890. {
  1891. foreach (string section in sections.AsSpan())
  1892. {
  1893. IConfig cnf = config.Configs[section];
  1894. if (cnf == null)
  1895. continue;
  1896. if (typeof(T) == typeof(String))
  1897. val = cnf.GetString(varname, (string)val);
  1898. else if (typeof(T) == typeof(Boolean))
  1899. val = cnf.GetBoolean(varname, (bool)val);
  1900. else if (typeof(T) == typeof(Int32))
  1901. val = cnf.GetInt(varname, (int)val);
  1902. else if (typeof(T) == typeof(float))
  1903. val = cnf.GetFloat(varname, (float)val);
  1904. else
  1905. m_log.ErrorFormat("[UTIL]: Unhandled type {0}", typeof(T));
  1906. }
  1907. return (T)val;
  1908. }
  1909. public static void MergeEnvironmentToConfig(IConfigSource ConfigSource)
  1910. {
  1911. IConfig enVars = ConfigSource.Configs["Environment"];
  1912. // if section does not exist then user isn't expecting them, so don't bother.
  1913. if (enVars != null)
  1914. {
  1915. // load the values from the environment
  1916. EnvConfigSource envConfigSource = new();
  1917. // add the requested keys
  1918. string[] env_keys = enVars.GetKeys();
  1919. foreach (string key in env_keys)
  1920. {
  1921. envConfigSource.AddEnv(key, string.Empty);
  1922. }
  1923. // load the values from environment
  1924. envConfigSource.LoadEnv();
  1925. // add them in to the master
  1926. ConfigSource.Merge(envConfigSource);
  1927. ConfigSource.ExpandKeyValues();
  1928. }
  1929. }
  1930. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  1931. {
  1932. Type settingsType = settingsClass.GetType();
  1933. FieldInfo[] fieldInfos = settingsType.GetFields();
  1934. foreach (FieldInfo fieldInfo in fieldInfos)
  1935. {
  1936. if (!fieldInfo.IsStatic)
  1937. {
  1938. if (fieldInfo.FieldType == typeof(System.String))
  1939. {
  1940. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  1941. }
  1942. else if (fieldInfo.FieldType == typeof(System.Boolean))
  1943. {
  1944. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  1945. }
  1946. else if (fieldInfo.FieldType == typeof(System.Int32))
  1947. {
  1948. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  1949. }
  1950. else if (fieldInfo.FieldType == typeof(System.Single))
  1951. {
  1952. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  1953. }
  1954. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1955. {
  1956. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1957. }
  1958. }
  1959. }
  1960. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1961. foreach (PropertyInfo propInfo in propertyInfos)
  1962. {
  1963. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1964. {
  1965. if (propInfo.PropertyType == typeof(System.String))
  1966. {
  1967. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1968. }
  1969. else if (propInfo.PropertyType == typeof(System.Boolean))
  1970. {
  1971. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1972. }
  1973. else if (propInfo.PropertyType == typeof(System.Int32))
  1974. {
  1975. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1976. }
  1977. else if (propInfo.PropertyType == typeof(System.Single))
  1978. {
  1979. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1980. }
  1981. if (propInfo.PropertyType == typeof(System.UInt32))
  1982. {
  1983. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1984. }
  1985. }
  1986. }
  1987. return settingsClass;
  1988. }
  1989. /// <summary>
  1990. /// Reads a configuration file, configFile, merging it with the main configuration, config.
  1991. /// If the file doesn't exist, it copies a given exampleConfigFile onto configFile, and then
  1992. /// merges it.
  1993. /// </summary>
  1994. /// <param name="config">The main configuration data</param>
  1995. /// <param name="configFileName">The name of a configuration file in ConfigDirectory variable, no path</param>
  1996. /// <param name="exampleConfigFile">Full path to an example configuration file</param>
  1997. /// <param name="configFilePath">Full path ConfigDirectory/configFileName</param>
  1998. /// <param name="created">True if the file was created in ConfigDirectory, false if it existed</param>
  1999. /// <returns>True if success</returns>
  2000. public static bool MergeConfigurationFile(IConfigSource config, string configFileName, string exampleConfigFile, out string configFilePath, out bool created)
  2001. {
  2002. created = false;
  2003. configFilePath = string.Empty;
  2004. IConfig cnf = config.Configs["Startup"];
  2005. if (cnf == null)
  2006. {
  2007. m_log.Warn("[UTILS]: Startup section doesn't exist");
  2008. return false;
  2009. }
  2010. string configDirectory = cnf.GetString("ConfigDirectory", ".");
  2011. string configFile = Path.Combine(configDirectory, configFileName);
  2012. if (!File.Exists(configFile) && !string.IsNullOrEmpty(exampleConfigFile))
  2013. {
  2014. // We need to copy the example onto it
  2015. if (!Directory.Exists(configDirectory))
  2016. Directory.CreateDirectory(configDirectory);
  2017. try
  2018. {
  2019. File.Copy(exampleConfigFile, configFile);
  2020. created = true;
  2021. }
  2022. catch (Exception e)
  2023. {
  2024. m_log.Warn($"[UTILS]: Exception copying configuration file {configFile} to {exampleConfigFile}: {e.Message}");
  2025. return false;
  2026. }
  2027. }
  2028. if (File.Exists(configFile))
  2029. {
  2030. // Merge
  2031. config.Merge(new IniConfigSource(configFile));
  2032. config.ExpandKeyValues();
  2033. configFilePath = configFile;
  2034. return true;
  2035. }
  2036. else
  2037. return false;
  2038. }
  2039. #endregion
  2040. /// <summary>
  2041. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  2042. /// </summary>
  2043. /// <param name="UUID"></param>
  2044. /// <returns></returns>
  2045. public static String ToRawUuidString(UUID UUID)
  2046. {
  2047. return UUID.Guid.ToString("n");
  2048. }
  2049. public static string CleanString(string input)
  2050. {
  2051. for (int i = 0; i < input.Length; i++)
  2052. {
  2053. if (input[i] == '\0' || input[i] == '\r' || input[i] == '\n')
  2054. return input[..i];
  2055. }
  2056. return input;
  2057. }
  2058. /// <summary>
  2059. /// returns the contents of /etc/issue on Unix Systems
  2060. /// Use this for where it's absolutely necessary to implement platform specific stuff
  2061. /// </summary>
  2062. /// <returns></returns>
  2063. public static string ReadEtcIssue()
  2064. {
  2065. try
  2066. {
  2067. using StreamReader sr = new("/etc/issue.net");
  2068. string issue = sr.ReadToEnd();
  2069. return issue;
  2070. }
  2071. catch
  2072. {
  2073. return "";
  2074. }
  2075. }
  2076. public static void SerializeToFile(string filename, Object obj)
  2077. {
  2078. var formatter = new BinaryFormatter();
  2079. try
  2080. {
  2081. using Stream stream = new FileStream(filename, FileMode.Create,FileAccess.Write, FileShare.None);
  2082. formatter.Serialize(stream, obj);
  2083. }
  2084. catch (Exception e)
  2085. {
  2086. m_log.Error(e.ToString());
  2087. }
  2088. }
  2089. public static Object DeserializeFromFile(string filename)
  2090. {
  2091. try
  2092. {
  2093. using Stream stream = new FileStream(filename, FileMode.Open,FileAccess.Read, FileShare.None);
  2094. var formatter = new BinaryFormatter();
  2095. return formatter.Deserialize(stream);
  2096. }
  2097. catch (Exception e)
  2098. {
  2099. m_log.Error(e.ToString());
  2100. }
  2101. return null;
  2102. }
  2103. public static string Compress(string text)
  2104. {
  2105. using MemoryStream memory = new();
  2106. using GZipStream compressor = new(memory, CompressionMode.Compress, true);
  2107. byte[] buffer = Util.UTF8.GetBytes(text);
  2108. compressor.Write(buffer, 0, buffer.Length);
  2109. memory.Position = 0;
  2110. byte[] compressed = new byte[memory.Length];
  2111. memory.Read(compressed, 0, compressed.Length);
  2112. byte[] compressedBuffer = new byte[compressed.Length + 4];
  2113. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  2114. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  2115. return Convert.ToBase64String(compressedBuffer);
  2116. }
  2117. public static string Decompress(string compressedText)
  2118. {
  2119. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  2120. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  2121. using MemoryStream memory = new();
  2122. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  2123. byte[] buffer = new byte[msgLength];
  2124. memory.Position = 0;
  2125. using GZipStream decompressor = new(memory, CompressionMode.Decompress);
  2126. decompressor.Read(buffer, 0, buffer.Length);
  2127. return Util.UTF8.GetString(buffer);
  2128. }
  2129. /// <summary>
  2130. /// Copy data from one stream to another, leaving the read position of both streams at the beginning.
  2131. /// </summary>
  2132. /// <param name='inputStream'>
  2133. /// Input stream. Must be seekable.
  2134. /// </param>
  2135. /// <exception cref='ArgumentException'>
  2136. /// Thrown if the input stream is not seekable.
  2137. /// </exception>
  2138. public static Stream Copy(Stream inputStream)
  2139. {
  2140. if (!inputStream.CanSeek)
  2141. throw new ArgumentException("Util.Copy(Stream inputStream) must receive an inputStream that can seek");
  2142. const int readSize = 256;
  2143. byte[] buffer = new byte[readSize];
  2144. MemoryStream ms = new();
  2145. int count = inputStream.Read(buffer, 0, readSize);
  2146. while (count > 0)
  2147. {
  2148. ms.Write(buffer, 0, count);
  2149. count = inputStream.Read(buffer, 0, readSize);
  2150. }
  2151. ms.Position = 0;
  2152. inputStream.Position = 0;
  2153. return ms;
  2154. }
  2155. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2156. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  2157. {
  2158. return SendXmlRpcCommand(url, methodName, args);
  2159. }
  2160. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  2161. {
  2162. XmlRpcRequest xmlclient = new(methodName, args);
  2163. using HttpClient hclient = WebUtil.GetNewGlobalHttpClient(10000);
  2164. return xmlclient.Send(url, hclient);
  2165. }
  2166. /// <summary>
  2167. /// Returns an error message that the user could not be found in the database
  2168. /// </summary>
  2169. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  2170. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  2171. {
  2172. Hashtable responseData = new()
  2173. {
  2174. ["error_type"] = "unknown_user",
  2175. ["error_desc"] = "The user requested is not in the database"
  2176. };
  2177. XmlRpcResponse response = new()
  2178. {
  2179. Value = responseData
  2180. };
  2181. return response;
  2182. }
  2183. /// <summary>
  2184. /// Converts a byte array in big endian order into an ulong.
  2185. /// </summary>
  2186. /// <param name="bytes">
  2187. /// The array of bytes
  2188. /// </param>
  2189. /// <returns>
  2190. /// The extracted ulong
  2191. /// </returns>
  2192. public static ulong BytesToUInt64Big(byte[] bytes)
  2193. {
  2194. if (bytes.Length < 8) return 0;
  2195. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  2196. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  2197. }
  2198. // used for RemoteParcelRequest (for "About Landmark")
  2199. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  2200. {
  2201. byte[] bytes =
  2202. {
  2203. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  2204. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
  2205. (byte)x, (byte)(x >> 8), 0, 0,
  2206. (byte)y, (byte)(y >> 8), 0, 0 };
  2207. return new UUID(bytes, 0);
  2208. }
  2209. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  2210. {
  2211. byte[] bytes =
  2212. {
  2213. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  2214. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle >> 56),
  2215. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  2216. (byte)y, (byte)(y >> 8), 0, 0 };
  2217. return new UUID(bytes, 0);
  2218. }
  2219. public static bool ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  2220. {
  2221. byte[] bytes = parcelID.GetBytes();
  2222. regionHandle = Utils.BytesToUInt64(bytes);
  2223. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  2224. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  2225. // validation may fail, just reducing the odds of using a real UUID as encoded parcel
  2226. return (bytes[0] == 0 && bytes[4] == 0 && // handler x,y multiples of 256
  2227. bytes[9] < 64 && bytes[13] < 64 && // positions < 16km
  2228. bytes[14] == 0 && bytes[15] == 0);
  2229. }
  2230. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  2231. {
  2232. byte[] bytes = parcelID.GetBytes();
  2233. regionHandle = Utils.BytesToUInt64(bytes);
  2234. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  2235. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  2236. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  2237. }
  2238. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  2239. {
  2240. ParseFakeParcelID(parcelID, out ulong regionHandle, out x, out y);
  2241. Utils.LongToUInts(regionHandle, out uint rx, out uint ry);
  2242. x += rx;
  2243. y += ry;
  2244. }
  2245. /// <summary>
  2246. /// Get operating system information if available. Returns only the first 45 characters of information
  2247. /// </summary>
  2248. /// <returns>
  2249. /// Operating system information. Returns an empty string if none was available.
  2250. /// </returns>
  2251. public static string GetOperatingSystemInformation()
  2252. {
  2253. return String.Empty;
  2254. //string os;
  2255. //if (Environment.OSVersion.Platform != PlatformID.Unix)
  2256. //{
  2257. // os = Environment.OSVersion.ToString();
  2258. //}
  2259. //else
  2260. //{
  2261. // os = ReadEtcIssue();
  2262. //}
  2263. //if (os.Length > 45)
  2264. //{
  2265. // os = os.Substring(0, 45);
  2266. //}
  2267. //return os;
  2268. }
  2269. public static readonly string RuntimeInformationStr = RuntimeInformation.ProcessArchitecture.ToString() + "/" + Environment.OSVersion.Platform switch
  2270. {
  2271. PlatformID.MacOSX or PlatformID.Unix => RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "OSX/DotNet" : "Unix/DotNet",
  2272. _ => "Win/DotNet"
  2273. };
  2274. public static readonly string RuntimePlatformStr = Environment.OSVersion.Platform switch
  2275. {
  2276. PlatformID.MacOSX or PlatformID.Unix => RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? "OSX/DotNet" : "Unix/DotNet",
  2277. _ => "Win/DotNet"
  2278. };
  2279. /// <summary>
  2280. /// Is the given string a UUID?
  2281. /// </summary>
  2282. /// <param name="s"></param>
  2283. /// <returns></returns>
  2284. public static bool isUUID(string s)
  2285. {
  2286. return UUIDPattern.IsMatch(s);
  2287. }
  2288. public static string GetDisplayConnectionString(string connectionString)
  2289. {
  2290. int passPosition;
  2291. int passEndPosition;
  2292. // hide the password in the connection string
  2293. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  2294. if (passPosition == -1)
  2295. return connectionString;
  2296. passPosition = connectionString.IndexOf('=', passPosition);
  2297. if (passPosition < connectionString.Length)
  2298. passPosition += 1;
  2299. passEndPosition = connectionString.IndexOf(';', passPosition);
  2300. return $"{connectionString[..passPosition]}***{connectionString[passEndPosition..]}";
  2301. }
  2302. public static string Base64ToString(string str)
  2303. {
  2304. Decoder utf8Decode = Encoding.UTF8.GetDecoder();
  2305. byte[] todecode_byte = Convert.FromBase64String(str);
  2306. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  2307. char[] decoded_char = new char[charCount];
  2308. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  2309. string result = new(decoded_char);
  2310. return result;
  2311. }
  2312. public static void BinaryToASCII(char[] chars)
  2313. {
  2314. for (int i = 0; i < chars.Length; i++)
  2315. {
  2316. char ch = chars[i];
  2317. if (ch < 32 || ch > 127)
  2318. chars[i] = '.';
  2319. }
  2320. }
  2321. public static string BinaryToASCII(string src)
  2322. {
  2323. char[] chars = src.ToCharArray();
  2324. BinaryToASCII(chars);
  2325. return new String(chars);
  2326. }
  2327. /// <summary>
  2328. /// Reads a known number of bytes from a stream.
  2329. /// Throws EndOfStreamException if the stream doesn't contain enough data.
  2330. /// </summary>
  2331. /// <param name="stream">The stream to read data from</param>
  2332. /// <param name="data">The array to write bytes into. The array
  2333. /// will be completely filled from the stream, so an appropriate
  2334. /// size must be given.</param>
  2335. public static void ReadStream(Stream stream, byte[] data)
  2336. {
  2337. int offset = 0;
  2338. int remaining = data.Length;
  2339. while (remaining > 0)
  2340. {
  2341. int read = stream.Read(data, offset, remaining);
  2342. if (read <= 0)
  2343. throw new EndOfStreamException(String.Format("End of stream reached with {0} bytes left to read", remaining));
  2344. remaining -= read;
  2345. offset += read;
  2346. }
  2347. }
  2348. public static Guid GetHashGuid(string data, string salt)
  2349. {
  2350. byte[] hash = ComputeMD5Hash(data + salt, Encoding.Default);
  2351. Guid guid = new(hash);
  2352. return guid;
  2353. }
  2354. public static byte ConvertMaturityToAccessLevel(uint maturity)
  2355. {
  2356. byte retVal = 0;
  2357. switch (maturity)
  2358. {
  2359. case 0: //PG
  2360. retVal = 13;
  2361. break;
  2362. case 1: //Mature
  2363. retVal = 21;
  2364. break;
  2365. case 2: // Adult
  2366. retVal = 42;
  2367. break;
  2368. }
  2369. return retVal;
  2370. }
  2371. public static uint ConvertAccessLevelToMaturity(byte maturity)
  2372. {
  2373. if (maturity <= 13)
  2374. return 0;
  2375. else if (maturity <= 21)
  2376. return 1;
  2377. else
  2378. return 2;
  2379. }
  2380. /// <summary>
  2381. /// Produces an OSDMap from its string representation on a stream
  2382. /// </summary>
  2383. /// <param name="data">The stream</param>
  2384. /// <param name="length">The size of the data on the stream</param>
  2385. /// <returns>The OSDMap or an exception</returns>
  2386. public static OSDMap GetOSDMap(Stream stream, int length)
  2387. {
  2388. byte[] data = new byte[length];
  2389. stream.Read(data, 0, length);
  2390. string strdata = Util.UTF8.GetString(data);
  2391. OSDMap args;
  2392. OSD buffer;
  2393. buffer = OSDParser.DeserializeJson(strdata);
  2394. if (buffer.Type == OSDType.Map)
  2395. {
  2396. args = (OSDMap)buffer;
  2397. return args;
  2398. }
  2399. return null;
  2400. }
  2401. public static OSDMap GetOSDMap(string data)
  2402. {
  2403. OSDMap args;
  2404. try
  2405. {
  2406. OSD buffer;
  2407. // We should pay attention to the content-type, but let's assume we know it's Json
  2408. buffer = OSDParser.DeserializeJson(data);
  2409. if (buffer.Type == OSDType.Map)
  2410. {
  2411. args = (OSDMap)buffer;
  2412. return args;
  2413. }
  2414. else
  2415. {
  2416. // uh?
  2417. m_log.Debug($"[UTILS]: Got OSD of unexpected type {buffer.Type}");
  2418. return null;
  2419. }
  2420. }
  2421. catch (Exception ex)
  2422. {
  2423. m_log.Debug($"[UTILS]: exception on GetOSDMap {ex.Message}");
  2424. return null;
  2425. }
  2426. }
  2427. public static string[] Glob(string path)
  2428. {
  2429. string vol = String.Empty;
  2430. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  2431. {
  2432. string[] vcomps = path.Split(new char[] { Path.VolumeSeparatorChar }, 2, StringSplitOptions.RemoveEmptyEntries);
  2433. if (vcomps.Length > 1)
  2434. {
  2435. path = vcomps[1];
  2436. vol = vcomps[0];
  2437. }
  2438. }
  2439. string[] comps = path.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
  2440. // Glob
  2441. path = vol;
  2442. if (vol != String.Empty)
  2443. path += new String(new char[] { Path.VolumeSeparatorChar, Path.DirectorySeparatorChar });
  2444. else
  2445. path = new String(new char[] { Path.DirectorySeparatorChar });
  2446. List<string> paths = new();
  2447. List<string> found = new();
  2448. paths.Add(path);
  2449. int compIndex = -1;
  2450. foreach (string c in comps)
  2451. {
  2452. compIndex++;
  2453. List<string> addpaths = new();
  2454. foreach (string p in paths)
  2455. {
  2456. string[] dirs = Directory.GetDirectories(p, c);
  2457. if (dirs.Length != 0)
  2458. {
  2459. foreach (string dir in dirs)
  2460. addpaths.Add(Path.Combine(path, dir));
  2461. }
  2462. // Only add files if that is the last path component
  2463. if (compIndex == comps.Length - 1)
  2464. {
  2465. string[] files = Directory.GetFiles(p, c);
  2466. foreach (string f in files)
  2467. found.Add(f);
  2468. }
  2469. }
  2470. paths = addpaths;
  2471. }
  2472. return found.ToArray();
  2473. }
  2474. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2475. public static string AppendEndSlash(string path)
  2476. {
  2477. int len = path.Length;
  2478. --len;
  2479. if (len > 0 && path[len] != '/')
  2480. return path + '/';
  2481. return path;
  2482. }
  2483. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2484. public static string TrimEndSlash(string path)
  2485. {
  2486. int len = path.Length;
  2487. --len;
  2488. if (len > 0 && path[len] == '/')
  2489. return path[..len];
  2490. return path;
  2491. }
  2492. public static string ServerURIasIP(string uri)
  2493. {
  2494. if (uri.Length == 0)
  2495. return string.Empty;
  2496. // Get rid of eventual slashes at the end
  2497. uri = uri.TrimEnd('/');
  2498. IPAddress ipaddr1 = null;
  2499. string port1 = "";
  2500. try
  2501. {
  2502. ipaddr1 = Util.GetHostFromURL(uri);
  2503. }
  2504. catch { }
  2505. try
  2506. {
  2507. port1 = uri.Split(Util.SplitColonArray)[2];
  2508. }
  2509. catch { }
  2510. // We tried our best to convert the domain names to IP addresses
  2511. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  2512. }
  2513. /// <summary>
  2514. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  2515. /// </summary>
  2516. /// <param name="str">
  2517. /// If null or empty, then an bytes[0] is returned.
  2518. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  2519. /// </param>
  2520. /// <param name="args">
  2521. /// Arguments to substitute into the string via the {} mechanism.
  2522. /// </param>
  2523. /// <returns></returns>
  2524. /*
  2525. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2526. public static byte[] StringToBytes256(string str, params object[] args)
  2527. {
  2528. return Utils.StringToBytes(string.Format(str, args), 255);
  2529. }
  2530. */
  2531. /// <summary>
  2532. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  2533. /// </summary>
  2534. /// <param name="str">
  2535. /// If null or empty, then an bytes[0] is returned.
  2536. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  2537. /// </param>
  2538. /// <returns></returns>
  2539. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2540. public static byte[] StringToBytes256(ReadOnlySpan<char> str)
  2541. {
  2542. return Utils.StringToBytes(str, 255);
  2543. }
  2544. /// <summary>
  2545. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  2546. /// </summary>
  2547. /// <param name="str">
  2548. /// If null or empty, then an bytes[0] is returned.
  2549. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  2550. /// </param>
  2551. /// <param name="args">
  2552. /// Arguments to substitute into the string via the {} mechanism.
  2553. /// </param>
  2554. /// <returns></returns>
  2555. /*
  2556. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2557. public static byte[] StringToBytes1024(string str, params object[] args)
  2558. {
  2559. return Utils.StringToBytes(string.Format(str, args).AsSpan(), 1024);
  2560. }
  2561. */
  2562. /// <summary>
  2563. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  2564. /// </summary>
  2565. /// <param name="str">
  2566. /// If null or empty, then an bytes[0] is returned.
  2567. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  2568. /// </param>
  2569. /// <returns></returns>
  2570. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2571. public static byte[] StringToBytes1024(ReadOnlySpan<char> str)
  2572. {
  2573. return Utils.StringToBytes(str, 1024);
  2574. }
  2575. /// <summary>
  2576. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to MaxLength bytes if necessary.
  2577. /// </summary>
  2578. /// <param name="str">
  2579. /// If null or empty, then an bytes[0] is returned.
  2580. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  2581. /// </param>
  2582. /// <param name="args">
  2583. /// Arguments to substitute into the string via the {} mechanism.
  2584. /// </param>
  2585. /// <returns></returns>
  2586. /*
  2587. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2588. public static byte[] StringToBytes(string str, int MaxLength, params object[] args)
  2589. {
  2590. return Utils.StringToBytes(string.Format(str, args).AsSpan(), MaxLength);
  2591. }
  2592. */
  2593. /// <summary>
  2594. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to MaxLength bytes if necessary.
  2595. /// </summary>
  2596. /// <param name="str">
  2597. /// If null or empty, then an bytes[0] is returned.
  2598. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  2599. /// </param>
  2600. /// <returns></returns>
  2601. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2602. public static byte[] StringToBytes(ReadOnlySpan<char> str, int MaxLength)
  2603. {
  2604. return Utils.StringToBytes(str, MaxLength);
  2605. }
  2606. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2607. public static byte[] StringToBytesNoTerm(ReadOnlySpan<char> str, int MaxLength)
  2608. {
  2609. return Utils.StringToBytesNoTerm(str, MaxLength);
  2610. }
  2611. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2612. public static int osUTF8Getbytes(ReadOnlySpan<char> srcstr, byte[] dstarray, int maxdstlen, bool NullTerm = true)
  2613. {
  2614. return osUTF8Getbytes(srcstr, dstarray, 0, maxdstlen, NullTerm);
  2615. }
  2616. public static unsafe int osUTF8Getbytes(ReadOnlySpan<char> srcstr, byte* dstarray, int maxdstlen, bool NullTerm = true)
  2617. {
  2618. if (srcstr.Length == 0)
  2619. return 0;
  2620. fixed (char* srcbase = srcstr)
  2621. {
  2622. return osUTF8Getbytes(srcbase, srcstr.Length, dstarray, maxdstlen, NullTerm);
  2623. }
  2624. }
  2625. public static unsafe int osUTF8Getbytes(ReadOnlySpan<char> srcstr, byte[] dstarray, int pos, int maxdstlen, bool NullTerm = true)
  2626. {
  2627. if (srcstr.Length == 0)
  2628. return 0;
  2629. if (pos + maxdstlen > dstarray.Length)
  2630. return 0;
  2631. fixed (char* srcbase = srcstr)
  2632. {
  2633. fixed (byte* dstbase = &dstarray[pos])
  2634. {
  2635. return osUTF8Getbytes(srcbase, srcstr.Length, dstbase, maxdstlen, NullTerm);
  2636. }
  2637. }
  2638. }
  2639. public static unsafe int osUTF8Getbytes(char* srcarray, int srclength, byte* dstarray, int maxdstlen, bool NullTerm = true)
  2640. {
  2641. int dstlen = NullTerm ? maxdstlen - 1 : maxdstlen;
  2642. int srclen = srclength >= dstlen ? dstlen : srclength;
  2643. char c;
  2644. char* src = srcarray;
  2645. char* srcend = src + srclen;
  2646. byte* dst = dstarray;
  2647. byte* dstend = dst + dstlen;
  2648. while (src < srcend && dst < dstend)
  2649. {
  2650. c = *src;
  2651. ++src;
  2652. if (c <= 0x7f)
  2653. {
  2654. *dst = (byte)c;
  2655. ++dst;
  2656. continue;
  2657. }
  2658. if (c < 0x800)
  2659. {
  2660. if (dst + 1 >= dstend)
  2661. break;
  2662. *dst = (byte)(0xC0 | (c >> 6));
  2663. ++dst;
  2664. *dst = (byte)(0x80 | (c & 0x3F));
  2665. ++dst;
  2666. continue;
  2667. }
  2668. if (c >= 0xD800 && c < 0xE000)
  2669. {
  2670. if (c >= 0xDC00)
  2671. continue; // ignore invalid
  2672. if (src >= srcend || dst + 3 >= dstend)
  2673. break;
  2674. int a = c;
  2675. c = *src;
  2676. ++src;
  2677. if (c < 0xDC00 || c > 0xDFFF)
  2678. continue; // ignore invalid
  2679. a = (a << 10) + c - 0x35fdc00;
  2680. *dst = (byte)(0xF0 | (a >> 18));
  2681. ++dst;
  2682. *dst = (byte)(0x80 | ((a >> 12) & 0x3f));
  2683. ++dst;
  2684. *dst = (byte)(0x80 | ((a >> 6) & 0x3f));
  2685. ++dst;
  2686. *dst = (byte)(0x80 | (a & 0x3f));
  2687. ++dst;
  2688. continue;
  2689. }
  2690. if (dst + 2 >= dstend)
  2691. break;
  2692. *dst = (byte)(0xE0 | (c >> 12));
  2693. ++dst;
  2694. *dst = (byte)(0x80 | ((c >> 6) & 0x3f));
  2695. ++dst;
  2696. *dst = (byte)(0x80 | (c & 0x3f));
  2697. ++dst;
  2698. }
  2699. int ret = (int)(dst - dstarray);
  2700. if (NullTerm && ret > 0 && *(dst - 1) != 0)
  2701. {
  2702. *dst = 0;
  2703. ++ret;
  2704. }
  2705. return ret;
  2706. }
  2707. /// <summary>
  2708. /// Pretty format the hashtable contents to a single line.
  2709. /// </summary>
  2710. /// <remarks>
  2711. /// Used for debugging output.
  2712. /// </remarks>
  2713. /// <param name='ht'></param>
  2714. public static string PrettyFormatToSingleLine(Hashtable ht)
  2715. {
  2716. StringBuilder sb = new();
  2717. int i = 0;
  2718. foreach (string key in ht.Keys)
  2719. {
  2720. sb.Append($"{key}:{ht[key]}");
  2721. if (++i < ht.Count)
  2722. sb.AppendFormat(", ");
  2723. }
  2724. return sb.ToString();
  2725. }
  2726. public static bool TryParseHttpRange(string header, out int start, out int end)
  2727. {
  2728. start = end = 0;
  2729. if (string.IsNullOrWhiteSpace(header))
  2730. return false;
  2731. if (header.StartsWith("bytes="))
  2732. {
  2733. string[] rangeValues = header[6..].Split('-');
  2734. if (rangeValues.Length == 2)
  2735. {
  2736. string rawStart = rangeValues[0].Trim();
  2737. if (rawStart != "" && !Int32.TryParse(rawStart, out start))
  2738. return false;
  2739. if (start < 0)
  2740. return false;
  2741. string rawEnd = rangeValues[1].Trim();
  2742. if (rawEnd.Length == 0)
  2743. {
  2744. end = -1;
  2745. return true;
  2746. }
  2747. else if (Int32.TryParse(rawEnd, out end))
  2748. return end > 0;
  2749. }
  2750. }
  2751. start = end = 0;
  2752. return false;
  2753. }
  2754. [DllImport("winmm.dll")]
  2755. private static extern uint timeBeginPeriod(uint period);
  2756. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2757. public static void TimeBeginPeriod(uint period)
  2758. {
  2759. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  2760. timeBeginPeriod(period);
  2761. }
  2762. [DllImport("winmm.dll")]
  2763. private static extern uint timeEndPeriod(uint period);
  2764. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2765. public static void TimeEndPeriod(uint period)
  2766. {
  2767. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  2768. timeEndPeriod(period);
  2769. }
  2770. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2771. public static void ThreadSleep(int period)
  2772. {
  2773. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  2774. {
  2775. timeEndPeriod(1);
  2776. Thread.Sleep(period);
  2777. timeEndPeriod(1);
  2778. }
  2779. else
  2780. Thread.Sleep(period);
  2781. }
  2782. /// <summary>
  2783. /// Used to trigger an early library load on Windows systems.
  2784. /// </summary>
  2785. /// <remarks>
  2786. /// Required to get 32-bit and 64-bit processes to automatically use the
  2787. /// appropriate native library.
  2788. /// </remarks>
  2789. /// <param name="dllToLoad"></param>
  2790. /// <returns></returns>
  2791. [DllImport("kernel32.dll")]
  2792. public static extern IntPtr LoadLibrary(string dllToLoad);
  2793. /// <summary>
  2794. /// Determine whether the current process is 64 bit
  2795. /// </summary>
  2796. /// <returns>true if so, false if not</returns>
  2797. #region FireAndForget Threading Pattern
  2798. public static void InitThreadPool(int minThreads, int maxThreads)
  2799. {
  2800. if (maxThreads < 2)
  2801. throw new ArgumentOutOfRangeException(nameof(maxThreads), "maxThreads must be greater than 2");
  2802. if (minThreads > maxThreads || minThreads < 2)
  2803. throw new ArgumentOutOfRangeException(nameof(minThreads), "minThreads must be greater than 2 and less than or equal to maxThreads");
  2804. if (m_ThreadPool != null)
  2805. {
  2806. m_log.Warn("SmartThreadPool is already initialized. Ignoring request.");
  2807. return;
  2808. }
  2809. STPStartInfo startInfo = new()
  2810. {
  2811. ThreadPoolName = "Util",
  2812. IdleTimeout = 20000,
  2813. MaxWorkerThreads = maxThreads,
  2814. MinWorkerThreads = minThreads,
  2815. SuppressFlow = true
  2816. };
  2817. m_ThreadPool = new SmartThreadPool(startInfo);
  2818. m_threadPoolWatchdog = new Timer(ThreadPoolWatchdog, null, 0, 1000);
  2819. }
  2820. public static int FireAndForgetCount()
  2821. {
  2822. const int MAX_SYSTEM_THREADS = 200;
  2823. switch (FireAndForgetMethod)
  2824. {
  2825. case FireAndForgetMethod.QueueUserWorkItem:
  2826. ThreadPool.GetAvailableThreads(out int workerThreads, out _);
  2827. return workerThreads;
  2828. case FireAndForgetMethod.SmartThreadPool:
  2829. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  2830. case FireAndForgetMethod.Thread:
  2831. {
  2832. using Process p = System.Diagnostics.Process.GetCurrentProcess();
  2833. return MAX_SYSTEM_THREADS - p.Threads.Count;
  2834. }
  2835. default:
  2836. throw new NotImplementedException();
  2837. }
  2838. }
  2839. /// <summary>
  2840. /// Additional information about threads in the main thread pool. Used to time how long the
  2841. /// thread has been running, and abort it if it has timed-out.
  2842. /// </summary>
  2843. private class ThreadInfo
  2844. {
  2845. public long ThreadFuncNum { get; set; }
  2846. public string StackTrace { get; set; }
  2847. private readonly string context;
  2848. public bool LogThread { get; set; }
  2849. public IWorkItemResult WorkItem { get; set; }
  2850. public Thread Thread { get; set; }
  2851. public bool Running { get; set; }
  2852. public bool Aborted { get; set; }
  2853. private int started;
  2854. public bool DoTimeout;
  2855. public ThreadInfo(long threadFuncNum, string context, bool dotimeout = true)
  2856. {
  2857. ThreadFuncNum = threadFuncNum;
  2858. this.context = context;
  2859. LogThread = false;
  2860. Thread = null;
  2861. Running = false;
  2862. Aborted = false;
  2863. DoTimeout = dotimeout;
  2864. }
  2865. public void Started()
  2866. {
  2867. Thread = Thread.CurrentThread;
  2868. started = EnvironmentTickCount();
  2869. Running = true;
  2870. }
  2871. public void Ended()
  2872. {
  2873. Running = false;
  2874. }
  2875. public int Elapsed()
  2876. {
  2877. return EnvironmentTickCountSubtract(started);
  2878. }
  2879. public void Abort()
  2880. {
  2881. Aborted = true;
  2882. WorkItem.Cancel(true);
  2883. }
  2884. /// <summary>
  2885. /// Returns the thread's stack trace.
  2886. /// </summary>
  2887. /// <remarks>
  2888. /// May return one of two stack traces. First, tries to get the thread's active stack
  2889. /// trace. But this can fail, so as a fallback this method will return the stack
  2890. /// trace that was active when the task was queued.
  2891. /// </remarks>
  2892. public string GetStackTrace()
  2893. {
  2894. string ret = (context == null) ? "" : ("(" + context + ") ");
  2895. StackTrace activeStackTrace = Util.GetStackTrace(Thread);
  2896. if (activeStackTrace != null)
  2897. ret += activeStackTrace.ToString();
  2898. else if (StackTrace != null)
  2899. ret += "(Stack trace when queued) " + StackTrace;
  2900. // else, no stack trace available
  2901. return ret;
  2902. }
  2903. }
  2904. private static long nextThreadFuncNum = 0;
  2905. private static long numQueuedThreadFuncs = 0;
  2906. private static long numRunningThreadFuncs = 0;
  2907. private static long numTotalThreadFuncsCalled = 0;
  2908. public static long TotalQueuedFireAndForgetCalls { get { return numQueuedThreadFuncs; } }
  2909. public static long TotalRunningFireAndForgetCalls { get { return numRunningThreadFuncs; } }
  2910. // Maps (ThreadFunc number -> Thread)
  2911. private static readonly ConcurrentDictionary<long, ThreadInfo> activeThreads = new();
  2912. private static readonly int THREAD_TIMEOUT = 10 * 60 * 1000; // 10 minutes
  2913. /// <summary>
  2914. /// Finds threads in the main thread pool that have timed-out, and aborts them.
  2915. /// </summary>
  2916. private static void ThreadPoolWatchdog(object state)
  2917. {
  2918. foreach (KeyValuePair<long, ThreadInfo> entry in activeThreads)
  2919. {
  2920. ThreadInfo t = entry.Value;
  2921. if (t.DoTimeout && t.Running && !t.Aborted && (t.Elapsed() >= THREAD_TIMEOUT))
  2922. {
  2923. m_log.Warn($"Timeout in threadfunc {t.ThreadFuncNum} ({t.Thread.Name}) {t.GetStackTrace()}");
  2924. t.Abort();
  2925. activeThreads.TryRemove(entry.Key, out _);
  2926. // It's possible that the thread won't abort. To make sure the thread pool isn't
  2927. // depleted, increase the pool size.
  2928. // m_ThreadPool.MaxThreads++;
  2929. }
  2930. }
  2931. }
  2932. public static long TotalFireAndForgetCallsMade { get { return numTotalThreadFuncsCalled; } }
  2933. public static Dictionary<string, int> GetFireAndForgetCallsMade()
  2934. {
  2935. return new Dictionary<string, int>(m_fireAndForgetCallsMade);
  2936. }
  2937. private static readonly Dictionary<string, int> m_fireAndForgetCallsMade = new();
  2938. public static Dictionary<string, int> GetFireAndForgetCallsInProgress()
  2939. {
  2940. return new Dictionary<string, int>(m_fireAndForgetCallsInProgress);
  2941. }
  2942. private static readonly Dictionary<string, int> m_fireAndForgetCallsInProgress = new();
  2943. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2944. public static void FireAndForget(System.Threading.WaitCallback callback)
  2945. {
  2946. FireAndForget(callback, null, null);
  2947. }
  2948. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  2949. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  2950. {
  2951. FireAndForget(callback, obj, null);
  2952. }
  2953. public static void FireAndForget(System.Threading.WaitCallback callback, object obj, string context, bool dotimeout = true)
  2954. {
  2955. Interlocked.Increment(ref numTotalThreadFuncsCalled);
  2956. WaitCallback realCallback;
  2957. bool loggingEnabled = LogThreadPool > 0;
  2958. long threadFuncNum = Interlocked.Increment(ref nextThreadFuncNum);
  2959. ThreadInfo threadInfo = new(threadFuncNum, context, dotimeout);
  2960. if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
  2961. {
  2962. // If we're running regression tests, then we want any exceptions to rise up to the test code.
  2963. realCallback =
  2964. o =>
  2965. {
  2966. Culture.SetCurrentCulture();
  2967. callback(o);
  2968. };
  2969. }
  2970. else
  2971. {
  2972. // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
  2973. // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
  2974. // for decimals places but is read by a culture that treats commas as number seperators.
  2975. realCallback = o =>
  2976. {
  2977. long numQueued1 = Interlocked.Decrement(ref numQueuedThreadFuncs);
  2978. long numRunning1 = Interlocked.Increment(ref numRunningThreadFuncs);
  2979. threadInfo.Started();
  2980. activeThreads[threadFuncNum] = threadInfo;
  2981. try
  2982. {
  2983. if (loggingEnabled && threadInfo.LogThread)
  2984. m_log.DebugFormat("Run threadfunc {0} (Queued {1}, Running {2})", threadFuncNum, numQueued1, numRunning1);
  2985. Culture.SetCurrentCulture();
  2986. callback(o);
  2987. }
  2988. catch (ThreadAbortException)
  2989. {
  2990. }
  2991. catch (Exception e)
  2992. {
  2993. m_log.Error($"[UTIL]: Util STP threadfunc {threadFuncNum} terminated with error {e.Message}");
  2994. }
  2995. finally
  2996. {
  2997. Interlocked.Decrement(ref numRunningThreadFuncs);
  2998. activeThreads.TryRemove(threadFuncNum, out ThreadInfo dummy);
  2999. if (loggingEnabled && threadInfo.LogThread)
  3000. m_log.Debug($"Exit threadfunc {threadFuncNum} ({FormatDuration(threadInfo.Elapsed())}");
  3001. callback = null;
  3002. o = null;
  3003. threadInfo = null;
  3004. }
  3005. };
  3006. }
  3007. Interlocked.Increment(ref numQueuedThreadFuncs);
  3008. try
  3009. {
  3010. threadInfo.LogThread = false;
  3011. switch (FireAndForgetMethod)
  3012. {
  3013. case FireAndForgetMethod.RegressionTest:
  3014. case FireAndForgetMethod.None:
  3015. realCallback.Invoke(obj);
  3016. break;
  3017. case FireAndForgetMethod.QueueUserWorkItem:
  3018. ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
  3019. break;
  3020. case FireAndForgetMethod.SmartThreadPool:
  3021. if (m_ThreadPool == null)
  3022. InitThreadPool(2, 15);
  3023. threadInfo.WorkItem = m_ThreadPool.QueueWorkItem(realCallback, obj);
  3024. break;
  3025. case FireAndForgetMethod.Thread:
  3026. Thread thread = new(delegate (object o) { realCallback(o); realCallback = null; });
  3027. thread.Start(obj);
  3028. break;
  3029. default:
  3030. throw new NotImplementedException();
  3031. }
  3032. }
  3033. catch (Exception)
  3034. {
  3035. Interlocked.Decrement(ref numQueuedThreadFuncs);
  3036. activeThreads.TryRemove(threadFuncNum, out ThreadInfo dummy);
  3037. throw;
  3038. }
  3039. }
  3040. /// <summary>
  3041. /// Returns whether the thread should be logged. Some very common threads aren't logged,
  3042. /// to avoid filling up the log.
  3043. /// </summary>
  3044. /// <param name="stackTrace">A partial stack trace of where the thread was queued</param>
  3045. /// <returns>Whether to log this thread</returns>
  3046. private static bool ShouldLogThread(string stackTrace)
  3047. {
  3048. if (LogThreadPool < 3)
  3049. {
  3050. if (stackTrace.Contains("BeginFireQueueEmpty"))
  3051. return false;
  3052. }
  3053. return true;
  3054. }
  3055. /// <summary>
  3056. /// Returns a stack trace for a thread added using FireAndForget().
  3057. /// </summary>
  3058. /// <param name="full">Will contain the full stack trace</param>
  3059. /// <param name="partial">Will contain only the first frame of the stack trace</param>
  3060. private static void GetFireAndForgetStackTrace(out string full, out string partial)
  3061. {
  3062. string src = Environment.StackTrace;
  3063. string[] lines = src.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
  3064. StringBuilder dest = new(src.Length);
  3065. bool started = false;
  3066. bool first = true;
  3067. partial = "";
  3068. for (int i = 0; i < lines.Length; i++)
  3069. {
  3070. string line = lines[i];
  3071. if (!started)
  3072. {
  3073. // Skip the initial stack frames, because they're of no interest for debugging
  3074. if (line.Contains("StackTrace") || line.Contains("FireAndForget"))
  3075. continue;
  3076. started = true;
  3077. }
  3078. if (first)
  3079. {
  3080. line = line.TrimStart();
  3081. first = false;
  3082. partial = line;
  3083. }
  3084. bool last = (i == lines.Length - 1);
  3085. if (last)
  3086. dest.Append(line);
  3087. else
  3088. dest.AppendLine(line);
  3089. }
  3090. full = dest.ToString();
  3091. }
  3092. /// <summary>
  3093. /// Return the stack trace of a different thread.
  3094. /// </summary>
  3095. /// <remarks>
  3096. /// This is complicated because the thread needs to be paused in order to get its stack
  3097. /// trace. And pausing another thread can cause a deadlock. This method attempts to
  3098. /// avoid deadlock by using a short timeout (200ms), after which it gives up and
  3099. /// returns 'null' instead of the stack trace.
  3100. ///
  3101. /// Take from: http://stackoverflow.com/a/14935378
  3102. ///
  3103. /// WARNING: this doesn't work in Mono. See https://bugzilla.novell.com/show_bug.cgi?id=571691
  3104. ///
  3105. /// </remarks>
  3106. /// <returns>The stack trace, or null if failed to get it</returns>
  3107. private static StackTrace GetStackTrace(Thread targetThread)
  3108. {
  3109. return null;
  3110. /*
  3111. not only this does not work on mono but it is not longer recomended on windows.
  3112. can cause deadlocks etc.
  3113. if (IsPlatformMono)
  3114. {
  3115. // This doesn't work in Mono
  3116. return null;
  3117. }
  3118. ManualResetEventSlim fallbackThreadReady = new ManualResetEventSlim();
  3119. ManualResetEventSlim exitedSafely = new ManualResetEventSlim();
  3120. try
  3121. {
  3122. new Thread(delegate()
  3123. {
  3124. fallbackThreadReady.Set();
  3125. while (!exitedSafely.Wait(200))
  3126. {
  3127. try
  3128. {
  3129. targetThread.Resume();
  3130. }
  3131. catch (Exception)
  3132. {
  3133. // Whatever happens, do never stop to resume the main-thread regularly until the main-thread has exited safely.
  3134. }
  3135. }
  3136. }).Start();
  3137. fallbackThreadReady.Wait();
  3138. // From here, you have about 200ms to get the stack-trace
  3139. targetThread.Suspend();
  3140. StackTrace trace = null;
  3141. try
  3142. {
  3143. trace = new StackTrace(targetThread, true);
  3144. }
  3145. catch (ThreadStateException)
  3146. {
  3147. //failed to get stack trace, since the fallback-thread resumed the thread
  3148. //possible reasons:
  3149. //1.) This thread was just too slow
  3150. //2.) A deadlock ocurred
  3151. //Automatic retry seems too risky here, so just return null.
  3152. }
  3153. try
  3154. {
  3155. targetThread.Resume();
  3156. }
  3157. catch (ThreadStateException)
  3158. {
  3159. // Thread is running again already
  3160. }
  3161. return trace;
  3162. }
  3163. finally
  3164. {
  3165. // Signal the fallack-thread to stop
  3166. exitedSafely.Set();
  3167. }
  3168. */
  3169. }
  3170. /// <summary>
  3171. /// Get information about the current state of the smart thread pool.
  3172. /// </summary>
  3173. /// <returns>
  3174. /// null if this isn't the pool being used for non-scriptengine threads.
  3175. /// </returns>
  3176. public static STPInfo GetSmartThreadPoolInfo()
  3177. {
  3178. if (m_ThreadPool == null)
  3179. return null;
  3180. return new STPInfo()
  3181. {
  3182. Name = m_ThreadPool.Name,
  3183. IsIdle = m_ThreadPool.IsIdle,
  3184. IsShuttingDown = m_ThreadPool.IsShuttingdown,
  3185. MaxThreads = m_ThreadPool.MaxThreads,
  3186. MinThreads = m_ThreadPool.MinThreads,
  3187. InUseThreads = m_ThreadPool.InUseThreads,
  3188. ActiveThreads = m_ThreadPool.ActiveThreads,
  3189. WaitingCallbacks = m_ThreadPool.WaitingCallbacks,
  3190. MaxConcurrentWorkItems = m_ThreadPool.Concurrency
  3191. };
  3192. }
  3193. public static void StopThreadPool()
  3194. {
  3195. if (m_ThreadPool == null)
  3196. return;
  3197. SmartThreadPool pool = m_ThreadPool;
  3198. m_ThreadPool = null;
  3199. try { pool.Shutdown(); } catch { }
  3200. }
  3201. #endregion FireAndForget Threading Pattern
  3202. /// <summary>
  3203. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  3204. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  3205. /// for the callers.
  3206. /// This trims it to a 12 day interval so don't let your frame time get too long.
  3207. /// </summary>
  3208. /// <returns></returns>
  3209. public static Int32 EnvironmentTickCount()
  3210. {
  3211. return Environment.TickCount & EnvironmentTickCountMask;
  3212. }
  3213. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  3214. /// <summary>
  3215. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  3216. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  3217. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  3218. /// </summary>
  3219. /// <param name="newValue"></param>
  3220. /// <param name="prevValue"></param>
  3221. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  3222. public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  3223. {
  3224. Int32 diff = newValue - prevValue;
  3225. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  3226. }
  3227. /// <summary>
  3228. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  3229. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  3230. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  3231. /// </summary>
  3232. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  3233. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  3234. {
  3235. return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
  3236. }
  3237. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  3238. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  3239. // A positive return value indicates A occured later than B
  3240. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  3241. {
  3242. // A, B and TC are all between 0 and 0x3fffffff
  3243. int tc = EnvironmentTickCount();
  3244. if (tc - tcA >= 0)
  3245. tcA += EnvironmentTickCountMask + 1;
  3246. if (tc - tcB >= 0)
  3247. tcB += EnvironmentTickCountMask + 1;
  3248. return tcA - tcB;
  3249. }
  3250. public static long GetPhysicalMemUse()
  3251. {
  3252. using Process p = System.Diagnostics.Process.GetCurrentProcess();
  3253. return p.WorkingSet64;
  3254. }
  3255. // returns a timestamp in seconds as double
  3256. // using the time resolution avaiable to StopWatch
  3257. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  3258. public static double GetTimeStamp()
  3259. {
  3260. return Stopwatch.GetTimestamp() * TimeStampClockPeriod;
  3261. }
  3262. // returns a timestamp in ms as double
  3263. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  3264. public static double GetTimeStampMS()
  3265. {
  3266. return Stopwatch.GetTimestamp() * TimeStampClockPeriodMS;
  3267. }
  3268. // doing math in ticks is usefull to avoid loss of resolution
  3269. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  3270. public static long GetTimeStampTicks()
  3271. {
  3272. return Stopwatch.GetTimestamp();
  3273. }
  3274. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  3275. public static double TimeStampTicksToMS(long ticks)
  3276. {
  3277. return ticks * TimeStampClockPeriodMS;
  3278. }
  3279. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  3280. public static void AddToGatheredIds(Dictionary<UUID, sbyte> uuids, UUID id, sbyte type)
  3281. {
  3282. if (id.IsZero())
  3283. return;
  3284. uuids[id] = type;
  3285. }
  3286. /// <summary>
  3287. /// Formats a duration (given in milliseconds).
  3288. /// </summary>
  3289. public static string FormatDuration(int ms)
  3290. {
  3291. TimeSpan span = new(ms * TimeSpan.TicksPerMillisecond);
  3292. string str = "";
  3293. string suffix = null;
  3294. int hours = (int)span.TotalHours;
  3295. if (hours > 0)
  3296. {
  3297. str += hours.ToString(str.Length == 0 ? "0" : "00");
  3298. suffix = "hours";
  3299. }
  3300. if ((hours > 0) || (span.Minutes > 0))
  3301. {
  3302. if (str.Length > 0)
  3303. str += ":";
  3304. str += span.Minutes.ToString(str.Length == 0 ? "0" : "00");
  3305. suffix ??= "min";
  3306. }
  3307. if ((hours > 0) || (span.Minutes > 0) || (span.Seconds > 0))
  3308. {
  3309. if (str.Length > 0)
  3310. str += ":";
  3311. str += span.Seconds.ToString(str.Length == 0 ? "0" : "00");
  3312. suffix ??= "sec";
  3313. }
  3314. suffix ??= "ms";
  3315. if (span.TotalMinutes < 1)
  3316. {
  3317. int ms1 = span.Milliseconds;
  3318. if (str.Length > 0)
  3319. {
  3320. ms1 /= 100;
  3321. str += ".";
  3322. }
  3323. str += ms1.ToString("0");
  3324. }
  3325. str += " " + suffix;
  3326. return str;
  3327. }
  3328. /// <summary>
  3329. /// Prints the call stack at any given point. Useful for debugging.
  3330. /// </summary>
  3331. public static void PrintCallStack()
  3332. {
  3333. PrintCallStack(m_log.DebugFormat);
  3334. }
  3335. public delegate void DebugPrinter(string msg, params Object[] parm);
  3336. public static void PrintCallStack(DebugPrinter printer)
  3337. {
  3338. StackTrace stackTrace = new(true); // get call stack
  3339. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  3340. // write call stack method names
  3341. foreach (StackFrame stackFrame in stackFrames)
  3342. {
  3343. MethodBase mb = stackFrame.GetMethod();
  3344. printer($"{mb.DeclaringType}.{mb.Name}:{stackFrame.GetFileLineNumber()}"); // write method name
  3345. }
  3346. }
  3347. /// <summary>
  3348. /// Gets the client IP address
  3349. /// </summary>
  3350. /// <param name="xff"></param>
  3351. /// <returns></returns>
  3352. public static IPEndPoint GetClientIPFromXFF(string xff)
  3353. {
  3354. if (xff.Length == 0)
  3355. return null;
  3356. string[] parts = xff.Split(Util.SplitCommaArray);
  3357. if (parts.Length > 0)
  3358. {
  3359. try
  3360. {
  3361. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  3362. }
  3363. catch (Exception e)
  3364. {
  3365. m_log.Warn($"[UTIL]: Exception parsing XFF header {xff}: {e.Message}");
  3366. }
  3367. }
  3368. return null;
  3369. }
  3370. public static string GetCallerIP(Hashtable req)
  3371. {
  3372. if (req.ContainsKey("headers"))
  3373. {
  3374. try
  3375. {
  3376. Hashtable headers = (Hashtable)req["headers"];
  3377. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  3378. return headers["remote_addr"].ToString();
  3379. }
  3380. catch (Exception e)
  3381. {
  3382. m_log.Warn($"[UTIL]: exception in GetCallerIP: {e.Message}");
  3383. }
  3384. }
  3385. return string.Empty;
  3386. }
  3387. #region Xml Serialization Utilities
  3388. public static bool ReadBoolean(XmlReader reader)
  3389. {
  3390. // AuroraSim uses "int" for some fields that are boolean in OpenSim, e.g. "PassCollisions". Don't fail because of this.
  3391. reader.ReadStartElement();
  3392. string val = reader.ReadContentAsString().ToLower();
  3393. bool result = val.Equals("true") || val.Equals("1");
  3394. reader.ReadEndElement();
  3395. return result;
  3396. }
  3397. public static UUID ReadUUID(XmlReader reader, string name)
  3398. {
  3399. reader.ReadStartElement(name);
  3400. string idStr = reader.Name switch
  3401. {
  3402. "Guid" => reader.ReadElementString("Guid"),
  3403. "UUID" => reader.ReadElementString("UUID"),
  3404. // no leading tag
  3405. _ => reader.ReadContentAsString(),
  3406. };
  3407. reader.ReadEndElement();
  3408. _ = UUID.TryParse(idStr, out UUID id);
  3409. return id;
  3410. }
  3411. public static Vector3 ReadVector(XmlReader reader, string name)
  3412. {
  3413. Vector3 vec;
  3414. reader.ReadStartElement(name);
  3415. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  3416. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  3417. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  3418. reader.ReadEndElement();
  3419. return vec;
  3420. }
  3421. public static Quaternion ReadQuaternion(XmlReader reader, string name)
  3422. {
  3423. Quaternion quat = new();
  3424. reader.ReadStartElement(name);
  3425. while (reader.NodeType != XmlNodeType.EndElement)
  3426. {
  3427. switch (reader.Name.ToLower())
  3428. {
  3429. case "x":
  3430. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  3431. break;
  3432. case "y":
  3433. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  3434. break;
  3435. case "z":
  3436. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  3437. break;
  3438. case "w":
  3439. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  3440. break;
  3441. }
  3442. }
  3443. reader.ReadEndElement();
  3444. return quat;
  3445. }
  3446. public static T ReadEnum<T>(XmlReader reader, string name)
  3447. {
  3448. string value = reader.ReadElementContentAsString(name, String.Empty);
  3449. // !!!!! to deal with flags without commas
  3450. if (value.Contains(' ') && !value.Contains(','))
  3451. value = value.Replace(" ", ", ");
  3452. return (T)Enum.Parse(typeof(T), value);
  3453. }
  3454. #endregion
  3455. #region Universal User Identifiers
  3456. /// <summary>
  3457. /// Attempts to parse a UUI into its components: UUID, name and URL.
  3458. /// </summary>
  3459. /// <param name="value">uuid[;endpoint[;first last[;secret]]]</param>
  3460. /// <param name="uuid">the uuid part</param>
  3461. /// <param name="url">the endpoint part (e.g. http://foo.com)</param>
  3462. /// <param name="firstname">the first name part (e.g. Test)</param>
  3463. /// <param name="lastname">the last name part (e.g User)</param>
  3464. /// <param name="secret">the secret part</param>
  3465. public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  3466. {
  3467. secret = string.Empty;
  3468. if (value == null || value.Length == 36)
  3469. {
  3470. url = string.Empty;
  3471. firstname = string.Empty;
  3472. lastname = string.Empty;
  3473. return UUID.TryParse(value, out uuid);
  3474. }
  3475. if (value.Length < 38)
  3476. {
  3477. url = string.Empty;
  3478. firstname = string.Empty;
  3479. lastname = string.Empty;
  3480. uuid = UUID.Zero;
  3481. return false;
  3482. }
  3483. if (!UUID.TryParse(value[..36], out uuid))
  3484. {
  3485. url = string.Empty;
  3486. firstname = string.Empty;
  3487. lastname = string.Empty;
  3488. return false;
  3489. }
  3490. int* seps = stackalloc int[3];
  3491. int nseps = 0;
  3492. for (int i = 36; i < value.Length && nseps < 3; ++i)
  3493. {
  3494. if (value[i] == ';')
  3495. seps[nseps++] = i;
  3496. }
  3497. if (nseps < 2)
  3498. {
  3499. url = string.Empty;
  3500. firstname = string.Empty;
  3501. lastname = string.Empty;
  3502. uuid = UUID.Zero;
  3503. return false;
  3504. }
  3505. int indxA = seps[0] + 1;
  3506. int indxB = seps[1];
  3507. url = value[indxA..indxB].Trim().ToLower();
  3508. ++indxB;
  3509. if (indxB >= value.Length)
  3510. {
  3511. firstname = string.Empty;
  3512. lastname = string.Empty;
  3513. return false;
  3514. }
  3515. string n;
  3516. if (nseps == 2)
  3517. n = value[indxB..].Trim();
  3518. else
  3519. {
  3520. indxA = seps[2];
  3521. n = value[indxB..indxA];
  3522. ++indxA;
  3523. if (indxA < value.Length)
  3524. secret = value[indxA..];
  3525. }
  3526. string[] name = n.Split(SplitSpaceArray, StringSplitOptions.RemoveEmptyEntries);
  3527. if (name.Length == 0)
  3528. {
  3529. firstname = string.Empty;
  3530. lastname = string.Empty;
  3531. return false;
  3532. }
  3533. firstname = name[0];
  3534. lastname = (name.Length > 1) ? name[1] : string.Empty;
  3535. return firstname.Length > 0;
  3536. }
  3537. public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  3538. {
  3539. secret = string.Empty;
  3540. if (value == null || value.Length < 38)
  3541. {
  3542. url = string.Empty;
  3543. firstname = string.Empty;
  3544. lastname = string.Empty;
  3545. uuid = UUID.Zero;
  3546. return false;
  3547. }
  3548. if (!UUID.TryParse(value[..36], out uuid))
  3549. {
  3550. url = string.Empty;
  3551. firstname = string.Empty;
  3552. lastname = string.Empty;
  3553. return false;
  3554. }
  3555. int* seps = stackalloc int[3];
  3556. int nseps = 0;
  3557. for (int i = 36; i < value.Length && nseps < 3; ++i)
  3558. {
  3559. if (value[i] == ';')
  3560. seps[nseps++] = i;
  3561. }
  3562. if (nseps < 2)
  3563. {
  3564. url = string.Empty;
  3565. firstname = string.Empty;
  3566. lastname = string.Empty;
  3567. uuid = UUID.Zero;
  3568. return false;
  3569. }
  3570. int indxA = seps[0] + 1;
  3571. int indxB = seps[1];
  3572. url = value[indxA..indxB].Trim().ToLower();
  3573. ++indxB;
  3574. if (indxB >= value.Length)
  3575. {
  3576. firstname = string.Empty;
  3577. lastname = string.Empty;
  3578. return false;
  3579. }
  3580. string n;
  3581. if (nseps == 2)
  3582. n = value[indxB..].Trim();
  3583. else
  3584. {
  3585. indxA = seps[2];
  3586. n = value[indxB..indxA];
  3587. ++indxA;
  3588. if (indxA < value.Length)
  3589. secret = value[indxA..];
  3590. }
  3591. string[] name = n.Split(SplitSpaceArray, StringSplitOptions.RemoveEmptyEntries);
  3592. if (name.Length == 0)
  3593. {
  3594. firstname = string.Empty;
  3595. lastname = string.Empty;
  3596. return false;
  3597. }
  3598. firstname = name[0];
  3599. lastname = (name.Length > 1) ? name[1] : string.Empty;
  3600. return firstname.Length > 0;
  3601. }
  3602. public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname)
  3603. {
  3604. if (value == null || value.Length == 36)
  3605. {
  3606. url = string.Empty;
  3607. firstname = string.Empty;
  3608. lastname = string.Empty;
  3609. return UUID.TryParse(value, out uuid);
  3610. }
  3611. if (value.Length < 38)
  3612. {
  3613. url = string.Empty;
  3614. firstname = string.Empty;
  3615. lastname = string.Empty;
  3616. uuid = UUID.Zero;
  3617. return false;
  3618. }
  3619. if (!UUID.TryParse(value[..36], out uuid))
  3620. {
  3621. url = string.Empty;
  3622. firstname = string.Empty;
  3623. lastname = string.Empty;
  3624. return false;
  3625. }
  3626. int* seps = stackalloc int[3];
  3627. int nseps = 0;
  3628. for (int i = 36; i < value.Length && nseps < 3; ++i)
  3629. {
  3630. if (value[i] == ';')
  3631. seps[nseps++] = i;
  3632. }
  3633. if (nseps < 2)
  3634. {
  3635. url = string.Empty;
  3636. firstname = string.Empty;
  3637. lastname = string.Empty;
  3638. return false;
  3639. }
  3640. int indxA = seps[0] + 1;
  3641. int indxB = seps[1];
  3642. url = value[indxA..indxB].Trim().ToLower();
  3643. ++indxB;
  3644. if (indxB >= value.Length)
  3645. {
  3646. firstname = string.Empty;
  3647. lastname = string.Empty;
  3648. return false;
  3649. }
  3650. string n;
  3651. if (nseps == 2)
  3652. n = value[indxB..];
  3653. else
  3654. n = value[indxB..seps[2]];
  3655. string[] name = n.Split(SplitSpaceArray, StringSplitOptions.RemoveEmptyEntries);
  3656. if (name.Length == 0)
  3657. {
  3658. firstname = string.Empty;
  3659. lastname = string.Empty;
  3660. return false;
  3661. }
  3662. firstname = name[0];
  3663. lastname = (name.Length > 1) ? name[1] : string.Empty;
  3664. return firstname.Length > 0;
  3665. }
  3666. public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname)
  3667. {
  3668. if (value == null || value.Length < 38)
  3669. {
  3670. url = string.Empty;
  3671. firstname = string.Empty;
  3672. lastname = string.Empty;
  3673. uuid = UUID.Zero;
  3674. return false;
  3675. }
  3676. if (!UUID.TryParse(value[..36], out uuid))
  3677. {
  3678. url = string.Empty;
  3679. firstname = string.Empty;
  3680. lastname = string.Empty;
  3681. return false;
  3682. }
  3683. int* seps = stackalloc int[3];
  3684. int nseps = 0;
  3685. for (int i = 36; i < value.Length && nseps < 3; ++i)
  3686. {
  3687. if (value[i] == ';')
  3688. seps[nseps++] = i;
  3689. }
  3690. if (nseps < 2)
  3691. {
  3692. url = string.Empty;
  3693. firstname = string.Empty;
  3694. lastname = string.Empty;
  3695. return false;
  3696. }
  3697. int indxA = seps[0] + 1;
  3698. int indxB = seps[1];
  3699. url = value[indxA..indxB].Trim().ToLower();
  3700. ++indxB;
  3701. if (indxB >= value.Length)
  3702. {
  3703. firstname = string.Empty;
  3704. lastname = string.Empty;
  3705. return false;
  3706. }
  3707. string n;
  3708. if (nseps == 2)
  3709. n = value[indxB..];
  3710. else
  3711. n = value[indxB..seps[2]];
  3712. string[] name = n.Split(SplitSpaceArray, StringSplitOptions.RemoveEmptyEntries);
  3713. if (name.Length == 0)
  3714. {
  3715. firstname = string.Empty;
  3716. lastname = string.Empty;
  3717. return false;
  3718. }
  3719. firstname = name[0];
  3720. lastname = (name.Length > 1) ? name[1] : string.Empty;
  3721. return firstname.Length > 0;
  3722. }
  3723. public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUID uuid, out string url)
  3724. {
  3725. if (value == null || value.Length < 38)
  3726. {
  3727. url = string.Empty;
  3728. uuid = UUID.Zero;
  3729. return false;
  3730. }
  3731. if (!UUID.TryParse(value[..36], out uuid))
  3732. {
  3733. url = string.Empty;
  3734. return false;
  3735. }
  3736. int* seps = stackalloc int[3];
  3737. int nseps = 0;
  3738. for (int i = 36; i < value.Length && nseps < 3; ++i)
  3739. {
  3740. if (value[i] == ';')
  3741. seps[nseps++] = i;
  3742. }
  3743. if (nseps < 2)
  3744. {
  3745. url = string.Empty;
  3746. uuid = UUID.Zero;
  3747. return false;
  3748. }
  3749. int indxA = seps[0] + 1;
  3750. int indxB = seps[1];
  3751. url = value[indxA..indxB].Trim().ToLower();
  3752. indxA = seps[1] + 3;
  3753. indxB = nseps > 2 ? seps[2] : value.Length;
  3754. return indxA < indxB;
  3755. }
  3756. public static unsafe bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url)
  3757. {
  3758. if (value == null || value.Length < 38)
  3759. {
  3760. url = string.Empty;
  3761. uuid = UUID.Zero;
  3762. return false;
  3763. }
  3764. if (!UUID.TryParse(value[..36], out uuid))
  3765. {
  3766. url = string.Empty;
  3767. return false;
  3768. }
  3769. int* seps = stackalloc int[3];
  3770. int nseps = 0;
  3771. for (int i = 36; i < value.Length && nseps < 3; ++i)
  3772. {
  3773. if (value[i] == ';')
  3774. seps[nseps++] = i;
  3775. }
  3776. if (nseps < 2)
  3777. {
  3778. url = string.Empty;
  3779. uuid = UUID.Zero;
  3780. return false;
  3781. }
  3782. int indxA = seps[0] + 1;
  3783. int indxB = seps[1];
  3784. url = value[indxA..indxB].Trim().ToLower();
  3785. return true;
  3786. }
  3787. public static unsafe bool ParseFullUniversalUserIdentifier(string value, out UUID uuid)
  3788. {
  3789. if (value == null || value.Length < 38)
  3790. {
  3791. uuid = UUID.Zero;
  3792. return false;
  3793. }
  3794. int nseps = 0;
  3795. int* seps = stackalloc int[3];
  3796. for (int i = 36; i < value.Length && nseps < 3; ++i)
  3797. {
  3798. if (value[i] == ';')
  3799. seps[nseps++] = i;
  3800. }
  3801. if (nseps < 2)
  3802. {
  3803. uuid = UUID.Zero;
  3804. return false;
  3805. }
  3806. if (!UUID.TryParse(value[..seps[0]], out uuid))
  3807. return false;
  3808. int indxA = seps[1] + 3;
  3809. int indxB = nseps > 2 ? seps[2] : value.Length;
  3810. return indxA < indxB;
  3811. }
  3812. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid)
  3813. {
  3814. if (value == null || value.Length < 36)
  3815. {
  3816. uuid = UUID.Zero;
  3817. return false;
  3818. }
  3819. return (value.Length == 36) ? UUID.TryParse(value, out uuid) : UUID.TryParse(value[..36], out uuid);
  3820. }
  3821. public static unsafe string RemoveUniversalUserIdentifierSecret(string value)
  3822. {
  3823. if (value.Length < 39)
  3824. return value;
  3825. int nseps = 0;
  3826. int* seps = stackalloc int[3];
  3827. for (int i = 36; i < value.Length && nseps < 3; ++i)
  3828. {
  3829. if (value[i] == ';')
  3830. seps[nseps++] = i;
  3831. }
  3832. if (nseps < 3)
  3833. return value;
  3834. return value[..seps[3]];
  3835. }
  3836. /// <summary>
  3837. /// For foreign avatars, extracts their original name and Server URL from their First Name and Last Name.
  3838. /// </summary>
  3839. public static bool ParseForeignAvatarName(string firstname, string lastname,
  3840. out string realFirstName, out string realLastName, out string serverURI)
  3841. {
  3842. realFirstName = realLastName = serverURI = string.Empty;
  3843. if (!lastname.Contains('@'))
  3844. return false;
  3845. string[] parts = firstname.Split('.');
  3846. if (parts.Length != 2)
  3847. return false;
  3848. realFirstName = parts[0].Trim();
  3849. realLastName = parts[1].Trim();
  3850. lastname = lastname.Trim();
  3851. serverURI = new Uri($"http://{lastname.Replace("@", "")}").ToString();
  3852. return true;
  3853. }
  3854. public static int ParseAvatarName(string name, out string FirstName, out string LastName, out string serverURI)
  3855. {
  3856. FirstName = LastName = serverURI = string.Empty;
  3857. if (string.IsNullOrWhiteSpace(name) || name.Length < 1)
  3858. return 0;
  3859. int i = 0;
  3860. bool havedot = false;
  3861. while (i < name.Length && name[i] == ' ') ++i;
  3862. int start = i;
  3863. while (i < name.Length)
  3864. {
  3865. char c = name[i];
  3866. if (c == '@')
  3867. return 0;
  3868. if (c == ' ')
  3869. {
  3870. if (i >= name.Length - 1 || i == start)
  3871. return 0;
  3872. break;
  3873. }
  3874. if (c == '.')
  3875. {
  3876. if (i >= name.Length - 1 || i == start)
  3877. return 0;
  3878. havedot = true;
  3879. break;
  3880. }
  3881. ++i;
  3882. }
  3883. FirstName = name[start..i];
  3884. if (i >= name.Length - 1)
  3885. return 1;
  3886. ++i;
  3887. while (i < name.Length && name[i] == ' ') ++i;
  3888. if (i == name.Length)
  3889. return 1;
  3890. start = i;
  3891. while (i < name.Length)
  3892. {
  3893. char c = name[i];
  3894. if (c == '.')
  3895. {
  3896. if (havedot || i >= name.Length - 1)
  3897. return 0;
  3898. else start = i + 1;
  3899. }
  3900. else if (c == '@')
  3901. {
  3902. if (i >= name.Length - 1)
  3903. return 0;
  3904. int j = i;
  3905. while (j > start && name[j - 1] == ' ') --j;
  3906. if (j <= start)
  3907. return 0;
  3908. LastName = name[start..j];
  3909. ++i;
  3910. while (i < name.Length && name[i] == ' ') ++i;
  3911. if (i > name.Length - 3)
  3912. return 0;
  3913. serverURI = name[i..].TrimEnd();
  3914. return serverURI.Length == 0 ? 2 : 3;
  3915. }
  3916. ++i;
  3917. }
  3918. LastName = name[start..].TrimEnd();
  3919. return LastName.Length == 0 ? 1 : 2;
  3920. }
  3921. /// <summary>
  3922. /// Produces a universal (HG) system-facing identifier given the information
  3923. /// </summary>
  3924. /// <param name="acircuit"></param>
  3925. /// <returns>uuid[;homeURI[;first last]]</returns>
  3926. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  3927. {
  3928. if (acircuit.ServiceURLs.TryGetValue("HomeURI", out object homeobj))
  3929. return UniversalIdentifier(acircuit.AgentID, acircuit.firstname, acircuit.lastname, homeobj.ToString());
  3930. else
  3931. return acircuit.AgentID.ToString();
  3932. }
  3933. /// <summary>
  3934. /// Produces a universal (HG) system-facing identifier given the information
  3935. /// </summary>
  3936. /// <param name="id">UUID of the user</param>
  3937. /// <param name="firstName">first name (e.g Test)</param>
  3938. /// <param name="lastName">last name (e.g. User)</param>
  3939. /// <param name="homeURI">homeURI (e.g. http://foo.com)</param>
  3940. /// <returns>a string of the form uuid[;homeURI[;first last]]</returns>
  3941. public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
  3942. {
  3943. string agentsURI = homeURI;
  3944. if (!agentsURI.EndsWith('/'))
  3945. agentsURI += "/";
  3946. // This is ugly, but there's no other way, given that the name is changed
  3947. // in the agent circuit data for foreigners
  3948. if (lastName.Contains('@'))
  3949. {
  3950. string[] parts = firstName.Split(Util.SplitDotArray);
  3951. if (parts.Length == 2)
  3952. return CalcUniversalIdentifier(id, agentsURI, parts[0].Trim() + " " + parts[1].Trim());
  3953. }
  3954. return CalcUniversalIdentifier(id, agentsURI, firstName.Trim() + " " + lastName.Trim());
  3955. }
  3956. private static string CalcUniversalIdentifier(UUID id, string agentsURI, string name)
  3957. {
  3958. return id.ToString() + ";" + agentsURI + ";" + name;
  3959. }
  3960. /// <summary>
  3961. /// Produces a universal (HG) user-facing name given the information
  3962. /// </summary>
  3963. /// <param name="firstName"></param>
  3964. /// <param name="lastName"></param>
  3965. /// <param name="homeURI"></param>
  3966. /// <returns>string of the form first.last @foo.com or first last</returns>
  3967. public static string UniversalName(String firstName, String lastName, String homeURI)
  3968. {
  3969. Uri uri;
  3970. try
  3971. {
  3972. uri = new Uri(homeURI);
  3973. }
  3974. catch (UriFormatException)
  3975. {
  3976. return $"{firstName.Trim()} {lastName.Trim()}";
  3977. }
  3978. return $"{firstName.Trim()}.{lastName.Trim()}@{uri.Authority}";
  3979. }
  3980. #endregion
  3981. /// <summary>
  3982. /// Escapes the special characters used in "LIKE".
  3983. /// </summary>
  3984. /// <remarks>
  3985. /// For example: EscapeForLike("foo_bar%baz") = "foo\_bar\%baz"
  3986. /// </remarks>
  3987. public static string EscapeForLike(string str)
  3988. {
  3989. return str.Replace("_", "\\_").Replace("%", "\\%");
  3990. }
  3991. /// <summary>
  3992. /// Returns the name of the user's viewer.
  3993. /// </summary>
  3994. /// <remarks>
  3995. /// This method handles two ways that viewers specify their name:
  3996. /// 1. Viewer = "Firestorm-Release 4.4.2.34167", Channel = "(don't care)" -> "Firestorm-Release 4.4.2.34167"
  3997. /// 2. Viewer = "4.5.1.38838", Channel = "Firestorm-Beta" -> "Firestorm-Beta 4.5.1.38838"
  3998. /// </remarks>
  3999. public static string GetViewerName(AgentCircuitData agent)
  4000. {
  4001. string name = agent.Viewer;
  4002. if (name == null)
  4003. name = "";
  4004. else
  4005. name = name.Trim();
  4006. // Check if 'Viewer' is just a version number. If it's *not*, then we
  4007. // assume that it contains the real viewer name, and we return it.
  4008. foreach (char c in name)
  4009. {
  4010. if (Char.IsLetter(c))
  4011. return name;
  4012. }
  4013. // The 'Viewer' string contains just a version number. If there's anything in
  4014. // 'Channel' then assume that it's the viewer name.
  4015. if ((agent.Channel != null) && (agent.Channel.Length > 0))
  4016. name = agent.Channel.Trim() + " " + name;
  4017. return name;
  4018. }
  4019. public static void LogFailedXML(string message, string xml)
  4020. {
  4021. int length = xml.Length;
  4022. if (length > 250)
  4023. xml = xml[..250] + "...";
  4024. for (int i = 0; i < xml.Length; i++)
  4025. {
  4026. if (xml[i] < 0x20)
  4027. {
  4028. xml = "Unprintable binary data";
  4029. break;
  4030. }
  4031. }
  4032. m_log.Error($"{message} Failed XML ({length} bytes) = {xml}");
  4033. }
  4034. /// <summary>
  4035. /// Performs a high quality image resize
  4036. /// </summary>
  4037. /// <param name="image">Image to resize</param>
  4038. /// <param name="width">New width</param>
  4039. /// <param name="height">New height</param>
  4040. /// <returns>Resized image</returns>
  4041. public static Bitmap ResizeImageSolid(Image image, int width, int height)
  4042. {
  4043. Bitmap result = new(width, height, PixelFormat.Format24bppRgb);
  4044. using (ImageAttributes atrib = new())
  4045. using (Graphics graphics = Graphics.FromImage(result))
  4046. {
  4047. atrib.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
  4048. graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
  4049. graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
  4050. graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  4051. graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
  4052. graphics.DrawImage(image, new Rectangle(0, 0, result.Width, result.Height),
  4053. 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, atrib);
  4054. }
  4055. return result;
  4056. }
  4057. public static void SaveAssetToFile(string filename, byte[] data)
  4058. {
  4059. string assetPath = "UserAssets";
  4060. if (!Directory.Exists(assetPath))
  4061. {
  4062. Directory.CreateDirectory(assetPath);
  4063. }
  4064. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  4065. BinaryWriter bw = new(fs);
  4066. bw.Write(data);
  4067. bw.Close();
  4068. fs.Close();
  4069. }
  4070. //https://www.color.org/sRGB.pdf
  4071. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4072. public static float LinearTosRGB(float linear)
  4073. {
  4074. return linear <= 0.0031308f ? (linear * 12.92f) : (1.055f * MathF.Pow(linear, 0.4166667f) - 0.055f);
  4075. }
  4076. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  4077. public static float sRGBtoLinear(float rgb)
  4078. {
  4079. return (rgb < 0.04045f) ? rgb * 0.07739938f : MathF.Pow((rgb + 0.055f) / 1.055f, 2.4f);
  4080. }
  4081. }
  4082. }