1
0

Util.cs 103 KB

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