1
0

Util.cs 143 KB

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