Util.cs 129 KB

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