Util.cs 126 KB

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