Util.cs 108 KB

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