Util.cs 125 KB

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