1
0

Util.cs 103 KB

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