Util.cs 157 KB

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