Util.cs 140 KB

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