1
0

Util.cs 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Data;
  31. using System.Diagnostics;
  32. using System.Globalization;
  33. using System.IO;
  34. using System.IO.Compression;
  35. using System.Net;
  36. using System.Net.Sockets;
  37. using System.Reflection;
  38. using System.Runtime.InteropServices;
  39. using System.Runtime.Serialization;
  40. using System.Runtime.Serialization.Formatters.Binary;
  41. using System.Security.Cryptography;
  42. using System.Text;
  43. using System.Text.RegularExpressions;
  44. using System.Xml;
  45. using System.Threading;
  46. using log4net;
  47. using Nini.Config;
  48. using Nwc.XmlRpc;
  49. using OpenMetaverse;
  50. using OpenMetaverse.StructuredData;
  51. using Amib.Threading;
  52. namespace OpenSim.Framework
  53. {
  54. /// <summary>
  55. /// The method used by Util.FireAndForget for asynchronously firing events
  56. /// </summary>
  57. /// <remarks>
  58. /// None is used to execute the method in the same thread that made the call. It should only be used by regression
  59. /// test code that relies on predictable event ordering.
  60. /// RegressionTest is used by regression tests. It fires the call synchronously and does not catch any exceptions.
  61. /// </remarks>
  62. public enum FireAndForgetMethod
  63. {
  64. None,
  65. RegressionTest,
  66. UnsafeQueueUserWorkItem,
  67. QueueUserWorkItem,
  68. BeginInvoke,
  69. SmartThreadPool,
  70. Thread,
  71. }
  72. /// <summary>
  73. /// Miscellaneous utility functions
  74. /// </summary>
  75. public class Util
  76. {
  77. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  78. private static uint nextXferID = 5000;
  79. private static Random randomClass = new Random();
  80. // Get a list of invalid file characters (OS dependent)
  81. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  82. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  83. private static object XferLock = new object();
  84. /// <summary>
  85. /// Thread pool used for Util.FireAndForget if FireAndForgetMethod.SmartThreadPool is used
  86. /// </summary>
  87. private static SmartThreadPool m_ThreadPool;
  88. // 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.
  89. private static readonly DateTime unixEpoch =
  90. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  91. private static readonly string rawUUIDPattern
  92. = "[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}";
  93. public static readonly Regex PermissiveUUIDPattern = new Regex(rawUUIDPattern);
  94. public static readonly Regex UUIDPattern = new Regex(string.Format("^{0}$", rawUUIDPattern));
  95. public static FireAndForgetMethod DefaultFireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
  96. public static FireAndForgetMethod FireAndForgetMethod = DefaultFireAndForgetMethod;
  97. /// <summary>
  98. /// Gets the name of the directory where the current running executable
  99. /// is located
  100. /// </summary>
  101. /// <returns>Filesystem path to the directory containing the current
  102. /// executable</returns>
  103. public static string ExecutingDirectory()
  104. {
  105. return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  106. }
  107. /// <summary>
  108. /// Linear interpolates B<->C using percent A
  109. /// </summary>
  110. /// <param name="a"></param>
  111. /// <param name="b"></param>
  112. /// <param name="c"></param>
  113. /// <returns></returns>
  114. public static double lerp(double a, double b, double c)
  115. {
  116. return (b*a) + (c*(1 - a));
  117. }
  118. /// <summary>
  119. /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
  120. /// Layout:
  121. /// A B
  122. /// C D
  123. /// A<->C = Y
  124. /// C<->D = X
  125. /// </summary>
  126. /// <param name="x"></param>
  127. /// <param name="y"></param>
  128. /// <param name="a"></param>
  129. /// <param name="b"></param>
  130. /// <param name="c"></param>
  131. /// <param name="d"></param>
  132. /// <returns></returns>
  133. public static double lerp2D(double x, double y, double a, double b, double c, double d)
  134. {
  135. return lerp(y, lerp(x, a, b), lerp(x, c, d));
  136. }
  137. public static Encoding UTF8 = Encoding.UTF8;
  138. public static Encoding UTF8NoBomEncoding = new UTF8Encoding(false);
  139. /// <value>
  140. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  141. /// </value>
  142. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  143. #region Vector Equations
  144. /// <summary>
  145. /// Get the distance between two 3d vectors
  146. /// </summary>
  147. /// <param name="a">A 3d vector</param>
  148. /// <param name="b">A 3d vector</param>
  149. /// <returns>The distance between the two vectors</returns>
  150. public static double GetDistanceTo(Vector3 a, Vector3 b)
  151. {
  152. float dx = a.X - b.X;
  153. float dy = a.Y - b.Y;
  154. float dz = a.Z - b.Z;
  155. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  156. }
  157. /// <summary>
  158. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  159. /// </summary>
  160. /// <param name="a"></param>
  161. /// <param name="b"></param>
  162. /// <param name="amount"></param>
  163. /// <returns></returns>
  164. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  165. {
  166. float dx = a.X - b.X;
  167. float dy = a.Y - b.Y;
  168. float dz = a.Z - b.Z;
  169. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  170. }
  171. /// <summary>
  172. /// Get the magnitude of a 3d vector
  173. /// </summary>
  174. /// <param name="a">A 3d vector</param>
  175. /// <returns>The magnitude of the vector</returns>
  176. public static double GetMagnitude(Vector3 a)
  177. {
  178. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  179. }
  180. /// <summary>
  181. /// Get a normalized form of a 3d vector
  182. /// </summary>
  183. /// <param name="a">A 3d vector</param>
  184. /// <returns>A new vector which is normalized form of the vector</returns>
  185. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  186. public static Vector3 GetNormalizedVector(Vector3 a)
  187. {
  188. if (IsZeroVector(a))
  189. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  190. float Mag = (float) GetMagnitude(a);
  191. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  192. }
  193. /// <summary>
  194. /// Returns if a vector is a zero vector (has all zero components)
  195. /// </summary>
  196. /// <returns></returns>
  197. public static bool IsZeroVector(Vector3 v)
  198. {
  199. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  200. {
  201. return true;
  202. }
  203. return false;
  204. }
  205. # endregion
  206. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  207. {
  208. float s;
  209. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  210. if (tr >= 1.0)
  211. {
  212. s = (float) (0.5 / Math.Sqrt(tr));
  213. return new Quaternion(
  214. (left.Z - up.Y) * s,
  215. (up.X - fwd.Z) * s,
  216. (fwd.Y - left.X) * s,
  217. (float) 0.25 / s);
  218. }
  219. else
  220. {
  221. float max = (left.Y > up.Z) ? left.Y : up.Z;
  222. if (max < fwd.X)
  223. {
  224. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  225. float x = (float) (s * 0.5);
  226. s = (float) (0.5 / s);
  227. return new Quaternion(
  228. x,
  229. (fwd.Y + left.X) * s,
  230. (up.X + fwd.Z) * s,
  231. (left.Z - up.Y) * s);
  232. }
  233. else if (max == left.Y)
  234. {
  235. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  236. float y = (float) (s * 0.5);
  237. s = (float) (0.5 / s);
  238. return new Quaternion(
  239. (fwd.Y + left.X) * s,
  240. y,
  241. (left.Z + up.Y) * s,
  242. (up.X - fwd.Z) * s);
  243. }
  244. else
  245. {
  246. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  247. float z = (float) (s * 0.5);
  248. s = (float) (0.5 / s);
  249. return new Quaternion(
  250. (up.X + fwd.Z) * s,
  251. (left.Z + up.Y) * s,
  252. z,
  253. (fwd.Y - left.X) * s);
  254. }
  255. }
  256. }
  257. public static Random RandomClass
  258. {
  259. get { return randomClass; }
  260. }
  261. public static ulong UIntsToLong(uint X, uint Y)
  262. {
  263. return Utils.UIntsToLong(X, Y);
  264. }
  265. public static T Clamp<T>(T x, T min, T max)
  266. where T : IComparable<T>
  267. {
  268. return x.CompareTo(max) > 0 ? max :
  269. x.CompareTo(min) < 0 ? min :
  270. x;
  271. }
  272. public static uint GetNextXferID()
  273. {
  274. uint id = 0;
  275. lock (XferLock)
  276. {
  277. id = nextXferID;
  278. nextXferID++;
  279. }
  280. return id;
  281. }
  282. public static string GetFileName(string file)
  283. {
  284. // Return just the filename on UNIX platforms
  285. // TODO: this should be customisable with a prefix, but that's something to do later.
  286. if (Environment.OSVersion.Platform == PlatformID.Unix)
  287. {
  288. return file;
  289. }
  290. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  291. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  292. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  293. {
  294. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  295. {
  296. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  297. }
  298. return "%APPDATA%\\OpenSim\\" + file;
  299. }
  300. // Catch all - covers older windows versions
  301. // (but those probably wont work anyway)
  302. return file;
  303. }
  304. /// <summary>
  305. /// Debug utility function to convert OSD into formatted XML for debugging purposes.
  306. /// </summary>
  307. /// <param name="osd">
  308. /// A <see cref="OSD"/>
  309. /// </param>
  310. /// <returns>
  311. /// A <see cref="System.String"/>
  312. /// </returns>
  313. public static string GetFormattedXml(OSD osd)
  314. {
  315. return GetFormattedXml(OSDParser.SerializeLLSDXmlString(osd));
  316. }
  317. /// <summary>
  318. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  319. /// </summary>
  320. /// <remarks>
  321. /// Please don't delete me even if I appear currently unused!
  322. /// </remarks>
  323. /// <param name="rawXml"></param>
  324. /// <returns></returns>
  325. public static string GetFormattedXml(string rawXml)
  326. {
  327. XmlDocument xd = new XmlDocument();
  328. xd.LoadXml(rawXml);
  329. StringBuilder sb = new StringBuilder();
  330. StringWriter sw = new StringWriter(sb);
  331. XmlTextWriter xtw = new XmlTextWriter(sw);
  332. xtw.Formatting = Formatting.Indented;
  333. try
  334. {
  335. xd.WriteTo(xtw);
  336. }
  337. finally
  338. {
  339. xtw.Close();
  340. }
  341. return sb.ToString();
  342. }
  343. /// <summary>
  344. /// Is the platform Windows?
  345. /// </summary>
  346. /// <returns>true if so, false otherwise</returns>
  347. public static bool IsWindows()
  348. {
  349. PlatformID platformId = Environment.OSVersion.Platform;
  350. return (platformId == PlatformID.Win32NT
  351. || platformId == PlatformID.Win32S
  352. || platformId == PlatformID.Win32Windows
  353. || platformId == PlatformID.WinCE);
  354. }
  355. public static bool LoadArchSpecificWindowsDll(string libraryName)
  356. {
  357. // We do this so that OpenSimulator on Windows loads the correct native library depending on whether
  358. // it's running as a 32-bit process or a 64-bit one. By invoking LoadLibary here, later DLLImports
  359. // will find it already loaded later on.
  360. //
  361. // This isn't necessary for other platforms (e.g. Mac OSX and Linux) since the DLL used can be
  362. // controlled in config files.
  363. string nativeLibraryPath;
  364. if (Util.Is64BitProcess())
  365. nativeLibraryPath = "lib64/" + libraryName;
  366. else
  367. nativeLibraryPath = "lib32/" + libraryName;
  368. m_log.DebugFormat("[UTIL]: Loading native Windows library at {0}", nativeLibraryPath);
  369. if (Util.LoadLibrary(nativeLibraryPath) == IntPtr.Zero)
  370. {
  371. m_log.ErrorFormat(
  372. "[UTIL]: Couldn't find native Windows library at {0}", nativeLibraryPath);
  373. return false;
  374. }
  375. else
  376. {
  377. return true;
  378. }
  379. }
  380. public static bool IsEnvironmentSupported(ref string reason)
  381. {
  382. // Must have .NET 2.0 (Generics / libsl)
  383. if (Environment.Version.Major < 2)
  384. {
  385. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  386. return false;
  387. }
  388. // Windows 95/98/ME are unsupported
  389. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  390. Environment.OSVersion.Platform != PlatformID.Win32NT)
  391. {
  392. reason = "Windows 95/98/ME will not run OpenSim";
  393. return false;
  394. }
  395. // Windows 2000 / Pre-SP2 XP
  396. if (Environment.OSVersion.Version.Major == 5 &&
  397. Environment.OSVersion.Version.Minor == 0)
  398. {
  399. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  400. return false;
  401. }
  402. return true;
  403. }
  404. public static int UnixTimeSinceEpoch()
  405. {
  406. return ToUnixTime(DateTime.UtcNow);
  407. }
  408. public static int ToUnixTime(DateTime stamp)
  409. {
  410. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  411. return (int) t.TotalSeconds;
  412. }
  413. public static DateTime ToDateTime(ulong seconds)
  414. {
  415. DateTime epoch = unixEpoch;
  416. return epoch.AddSeconds(seconds);
  417. }
  418. public static DateTime ToDateTime(int seconds)
  419. {
  420. DateTime epoch = unixEpoch;
  421. return epoch.AddSeconds(seconds);
  422. }
  423. /// <summary>
  424. /// Return an md5 hash of the given string
  425. /// </summary>
  426. /// <param name="data"></param>
  427. /// <returns></returns>
  428. public static string Md5Hash(string data)
  429. {
  430. byte[] dataMd5 = ComputeMD5Hash(data);
  431. StringBuilder sb = new StringBuilder();
  432. for (int i = 0; i < dataMd5.Length; i++)
  433. sb.AppendFormat("{0:x2}", dataMd5[i]);
  434. return sb.ToString();
  435. }
  436. private static byte[] ComputeMD5Hash(string data)
  437. {
  438. MD5 md5 = MD5.Create();
  439. return md5.ComputeHash(Encoding.Default.GetBytes(data));
  440. }
  441. /// <summary>
  442. /// Return an SHA1 hash
  443. /// </summary>
  444. /// <param name="data"></param>
  445. /// <returns></returns>
  446. public static string SHA1Hash(string data)
  447. {
  448. return SHA1Hash(Encoding.Default.GetBytes(data));
  449. }
  450. /// <summary>
  451. /// Return an SHA1 hash
  452. /// </summary>
  453. /// <param name="data"></param>
  454. /// <returns></returns>
  455. public static string SHA1Hash(byte[] data)
  456. {
  457. byte[] hash = ComputeSHA1Hash(data);
  458. return BitConverter.ToString(hash).Replace("-", String.Empty);
  459. }
  460. private static byte[] ComputeSHA1Hash(byte[] src)
  461. {
  462. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  463. return SHA1.ComputeHash(src);
  464. }
  465. public static int fast_distance2d(int x, int y)
  466. {
  467. x = Math.Abs(x);
  468. y = Math.Abs(y);
  469. int min = Math.Min(x, y);
  470. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  471. }
  472. /// <summary>
  473. /// Determines whether a point is inside a bounding box.
  474. /// </summary>
  475. /// <param name='v'></param>
  476. /// <param name='min'></param>
  477. /// <param name='max'></param>
  478. /// <returns></returns>
  479. public static bool IsInsideBox(Vector3 v, Vector3 min, Vector3 max)
  480. {
  481. return v.X >= min.X & v.Y >= min.Y && v.Z >= min.Z
  482. && v.X <= max.X && v.Y <= max.Y && v.Z <= max.Z;
  483. }
  484. /// <summary>
  485. /// Are the co-ordinates of the new region visible from the old region?
  486. /// </summary>
  487. /// <param name="oldx">Old region x-coord</param>
  488. /// <param name="newx">New region x-coord</param>
  489. /// <param name="oldy">Old region y-coord</param>
  490. /// <param name="newy">New region y-coord</param>
  491. /// <returns></returns>
  492. public static bool IsOutsideView(float drawdist, uint oldx, uint newx, uint oldy, uint newy)
  493. {
  494. int dd = (int)((drawdist + Constants.RegionSize - 1) / Constants.RegionSize);
  495. int startX = (int)oldx - dd;
  496. int startY = (int)oldy - dd;
  497. int endX = (int)oldx + dd;
  498. int endY = (int)oldy + dd;
  499. return (newx < startX || endX < newx || newy < startY || endY < newy);
  500. }
  501. public static string FieldToString(byte[] bytes)
  502. {
  503. return FieldToString(bytes, String.Empty);
  504. }
  505. /// <summary>
  506. /// Convert a variable length field (byte array) to a string, with a
  507. /// field name prepended to each line of the output
  508. /// </summary>
  509. /// <remarks>If the byte array has unprintable characters in it, a
  510. /// hex dump will be put in the string instead</remarks>
  511. /// <param name="bytes">The byte array to convert to a string</param>
  512. /// <param name="fieldName">A field name to prepend to each line of output</param>
  513. /// <returns>An ASCII string or a string containing a hex dump, minus
  514. /// the null terminator</returns>
  515. public static string FieldToString(byte[] bytes, string fieldName)
  516. {
  517. // Check for a common case
  518. if (bytes.Length == 0) return String.Empty;
  519. StringBuilder output = new StringBuilder();
  520. bool printable = true;
  521. for (int i = 0; i < bytes.Length; ++i)
  522. {
  523. // Check if there are any unprintable characters in the array
  524. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  525. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  526. {
  527. printable = false;
  528. break;
  529. }
  530. }
  531. if (printable)
  532. {
  533. if (fieldName.Length > 0)
  534. {
  535. output.Append(fieldName);
  536. output.Append(": ");
  537. }
  538. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  539. }
  540. else
  541. {
  542. for (int i = 0; i < bytes.Length; i += 16)
  543. {
  544. if (i != 0)
  545. output.Append(Environment.NewLine);
  546. if (fieldName.Length > 0)
  547. {
  548. output.Append(fieldName);
  549. output.Append(": ");
  550. }
  551. for (int j = 0; j < 16; j++)
  552. {
  553. if ((i + j) < bytes.Length)
  554. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  555. else
  556. output.Append(" ");
  557. }
  558. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  559. {
  560. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  561. output.Append((char) bytes[i + j]);
  562. else
  563. output.Append(".");
  564. }
  565. }
  566. }
  567. return output.ToString();
  568. }
  569. /// <summary>
  570. /// Converts a URL to a IPAddress
  571. /// </summary>
  572. /// <param name="url">URL Standard Format</param>
  573. /// <returns>A resolved IP Address</returns>
  574. public static IPAddress GetHostFromURL(string url)
  575. {
  576. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  577. }
  578. /// <summary>
  579. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  580. /// </summary>
  581. /// <param name="dnsAddress">DNS Hostname</param>
  582. /// <returns>An IP address, or null</returns>
  583. public static IPAddress GetHostFromDNS(string dnsAddress)
  584. {
  585. // Is it already a valid IP? No need to look it up.
  586. IPAddress ipa;
  587. if (IPAddress.TryParse(dnsAddress, out ipa))
  588. return ipa;
  589. IPAddress[] hosts = null;
  590. // Not an IP, lookup required
  591. try
  592. {
  593. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  594. }
  595. catch (Exception e)
  596. {
  597. m_log.WarnFormat("[UTIL]: An error occurred while resolving host name {0}, {1}", dnsAddress, e);
  598. // Still going to throw the exception on for now, since this was what was happening in the first place
  599. throw e;
  600. }
  601. foreach (IPAddress host in hosts)
  602. {
  603. if (host.AddressFamily == AddressFamily.InterNetwork)
  604. {
  605. return host;
  606. }
  607. }
  608. if (hosts.Length > 0)
  609. return hosts[0];
  610. return null;
  611. }
  612. public static Uri GetURI(string protocol, string hostname, int port, string path)
  613. {
  614. return new UriBuilder(protocol, hostname, port, path).Uri;
  615. }
  616. /// <summary>
  617. /// Gets a list of all local system IP addresses
  618. /// </summary>
  619. /// <returns></returns>
  620. public static IPAddress[] GetLocalHosts()
  621. {
  622. return Dns.GetHostAddresses(Dns.GetHostName());
  623. }
  624. public static IPAddress GetLocalHost()
  625. {
  626. IPAddress[] iplist = GetLocalHosts();
  627. if (iplist.Length == 0) // No accessible external interfaces
  628. {
  629. IPAddress[] loopback = Dns.GetHostAddresses("localhost");
  630. IPAddress localhost = loopback[0];
  631. return localhost;
  632. }
  633. foreach (IPAddress host in iplist)
  634. {
  635. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  636. {
  637. return host;
  638. }
  639. }
  640. if (iplist.Length > 0)
  641. {
  642. foreach (IPAddress host in iplist)
  643. {
  644. if (host.AddressFamily == AddressFamily.InterNetwork)
  645. return host;
  646. }
  647. // Well all else failed...
  648. return iplist[0];
  649. }
  650. return null;
  651. }
  652. /// <summary>
  653. /// Removes all invalid path chars (OS dependent)
  654. /// </summary>
  655. /// <param name="path">path</param>
  656. /// <returns>safe path</returns>
  657. public static string safePath(string path)
  658. {
  659. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  660. }
  661. /// <summary>
  662. /// Removes all invalid filename chars (OS dependent)
  663. /// </summary>
  664. /// <param name="path">filename</param>
  665. /// <returns>safe filename</returns>
  666. public static string safeFileName(string filename)
  667. {
  668. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  669. ;
  670. }
  671. //
  672. // directory locations
  673. //
  674. public static string homeDir()
  675. {
  676. string temp;
  677. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  678. // temp = Path.Combine(personal,".OpenSim");
  679. temp = ".";
  680. return temp;
  681. }
  682. public static string assetsDir()
  683. {
  684. return Path.Combine(configDir(), "assets");
  685. }
  686. public static string inventoryDir()
  687. {
  688. return Path.Combine(configDir(), "inventory");
  689. }
  690. public static string configDir()
  691. {
  692. return ".";
  693. }
  694. public static string dataDir()
  695. {
  696. return ".";
  697. }
  698. public static string logDir()
  699. {
  700. return ".";
  701. }
  702. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  703. public static string GetUniqueFilename(string FileName)
  704. {
  705. int count = 0;
  706. string Name;
  707. if (File.Exists(FileName))
  708. {
  709. FileInfo f = new FileInfo(FileName);
  710. if (!String.IsNullOrEmpty(f.Extension))
  711. {
  712. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  713. }
  714. else
  715. {
  716. Name = f.FullName;
  717. }
  718. while (File.Exists(FileName))
  719. {
  720. count++;
  721. FileName = Name + count + f.Extension;
  722. }
  723. }
  724. return FileName;
  725. }
  726. // Nini (config) related Methods
  727. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  728. {
  729. if (!File.Exists(fileName))
  730. {
  731. //create new file
  732. }
  733. XmlConfigSource config = new XmlConfigSource(fileName);
  734. AddDataRowToConfig(config, row);
  735. config.Save();
  736. return config;
  737. }
  738. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  739. {
  740. config.Configs.Add((string) row[0]);
  741. for (int i = 0; i < row.Table.Columns.Count; i++)
  742. {
  743. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  744. }
  745. }
  746. public static float Clip(float x, float min, float max)
  747. {
  748. return Math.Min(Math.Max(x, min), max);
  749. }
  750. public static int Clip(int x, int min, int max)
  751. {
  752. return Math.Min(Math.Max(x, min), max);
  753. }
  754. public static Vector3 Clip(Vector3 vec, float min, float max)
  755. {
  756. return new Vector3(Clip(vec.X, min, max), Clip(vec.Y, min, max),
  757. Clip(vec.Z, min, max));
  758. }
  759. /// <summary>
  760. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  761. /// </summary>
  762. /// <param name="UUID"></param>
  763. /// <returns></returns>
  764. public static String ToRawUuidString(UUID UUID)
  765. {
  766. return UUID.Guid.ToString("n");
  767. }
  768. public static string CleanString(string input)
  769. {
  770. if (input.Length == 0)
  771. return input;
  772. int clip = input.Length;
  773. // Test for ++ string terminator
  774. int pos = input.IndexOf("\0");
  775. if (pos != -1 && pos < clip)
  776. clip = pos;
  777. // Test for CR
  778. pos = input.IndexOf("\r");
  779. if (pos != -1 && pos < clip)
  780. clip = pos;
  781. // Test for LF
  782. pos = input.IndexOf("\n");
  783. if (pos != -1 && pos < clip)
  784. clip = pos;
  785. // Truncate string before first end-of-line character found
  786. return input.Substring(0, clip);
  787. }
  788. /// <summary>
  789. /// returns the contents of /etc/issue on Unix Systems
  790. /// Use this for where it's absolutely necessary to implement platform specific stuff
  791. /// </summary>
  792. /// <returns></returns>
  793. public static string ReadEtcIssue()
  794. {
  795. try
  796. {
  797. StreamReader sr = new StreamReader("/etc/issue.net");
  798. string issue = sr.ReadToEnd();
  799. sr.Close();
  800. return issue;
  801. }
  802. catch (Exception)
  803. {
  804. return "";
  805. }
  806. }
  807. public static void SerializeToFile(string filename, Object obj)
  808. {
  809. IFormatter formatter = new BinaryFormatter();
  810. Stream stream = null;
  811. try
  812. {
  813. stream = new FileStream(
  814. filename, FileMode.Create,
  815. FileAccess.Write, FileShare.None);
  816. formatter.Serialize(stream, obj);
  817. }
  818. catch (Exception e)
  819. {
  820. m_log.Error(e.ToString());
  821. }
  822. finally
  823. {
  824. if (stream != null)
  825. {
  826. stream.Close();
  827. }
  828. }
  829. }
  830. public static Object DeserializeFromFile(string filename)
  831. {
  832. IFormatter formatter = new BinaryFormatter();
  833. Stream stream = null;
  834. Object ret = null;
  835. try
  836. {
  837. stream = new FileStream(
  838. filename, FileMode.Open,
  839. FileAccess.Read, FileShare.None);
  840. ret = formatter.Deserialize(stream);
  841. }
  842. catch (Exception e)
  843. {
  844. m_log.Error(e.ToString());
  845. }
  846. finally
  847. {
  848. if (stream != null)
  849. {
  850. stream.Close();
  851. }
  852. }
  853. return ret;
  854. }
  855. public static string Compress(string text)
  856. {
  857. byte[] buffer = Util.UTF8.GetBytes(text);
  858. MemoryStream memory = new MemoryStream();
  859. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  860. {
  861. compressor.Write(buffer, 0, buffer.Length);
  862. }
  863. memory.Position = 0;
  864. byte[] compressed = new byte[memory.Length];
  865. memory.Read(compressed, 0, compressed.Length);
  866. byte[] compressedBuffer = new byte[compressed.Length + 4];
  867. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  868. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  869. return Convert.ToBase64String(compressedBuffer);
  870. }
  871. public static string Decompress(string compressedText)
  872. {
  873. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  874. using (MemoryStream memory = new MemoryStream())
  875. {
  876. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  877. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  878. byte[] buffer = new byte[msgLength];
  879. memory.Position = 0;
  880. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  881. {
  882. decompressor.Read(buffer, 0, buffer.Length);
  883. }
  884. return Util.UTF8.GetString(buffer);
  885. }
  886. }
  887. /// <summary>
  888. /// Copy data from one stream to another, leaving the read position of both streams at the beginning.
  889. /// </summary>
  890. /// <param name='inputStream'>
  891. /// Input stream. Must be seekable.
  892. /// </param>
  893. /// <exception cref='ArgumentException'>
  894. /// Thrown if the input stream is not seekable.
  895. /// </exception>
  896. public static Stream Copy(Stream inputStream)
  897. {
  898. if (!inputStream.CanSeek)
  899. throw new ArgumentException("Util.Copy(Stream inputStream) must receive an inputStream that can seek");
  900. const int readSize = 256;
  901. byte[] buffer = new byte[readSize];
  902. MemoryStream ms = new MemoryStream();
  903. int count = inputStream.Read(buffer, 0, readSize);
  904. while (count > 0)
  905. {
  906. ms.Write(buffer, 0, count);
  907. count = inputStream.Read(buffer, 0, readSize);
  908. }
  909. ms.Position = 0;
  910. inputStream.Position = 0;
  911. return ms;
  912. }
  913. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  914. {
  915. return SendXmlRpcCommand(url, methodName, args);
  916. }
  917. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  918. {
  919. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  920. return client.Send(url, 6000);
  921. }
  922. /// <summary>
  923. /// Returns an error message that the user could not be found in the database
  924. /// </summary>
  925. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  926. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  927. {
  928. XmlRpcResponse response = new XmlRpcResponse();
  929. Hashtable responseData = new Hashtable();
  930. responseData["error_type"] = "unknown_user";
  931. responseData["error_desc"] = "The user requested is not in the database";
  932. response.Value = responseData;
  933. return response;
  934. }
  935. /// <summary>
  936. /// Converts a byte array in big endian order into an ulong.
  937. /// </summary>
  938. /// <param name="bytes">
  939. /// The array of bytes
  940. /// </param>
  941. /// <returns>
  942. /// The extracted ulong
  943. /// </returns>
  944. public static ulong BytesToUInt64Big(byte[] bytes)
  945. {
  946. if (bytes.Length < 8) return 0;
  947. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  948. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  949. }
  950. // used for RemoteParcelRequest (for "About Landmark")
  951. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  952. {
  953. byte[] bytes =
  954. {
  955. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  956. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  957. (byte)x, (byte)(x >> 8), 0, 0,
  958. (byte)y, (byte)(y >> 8), 0, 0 };
  959. return new UUID(bytes, 0);
  960. }
  961. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  962. {
  963. byte[] bytes =
  964. {
  965. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  966. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  967. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  968. (byte)y, (byte)(y >> 8), 0, 0 };
  969. return new UUID(bytes, 0);
  970. }
  971. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  972. {
  973. byte[] bytes = parcelID.GetBytes();
  974. regionHandle = Utils.BytesToUInt64(bytes);
  975. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  976. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  977. }
  978. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  979. {
  980. byte[] bytes = parcelID.GetBytes();
  981. regionHandle = Utils.BytesToUInt64(bytes);
  982. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  983. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  984. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  985. }
  986. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  987. {
  988. ulong regionHandle;
  989. uint rx, ry;
  990. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  991. Utils.LongToUInts(regionHandle, out rx, out ry);
  992. x += rx;
  993. y += ry;
  994. }
  995. /// <summary>
  996. /// Get operating system information if available. Returns only the first 45 characters of information
  997. /// </summary>
  998. /// <returns>
  999. /// Operating system information. Returns an empty string if none was available.
  1000. /// </returns>
  1001. public static string GetOperatingSystemInformation()
  1002. {
  1003. string os = String.Empty;
  1004. if (Environment.OSVersion.Platform != PlatformID.Unix)
  1005. {
  1006. os = Environment.OSVersion.ToString();
  1007. }
  1008. else
  1009. {
  1010. os = ReadEtcIssue();
  1011. }
  1012. if (os.Length > 45)
  1013. {
  1014. os = os.Substring(0, 45);
  1015. }
  1016. return os;
  1017. }
  1018. public static string GetRuntimeInformation()
  1019. {
  1020. string ru = String.Empty;
  1021. if (Environment.OSVersion.Platform == PlatformID.Unix)
  1022. ru = "Unix/Mono";
  1023. else
  1024. if (Environment.OSVersion.Platform == PlatformID.MacOSX)
  1025. ru = "OSX/Mono";
  1026. else
  1027. {
  1028. if (Type.GetType("Mono.Runtime") != null)
  1029. ru = "Win/Mono";
  1030. else
  1031. ru = "Win/.NET";
  1032. }
  1033. return ru;
  1034. }
  1035. /// <summary>
  1036. /// Is the given string a UUID?
  1037. /// </summary>
  1038. /// <param name="s"></param>
  1039. /// <returns></returns>
  1040. public static bool isUUID(string s)
  1041. {
  1042. return UUIDPattern.IsMatch(s);
  1043. }
  1044. public static string GetDisplayConnectionString(string connectionString)
  1045. {
  1046. int passPosition = 0;
  1047. int passEndPosition = 0;
  1048. string displayConnectionString = null;
  1049. // hide the password in the connection string
  1050. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  1051. passPosition = connectionString.IndexOf("=", passPosition);
  1052. if (passPosition < connectionString.Length)
  1053. passPosition += 1;
  1054. passEndPosition = connectionString.IndexOf(";", passPosition);
  1055. displayConnectionString = connectionString.Substring(0, passPosition);
  1056. displayConnectionString += "***";
  1057. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  1058. return displayConnectionString;
  1059. }
  1060. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  1061. {
  1062. Type settingsType = settingsClass.GetType();
  1063. FieldInfo[] fieldInfos = settingsType.GetFields();
  1064. foreach (FieldInfo fieldInfo in fieldInfos)
  1065. {
  1066. if (!fieldInfo.IsStatic)
  1067. {
  1068. if (fieldInfo.FieldType == typeof(System.String))
  1069. {
  1070. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  1071. }
  1072. else if (fieldInfo.FieldType == typeof(System.Boolean))
  1073. {
  1074. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  1075. }
  1076. else if (fieldInfo.FieldType == typeof(System.Int32))
  1077. {
  1078. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  1079. }
  1080. else if (fieldInfo.FieldType == typeof(System.Single))
  1081. {
  1082. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  1083. }
  1084. else if (fieldInfo.FieldType == typeof(System.UInt32))
  1085. {
  1086. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  1087. }
  1088. }
  1089. }
  1090. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  1091. foreach (PropertyInfo propInfo in propertyInfos)
  1092. {
  1093. if ((propInfo.CanRead) && (propInfo.CanWrite))
  1094. {
  1095. if (propInfo.PropertyType == typeof(System.String))
  1096. {
  1097. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  1098. }
  1099. else if (propInfo.PropertyType == typeof(System.Boolean))
  1100. {
  1101. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  1102. }
  1103. else if (propInfo.PropertyType == typeof(System.Int32))
  1104. {
  1105. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  1106. }
  1107. else if (propInfo.PropertyType == typeof(System.Single))
  1108. {
  1109. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  1110. }
  1111. if (propInfo.PropertyType == typeof(System.UInt32))
  1112. {
  1113. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  1114. }
  1115. }
  1116. }
  1117. return settingsClass;
  1118. }
  1119. public static string Base64ToString(string str)
  1120. {
  1121. Decoder utf8Decode = Encoding.UTF8.GetDecoder();
  1122. byte[] todecode_byte = Convert.FromBase64String(str);
  1123. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  1124. char[] decoded_char = new char[charCount];
  1125. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  1126. string result = new String(decoded_char);
  1127. return result;
  1128. }
  1129. public static Guid GetHashGuid(string data, string salt)
  1130. {
  1131. byte[] hash = ComputeMD5Hash(data + salt);
  1132. //string s = BitConverter.ToString(hash);
  1133. Guid guid = new Guid(hash);
  1134. return guid;
  1135. }
  1136. public static byte ConvertMaturityToAccessLevel(uint maturity)
  1137. {
  1138. byte retVal = 0;
  1139. switch (maturity)
  1140. {
  1141. case 0: //PG
  1142. retVal = 13;
  1143. break;
  1144. case 1: //Mature
  1145. retVal = 21;
  1146. break;
  1147. case 2: // Adult
  1148. retVal = 42;
  1149. break;
  1150. }
  1151. return retVal;
  1152. }
  1153. public static uint ConvertAccessLevelToMaturity(byte maturity)
  1154. {
  1155. if (maturity <= 13)
  1156. return 0;
  1157. else if (maturity <= 21)
  1158. return 1;
  1159. else
  1160. return 2;
  1161. }
  1162. /// <summary>
  1163. /// Produces an OSDMap from its string representation on a stream
  1164. /// </summary>
  1165. /// <param name="data">The stream</param>
  1166. /// <param name="length">The size of the data on the stream</param>
  1167. /// <returns>The OSDMap or an exception</returns>
  1168. public static OSDMap GetOSDMap(Stream stream, int length)
  1169. {
  1170. byte[] data = new byte[length];
  1171. stream.Read(data, 0, length);
  1172. string strdata = Util.UTF8.GetString(data);
  1173. OSDMap args = null;
  1174. OSD buffer;
  1175. buffer = OSDParser.DeserializeJson(strdata);
  1176. if (buffer.Type == OSDType.Map)
  1177. {
  1178. args = (OSDMap)buffer;
  1179. return args;
  1180. }
  1181. return null;
  1182. }
  1183. public static OSDMap GetOSDMap(string data)
  1184. {
  1185. OSDMap args = null;
  1186. try
  1187. {
  1188. OSD buffer;
  1189. // We should pay attention to the content-type, but let's assume we know it's Json
  1190. buffer = OSDParser.DeserializeJson(data);
  1191. if (buffer.Type == OSDType.Map)
  1192. {
  1193. args = (OSDMap)buffer;
  1194. return args;
  1195. }
  1196. else
  1197. {
  1198. // uh?
  1199. m_log.Debug(("[UTILS]: Got OSD of unexpected type " + buffer.Type.ToString()));
  1200. return null;
  1201. }
  1202. }
  1203. catch (Exception ex)
  1204. {
  1205. m_log.Debug("[UTILS]: exception on GetOSDMap " + ex.Message);
  1206. return null;
  1207. }
  1208. }
  1209. public static string[] Glob(string path)
  1210. {
  1211. string vol=String.Empty;
  1212. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1213. {
  1214. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1215. if (vcomps.Length > 1)
  1216. {
  1217. path = vcomps[1];
  1218. vol = vcomps[0];
  1219. }
  1220. }
  1221. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1222. // Glob
  1223. path = vol;
  1224. if (vol != String.Empty)
  1225. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1226. else
  1227. path = new String(new char[] {Path.DirectorySeparatorChar});
  1228. List<string> paths = new List<string>();
  1229. List<string> found = new List<string>();
  1230. paths.Add(path);
  1231. int compIndex = -1;
  1232. foreach (string c in comps)
  1233. {
  1234. compIndex++;
  1235. List<string> addpaths = new List<string>();
  1236. foreach (string p in paths)
  1237. {
  1238. string[] dirs = Directory.GetDirectories(p, c);
  1239. if (dirs.Length != 0)
  1240. {
  1241. foreach (string dir in dirs)
  1242. addpaths.Add(Path.Combine(path, dir));
  1243. }
  1244. // Only add files if that is the last path component
  1245. if (compIndex == comps.Length - 1)
  1246. {
  1247. string[] files = Directory.GetFiles(p, c);
  1248. foreach (string f in files)
  1249. found.Add(f);
  1250. }
  1251. }
  1252. paths = addpaths;
  1253. }
  1254. return found.ToArray();
  1255. }
  1256. public static string ServerURI(string uri)
  1257. {
  1258. if (uri == string.Empty)
  1259. return string.Empty;
  1260. // Get rid of eventual slashes at the end
  1261. uri = uri.TrimEnd('/');
  1262. IPAddress ipaddr1 = null;
  1263. string port1 = "";
  1264. try
  1265. {
  1266. ipaddr1 = Util.GetHostFromURL(uri);
  1267. }
  1268. catch { }
  1269. try
  1270. {
  1271. port1 = uri.Split(new char[] { ':' })[2];
  1272. }
  1273. catch { }
  1274. // We tried our best to convert the domain names to IP addresses
  1275. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1276. }
  1277. /// <summary>
  1278. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1279. /// </summary>
  1280. /// <param name="str">
  1281. /// If null or empty, then an bytes[0] is returned.
  1282. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1283. /// </param>
  1284. /// <param name="args">
  1285. /// Arguments to substitute into the string via the {} mechanism.
  1286. /// </param>
  1287. /// <returns></returns>
  1288. public static byte[] StringToBytes256(string str, params object[] args)
  1289. {
  1290. return StringToBytes256(string.Format(str, args));
  1291. }
  1292. /// <summary>
  1293. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 256 bytes if necessary.
  1294. /// </summary>
  1295. /// <param name="str">
  1296. /// If null or empty, then an bytes[0] is returned.
  1297. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1298. /// </param>
  1299. /// <returns></returns>
  1300. public static byte[] StringToBytes256(string str)
  1301. {
  1302. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1303. if (str.Length > 254) str = str.Remove(254);
  1304. if (!str.EndsWith("\0")) { str += "\0"; }
  1305. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1306. // might have gotten an oversized array even after the string trim
  1307. byte[] data = UTF8.GetBytes(str);
  1308. if (data.Length > 256)
  1309. {
  1310. Array.Resize<byte>(ref data, 256);
  1311. data[255] = 0;
  1312. }
  1313. return data;
  1314. }
  1315. /// <summary>
  1316. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1317. /// </summary>
  1318. /// <param name="str">
  1319. /// If null or empty, then an bytes[0] is returned.
  1320. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1321. /// </param>
  1322. /// <param name="args">
  1323. /// Arguments to substitute into the string via the {} mechanism.
  1324. /// </param>
  1325. /// <returns></returns>
  1326. public static byte[] StringToBytes1024(string str, params object[] args)
  1327. {
  1328. return StringToBytes1024(string.Format(str, args));
  1329. }
  1330. /// <summary>
  1331. /// Convert a string to a byte format suitable for transport in an LLUDP packet. The output is truncated to 1024 bytes if necessary.
  1332. /// </summary>
  1333. /// <param name="str">
  1334. /// If null or empty, then an bytes[0] is returned.
  1335. /// Using "\0" will return a conversion of the null character to a byte. This is not the same as bytes[0]
  1336. /// </param>
  1337. /// <returns></returns>
  1338. public static byte[] StringToBytes1024(string str)
  1339. {
  1340. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1341. if (str.Length > 1023) str = str.Remove(1023);
  1342. if (!str.EndsWith("\0")) { str += "\0"; }
  1343. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1344. // might have gotten an oversized array even after the string trim
  1345. byte[] data = UTF8.GetBytes(str);
  1346. if (data.Length > 1024)
  1347. {
  1348. Array.Resize<byte>(ref data, 1024);
  1349. data[1023] = 0;
  1350. }
  1351. return data;
  1352. }
  1353. /// <summary>
  1354. /// Used to trigger an early library load on Windows systems.
  1355. /// </summary>
  1356. /// <remarks>
  1357. /// Required to get 32-bit and 64-bit processes to automatically use the
  1358. /// appropriate native library.
  1359. /// </remarks>
  1360. /// <param name="dllToLoad"></param>
  1361. /// <returns></returns>
  1362. [DllImport("kernel32.dll")]
  1363. public static extern IntPtr LoadLibrary(string dllToLoad);
  1364. /// <summary>
  1365. /// Determine whether the current process is 64 bit
  1366. /// </summary>
  1367. /// <returns>true if so, false if not</returns>
  1368. public static bool Is64BitProcess()
  1369. {
  1370. return IntPtr.Size == 8;
  1371. }
  1372. #region FireAndForget Threading Pattern
  1373. /// <summary>
  1374. /// Created to work around a limitation in Mono with nested delegates
  1375. /// </summary>
  1376. private sealed class FireAndForgetWrapper
  1377. {
  1378. private static volatile FireAndForgetWrapper instance;
  1379. private static object syncRoot = new Object();
  1380. public static FireAndForgetWrapper Instance {
  1381. get {
  1382. if (instance == null)
  1383. {
  1384. lock (syncRoot)
  1385. {
  1386. if (instance == null)
  1387. {
  1388. instance = new FireAndForgetWrapper();
  1389. }
  1390. }
  1391. }
  1392. return instance;
  1393. }
  1394. }
  1395. public void FireAndForget(System.Threading.WaitCallback callback)
  1396. {
  1397. callback.BeginInvoke(null, EndFireAndForget, callback);
  1398. }
  1399. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1400. {
  1401. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1402. }
  1403. private static void EndFireAndForget(IAsyncResult ar)
  1404. {
  1405. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1406. try { callback.EndInvoke(ar); }
  1407. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1408. ar.AsyncWaitHandle.Close();
  1409. }
  1410. }
  1411. public static void FireAndForget(System.Threading.WaitCallback callback)
  1412. {
  1413. FireAndForget(callback, null);
  1414. }
  1415. public static void InitThreadPool(int maxThreads)
  1416. {
  1417. if (maxThreads < 2)
  1418. throw new ArgumentOutOfRangeException("maxThreads", "maxThreads must be greater than 2");
  1419. if (m_ThreadPool != null)
  1420. throw new InvalidOperationException("SmartThreadPool is already initialized");
  1421. m_ThreadPool = new SmartThreadPool(2000, maxThreads, 2);
  1422. }
  1423. public static int FireAndForgetCount()
  1424. {
  1425. const int MAX_SYSTEM_THREADS = 200;
  1426. switch (FireAndForgetMethod)
  1427. {
  1428. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1429. case FireAndForgetMethod.QueueUserWorkItem:
  1430. case FireAndForgetMethod.BeginInvoke:
  1431. int workerThreads, iocpThreads;
  1432. ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
  1433. return workerThreads;
  1434. case FireAndForgetMethod.SmartThreadPool:
  1435. return m_ThreadPool.MaxThreads - m_ThreadPool.InUseThreads;
  1436. case FireAndForgetMethod.Thread:
  1437. return MAX_SYSTEM_THREADS - System.Diagnostics.Process.GetCurrentProcess().Threads.Count;
  1438. default:
  1439. throw new NotImplementedException();
  1440. }
  1441. }
  1442. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1443. {
  1444. WaitCallback realCallback;
  1445. if (FireAndForgetMethod == FireAndForgetMethod.RegressionTest)
  1446. {
  1447. // If we're running regression tests, then we want any exceptions to rise up to the test code.
  1448. realCallback = o => { Culture.SetCurrentCulture(); callback(o); };
  1449. }
  1450. else
  1451. {
  1452. // When OpenSim interacts with a database or sends data over the wire, it must send this in en_US culture
  1453. // so that we don't encounter problems where, for instance, data is saved with a culture that uses commas
  1454. // for decimals places but is read by a culture that treats commas as number seperators.
  1455. realCallback = o =>
  1456. {
  1457. Culture.SetCurrentCulture();
  1458. try
  1459. {
  1460. callback(o);
  1461. }
  1462. catch (Exception e)
  1463. {
  1464. m_log.ErrorFormat(
  1465. "[UTIL]: Continuing after async_call_method thread terminated with exception {0}{1}",
  1466. e.Message, e.StackTrace);
  1467. }
  1468. };
  1469. }
  1470. switch (FireAndForgetMethod)
  1471. {
  1472. case FireAndForgetMethod.RegressionTest:
  1473. case FireAndForgetMethod.None:
  1474. realCallback.Invoke(obj);
  1475. break;
  1476. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1477. ThreadPool.UnsafeQueueUserWorkItem(realCallback, obj);
  1478. break;
  1479. case FireAndForgetMethod.QueueUserWorkItem:
  1480. ThreadPool.QueueUserWorkItem(realCallback, obj);
  1481. break;
  1482. case FireAndForgetMethod.BeginInvoke:
  1483. FireAndForgetWrapper wrapper = FireAndForgetWrapper.Instance;
  1484. wrapper.FireAndForget(realCallback, obj);
  1485. break;
  1486. case FireAndForgetMethod.SmartThreadPool:
  1487. if (m_ThreadPool == null)
  1488. m_ThreadPool = new SmartThreadPool(2000, 15, 2);
  1489. m_ThreadPool.QueueWorkItem(SmartThreadPoolCallback, new object[] { realCallback, obj });
  1490. break;
  1491. case FireAndForgetMethod.Thread:
  1492. Thread thread = new Thread(delegate(object o) { realCallback(o); });
  1493. thread.Start(obj);
  1494. break;
  1495. default:
  1496. throw new NotImplementedException();
  1497. }
  1498. }
  1499. /// <summary>
  1500. /// Get a thread pool report.
  1501. /// </summary>
  1502. /// <returns></returns>
  1503. public static string GetThreadPoolReport()
  1504. {
  1505. string threadPoolUsed = null;
  1506. int maxThreads = 0;
  1507. int minThreads = 0;
  1508. int allocatedThreads = 0;
  1509. int inUseThreads = 0;
  1510. int waitingCallbacks = 0;
  1511. int completionPortThreads = 0;
  1512. StringBuilder sb = new StringBuilder();
  1513. if (FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool)
  1514. {
  1515. // ROBUST currently leaves this the FireAndForgetMethod but never actually initializes the threadpool.
  1516. if (m_ThreadPool != null)
  1517. {
  1518. threadPoolUsed = "SmartThreadPool";
  1519. maxThreads = m_ThreadPool.MaxThreads;
  1520. minThreads = m_ThreadPool.MinThreads;
  1521. inUseThreads = m_ThreadPool.InUseThreads;
  1522. allocatedThreads = m_ThreadPool.ActiveThreads;
  1523. waitingCallbacks = m_ThreadPool.WaitingCallbacks;
  1524. }
  1525. }
  1526. else if (
  1527. FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem
  1528. || FireAndForgetMethod == FireAndForgetMethod.UnsafeQueueUserWorkItem)
  1529. {
  1530. threadPoolUsed = "BuiltInThreadPool";
  1531. ThreadPool.GetMaxThreads(out maxThreads, out completionPortThreads);
  1532. ThreadPool.GetMinThreads(out minThreads, out completionPortThreads);
  1533. int availableThreads;
  1534. ThreadPool.GetAvailableThreads(out availableThreads, out completionPortThreads);
  1535. inUseThreads = maxThreads - availableThreads;
  1536. allocatedThreads = -1;
  1537. waitingCallbacks = -1;
  1538. }
  1539. if (threadPoolUsed != null)
  1540. {
  1541. sb.AppendFormat("Thread pool used : {0}\n", threadPoolUsed);
  1542. sb.AppendFormat("Max threads : {0}\n", maxThreads);
  1543. sb.AppendFormat("Min threads : {0}\n", minThreads);
  1544. sb.AppendFormat("Allocated threads : {0}\n", allocatedThreads < 0 ? "not applicable" : allocatedThreads.ToString());
  1545. sb.AppendFormat("In use threads : {0}\n", inUseThreads);
  1546. sb.AppendFormat("Work items waiting : {0}\n", waitingCallbacks < 0 ? "not available" : waitingCallbacks.ToString());
  1547. }
  1548. else
  1549. {
  1550. sb.AppendFormat("Thread pool not used\n");
  1551. }
  1552. return sb.ToString();
  1553. }
  1554. private static object SmartThreadPoolCallback(object o)
  1555. {
  1556. object[] array = (object[])o;
  1557. WaitCallback callback = (WaitCallback)array[0];
  1558. object obj = array[1];
  1559. callback(obj);
  1560. return null;
  1561. }
  1562. #endregion FireAndForget Threading Pattern
  1563. /// <summary>
  1564. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1565. /// and negative every 24.9 days. This trims down TickCount so it doesn't wrap
  1566. /// for the callers.
  1567. /// This trims it to a 12 day interval so don't let your frame time get too long.
  1568. /// </summary>
  1569. /// <returns></returns>
  1570. public static Int32 EnvironmentTickCount()
  1571. {
  1572. return Environment.TickCount & EnvironmentTickCountMask;
  1573. }
  1574. const Int32 EnvironmentTickCountMask = 0x3fffffff;
  1575. /// <summary>
  1576. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1577. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1578. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1579. /// </summary>
  1580. /// <param name="newValue"></param>
  1581. /// <param name="prevValue"></param>
  1582. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1583. public static Int32 EnvironmentTickCountSubtract(Int32 newValue, Int32 prevValue)
  1584. {
  1585. Int32 diff = newValue - prevValue;
  1586. return (diff >= 0) ? diff : (diff + EnvironmentTickCountMask + 1);
  1587. }
  1588. /// <summary>
  1589. /// Environment.TickCount is an int but it counts all 32 bits so it goes positive
  1590. /// and negative every 24.9 days. Subtracts the passed value (previously fetched by
  1591. /// 'EnvironmentTickCount()') and accounts for any wrapping.
  1592. /// </summary>
  1593. /// <returns>subtraction of passed prevValue from current Environment.TickCount</returns>
  1594. public static Int32 EnvironmentTickCountSubtract(Int32 prevValue)
  1595. {
  1596. return EnvironmentTickCountSubtract(EnvironmentTickCount(), prevValue);
  1597. }
  1598. // Returns value of Tick Count A - TickCount B accounting for wrapping of TickCount
  1599. // Assumes both tcA and tcB came from previous calls to Util.EnvironmentTickCount().
  1600. // A positive return value indicates A occured later than B
  1601. public static Int32 EnvironmentTickCountCompare(Int32 tcA, Int32 tcB)
  1602. {
  1603. // A, B and TC are all between 0 and 0x3fffffff
  1604. int tc = EnvironmentTickCount();
  1605. if (tc - tcA >= 0)
  1606. tcA += EnvironmentTickCountMask + 1;
  1607. if (tc - tcB >= 0)
  1608. tcB += EnvironmentTickCountMask + 1;
  1609. return tcA - tcB;
  1610. }
  1611. /// <summary>
  1612. /// Prints the call stack at any given point. Useful for debugging.
  1613. /// </summary>
  1614. public static void PrintCallStack()
  1615. {
  1616. StackTrace stackTrace = new StackTrace(true); // get call stack
  1617. StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)
  1618. // write call stack method names
  1619. foreach (StackFrame stackFrame in stackFrames)
  1620. {
  1621. MethodBase mb = stackFrame.GetMethod();
  1622. m_log.DebugFormat("{0}.{1}:{2}", mb.DeclaringType, mb.Name, stackFrame.GetFileLineNumber()); // write method name
  1623. }
  1624. }
  1625. /// <summary>
  1626. /// Gets the client IP address
  1627. /// </summary>
  1628. /// <param name="xff"></param>
  1629. /// <returns></returns>
  1630. public static IPEndPoint GetClientIPFromXFF(string xff)
  1631. {
  1632. if (xff == string.Empty)
  1633. return null;
  1634. string[] parts = xff.Split(new char[] { ',' });
  1635. if (parts.Length > 0)
  1636. {
  1637. try
  1638. {
  1639. return new IPEndPoint(IPAddress.Parse(parts[0]), 0);
  1640. }
  1641. catch (Exception e)
  1642. {
  1643. m_log.WarnFormat("[UTIL]: Exception parsing XFF header {0}: {1}", xff, e.Message);
  1644. }
  1645. }
  1646. return null;
  1647. }
  1648. public static string GetCallerIP(Hashtable req)
  1649. {
  1650. if (req.ContainsKey("headers"))
  1651. {
  1652. try
  1653. {
  1654. Hashtable headers = (Hashtable)req["headers"];
  1655. if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null)
  1656. return headers["remote_addr"].ToString();
  1657. }
  1658. catch (Exception e)
  1659. {
  1660. m_log.WarnFormat("[UTIL]: exception in GetCallerIP: {0}", e.Message);
  1661. }
  1662. }
  1663. return string.Empty;
  1664. }
  1665. #region Xml Serialization Utilities
  1666. public static bool ReadBoolean(XmlTextReader reader)
  1667. {
  1668. reader.ReadStartElement();
  1669. bool result = Boolean.Parse(reader.ReadContentAsString().ToLower());
  1670. reader.ReadEndElement();
  1671. return result;
  1672. }
  1673. public static UUID ReadUUID(XmlTextReader reader, string name)
  1674. {
  1675. UUID id;
  1676. string idStr;
  1677. reader.ReadStartElement(name);
  1678. if (reader.Name == "Guid")
  1679. idStr = reader.ReadElementString("Guid");
  1680. else if (reader.Name == "UUID")
  1681. idStr = reader.ReadElementString("UUID");
  1682. else // no leading tag
  1683. idStr = reader.ReadContentAsString();
  1684. UUID.TryParse(idStr, out id);
  1685. reader.ReadEndElement();
  1686. return id;
  1687. }
  1688. public static Vector3 ReadVector(XmlTextReader reader, string name)
  1689. {
  1690. Vector3 vec;
  1691. reader.ReadStartElement(name);
  1692. vec.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // X or x
  1693. vec.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Y or y
  1694. vec.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty); // Z or z
  1695. reader.ReadEndElement();
  1696. return vec;
  1697. }
  1698. public static Quaternion ReadQuaternion(XmlTextReader reader, string name)
  1699. {
  1700. Quaternion quat = new Quaternion();
  1701. reader.ReadStartElement(name);
  1702. while (reader.NodeType != XmlNodeType.EndElement)
  1703. {
  1704. switch (reader.Name.ToLower())
  1705. {
  1706. case "x":
  1707. quat.X = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1708. break;
  1709. case "y":
  1710. quat.Y = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1711. break;
  1712. case "z":
  1713. quat.Z = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1714. break;
  1715. case "w":
  1716. quat.W = reader.ReadElementContentAsFloat(reader.Name, String.Empty);
  1717. break;
  1718. }
  1719. }
  1720. reader.ReadEndElement();
  1721. return quat;
  1722. }
  1723. public static T ReadEnum<T>(XmlTextReader reader, string name)
  1724. {
  1725. string value = reader.ReadElementContentAsString(name, String.Empty);
  1726. // !!!!! to deal with flags without commas
  1727. if (value.Contains(" ") && !value.Contains(","))
  1728. value = value.Replace(" ", ", ");
  1729. return (T)Enum.Parse(typeof(T), value); ;
  1730. }
  1731. #endregion
  1732. #region Universal User Identifiers
  1733. /// <summary>
  1734. /// </summary>
  1735. /// <param name="value">uuid[;endpoint[;first last[;secret]]]</param>
  1736. /// <param name="uuid">the uuid part</param>
  1737. /// <param name="url">the endpoint part (e.g. http://foo.com)</param>
  1738. /// <param name="firstname">the first name part (e.g. Test)</param>
  1739. /// <param name="lastname">the last name part (e.g User)</param>
  1740. /// <param name="secret">the secret part</param>
  1741. public static bool ParseUniversalUserIdentifier(string value, out UUID uuid, out string url, out string firstname, out string lastname, out string secret)
  1742. {
  1743. uuid = UUID.Zero; url = string.Empty; firstname = "Unknown"; lastname = "User"; secret = string.Empty;
  1744. string[] parts = value.Split(';');
  1745. if (parts.Length >= 1)
  1746. if (!UUID.TryParse(parts[0], out uuid))
  1747. return false;
  1748. if (parts.Length >= 2)
  1749. url = parts[1];
  1750. if (parts.Length >= 3)
  1751. {
  1752. string[] name = parts[2].Split();
  1753. if (name.Length == 2)
  1754. {
  1755. firstname = name[0];
  1756. lastname = name[1];
  1757. }
  1758. }
  1759. if (parts.Length >= 4)
  1760. secret = parts[3];
  1761. return true;
  1762. }
  1763. /// <summary>
  1764. /// Produces a universal (HG) system-facing identifier given the information
  1765. /// </summary>
  1766. /// <param name="acircuit"></param>
  1767. /// <returns>uuid[;homeURI[;first last]]</returns>
  1768. public static string ProduceUserUniversalIdentifier(AgentCircuitData acircuit)
  1769. {
  1770. if (acircuit.ServiceURLs.ContainsKey("HomeURI"))
  1771. return UniversalIdentifier(acircuit.AgentID, acircuit.firstname, acircuit.lastname, acircuit.ServiceURLs["HomeURI"].ToString());
  1772. else
  1773. return acircuit.AgentID.ToString();
  1774. }
  1775. /// <summary>
  1776. /// Produces a universal (HG) system-facing identifier given the information
  1777. /// </summary>
  1778. /// <param name="id">UUID of the user</param>
  1779. /// <param name="firstName">first name (e.g Test)</param>
  1780. /// <param name="lastName">last name (e.g. User)</param>
  1781. /// <param name="homeURI">homeURI (e.g. http://foo.com)</param>
  1782. /// <returns>a string of the form uuid[;homeURI[;first last]]</returns>
  1783. public static string UniversalIdentifier(UUID id, String firstName, String lastName, String homeURI)
  1784. {
  1785. string agentsURI = homeURI;
  1786. if (!agentsURI.EndsWith("/"))
  1787. agentsURI += "/";
  1788. // This is ugly, but there's no other way, given that the name is changed
  1789. // in the agent circuit data for foreigners
  1790. if (lastName.Contains("@"))
  1791. {
  1792. string[] parts = firstName.Split(new char[] { '.' });
  1793. if (parts.Length == 2)
  1794. return id.ToString() + ";" + agentsURI + ";" + parts[0] + " " + parts[1];
  1795. }
  1796. return id.ToString() + ";" + agentsURI + ";" + firstName + " " + lastName;
  1797. }
  1798. /// <summary>
  1799. /// Produces a universal (HG) user-facing name given the information
  1800. /// </summary>
  1801. /// <param name="firstName"></param>
  1802. /// <param name="lastName"></param>
  1803. /// <param name="homeURI"></param>
  1804. /// <returns>string of the form first.last @foo.com or first last</returns>
  1805. public static string UniversalName(String firstName, String lastName, String homeURI)
  1806. {
  1807. Uri uri = null;
  1808. try
  1809. {
  1810. uri = new Uri(homeURI);
  1811. }
  1812. catch (UriFormatException)
  1813. {
  1814. return firstName + " " + lastName;
  1815. }
  1816. return firstName + "." + lastName + " " + "@" + uri.Authority;
  1817. }
  1818. #endregion
  1819. }
  1820. }