Util.cs 125 KB

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