Util.cs 126 KB

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