Util.cs 107 KB

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