Util.cs 105 KB

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