Util.cs 133 KB

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