Util.cs 114 KB

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