Util.cs 125 KB

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