Util.cs 122 KB

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