Util.cs 140 KB

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